]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/attributes.rs
Auto merge of #79668 - coolreader18:recover-const-impl, r=petrochenkov
[rust.git] / compiler / rustc_codegen_llvm / src / attributes.rs
1 //! Set and unset common attributes on LLVM values.
2
3 use std::ffi::CString;
4
5 use rustc_codegen_ssa::traits::*;
6 use rustc_data_structures::const_cstr;
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_data_structures::small_c_str::SmallCStr;
9 use rustc_hir::def_id::DefId;
10 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
11 use rustc_middle::ty::layout::HasTyCtxt;
12 use rustc_middle::ty::query::Providers;
13 use rustc_middle::ty::{self, TyCtxt};
14 use rustc_session::config::{OptLevel, SanitizerSet};
15 use rustc_session::Session;
16
17 use crate::attributes;
18 use crate::llvm::AttributePlace::Function;
19 use crate::llvm::{self, Attribute};
20 use crate::llvm_util;
21 pub use rustc_attr::{InlineAttr, InstructionSetAttr, OptimizeAttr};
22
23 use crate::context::CodegenCx;
24 use crate::value::Value;
25
26 /// Mark LLVM function to use provided inline heuristic.
27 #[inline]
28 fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) {
29     use self::InlineAttr::*;
30     match inline {
31         Hint => Attribute::InlineHint.apply_llfn(Function, val),
32         Always => Attribute::AlwaysInline.apply_llfn(Function, val),
33         Never => {
34             if cx.tcx().sess.target.arch != "amdgpu" {
35                 Attribute::NoInline.apply_llfn(Function, val);
36             }
37         }
38         None => {}
39     };
40 }
41
42 /// Apply LLVM sanitize attributes.
43 #[inline]
44 pub fn sanitize(cx: &CodegenCx<'ll, '_>, no_sanitize: SanitizerSet, llfn: &'ll Value) {
45     let enabled = cx.tcx.sess.opts.debugging_opts.sanitizer - no_sanitize;
46     if enabled.contains(SanitizerSet::ADDRESS) {
47         llvm::Attribute::SanitizeAddress.apply_llfn(Function, llfn);
48     }
49     if enabled.contains(SanitizerSet::MEMORY) {
50         llvm::Attribute::SanitizeMemory.apply_llfn(Function, llfn);
51     }
52     if enabled.contains(SanitizerSet::THREAD) {
53         llvm::Attribute::SanitizeThread.apply_llfn(Function, llfn);
54     }
55 }
56
57 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
58 #[inline]
59 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
60     Attribute::UWTable.toggle_llfn(Function, val, emit);
61 }
62
63 /// Tell LLVM if this function should be 'naked', i.e., skip the epilogue and prologue.
64 #[inline]
65 fn naked(val: &'ll Value, is_naked: bool) {
66     Attribute::Naked.toggle_llfn(Function, val, is_naked);
67 }
68
69 pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
70     if cx.sess().must_not_eliminate_frame_pointers() {
71         llvm::AddFunctionAttrStringValue(
72             llfn,
73             llvm::AttributePlace::Function,
74             const_cstr!("frame-pointer"),
75             const_cstr!("all"),
76         );
77     }
78 }
79
80 /// Tell LLVM what instrument function to insert.
81 #[inline]
82 fn set_instrument_function(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
83     if cx.sess().instrument_mcount() {
84         // Similar to `clang -pg` behavior. Handled by the
85         // `post-inline-ee-instrument` LLVM pass.
86
87         // The function name varies on platforms.
88         // See test/CodeGen/mcount.c in clang.
89         let mcount_name = CString::new(cx.sess().target.mcount.as_str().as_bytes()).unwrap();
90
91         llvm::AddFunctionAttrStringValue(
92             llfn,
93             llvm::AttributePlace::Function,
94             const_cstr!("instrument-function-entry-inlined"),
95             &mcount_name,
96         );
97     }
98 }
99
100 fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
101     // Only use stack probes if the target specification indicates that we
102     // should be using stack probes
103     if !cx.sess().target.stack_probes {
104         return;
105     }
106
107     // Currently stack probes seem somewhat incompatible with the address
108     // sanitizer and thread sanitizer. With asan we're already protected from
109     // stack overflow anyway so we don't really need stack probes regardless.
110     if cx
111         .sess()
112         .opts
113         .debugging_opts
114         .sanitizer
115         .intersects(SanitizerSet::ADDRESS | SanitizerSet::THREAD)
116     {
117         return;
118     }
119
120     // probestack doesn't play nice either with `-C profile-generate`.
121     if cx.sess().opts.cg.profile_generate.enabled() {
122         return;
123     }
124
125     // probestack doesn't play nice either with gcov profiling.
126     if cx.sess().opts.debugging_opts.profile {
127         return;
128     }
129
130     // Flag our internal `__rust_probestack` function as the stack probe symbol.
131     // This is defined in the `compiler-builtins` crate for each architecture.
132     llvm::AddFunctionAttrStringValue(
133         llfn,
134         llvm::AttributePlace::Function,
135         const_cstr!("probe-stack"),
136         const_cstr!("__rust_probestack"),
137     );
138 }
139
140 pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
141     const RUSTC_SPECIFIC_FEATURES: &[&str] = &["crt-static"];
142
143     let cmdline = sess
144         .opts
145         .cg
146         .target_feature
147         .split(',')
148         .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
149     sess.target.features.split(',').chain(cmdline).filter(|l| !l.is_empty())
150 }
151
152 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
153     let target_cpu = SmallCStr::new(llvm_util::target_cpu(cx.tcx.sess));
154     llvm::AddFunctionAttrStringValue(
155         llfn,
156         llvm::AttributePlace::Function,
157         const_cstr!("target-cpu"),
158         target_cpu.as_c_str(),
159     );
160 }
161
162 pub fn apply_tune_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
163     if let Some(tune) = llvm_util::tune_cpu(cx.tcx.sess) {
164         let tune_cpu = SmallCStr::new(tune);
165         llvm::AddFunctionAttrStringValue(
166             llfn,
167             llvm::AttributePlace::Function,
168             const_cstr!("tune-cpu"),
169             tune_cpu.as_c_str(),
170         );
171     }
172 }
173
174 /// Sets the `NonLazyBind` LLVM attribute on a given function,
175 /// assuming the codegen options allow skipping the PLT.
176 pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
177     // Don't generate calls through PLT if it's not necessary
178     if !sess.needs_plt() {
179         Attribute::NonLazyBind.apply_llfn(Function, llfn);
180     }
181 }
182
183 pub(crate) fn default_optimisation_attrs(sess: &Session, llfn: &'ll Value) {
184     match sess.opts.optimize {
185         OptLevel::Size => {
186             llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
187             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
188             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
189         }
190         OptLevel::SizeMin => {
191             llvm::Attribute::MinSize.apply_llfn(Function, llfn);
192             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
193             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
194         }
195         OptLevel::No => {
196             llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
197             llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
198             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
199         }
200         _ => {}
201     }
202 }
203
204 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
205 /// attributes.
206 pub fn from_fn_attrs(cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value, instance: ty::Instance<'tcx>) {
207     let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(instance.def_id());
208
209     match codegen_fn_attrs.optimize {
210         OptimizeAttr::None => {
211             default_optimisation_attrs(cx.tcx.sess, llfn);
212         }
213         OptimizeAttr::Speed => {
214             llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
215             llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
216             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
217         }
218         OptimizeAttr::Size => {
219             llvm::Attribute::MinSize.apply_llfn(Function, llfn);
220             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
221             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
222         }
223     }
224
225     let inline_attr = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
226         InlineAttr::Never
227     } else if codegen_fn_attrs.inline == InlineAttr::None && instance.def.requires_inline(cx.tcx) {
228         InlineAttr::Hint
229     } else {
230         codegen_fn_attrs.inline
231     };
232     inline(cx, llfn, inline_attr);
233
234     // The `uwtable` attribute according to LLVM is:
235     //
236     //     This attribute indicates that the ABI being targeted requires that an
237     //     unwind table entry be produced for this function even if we can show
238     //     that no exceptions passes by it. This is normally the case for the
239     //     ELF x86-64 abi, but it can be disabled for some compilation units.
240     //
241     // Typically when we're compiling with `-C panic=abort` (which implies this
242     // `no_landing_pads` check) we don't need `uwtable` because we can't
243     // generate any exceptions! On Windows, however, exceptions include other
244     // events such as illegal instructions, segfaults, etc. This means that on
245     // Windows we end up still needing the `uwtable` attribute even if the `-C
246     // panic=abort` flag is passed.
247     //
248     // You can also find more info on why Windows always requires uwtables here:
249     //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
250     if cx.sess().must_emit_unwind_tables() {
251         attributes::emit_uwtable(llfn, true);
252     }
253
254     set_frame_pointer_elimination(cx, llfn);
255     set_instrument_function(cx, llfn);
256     set_probestack(cx, llfn);
257
258     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
259         Attribute::Cold.apply_llfn(Function, llfn);
260     }
261     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_RETURNS_TWICE) {
262         Attribute::ReturnsTwice.apply_llfn(Function, llfn);
263     }
264     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_PURE) {
265         Attribute::ReadOnly.apply_llfn(Function, llfn);
266     }
267     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_CONST) {
268         Attribute::ReadNone.apply_llfn(Function, llfn);
269     }
270     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
271         naked(llfn, true);
272     }
273     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
274         Attribute::NoAlias.apply_llfn(llvm::AttributePlace::ReturnValue, llfn);
275     }
276     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY) {
277         llvm::AddFunctionAttrString(llfn, Function, const_cstr!("cmse_nonsecure_entry"));
278     }
279     sanitize(cx, codegen_fn_attrs.no_sanitize, llfn);
280
281     // Always annotate functions with the target-cpu they are compiled for.
282     // Without this, ThinLTO won't inline Rust functions into Clang generated
283     // functions (because Clang annotates functions this way too).
284     apply_target_cpu_attr(cx, llfn);
285     // tune-cpu is only conveyed through the attribute for our purpose.
286     // The target doesn't care; the subtarget reads our attribute.
287     apply_tune_cpu_attr(cx, llfn);
288
289     let features = llvm_target_features(cx.tcx.sess)
290         .map(|s| s.to_string())
291         .chain(codegen_fn_attrs.target_features.iter().map(|f| {
292             let feature = &f.as_str();
293             format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
294         }))
295         .chain(codegen_fn_attrs.instruction_set.iter().map(|x| match x {
296             InstructionSetAttr::ArmA32 => "-thumb-mode".to_string(),
297             InstructionSetAttr::ArmT32 => "+thumb-mode".to_string(),
298         }))
299         .collect::<Vec<String>>()
300         .join(",");
301
302     if !features.is_empty() {
303         let val = CString::new(features).unwrap();
304         llvm::AddFunctionAttrStringValue(
305             llfn,
306             llvm::AttributePlace::Function,
307             const_cstr!("target-features"),
308             &val,
309         );
310     }
311
312     // Note that currently the `wasm-import-module` doesn't do anything, but
313     // eventually LLVM 7 should read this and ferry the appropriate import
314     // module to the output file.
315     if cx.tcx.sess.target.arch == "wasm32" {
316         if let Some(module) = wasm_import_module(cx.tcx, instance.def_id()) {
317             llvm::AddFunctionAttrStringValue(
318                 llfn,
319                 llvm::AttributePlace::Function,
320                 const_cstr!("wasm-import-module"),
321                 &module,
322             );
323
324             let name =
325                 codegen_fn_attrs.link_name.unwrap_or_else(|| cx.tcx.item_name(instance.def_id()));
326             let name = CString::new(&name.as_str()[..]).unwrap();
327             llvm::AddFunctionAttrStringValue(
328                 llfn,
329                 llvm::AttributePlace::Function,
330                 const_cstr!("wasm-import-name"),
331                 &name,
332             );
333         }
334     }
335 }
336
337 pub fn provide_both(providers: &mut Providers) {
338     providers.wasm_import_module_map = |tcx, cnum| {
339         // Build up a map from DefId to a `NativeLib` structure, where
340         // `NativeLib` internally contains information about
341         // `#[link(wasm_import_module = "...")]` for example.
342         let native_libs = tcx.native_libraries(cnum);
343
344         let def_id_to_native_lib = native_libs
345             .iter()
346             .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
347             .collect::<FxHashMap<_, _>>();
348
349         let mut ret = FxHashMap::default();
350         for (def_id, lib) in tcx.foreign_modules(cnum).iter() {
351             let module = def_id_to_native_lib.get(&def_id).and_then(|s| s.wasm_import_module);
352             let module = match module {
353                 Some(s) => s,
354                 None => continue,
355             };
356             ret.extend(lib.foreign_items.iter().map(|id| {
357                 assert_eq!(id.krate, cnum);
358                 (*id, module.to_string())
359             }));
360         }
361
362         ret
363     };
364 }
365
366 fn wasm_import_module(tcx: TyCtxt<'_>, id: DefId) -> Option<CString> {
367     tcx.wasm_import_module_map(id.krate).get(&id).map(|s| CString::new(&s[..]).unwrap())
368 }