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