1 //! Set and unset common attributes on LLVM values.
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;
14 use crate::attributes;
15 use crate::llvm::AttributePlace::Function;
16 use crate::llvm::{self, Attribute, AttributeKind, AttributePlace};
18 pub use rustc_attr::{InlineAttr, InstructionSetAttr, OptimizeAttr};
20 use crate::context::CodegenCx;
21 use crate::value::Value;
23 pub fn apply_to_llfn(llfn: &Value, idx: AttributePlace, attrs: &[&Attribute]) {
24 if !attrs.is_empty() {
25 llvm::AddFunctionAttributes(llfn, idx, attrs);
29 pub fn apply_to_callsite(callsite: &Value, idx: AttributePlace, attrs: &[&Attribute]) {
30 if !attrs.is_empty() {
31 llvm::AddCallSiteAttributes(callsite, idx, attrs);
35 /// Get LLVM attribute for the provided inline heuristic.
37 fn inline_attr<'ll>(cx: &CodegenCx<'ll, '_>, inline: InlineAttr) -> Option<&'ll Attribute> {
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))
48 InlineAttr::None => None,
52 /// Get LLVM sanitize attributes.
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));
63 if enabled.contains(SanitizerSet::MEMORY) {
64 attrs.push(llvm::AttributeKind::SanitizeMemory.create_attr(cx.llcx));
66 if enabled.contains(SanitizerSet::THREAD) {
67 attrs.push(llvm::AttributeKind::SanitizeThread.create_attr(cx.llcx));
69 if enabled.contains(SanitizerSet::HWADDRESS) {
70 attrs.push(llvm::AttributeKind::SanitizeHWAddress.create_attr(cx.llcx));
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(());
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`");
81 attrs.push(llvm::AttributeKind::SanitizeMemTag.create_attr(cx.llcx));
86 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
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
92 llvm::CreateUWTableAttr(llcx, true)
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))
101 fp = FramePointer::Always;
103 let attr_value = match fp {
104 FramePointer::Always => "all",
105 FramePointer::NonLeaf => "non-leaf",
106 FramePointer::MayOmit => return None,
108 Some(llvm::CreateAttrStringValue(cx.llcx, "frame-pointer", attr_value))
111 /// Tell LLVM what instrument function to insert.
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.
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();
122 Some(llvm::CreateAttrStringValue(
124 "instrument-function-entry-inlined",
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.
141 .intersects(SanitizerSet::ADDRESS | SanitizerSet::THREAD)
146 // probestack doesn't play nice either with `-C profile-generate`.
147 if cx.sess().opts.cg.profile_generate.enabled() {
151 // probestack doesn't play nice either with gcov profiling.
152 if cx.sess().opts.debugging_opts.profile {
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 {
173 Some(llvm::CreateAttrStringValue(cx.llcx, "probe-stack", attr_value))
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,
184 Some(sspattr.create_attr(cx.llcx))
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)
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))
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))
208 /// Get the default optimizations attrs for a function.
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 {
216 attrs.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
218 OptLevel::SizeMin => {
219 attrs.push(llvm::AttributeKind::MinSize.create_attr(cx.llcx));
220 attrs.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
227 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
229 pub fn from_fn_attrs<'ll, 'tcx>(
230 cx: &CodegenCx<'ll, 'tcx>,
232 instance: ty::Instance<'tcx>,
234 let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(instance.def_id());
236 let mut to_add = SmallVec::<[_; 16]>::new();
238 match codegen_fn_attrs.optimize {
239 OptimizeAttr::None => {
240 to_add.extend(default_optimisation_attrs(cx));
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));
246 OptimizeAttr::Speed => {}
249 let inline = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
251 } else if codegen_fn_attrs.inline == InlineAttr::None && instance.def.requires_inline(cx.tcx) {
254 codegen_fn_attrs.inline
256 to_add.extend(inline_attr(cx, inline));
258 // The `uwtable` attribute according to LLVM is:
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.
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.
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));
278 if cx.sess().opts.debugging_opts.profile_sample_use.is_some() {
279 to_add.push(llvm::CreateAttrString(cx.llcx, "use-sample-profile"));
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));
288 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
289 to_add.push(AttributeKind::Cold.create_attr(cx.llcx));
291 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_RETURNS_TWICE) {
292 to_add.push(AttributeKind::ReturnsTwice.create_attr(cx.llcx));
294 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_PURE) {
295 to_add.push(AttributeKind::ReadOnly.create_attr(cx.llcx));
297 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_CONST) {
298 to_add.push(AttributeKind::ReadNone.create_attr(cx.llcx));
300 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
301 to_add.push(AttributeKind::Naked.create_attr(cx.llcx));
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]);
308 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY) {
309 to_add.push(llvm::CreateAttrString(cx.llcx, "cmse_nonsecure_entry"));
311 if let Some(align) = codegen_fn_attrs.alignment {
312 llvm::set_alignment(llfn, align as usize);
314 to_add.extend(sanitize_attrs(cx, codegen_fn_attrs.no_sanitize));
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));
324 let function_features =
325 codegen_fn_attrs.target_features.iter().map(|f| f.as_str()).collect::<Vec<&str>>();
327 if let Some(f) = llvm_util::check_tied_features(
329 &function_features.iter().map(|f| (*f, true)).collect(),
333 .get_attr(instance.def_id(), sym::target_feature)
334 .map_or_else(|| cx.tcx.def_span(instance.def_id()), |a| a.span);
336 "the target features {} must all be either enabled or disabled together",
339 let mut err = cx.tcx.sess.struct_span_err(span, &msg);
340 err.help("add the missing features in a `target_feature` attribute");
345 let mut function_features = function_features
348 llvm_util::to_llvm_features(cx.tcx.sess, feat).into_iter().map(|f| format!("+{}", f))
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(),
354 .collect::<Vec<String>>();
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));
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));
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());
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));
388 attributes::apply_to_llfn(llfn, Function, &to_add);
391 fn wasm_import_module(tcx: TyCtxt<'_>, id: DefId) -> Option<&String> {
392 tcx.wasm_import_module_map(id.krate).get(&id)