]> git.proxmox.com Git - rustc.git/blame - src/doc/unstable-book/src/language-features/ffi-const.md
New upstream version 1.48.0~beta.8+dfsg1
[rustc.git] / src / doc / unstable-book / src / language-features / ffi-const.md
CommitLineData
f9f354fc
XL
1# `ffi_const`
2
1b1a35ee
XL
3The tracking issue for this feature is: [#58328]
4
5------
6
f9f354fc
XL
7The `#[ffi_const]` attribute applies clang's `const` attribute to foreign
8functions declarations.
9
10That is, `#[ffi_const]` functions shall have no effects except for its return
11value, which can only depend on the values of the function parameters, and is
12not affected by changes to the observable state of the program.
13
14Applying the `#[ffi_const]` attribute to a function that violates these
15requirements is undefined behaviour.
16
17This attribute enables Rust to perform common optimizations, like sub-expression
18elimination, and it can avoid emitting some calls in repeated invocations of the
19function with the same argument values regardless of other operations being
20performed in between these functions calls (as opposed to `#[ffi_pure]`
21functions).
22
23## Pitfalls
24
25A `#[ffi_const]` function can only read global memory that would not affect
26its return value for the whole execution of the program (e.g. immutable global
27memory). `#[ffi_const]` functions are referentially-transparent and therefore
28more strict than `#[ffi_pure]` functions.
29
30A common pitfall involves applying the `#[ffi_const]` attribute to a
31function that reads memory through pointer arguments which do not necessarily
32point to immutable global memory.
33
34A `#[ffi_const]` function that returns unit has no effect on the abstract
35machine's state, and a `#[ffi_const]` function cannot be `#[ffi_pure]`.
36
37A `#[ffi_const]` function must not diverge, neither via a side effect (e.g. a
38call to `abort`) nor by infinite loops.
39
40When translating C headers to Rust FFI, it is worth verifying for which targets
41the `const` attribute is enabled in those headers, and using the appropriate
42`cfg` macros in the Rust side to match those definitions. While the semantics of
43`const` are implemented identically by many C and C++ compilers, e.g., clang,
44[GCC], [ARM C/C++ compiler], [IBM ILE C/C++], etc. they are not necessarily
45implemented in this way on all of them. It is therefore also worth verifying
46that the semantics of the C toolchain used to compile the binary being linked
47against are compatible with those of the `#[ffi_const]`.
48
1b1a35ee 49[#58328]: https://github.com/rust-lang/rust/issues/58328
f9f354fc
XL
50[ARM C/C++ compiler]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0491c/Cacgigch.html
51[GCC]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-const-function-attribute
52[IBM ILE C/C++]: https://www.ibm.com/support/knowledgecenter/fr/ssw_ibm_i_71/rzarg/fn_attrib_const.htm