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