1 //! Set and unset common attributes on LLVM values.
6 use rustc_codegen_ssa::traits::*;
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_data_structures::small_c_str::SmallCStr;
9 use rustc_hir::def_id::DefId;
10 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
11 use rustc_middle::ty::layout::HasTyCtxt;
12 use rustc_middle::ty::query::Providers;
13 use rustc_middle::ty::{self, TyCtxt};
14 use rustc_session::config::OptLevel;
15 use rustc_session::Session;
16 use rustc_target::spec::abi::Abi;
17 use rustc_target::spec::{SanitizerSet, StackProbeType};
19 use crate::attributes;
20 use crate::llvm::AttributePlace::Function;
21 use crate::llvm::{self, Attribute};
23 pub use rustc_attr::{InlineAttr, InstructionSetAttr, OptimizeAttr};
25 use crate::context::CodegenCx;
26 use crate::value::Value;
28 /// Mark LLVM function to use provided inline heuristic.
30 fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) {
31 use self::InlineAttr::*;
33 Hint => Attribute::InlineHint.apply_llfn(Function, val),
34 Always => Attribute::AlwaysInline.apply_llfn(Function, val),
36 if cx.tcx().sess.target.arch != "amdgpu" {
37 Attribute::NoInline.apply_llfn(Function, val);
44 /// Apply LLVM sanitize attributes.
46 pub fn sanitize(cx: &CodegenCx<'ll, '_>, no_sanitize: SanitizerSet, llfn: &'ll Value) {
47 let enabled = cx.tcx.sess.opts.debugging_opts.sanitizer - no_sanitize;
48 if enabled.contains(SanitizerSet::ADDRESS) {
49 llvm::Attribute::SanitizeAddress.apply_llfn(Function, llfn);
51 if enabled.contains(SanitizerSet::MEMORY) {
52 llvm::Attribute::SanitizeMemory.apply_llfn(Function, llfn);
54 if enabled.contains(SanitizerSet::THREAD) {
55 llvm::Attribute::SanitizeThread.apply_llfn(Function, llfn);
57 if enabled.contains(SanitizerSet::HWADDRESS) {
58 llvm::Attribute::SanitizeHWAddress.apply_llfn(Function, llfn);
62 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
64 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
65 Attribute::UWTable.toggle_llfn(Function, val, emit);
68 /// Tell LLVM if this function should be 'naked', i.e., skip the epilogue and prologue.
70 fn naked(val: &'ll Value, is_naked: bool) {
71 Attribute::Naked.toggle_llfn(Function, val, is_naked);
74 pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
75 if cx.sess().must_not_eliminate_frame_pointers() {
76 llvm::AddFunctionAttrStringValue(
78 llvm::AttributePlace::Function,
79 cstr!("frame-pointer"),
85 /// Tell LLVM what instrument function to insert.
87 fn set_instrument_function(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
88 if cx.sess().instrument_mcount() {
89 // Similar to `clang -pg` behavior. Handled by the
90 // `post-inline-ee-instrument` LLVM pass.
92 // The function name varies on platforms.
93 // See test/CodeGen/mcount.c in clang.
94 let mcount_name = CString::new(cx.sess().target.mcount.as_str().as_bytes()).unwrap();
96 llvm::AddFunctionAttrStringValue(
98 llvm::AttributePlace::Function,
99 cstr!("instrument-function-entry-inlined"),
105 fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
106 // Currently stack probes seem somewhat incompatible with the address
107 // sanitizer and thread sanitizer. With asan we're already protected from
108 // stack overflow anyway so we don't really need stack probes regardless.
114 .intersects(SanitizerSet::ADDRESS | SanitizerSet::THREAD)
119 // probestack doesn't play nice either with `-C profile-generate`.
120 if cx.sess().opts.cg.profile_generate.enabled() {
124 // probestack doesn't play nice either with gcov profiling.
125 if cx.sess().opts.debugging_opts.profile {
129 let attr_value = match cx.sess().target.stack_probes {
130 StackProbeType::None => None,
131 // Request LLVM to generate the probes inline. If the given LLVM version does not support
132 // this, no probe is generated at all (even if the attribute is specified).
133 StackProbeType::Inline => Some(cstr!("inline-asm")),
134 // Flag our internal `__rust_probestack` function as the stack probe symbol.
135 // This is defined in the `compiler-builtins` crate for each architecture.
136 StackProbeType::Call => Some(cstr!("__rust_probestack")),
137 // Pick from the two above based on the LLVM version.
138 StackProbeType::InlineOrCall { min_llvm_version_for_inline } => {
139 if llvm_util::get_version() < min_llvm_version_for_inline {
140 Some(cstr!("__rust_probestack"))
142 Some(cstr!("inline-asm"))
146 if let Some(attr_value) = attr_value {
147 llvm::AddFunctionAttrStringValue(
149 llvm::AttributePlace::Function,
150 cstr!("probe-stack"),
156 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
157 let target_cpu = SmallCStr::new(llvm_util::target_cpu(cx.tcx.sess));
158 llvm::AddFunctionAttrStringValue(
160 llvm::AttributePlace::Function,
162 target_cpu.as_c_str(),
166 pub fn apply_tune_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
167 if let Some(tune) = llvm_util::tune_cpu(cx.tcx.sess) {
168 let tune_cpu = SmallCStr::new(tune);
169 llvm::AddFunctionAttrStringValue(
171 llvm::AttributePlace::Function,
178 /// Sets the `NonLazyBind` LLVM attribute on a given function,
179 /// assuming the codegen options allow skipping the PLT.
180 pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
181 // Don't generate calls through PLT if it's not necessary
182 if !sess.needs_plt() {
183 Attribute::NonLazyBind.apply_llfn(Function, llfn);
187 pub(crate) fn default_optimisation_attrs(sess: &Session, llfn: &'ll Value) {
188 match sess.opts.optimize {
190 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
191 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
192 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
194 OptLevel::SizeMin => {
195 llvm::Attribute::MinSize.apply_llfn(Function, llfn);
196 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
197 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
200 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
201 llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
202 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
208 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
210 pub fn from_fn_attrs(cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value, instance: ty::Instance<'tcx>) {
211 let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(instance.def_id());
213 match codegen_fn_attrs.optimize {
214 OptimizeAttr::None => {
215 default_optimisation_attrs(cx.tcx.sess, llfn);
217 OptimizeAttr::Speed => {
218 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
219 llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
220 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
222 OptimizeAttr::Size => {
223 llvm::Attribute::MinSize.apply_llfn(Function, llfn);
224 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
225 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
229 let inline_attr = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
231 } else if codegen_fn_attrs.inline == InlineAttr::None && instance.def.requires_inline(cx.tcx) {
234 codegen_fn_attrs.inline
236 inline(cx, llfn, inline_attr);
238 // The `uwtable` attribute according to LLVM is:
240 // This attribute indicates that the ABI being targeted requires that an
241 // unwind table entry be produced for this function even if we can show
242 // that no exceptions passes by it. This is normally the case for the
243 // ELF x86-64 abi, but it can be disabled for some compilation units.
245 // Typically when we're compiling with `-C panic=abort` (which implies this
246 // `no_landing_pads` check) we don't need `uwtable` because we can't
247 // generate any exceptions! On Windows, however, exceptions include other
248 // events such as illegal instructions, segfaults, etc. This means that on
249 // Windows we end up still needing the `uwtable` attribute even if the `-C
250 // panic=abort` flag is passed.
252 // You can also find more info on why Windows always requires uwtables here:
253 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
254 if cx.sess().must_emit_unwind_tables() {
255 attributes::emit_uwtable(llfn, true);
258 // FIXME: none of these three functions interact with source level attributes.
259 set_frame_pointer_elimination(cx, llfn);
260 set_instrument_function(cx, llfn);
261 set_probestack(cx, llfn);
263 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
264 Attribute::Cold.apply_llfn(Function, llfn);
266 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_RETURNS_TWICE) {
267 Attribute::ReturnsTwice.apply_llfn(Function, llfn);
269 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_PURE) {
270 Attribute::ReadOnly.apply_llfn(Function, llfn);
272 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_CONST) {
273 Attribute::ReadNone.apply_llfn(Function, llfn);
275 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
278 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
279 Attribute::NoAlias.apply_llfn(llvm::AttributePlace::ReturnValue, llfn);
281 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY) {
282 llvm::AddFunctionAttrString(llfn, Function, cstr!("cmse_nonsecure_entry"));
284 if let Some(align) = codegen_fn_attrs.alignment {
285 llvm::set_alignment(llfn, align as usize);
287 sanitize(cx, codegen_fn_attrs.no_sanitize, llfn);
289 // Always annotate functions with the target-cpu they are compiled for.
290 // Without this, ThinLTO won't inline Rust functions into Clang generated
291 // functions (because Clang annotates functions this way too).
292 apply_target_cpu_attr(cx, llfn);
293 // tune-cpu is only conveyed through the attribute for our purpose.
294 // The target doesn't care; the subtarget reads our attribute.
295 apply_tune_cpu_attr(cx, llfn);
297 let mut function_features = codegen_fn_attrs
301 let feature = &f.as_str();
302 format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
304 .chain(codegen_fn_attrs.instruction_set.iter().map(|x| match x {
305 InstructionSetAttr::ArmA32 => "-thumb-mode".to_string(),
306 InstructionSetAttr::ArmT32 => "+thumb-mode".to_string(),
308 .collect::<Vec<String>>();
310 if cx.tcx.sess.target.is_like_wasm {
311 // If this function is an import from the environment but the wasm
312 // import has a specific module/name, apply them here.
313 if let Some(module) = wasm_import_module(cx.tcx, instance.def_id()) {
314 llvm::AddFunctionAttrStringValue(
316 llvm::AttributePlace::Function,
317 cstr!("wasm-import-module"),
322 codegen_fn_attrs.link_name.unwrap_or_else(|| cx.tcx.item_name(instance.def_id()));
323 let name = CString::new(&name.as_str()[..]).unwrap();
324 llvm::AddFunctionAttrStringValue(
326 llvm::AttributePlace::Function,
327 cstr!("wasm-import-name"),
332 // The `"wasm"` abi on wasm targets automatically enables the
333 // `+multivalue` feature because the purpose of the wasm abi is to match
334 // the WebAssembly specification, which has this feature. This won't be
335 // needed when LLVM enables this `multivalue` feature by default.
336 if !cx.tcx.is_closure(instance.def_id()) {
337 let abi = cx.tcx.fn_sig(instance.def_id()).abi();
338 if abi == Abi::Wasm {
339 function_features.push("+multivalue".to_string());
344 if !function_features.is_empty() {
345 let mut global_features = llvm_util::llvm_global_features(cx.tcx.sess);
346 global_features.extend(function_features.into_iter());
347 let features = global_features.join(",");
348 let val = CString::new(features).unwrap();
349 llvm::AddFunctionAttrStringValue(
351 llvm::AttributePlace::Function,
352 cstr!("target-features"),
358 pub fn provide_both(providers: &mut Providers) {
359 providers.wasm_import_module_map = |tcx, cnum| {
360 // Build up a map from DefId to a `NativeLib` structure, where
361 // `NativeLib` internally contains information about
362 // `#[link(wasm_import_module = "...")]` for example.
363 let native_libs = tcx.native_libraries(cnum);
365 let def_id_to_native_lib = native_libs
367 .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
368 .collect::<FxHashMap<_, _>>();
370 let mut ret = FxHashMap::default();
371 for (def_id, lib) in tcx.foreign_modules(cnum).iter() {
372 let module = def_id_to_native_lib.get(&def_id).and_then(|s| s.wasm_import_module);
373 let module = match module {
377 ret.extend(lib.foreign_items.iter().map(|id| {
378 assert_eq!(id.krate, cnum);
379 (*id, module.to_string())
387 fn wasm_import_module(tcx: TyCtxt<'_>, id: DefId) -> Option<CString> {
388 tcx.wasm_import_module_map(id.krate).get(&id).map(|s| CString::new(&s[..]).unwrap())