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