]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/attributes.rs
Auto merge of #98816 - estebank:implicit-sized, r=oli-obk
[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.debugging_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::MEMTAG) {
73         // Check to make sure the mte target feature is actually enabled.
74         let features = cx.tcx.global_backend_features(());
75         let mte_feature =
76             features.iter().map(|s| &s[..]).rfind(|n| ["+mte", "-mte"].contains(&&n[..]));
77         if let None | Some("-mte") = mte_feature {
78             cx.tcx.sess.err("`-Zsanitizer=memtag` requires `-Ctarget-feature=+mte`");
79         }
80
81         attrs.push(llvm::AttributeKind::SanitizeMemTag.create_attr(cx.llcx));
82     }
83     attrs
84 }
85
86 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
87 #[inline]
88 pub fn uwtable_attr(llcx: &llvm::Context) -> &Attribute {
89     // NOTE: We should determine if we even need async unwind tables, as they
90     // take have more overhead and if we can use sync unwind tables we
91     // probably should.
92     llvm::CreateUWTableAttr(llcx, true)
93 }
94
95 pub fn frame_pointer_type_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
96     let mut fp = cx.sess().target.frame_pointer;
97     // "mcount" function relies on stack pointer.
98     // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
99     if cx.sess().instrument_mcount() || matches!(cx.sess().opts.cg.force_frame_pointers, Some(true))
100     {
101         fp = FramePointer::Always;
102     }
103     let attr_value = match fp {
104         FramePointer::Always => "all",
105         FramePointer::NonLeaf => "non-leaf",
106         FramePointer::MayOmit => return None,
107     };
108     Some(llvm::CreateAttrStringValue(cx.llcx, "frame-pointer", attr_value))
109 }
110
111 /// Tell LLVM what instrument function to insert.
112 #[inline]
113 fn instrument_function_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
114     if cx.sess().instrument_mcount() {
115         // Similar to `clang -pg` behavior. Handled by the
116         // `post-inline-ee-instrument` LLVM pass.
117
118         // The function name varies on platforms.
119         // See test/CodeGen/mcount.c in clang.
120         let mcount_name = cx.sess().target.mcount.as_ref();
121
122         Some(llvm::CreateAttrStringValue(
123             cx.llcx,
124             "instrument-function-entry-inlined",
125             &mcount_name,
126         ))
127     } else {
128         None
129     }
130 }
131
132 fn probestack_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
133     // Currently stack probes seem somewhat incompatible with the address
134     // sanitizer and thread sanitizer. With asan we're already protected from
135     // stack overflow anyway so we don't really need stack probes regardless.
136     if cx
137         .sess()
138         .opts
139         .debugging_opts
140         .sanitizer
141         .intersects(SanitizerSet::ADDRESS | SanitizerSet::THREAD)
142     {
143         return None;
144     }
145
146     // probestack doesn't play nice either with `-C profile-generate`.
147     if cx.sess().opts.cg.profile_generate.enabled() {
148         return None;
149     }
150
151     // probestack doesn't play nice either with gcov profiling.
152     if cx.sess().opts.debugging_opts.profile {
153         return None;
154     }
155
156     let attr_value = match cx.sess().target.stack_probes {
157         StackProbeType::None => return None,
158         // Request LLVM to generate the probes inline. If the given LLVM version does not support
159         // this, no probe is generated at all (even if the attribute is specified).
160         StackProbeType::Inline => "inline-asm",
161         // Flag our internal `__rust_probestack` function as the stack probe symbol.
162         // This is defined in the `compiler-builtins` crate for each architecture.
163         StackProbeType::Call => "__rust_probestack",
164         // Pick from the two above based on the LLVM version.
165         StackProbeType::InlineOrCall { min_llvm_version_for_inline } => {
166             if llvm_util::get_version() < min_llvm_version_for_inline {
167                 "__rust_probestack"
168             } else {
169                 "inline-asm"
170             }
171         }
172     };
173     Some(llvm::CreateAttrStringValue(cx.llcx, "probe-stack", attr_value))
174 }
175
176 fn stackprotector_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
177     let sspattr = match cx.sess().stack_protector() {
178         StackProtector::None => return None,
179         StackProtector::All => AttributeKind::StackProtectReq,
180         StackProtector::Strong => AttributeKind::StackProtectStrong,
181         StackProtector::Basic => AttributeKind::StackProtect,
182     };
183
184     Some(sspattr.create_attr(cx.llcx))
185 }
186
187 pub fn target_cpu_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll Attribute {
188     let target_cpu = llvm_util::target_cpu(cx.tcx.sess);
189     llvm::CreateAttrStringValue(cx.llcx, "target-cpu", target_cpu)
190 }
191
192 pub fn tune_cpu_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
193     llvm_util::tune_cpu(cx.tcx.sess)
194         .map(|tune_cpu| llvm::CreateAttrStringValue(cx.llcx, "tune-cpu", tune_cpu))
195 }
196
197 /// Get the `NonLazyBind` LLVM attribute,
198 /// if the codegen options allow skipping the PLT.
199 pub fn non_lazy_bind_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
200     // Don't generate calls through PLT if it's not necessary
201     if !cx.sess().needs_plt() {
202         Some(AttributeKind::NonLazyBind.create_attr(cx.llcx))
203     } else {
204         None
205     }
206 }
207
208 /// Get the default optimizations attrs for a function.
209 #[inline]
210 pub(crate) fn default_optimisation_attrs<'ll>(
211     cx: &CodegenCx<'ll, '_>,
212 ) -> SmallVec<[&'ll Attribute; 2]> {
213     let mut attrs = SmallVec::new();
214     match cx.sess().opts.optimize {
215         OptLevel::Size => {
216             attrs.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
217         }
218         OptLevel::SizeMin => {
219             attrs.push(llvm::AttributeKind::MinSize.create_attr(cx.llcx));
220             attrs.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
221         }
222         _ => {}
223     }
224     attrs
225 }
226
227 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
228 /// attributes.
229 pub fn from_fn_attrs<'ll, 'tcx>(
230     cx: &CodegenCx<'ll, 'tcx>,
231     llfn: &'ll Value,
232     instance: ty::Instance<'tcx>,
233 ) {
234     let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(instance.def_id());
235
236     let mut to_add = SmallVec::<[_; 16]>::new();
237
238     match codegen_fn_attrs.optimize {
239         OptimizeAttr::None => {
240             to_add.extend(default_optimisation_attrs(cx));
241         }
242         OptimizeAttr::Size => {
243             to_add.push(llvm::AttributeKind::MinSize.create_attr(cx.llcx));
244             to_add.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
245         }
246         OptimizeAttr::Speed => {}
247     }
248
249     let inline = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
250         InlineAttr::Never
251     } else if codegen_fn_attrs.inline == InlineAttr::None && instance.def.requires_inline(cx.tcx) {
252         InlineAttr::Hint
253     } else {
254         codegen_fn_attrs.inline
255     };
256     to_add.extend(inline_attr(cx, inline));
257
258     // The `uwtable` attribute according to LLVM is:
259     //
260     //     This attribute indicates that the ABI being targeted requires that an
261     //     unwind table entry be produced for this function even if we can show
262     //     that no exceptions passes by it. This is normally the case for the
263     //     ELF x86-64 abi, but it can be disabled for some compilation units.
264     //
265     // Typically when we're compiling with `-C panic=abort` (which implies this
266     // `no_landing_pads` check) we don't need `uwtable` because we can't
267     // generate any exceptions! On Windows, however, exceptions include other
268     // events such as illegal instructions, segfaults, etc. This means that on
269     // Windows we end up still needing the `uwtable` attribute even if the `-C
270     // panic=abort` flag is passed.
271     //
272     // You can also find more info on why Windows always requires uwtables here:
273     //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
274     if cx.sess().must_emit_unwind_tables() {
275         to_add.push(uwtable_attr(cx.llcx));
276     }
277
278     if cx.sess().opts.debugging_opts.profile_sample_use.is_some() {
279         to_add.push(llvm::CreateAttrString(cx.llcx, "use-sample-profile"));
280     }
281
282     // FIXME: none of these three functions interact with source level attributes.
283     to_add.extend(frame_pointer_type_attr(cx));
284     to_add.extend(instrument_function_attr(cx));
285     to_add.extend(probestack_attr(cx));
286     to_add.extend(stackprotector_attr(cx));
287
288     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
289         to_add.push(AttributeKind::Cold.create_attr(cx.llcx));
290     }
291     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_RETURNS_TWICE) {
292         to_add.push(AttributeKind::ReturnsTwice.create_attr(cx.llcx));
293     }
294     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_PURE) {
295         to_add.push(AttributeKind::ReadOnly.create_attr(cx.llcx));
296     }
297     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_CONST) {
298         to_add.push(AttributeKind::ReadNone.create_attr(cx.llcx));
299     }
300     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
301         to_add.push(AttributeKind::Naked.create_attr(cx.llcx));
302     }
303     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
304         // apply to return place instead of function (unlike all other attributes applied in this function)
305         let no_alias = AttributeKind::NoAlias.create_attr(cx.llcx);
306         attributes::apply_to_llfn(llfn, AttributePlace::ReturnValue, &[no_alias]);
307     }
308     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY) {
309         to_add.push(llvm::CreateAttrString(cx.llcx, "cmse_nonsecure_entry"));
310     }
311     if let Some(align) = codegen_fn_attrs.alignment {
312         llvm::set_alignment(llfn, align as usize);
313     }
314     to_add.extend(sanitize_attrs(cx, codegen_fn_attrs.no_sanitize));
315
316     // Always annotate functions with the target-cpu they are compiled for.
317     // Without this, ThinLTO won't inline Rust functions into Clang generated
318     // functions (because Clang annotates functions this way too).
319     to_add.push(target_cpu_attr(cx));
320     // tune-cpu is only conveyed through the attribute for our purpose.
321     // The target doesn't care; the subtarget reads our attribute.
322     to_add.extend(tune_cpu_attr(cx));
323
324     let function_features =
325         codegen_fn_attrs.target_features.iter().map(|f| f.as_str()).collect::<Vec<&str>>();
326
327     if let Some(f) = llvm_util::check_tied_features(
328         cx.tcx.sess,
329         &function_features.iter().map(|f| (*f, true)).collect(),
330     ) {
331         let span = cx
332             .tcx
333             .get_attr(instance.def_id(), sym::target_feature)
334             .map_or_else(|| cx.tcx.def_span(instance.def_id()), |a| a.span);
335         let msg = format!(
336             "the target features {} must all be either enabled or disabled together",
337             f.join(", ")
338         );
339         let mut err = cx.tcx.sess.struct_span_err(span, &msg);
340         err.help("add the missing features in a `target_feature` attribute");
341         err.emit();
342         return;
343     }
344
345     let mut function_features = function_features
346         .iter()
347         .flat_map(|feat| {
348             llvm_util::to_llvm_features(cx.tcx.sess, feat).into_iter().map(|f| format!("+{}", f))
349         })
350         .chain(codegen_fn_attrs.instruction_set.iter().map(|x| match x {
351             InstructionSetAttr::ArmA32 => "-thumb-mode".to_string(),
352             InstructionSetAttr::ArmT32 => "+thumb-mode".to_string(),
353         }))
354         .collect::<Vec<String>>();
355
356     if cx.tcx.sess.target.is_like_wasm {
357         // If this function is an import from the environment but the wasm
358         // import has a specific module/name, apply them here.
359         if let Some(module) = wasm_import_module(cx.tcx, instance.def_id()) {
360             to_add.push(llvm::CreateAttrStringValue(cx.llcx, "wasm-import-module", &module));
361
362             let name =
363                 codegen_fn_attrs.link_name.unwrap_or_else(|| cx.tcx.item_name(instance.def_id()));
364             let name = name.as_str();
365             to_add.push(llvm::CreateAttrStringValue(cx.llcx, "wasm-import-name", name));
366         }
367
368         // The `"wasm"` abi on wasm targets automatically enables the
369         // `+multivalue` feature because the purpose of the wasm abi is to match
370         // the WebAssembly specification, which has this feature. This won't be
371         // needed when LLVM enables this `multivalue` feature by default.
372         if !cx.tcx.is_closure(instance.def_id()) {
373             let abi = cx.tcx.fn_sig(instance.def_id()).abi();
374             if abi == Abi::Wasm {
375                 function_features.push("+multivalue".to_string());
376             }
377         }
378     }
379
380     let global_features = cx.tcx.global_backend_features(()).iter().map(|s| s.as_str());
381     let function_features = function_features.iter().map(|s| s.as_str());
382     let target_features =
383         global_features.chain(function_features).intersperse(",").collect::<SmallStr<1024>>();
384     if !target_features.is_empty() {
385         to_add.push(llvm::CreateAttrStringValue(cx.llcx, "target-features", &target_features));
386     }
387
388     attributes::apply_to_llfn(llfn, Function, &to_add);
389 }
390
391 fn wasm_import_module(tcx: TyCtxt<'_>, id: DefId) -> Option<&String> {
392     tcx.wasm_import_module_map(id.krate).get(&id)
393 }