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