]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/attributes.rs
Auto merge of #97313 - cjgillot:ast-lifetimes-anon, r=petrochenkov
[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, 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 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
231 /// attributes.
232 pub fn from_fn_attrs<'ll, 'tcx>(
233     cx: &CodegenCx<'ll, 'tcx>,
234     llfn: &'ll Value,
235     instance: ty::Instance<'tcx>,
236 ) {
237     let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(instance.def_id());
238
239     let mut to_add = SmallVec::<[_; 16]>::new();
240
241     match codegen_fn_attrs.optimize {
242         OptimizeAttr::None => {
243             to_add.extend(default_optimisation_attrs(cx));
244         }
245         OptimizeAttr::Size => {
246             to_add.push(llvm::AttributeKind::MinSize.create_attr(cx.llcx));
247             to_add.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
248         }
249         OptimizeAttr::Speed => {}
250     }
251
252     let inline = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
253         InlineAttr::Never
254     } else if codegen_fn_attrs.inline == InlineAttr::None && instance.def.requires_inline(cx.tcx) {
255         InlineAttr::Hint
256     } else {
257         codegen_fn_attrs.inline
258     };
259     to_add.extend(inline_attr(cx, inline));
260
261     // The `uwtable` attribute according to LLVM is:
262     //
263     //     This attribute indicates that the ABI being targeted requires that an
264     //     unwind table entry be produced for this function even if we can show
265     //     that no exceptions passes by it. This is normally the case for the
266     //     ELF x86-64 abi, but it can be disabled for some compilation units.
267     //
268     // Typically when we're compiling with `-C panic=abort` (which implies this
269     // `no_landing_pads` check) we don't need `uwtable` because we can't
270     // generate any exceptions! On Windows, however, exceptions include other
271     // events such as illegal instructions, segfaults, etc. This means that on
272     // Windows we end up still needing the `uwtable` attribute even if the `-C
273     // panic=abort` flag is passed.
274     //
275     // You can also find more info on why Windows always requires uwtables here:
276     //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
277     if cx.sess().must_emit_unwind_tables() {
278         to_add.push(uwtable_attr(cx.llcx));
279     }
280
281     if cx.sess().opts.unstable_opts.profile_sample_use.is_some() {
282         to_add.push(llvm::CreateAttrString(cx.llcx, "use-sample-profile"));
283     }
284
285     // FIXME: none of these three functions interact with source level attributes.
286     to_add.extend(frame_pointer_type_attr(cx));
287     to_add.extend(instrument_function_attr(cx));
288     to_add.extend(probestack_attr(cx));
289     to_add.extend(stackprotector_attr(cx));
290
291     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
292         to_add.push(AttributeKind::Cold.create_attr(cx.llcx));
293     }
294     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_RETURNS_TWICE) {
295         to_add.push(AttributeKind::ReturnsTwice.create_attr(cx.llcx));
296     }
297     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_PURE) {
298         to_add.push(AttributeKind::ReadOnly.create_attr(cx.llcx));
299     }
300     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_CONST) {
301         to_add.push(AttributeKind::ReadNone.create_attr(cx.llcx));
302     }
303     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
304         to_add.push(AttributeKind::Naked.create_attr(cx.llcx));
305         // HACK(jubilee): "indirect branch tracking" works by attaching prologues to functions.
306         // And it is a module-level attribute, so the alternative is pulling naked functions into new LLVM modules.
307         // Otherwise LLVM's "naked" functions come with endbr prefixes per https://github.com/rust-lang/rust/issues/98768
308         to_add.push(AttributeKind::NoCfCheck.create_attr(cx.llcx));
309         // Need this for AArch64.
310         to_add.push(llvm::CreateAttrStringValue(cx.llcx, "branch-target-enforcement", "false"));
311     }
312     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
313         // apply to return place instead of function (unlike all other attributes applied in this function)
314         let no_alias = AttributeKind::NoAlias.create_attr(cx.llcx);
315         attributes::apply_to_llfn(llfn, AttributePlace::ReturnValue, &[no_alias]);
316     }
317     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY) {
318         to_add.push(llvm::CreateAttrString(cx.llcx, "cmse_nonsecure_entry"));
319     }
320     if let Some(align) = codegen_fn_attrs.alignment {
321         llvm::set_alignment(llfn, align as usize);
322     }
323     to_add.extend(sanitize_attrs(cx, codegen_fn_attrs.no_sanitize));
324
325     // Always annotate functions with the target-cpu they are compiled for.
326     // Without this, ThinLTO won't inline Rust functions into Clang generated
327     // functions (because Clang annotates functions this way too).
328     to_add.push(target_cpu_attr(cx));
329     // tune-cpu is only conveyed through the attribute for our purpose.
330     // The target doesn't care; the subtarget reads our attribute.
331     to_add.extend(tune_cpu_attr(cx));
332
333     let function_features =
334         codegen_fn_attrs.target_features.iter().map(|f| f.as_str()).collect::<Vec<&str>>();
335
336     if let Some(f) = llvm_util::check_tied_features(
337         cx.tcx.sess,
338         &function_features.iter().map(|f| (*f, true)).collect(),
339     ) {
340         let span = cx
341             .tcx
342             .get_attr(instance.def_id(), sym::target_feature)
343             .map_or_else(|| cx.tcx.def_span(instance.def_id()), |a| a.span);
344         let msg = format!(
345             "the target features {} must all be either enabled or disabled together",
346             f.join(", ")
347         );
348         let mut err = cx.tcx.sess.struct_span_err(span, &msg);
349         err.help("add the missing features in a `target_feature` attribute");
350         err.emit();
351         return;
352     }
353
354     let mut function_features = function_features
355         .iter()
356         .flat_map(|feat| {
357             llvm_util::to_llvm_features(cx.tcx.sess, feat).into_iter().map(|f| format!("+{}", f))
358         })
359         .chain(codegen_fn_attrs.instruction_set.iter().map(|x| match x {
360             InstructionSetAttr::ArmA32 => "-thumb-mode".to_string(),
361             InstructionSetAttr::ArmT32 => "+thumb-mode".to_string(),
362         }))
363         .collect::<Vec<String>>();
364
365     if cx.tcx.sess.target.is_like_wasm {
366         // If this function is an import from the environment but the wasm
367         // import has a specific module/name, apply them here.
368         if let Some(module) = wasm_import_module(cx.tcx, instance.def_id()) {
369             to_add.push(llvm::CreateAttrStringValue(cx.llcx, "wasm-import-module", &module));
370
371             let name =
372                 codegen_fn_attrs.link_name.unwrap_or_else(|| cx.tcx.item_name(instance.def_id()));
373             let name = name.as_str();
374             to_add.push(llvm::CreateAttrStringValue(cx.llcx, "wasm-import-name", name));
375         }
376
377         // The `"wasm"` abi on wasm targets automatically enables the
378         // `+multivalue` feature because the purpose of the wasm abi is to match
379         // the WebAssembly specification, which has this feature. This won't be
380         // needed when LLVM enables this `multivalue` feature by default.
381         if !cx.tcx.is_closure(instance.def_id()) {
382             let abi = cx.tcx.fn_sig(instance.def_id()).abi();
383             if abi == Abi::Wasm {
384                 function_features.push("+multivalue".to_string());
385             }
386         }
387     }
388
389     let global_features = cx.tcx.global_backend_features(()).iter().map(|s| s.as_str());
390     let function_features = function_features.iter().map(|s| s.as_str());
391     let target_features =
392         global_features.chain(function_features).intersperse(",").collect::<SmallStr<1024>>();
393     if !target_features.is_empty() {
394         to_add.push(llvm::CreateAttrStringValue(cx.llcx, "target-features", &target_features));
395     }
396
397     attributes::apply_to_llfn(llfn, Function, &to_add);
398 }
399
400 fn wasm_import_module(tcx: TyCtxt<'_>, id: DefId) -> Option<&String> {
401     tcx.wasm_import_module_map(id.krate).get(&id)
402 }