]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/attributes.rs
Rollup merge of #101600 - notriddle:notriddle/li, r=GuillaumeGomez
[rust.git] / compiler / rustc_codegen_llvm / src / attributes.rs
1 //! Set and unset common attributes on LLVM values.
2
3 use rustc_codegen_ssa::traits::*;
4 use rustc_data_structures::small_str::SmallStr;
5 use rustc_hir::def_id::DefId;
6 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
7 use rustc_middle::ty::{self, TyCtxt};
8 use rustc_session::config::OptLevel;
9 use rustc_span::symbol::sym;
10 use rustc_target::spec::abi::Abi;
11 use rustc_target::spec::{FramePointer, SanitizerSet, StackProbeType, StackProtector};
12 use smallvec::SmallVec;
13
14 use crate::attributes;
15 use crate::llvm::AttributePlace::Function;
16 use crate::llvm::{self, AllocKindFlags, Attribute, AttributeKind, AttributePlace};
17 use crate::llvm_util;
18 pub use rustc_attr::{InlineAttr, InstructionSetAttr, OptimizeAttr};
19
20 use crate::context::CodegenCx;
21 use crate::value::Value;
22
23 pub fn apply_to_llfn(llfn: &Value, idx: AttributePlace, attrs: &[&Attribute]) {
24     if !attrs.is_empty() {
25         llvm::AddFunctionAttributes(llfn, idx, attrs);
26     }
27 }
28
29 pub fn apply_to_callsite(callsite: &Value, idx: AttributePlace, attrs: &[&Attribute]) {
30     if !attrs.is_empty() {
31         llvm::AddCallSiteAttributes(callsite, idx, attrs);
32     }
33 }
34
35 /// Get LLVM attribute for the provided inline heuristic.
36 #[inline]
37 fn inline_attr<'ll>(cx: &CodegenCx<'ll, '_>, inline: InlineAttr) -> Option<&'ll Attribute> {
38     match inline {
39         InlineAttr::Hint => Some(AttributeKind::InlineHint.create_attr(cx.llcx)),
40         InlineAttr::Always => Some(AttributeKind::AlwaysInline.create_attr(cx.llcx)),
41         InlineAttr::Never => {
42             if cx.sess().target.arch != "amdgpu" {
43                 Some(AttributeKind::NoInline.create_attr(cx.llcx))
44             } else {
45                 None
46             }
47         }
48         InlineAttr::None => None,
49     }
50 }
51
52 /// Get LLVM sanitize attributes.
53 #[inline]
54 pub fn sanitize_attrs<'ll>(
55     cx: &CodegenCx<'ll, '_>,
56     no_sanitize: SanitizerSet,
57 ) -> SmallVec<[&'ll Attribute; 4]> {
58     let mut attrs = SmallVec::new();
59     let enabled = cx.tcx.sess.opts.unstable_opts.sanitizer - no_sanitize;
60     if enabled.contains(SanitizerSet::ADDRESS) {
61         attrs.push(llvm::AttributeKind::SanitizeAddress.create_attr(cx.llcx));
62     }
63     if enabled.contains(SanitizerSet::MEMORY) {
64         attrs.push(llvm::AttributeKind::SanitizeMemory.create_attr(cx.llcx));
65     }
66     if enabled.contains(SanitizerSet::THREAD) {
67         attrs.push(llvm::AttributeKind::SanitizeThread.create_attr(cx.llcx));
68     }
69     if enabled.contains(SanitizerSet::HWADDRESS) {
70         attrs.push(llvm::AttributeKind::SanitizeHWAddress.create_attr(cx.llcx));
71     }
72     if enabled.contains(SanitizerSet::SHADOWCALLSTACK) {
73         attrs.push(llvm::AttributeKind::ShadowCallStack.create_attr(cx.llcx));
74     }
75     if enabled.contains(SanitizerSet::MEMTAG) {
76         // Check to make sure the mte target feature is actually enabled.
77         let features = cx.tcx.global_backend_features(());
78         let mte_feature =
79             features.iter().map(|s| &s[..]).rfind(|n| ["+mte", "-mte"].contains(&&n[..]));
80         if let None | Some("-mte") = mte_feature {
81             cx.tcx.sess.err("`-Zsanitizer=memtag` requires `-Ctarget-feature=+mte`");
82         }
83
84         attrs.push(llvm::AttributeKind::SanitizeMemTag.create_attr(cx.llcx));
85     }
86     attrs
87 }
88
89 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
90 #[inline]
91 pub fn uwtable_attr(llcx: &llvm::Context) -> &Attribute {
92     // NOTE: We should determine if we even need async unwind tables, as they
93     // take have more overhead and if we can use sync unwind tables we
94     // probably should.
95     llvm::CreateUWTableAttr(llcx, true)
96 }
97
98 pub fn frame_pointer_type_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
99     let mut fp = cx.sess().target.frame_pointer;
100     // "mcount" function relies on stack pointer.
101     // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
102     if cx.sess().instrument_mcount() || matches!(cx.sess().opts.cg.force_frame_pointers, Some(true))
103     {
104         fp = FramePointer::Always;
105     }
106     let attr_value = match fp {
107         FramePointer::Always => "all",
108         FramePointer::NonLeaf => "non-leaf",
109         FramePointer::MayOmit => return None,
110     };
111     Some(llvm::CreateAttrStringValue(cx.llcx, "frame-pointer", attr_value))
112 }
113
114 /// Tell LLVM what instrument function to insert.
115 #[inline]
116 fn instrument_function_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
117     if cx.sess().instrument_mcount() {
118         // Similar to `clang -pg` behavior. Handled by the
119         // `post-inline-ee-instrument` LLVM pass.
120
121         // The function name varies on platforms.
122         // See test/CodeGen/mcount.c in clang.
123         let mcount_name = cx.sess().target.mcount.as_ref();
124
125         Some(llvm::CreateAttrStringValue(
126             cx.llcx,
127             "instrument-function-entry-inlined",
128             &mcount_name,
129         ))
130     } else {
131         None
132     }
133 }
134
135 fn probestack_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
136     // Currently stack probes seem somewhat incompatible with the address
137     // sanitizer and thread sanitizer. With asan we're already protected from
138     // stack overflow anyway so we don't really need stack probes regardless.
139     if cx
140         .sess()
141         .opts
142         .unstable_opts
143         .sanitizer
144         .intersects(SanitizerSet::ADDRESS | SanitizerSet::THREAD)
145     {
146         return None;
147     }
148
149     // probestack doesn't play nice either with `-C profile-generate`.
150     if cx.sess().opts.cg.profile_generate.enabled() {
151         return None;
152     }
153
154     // probestack doesn't play nice either with gcov profiling.
155     if cx.sess().opts.unstable_opts.profile {
156         return None;
157     }
158
159     let attr_value = match cx.sess().target.stack_probes {
160         StackProbeType::None => return None,
161         // Request LLVM to generate the probes inline. If the given LLVM version does not support
162         // this, no probe is generated at all (even if the attribute is specified).
163         StackProbeType::Inline => "inline-asm",
164         // Flag our internal `__rust_probestack` function as the stack probe symbol.
165         // This is defined in the `compiler-builtins` crate for each architecture.
166         StackProbeType::Call => "__rust_probestack",
167         // Pick from the two above based on the LLVM version.
168         StackProbeType::InlineOrCall { min_llvm_version_for_inline } => {
169             if llvm_util::get_version() < min_llvm_version_for_inline {
170                 "__rust_probestack"
171             } else {
172                 "inline-asm"
173             }
174         }
175     };
176     Some(llvm::CreateAttrStringValue(cx.llcx, "probe-stack", attr_value))
177 }
178
179 fn stackprotector_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
180     let sspattr = match cx.sess().stack_protector() {
181         StackProtector::None => return None,
182         StackProtector::All => AttributeKind::StackProtectReq,
183         StackProtector::Strong => AttributeKind::StackProtectStrong,
184         StackProtector::Basic => AttributeKind::StackProtect,
185     };
186
187     Some(sspattr.create_attr(cx.llcx))
188 }
189
190 pub fn target_cpu_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll Attribute {
191     let target_cpu = llvm_util::target_cpu(cx.tcx.sess);
192     llvm::CreateAttrStringValue(cx.llcx, "target-cpu", target_cpu)
193 }
194
195 pub fn tune_cpu_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
196     llvm_util::tune_cpu(cx.tcx.sess)
197         .map(|tune_cpu| llvm::CreateAttrStringValue(cx.llcx, "tune-cpu", tune_cpu))
198 }
199
200 /// Get the `NonLazyBind` LLVM attribute,
201 /// if the codegen options allow skipping the PLT.
202 pub fn non_lazy_bind_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
203     // Don't generate calls through PLT if it's not necessary
204     if !cx.sess().needs_plt() {
205         Some(AttributeKind::NonLazyBind.create_attr(cx.llcx))
206     } else {
207         None
208     }
209 }
210
211 /// Get the default optimizations attrs for a function.
212 #[inline]
213 pub(crate) fn default_optimisation_attrs<'ll>(
214     cx: &CodegenCx<'ll, '_>,
215 ) -> SmallVec<[&'ll Attribute; 2]> {
216     let mut attrs = SmallVec::new();
217     match cx.sess().opts.optimize {
218         OptLevel::Size => {
219             attrs.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
220         }
221         OptLevel::SizeMin => {
222             attrs.push(llvm::AttributeKind::MinSize.create_attr(cx.llcx));
223             attrs.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
224         }
225         _ => {}
226     }
227     attrs
228 }
229
230 fn create_alloc_family_attr(llcx: &llvm::Context) -> &llvm::Attribute {
231     llvm::CreateAttrStringValue(llcx, "alloc-family", "__rust_alloc")
232 }
233
234 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
235 /// attributes.
236 pub fn from_fn_attrs<'ll, 'tcx>(
237     cx: &CodegenCx<'ll, 'tcx>,
238     llfn: &'ll Value,
239     instance: ty::Instance<'tcx>,
240 ) {
241     let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(instance.def_id());
242
243     let mut to_add = SmallVec::<[_; 16]>::new();
244
245     match codegen_fn_attrs.optimize {
246         OptimizeAttr::None => {
247             to_add.extend(default_optimisation_attrs(cx));
248         }
249         OptimizeAttr::Size => {
250             to_add.push(llvm::AttributeKind::MinSize.create_attr(cx.llcx));
251             to_add.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
252         }
253         OptimizeAttr::Speed => {}
254     }
255
256     let inline = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
257         InlineAttr::Never
258     } else if codegen_fn_attrs.inline == InlineAttr::None && instance.def.requires_inline(cx.tcx) {
259         InlineAttr::Hint
260     } else {
261         codegen_fn_attrs.inline
262     };
263     to_add.extend(inline_attr(cx, inline));
264
265     // The `uwtable` attribute according to LLVM is:
266     //
267     //     This attribute indicates that the ABI being targeted requires that an
268     //     unwind table entry be produced for this function even if we can show
269     //     that no exceptions passes by it. This is normally the case for the
270     //     ELF x86-64 abi, but it can be disabled for some compilation units.
271     //
272     // Typically when we're compiling with `-C panic=abort` (which implies this
273     // `no_landing_pads` check) we don't need `uwtable` because we can't
274     // generate any exceptions! On Windows, however, exceptions include other
275     // events such as illegal instructions, segfaults, etc. This means that on
276     // Windows we end up still needing the `uwtable` attribute even if the `-C
277     // panic=abort` flag is passed.
278     //
279     // You can also find more info on why Windows always requires uwtables here:
280     //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
281     if cx.sess().must_emit_unwind_tables() {
282         to_add.push(uwtable_attr(cx.llcx));
283     }
284
285     if cx.sess().opts.unstable_opts.profile_sample_use.is_some() {
286         to_add.push(llvm::CreateAttrString(cx.llcx, "use-sample-profile"));
287     }
288
289     // FIXME: none of these three functions interact with source level attributes.
290     to_add.extend(frame_pointer_type_attr(cx));
291     to_add.extend(instrument_function_attr(cx));
292     to_add.extend(probestack_attr(cx));
293     to_add.extend(stackprotector_attr(cx));
294
295     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
296         to_add.push(AttributeKind::Cold.create_attr(cx.llcx));
297     }
298     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_RETURNS_TWICE) {
299         to_add.push(AttributeKind::ReturnsTwice.create_attr(cx.llcx));
300     }
301     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_PURE) {
302         to_add.push(AttributeKind::ReadOnly.create_attr(cx.llcx));
303     }
304     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_CONST) {
305         to_add.push(AttributeKind::ReadNone.create_attr(cx.llcx));
306     }
307     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
308         to_add.push(AttributeKind::Naked.create_attr(cx.llcx));
309         // HACK(jubilee): "indirect branch tracking" works by attaching prologues to functions.
310         // And it is a module-level attribute, so the alternative is pulling naked functions into new LLVM modules.
311         // Otherwise LLVM's "naked" functions come with endbr prefixes per https://github.com/rust-lang/rust/issues/98768
312         to_add.push(AttributeKind::NoCfCheck.create_attr(cx.llcx));
313         // Need this for AArch64.
314         to_add.push(llvm::CreateAttrStringValue(cx.llcx, "branch-target-enforcement", "false"));
315     }
316     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR)
317         || codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR_ZEROED)
318     {
319         if llvm_util::get_version() >= (15, 0, 0) {
320             to_add.push(create_alloc_family_attr(cx.llcx));
321             // apply to argument place instead of function
322             let alloc_align = AttributeKind::AllocAlign.create_attr(cx.llcx);
323             attributes::apply_to_llfn(llfn, AttributePlace::Argument(1), &[alloc_align]);
324             to_add.push(llvm::CreateAllocSizeAttr(cx.llcx, 0));
325             let mut flags = AllocKindFlags::Alloc | AllocKindFlags::Aligned;
326             if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
327                 flags |= AllocKindFlags::Uninitialized;
328             } else {
329                 flags |= AllocKindFlags::Zeroed;
330             }
331             to_add.push(llvm::CreateAllocKindAttr(cx.llcx, flags));
332         }
333         // apply to return place instead of function (unlike all other attributes applied in this function)
334         let no_alias = AttributeKind::NoAlias.create_attr(cx.llcx);
335         attributes::apply_to_llfn(llfn, AttributePlace::ReturnValue, &[no_alias]);
336     }
337     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::REALLOCATOR) {
338         if llvm_util::get_version() >= (15, 0, 0) {
339             to_add.push(create_alloc_family_attr(cx.llcx));
340             to_add.push(llvm::CreateAllocKindAttr(
341                 cx.llcx,
342                 AllocKindFlags::Realloc | AllocKindFlags::Aligned,
343             ));
344             // applies to argument place instead of function place
345             let allocated_pointer = AttributeKind::AllocatedPointer.create_attr(cx.llcx);
346             attributes::apply_to_llfn(llfn, AttributePlace::Argument(0), &[allocated_pointer]);
347             // apply to argument place instead of function
348             let alloc_align = AttributeKind::AllocAlign.create_attr(cx.llcx);
349             attributes::apply_to_llfn(llfn, AttributePlace::Argument(2), &[alloc_align]);
350             to_add.push(llvm::CreateAllocSizeAttr(cx.llcx, 3));
351         }
352         let no_alias = AttributeKind::NoAlias.create_attr(cx.llcx);
353         attributes::apply_to_llfn(llfn, AttributePlace::ReturnValue, &[no_alias]);
354     }
355     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::DEALLOCATOR) {
356         if llvm_util::get_version() >= (15, 0, 0) {
357             to_add.push(create_alloc_family_attr(cx.llcx));
358             to_add.push(llvm::CreateAllocKindAttr(cx.llcx, AllocKindFlags::Free));
359             // applies to argument place instead of function place
360             let allocated_pointer = AttributeKind::AllocatedPointer.create_attr(cx.llcx);
361             attributes::apply_to_llfn(llfn, AttributePlace::Argument(0), &[allocated_pointer]);
362         }
363     }
364     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY) {
365         to_add.push(llvm::CreateAttrString(cx.llcx, "cmse_nonsecure_entry"));
366     }
367     if let Some(align) = codegen_fn_attrs.alignment {
368         llvm::set_alignment(llfn, align as usize);
369     }
370     to_add.extend(sanitize_attrs(cx, codegen_fn_attrs.no_sanitize));
371
372     // Always annotate functions with the target-cpu they are compiled for.
373     // Without this, ThinLTO won't inline Rust functions into Clang generated
374     // functions (because Clang annotates functions this way too).
375     to_add.push(target_cpu_attr(cx));
376     // tune-cpu is only conveyed through the attribute for our purpose.
377     // The target doesn't care; the subtarget reads our attribute.
378     to_add.extend(tune_cpu_attr(cx));
379
380     let function_features =
381         codegen_fn_attrs.target_features.iter().map(|f| f.as_str()).collect::<Vec<&str>>();
382
383     if let Some(f) = llvm_util::check_tied_features(
384         cx.tcx.sess,
385         &function_features.iter().map(|f| (*f, true)).collect(),
386     ) {
387         let span = cx
388             .tcx
389             .get_attrs(instance.def_id(), sym::target_feature)
390             .next()
391             .map_or_else(|| cx.tcx.def_span(instance.def_id()), |a| a.span);
392         let msg = format!(
393             "the target features {} must all be either enabled or disabled together",
394             f.join(", ")
395         );
396         let mut err = cx.tcx.sess.struct_span_err(span, &msg);
397         err.help("add the missing features in a `target_feature` attribute");
398         err.emit();
399         return;
400     }
401
402     let mut function_features = function_features
403         .iter()
404         .flat_map(|feat| {
405             llvm_util::to_llvm_features(cx.tcx.sess, feat).into_iter().map(|f| format!("+{}", f))
406         })
407         .chain(codegen_fn_attrs.instruction_set.iter().map(|x| match x {
408             InstructionSetAttr::ArmA32 => "-thumb-mode".to_string(),
409             InstructionSetAttr::ArmT32 => "+thumb-mode".to_string(),
410         }))
411         .collect::<Vec<String>>();
412
413     if cx.tcx.sess.target.is_like_wasm {
414         // If this function is an import from the environment but the wasm
415         // import has a specific module/name, apply them here.
416         if let Some(module) = wasm_import_module(cx.tcx, instance.def_id()) {
417             to_add.push(llvm::CreateAttrStringValue(cx.llcx, "wasm-import-module", &module));
418
419             let name =
420                 codegen_fn_attrs.link_name.unwrap_or_else(|| cx.tcx.item_name(instance.def_id()));
421             let name = name.as_str();
422             to_add.push(llvm::CreateAttrStringValue(cx.llcx, "wasm-import-name", name));
423         }
424
425         // The `"wasm"` abi on wasm targets automatically enables the
426         // `+multivalue` feature because the purpose of the wasm abi is to match
427         // the WebAssembly specification, which has this feature. This won't be
428         // needed when LLVM enables this `multivalue` feature by default.
429         if !cx.tcx.is_closure(instance.def_id()) {
430             let abi = cx.tcx.fn_sig(instance.def_id()).abi();
431             if abi == Abi::Wasm {
432                 function_features.push("+multivalue".to_string());
433             }
434         }
435     }
436
437     let global_features = cx.tcx.global_backend_features(()).iter().map(|s| s.as_str());
438     let function_features = function_features.iter().map(|s| s.as_str());
439     let target_features =
440         global_features.chain(function_features).intersperse(",").collect::<SmallStr<1024>>();
441     if !target_features.is_empty() {
442         to_add.push(llvm::CreateAttrStringValue(cx.llcx, "target-features", &target_features));
443     }
444
445     attributes::apply_to_llfn(llfn, Function, &to_add);
446 }
447
448 fn wasm_import_module(tcx: TyCtxt<'_>, id: DefId) -> Option<&String> {
449     tcx.wasm_import_module_map(id.krate).get(&id)
450 }