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_target::spec::abi::Abi;
10 use rustc_target::spec::{FramePointer, SanitizerSet, StackProbeType, StackProtector};
11 use smallvec::SmallVec;
13 use crate::attributes;
14 use crate::llvm::AttributePlace::Function;
15 use crate::llvm::{self, Attribute, AttributeKind, AttributePlace};
17 pub use rustc_attr::{InlineAttr, InstructionSetAttr, OptimizeAttr};
19 use crate::context::CodegenCx;
20 use crate::value::Value;
22 pub fn apply_to_llfn(llfn: &Value, idx: AttributePlace, attrs: &[&Attribute]) {
23 if !attrs.is_empty() {
24 llvm::AddFunctionAttributes(llfn, idx, attrs);
28 pub fn apply_to_callsite(callsite: &Value, idx: AttributePlace, attrs: &[&Attribute]) {
29 if !attrs.is_empty() {
30 llvm::AddCallSiteAttributes(callsite, idx, attrs);
34 /// Get LLVM attribute for the provided inline heuristic.
36 fn inline_attr<'ll>(cx: &CodegenCx<'ll, '_>, inline: InlineAttr) -> Option<&'ll Attribute> {
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))
47 InlineAttr::None => None,
51 /// Get LLVM sanitize attributes.
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));
62 if enabled.contains(SanitizerSet::MEMORY) {
63 attrs.push(llvm::AttributeKind::SanitizeMemory.create_attr(cx.llcx));
65 if enabled.contains(SanitizerSet::THREAD) {
66 attrs.push(llvm::AttributeKind::SanitizeThread.create_attr(cx.llcx));
68 if enabled.contains(SanitizerSet::HWADDRESS) {
69 attrs.push(llvm::AttributeKind::SanitizeHWAddress.create_attr(cx.llcx));
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(());
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`");
80 attrs.push(llvm::AttributeKind::SanitizeMemTag.create_attr(cx.llcx));
85 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
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
91 llvm::CreateUWTableAttr(llcx, true)
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))
100 fp = FramePointer::Always;
102 let attr_value = match fp {
103 FramePointer::Always => "all",
104 FramePointer::NonLeaf => "non-leaf",
105 FramePointer::MayOmit => return None,
107 Some(llvm::CreateAttrStringValue(cx.llcx, "frame-pointer", attr_value))
110 /// Tell LLVM what instrument function to insert.
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.
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();
121 Some(llvm::CreateAttrStringValue(
123 "instrument-function-entry-inlined",
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.
140 .intersects(SanitizerSet::ADDRESS | SanitizerSet::THREAD)
145 // probestack doesn't play nice either with `-C profile-generate`.
146 if cx.sess().opts.cg.profile_generate.enabled() {
150 // probestack doesn't play nice either with gcov profiling.
151 if cx.sess().opts.debugging_opts.profile {
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 {
172 Some(llvm::CreateAttrStringValue(cx.llcx, "probe-stack", attr_value))
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,
183 Some(sspattr.create_attr(cx.llcx))
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)
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))
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))
207 /// Get the default optimizations attrs for a function.
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 {
215 attrs.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
217 OptLevel::SizeMin => {
218 attrs.push(llvm::AttributeKind::MinSize.create_attr(cx.llcx));
219 attrs.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
226 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
228 pub fn from_fn_attrs<'ll, 'tcx>(
229 cx: &CodegenCx<'ll, 'tcx>,
231 instance: ty::Instance<'tcx>,
233 let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(instance.def_id());
235 let mut to_add = SmallVec::<[_; 16]>::new();
237 match codegen_fn_attrs.optimize {
238 OptimizeAttr::None => {
239 to_add.extend(default_optimisation_attrs(cx));
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));
245 OptimizeAttr::Speed => {}
248 let inline = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
250 } else if codegen_fn_attrs.inline == InlineAttr::None && instance.def.requires_inline(cx.tcx) {
253 codegen_fn_attrs.inline
255 to_add.extend(inline_attr(cx, inline));
257 // The `uwtable` attribute according to LLVM is:
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.
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.
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));
277 if cx.sess().opts.debugging_opts.profile_sample_use.is_some() {
278 to_add.push(llvm::CreateAttrString(cx.llcx, "use-sample-profile"));
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));
287 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
288 to_add.push(AttributeKind::Cold.create_attr(cx.llcx));
290 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_RETURNS_TWICE) {
291 to_add.push(AttributeKind::ReturnsTwice.create_attr(cx.llcx));
293 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_PURE) {
294 to_add.push(AttributeKind::ReadOnly.create_attr(cx.llcx));
296 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_CONST) {
297 to_add.push(AttributeKind::ReadNone.create_attr(cx.llcx));
299 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
300 to_add.push(AttributeKind::Naked.create_attr(cx.llcx));
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]);
307 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY) {
308 to_add.push(llvm::CreateAttrString(cx.llcx, "cmse_nonsecure_entry"));
310 if let Some(align) = codegen_fn_attrs.alignment {
311 llvm::set_alignment(llfn, align as usize);
313 to_add.extend(sanitize_attrs(cx, codegen_fn_attrs.no_sanitize));
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));
323 let function_features =
324 codegen_fn_attrs.target_features.iter().map(|f| f.as_str()).collect::<Vec<&str>>();
326 if let Some(f) = llvm_util::check_tied_features(
328 &function_features.iter().map(|f| (*f, true)).collect(),
332 .get_attrs(instance.def_id())
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);
337 "the target features {} must all be either enabled or disabled together",
340 let mut err = cx.tcx.sess.struct_span_err(span, &msg);
341 err.help("add the missing features in a `target_feature` attribute");
346 let mut function_features = function_features
349 llvm_util::to_llvm_features(cx.tcx.sess, feat).into_iter().map(|f| format!("+{}", f))
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(),
355 .collect::<Vec<String>>();
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));
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));
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());
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));
389 attributes::apply_to_llfn(llfn, Function, &to_add);
392 fn wasm_import_module(tcx: TyCtxt<'_>, id: DefId) -> Option<&String> {
393 tcx.wasm_import_module_map(id.krate).get(&id)