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, SanitizerSet};
15 use rustc_session::Session;
16 use rustc_target::spec::StackProbeType;
18 use crate::attributes;
19 use crate::llvm::AttributePlace::Function;
20 use crate::llvm::{self, Attribute};
22 pub use rustc_attr::{InlineAttr, InstructionSetAttr, OptimizeAttr};
24 use crate::context::CodegenCx;
25 use crate::value::Value;
27 /// Mark LLVM function to use provided inline heuristic.
29 fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) {
30 use self::InlineAttr::*;
32 Hint => Attribute::InlineHint.apply_llfn(Function, val),
33 Always => Attribute::AlwaysInline.apply_llfn(Function, val),
35 if cx.tcx().sess.target.arch != "amdgpu" {
36 Attribute::NoInline.apply_llfn(Function, val);
43 /// Apply LLVM sanitize attributes.
45 pub fn sanitize(cx: &CodegenCx<'ll, '_>, no_sanitize: SanitizerSet, llfn: &'ll Value) {
46 let enabled = cx.tcx.sess.opts.debugging_opts.sanitizer - no_sanitize;
47 if enabled.contains(SanitizerSet::ADDRESS) {
48 llvm::Attribute::SanitizeAddress.apply_llfn(Function, llfn);
50 if enabled.contains(SanitizerSet::MEMORY) {
51 llvm::Attribute::SanitizeMemory.apply_llfn(Function, llfn);
53 if enabled.contains(SanitizerSet::THREAD) {
54 llvm::Attribute::SanitizeThread.apply_llfn(Function, llfn);
56 if enabled.contains(SanitizerSet::HWADDRESS) {
57 llvm::Attribute::SanitizeHWAddress.apply_llfn(Function, llfn);
61 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
63 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
64 Attribute::UWTable.toggle_llfn(Function, val, emit);
67 /// Tell LLVM if this function should be 'naked', i.e., skip the epilogue and prologue.
69 fn naked(val: &'ll Value, is_naked: bool) {
70 Attribute::Naked.toggle_llfn(Function, val, is_naked);
73 pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
74 if cx.sess().must_not_eliminate_frame_pointers() {
75 llvm::AddFunctionAttrStringValue(
77 llvm::AttributePlace::Function,
78 cstr!("frame-pointer"),
84 /// Tell LLVM what instrument function to insert.
86 fn set_instrument_function(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
87 if cx.sess().instrument_mcount() {
88 // Similar to `clang -pg` behavior. Handled by the
89 // `post-inline-ee-instrument` LLVM pass.
91 // The function name varies on platforms.
92 // See test/CodeGen/mcount.c in clang.
93 let mcount_name = CString::new(cx.sess().target.mcount.as_str().as_bytes()).unwrap();
95 llvm::AddFunctionAttrStringValue(
97 llvm::AttributePlace::Function,
98 cstr!("instrument-function-entry-inlined"),
104 fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
105 // Currently stack probes seem somewhat incompatible with the address
106 // sanitizer and thread sanitizer. With asan we're already protected from
107 // stack overflow anyway so we don't really need stack probes regardless.
113 .intersects(SanitizerSet::ADDRESS | SanitizerSet::THREAD)
118 // probestack doesn't play nice either with `-C profile-generate`.
119 if cx.sess().opts.cg.profile_generate.enabled() {
123 // probestack doesn't play nice either with gcov profiling.
124 if cx.sess().opts.debugging_opts.profile {
128 let attr_value = match cx.sess().target.stack_probes {
129 StackProbeType::None => None,
130 // Request LLVM to generate the probes inline. If the given LLVM version does not support
131 // this, no probe is generated at all (even if the attribute is specified).
132 StackProbeType::Inline => Some(cstr!("inline-asm")),
133 // Flag our internal `__rust_probestack` function as the stack probe symbol.
134 // This is defined in the `compiler-builtins` crate for each architecture.
135 StackProbeType::Call => Some(cstr!("__rust_probestack")),
136 // Pick from the two above based on the LLVM version.
137 StackProbeType::InlineOrCall { min_llvm_version_for_inline } => {
138 if llvm_util::get_version() < min_llvm_version_for_inline {
139 Some(cstr!("__rust_probestack"))
141 Some(cstr!("inline-asm"))
145 if let Some(attr_value) = attr_value {
146 llvm::AddFunctionAttrStringValue(
148 llvm::AttributePlace::Function,
149 cstr!("probe-stack"),
155 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
156 let target_cpu = SmallCStr::new(llvm_util::target_cpu(cx.tcx.sess));
157 llvm::AddFunctionAttrStringValue(
159 llvm::AttributePlace::Function,
161 target_cpu.as_c_str(),
165 pub fn apply_tune_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
166 if let Some(tune) = llvm_util::tune_cpu(cx.tcx.sess) {
167 let tune_cpu = SmallCStr::new(tune);
168 llvm::AddFunctionAttrStringValue(
170 llvm::AttributePlace::Function,
177 /// Sets the `NonLazyBind` LLVM attribute on a given function,
178 /// assuming the codegen options allow skipping the PLT.
179 pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
180 // Don't generate calls through PLT if it's not necessary
181 if !sess.needs_plt() {
182 Attribute::NonLazyBind.apply_llfn(Function, llfn);
186 pub(crate) fn default_optimisation_attrs(sess: &Session, llfn: &'ll Value) {
187 match sess.opts.optimize {
189 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
190 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
191 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
193 OptLevel::SizeMin => {
194 llvm::Attribute::MinSize.apply_llfn(Function, llfn);
195 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
196 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
199 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
200 llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
201 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
207 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
209 pub fn from_fn_attrs(cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value, instance: ty::Instance<'tcx>) {
210 let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(instance.def_id());
212 match codegen_fn_attrs.optimize {
213 OptimizeAttr::None => {
214 default_optimisation_attrs(cx.tcx.sess, llfn);
216 OptimizeAttr::Speed => {
217 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
218 llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
219 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
221 OptimizeAttr::Size => {
222 llvm::Attribute::MinSize.apply_llfn(Function, llfn);
223 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
224 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
228 let inline_attr = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
230 } else if codegen_fn_attrs.inline == InlineAttr::None && instance.def.requires_inline(cx.tcx) {
233 codegen_fn_attrs.inline
235 inline(cx, llfn, inline_attr);
237 // The `uwtable` attribute according to LLVM is:
239 // This attribute indicates that the ABI being targeted requires that an
240 // unwind table entry be produced for this function even if we can show
241 // that no exceptions passes by it. This is normally the case for the
242 // ELF x86-64 abi, but it can be disabled for some compilation units.
244 // Typically when we're compiling with `-C panic=abort` (which implies this
245 // `no_landing_pads` check) we don't need `uwtable` because we can't
246 // generate any exceptions! On Windows, however, exceptions include other
247 // events such as illegal instructions, segfaults, etc. This means that on
248 // Windows we end up still needing the `uwtable` attribute even if the `-C
249 // panic=abort` flag is passed.
251 // You can also find more info on why Windows always requires uwtables here:
252 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
253 if cx.sess().must_emit_unwind_tables() {
254 attributes::emit_uwtable(llfn, true);
257 set_frame_pointer_elimination(cx, llfn);
258 set_instrument_function(cx, llfn);
259 set_probestack(cx, llfn);
261 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
262 Attribute::Cold.apply_llfn(Function, llfn);
264 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_RETURNS_TWICE) {
265 Attribute::ReturnsTwice.apply_llfn(Function, llfn);
267 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_PURE) {
268 Attribute::ReadOnly.apply_llfn(Function, llfn);
270 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_CONST) {
271 Attribute::ReadNone.apply_llfn(Function, llfn);
273 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
276 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
277 Attribute::NoAlias.apply_llfn(llvm::AttributePlace::ReturnValue, llfn);
279 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY) {
280 llvm::AddFunctionAttrString(llfn, Function, cstr!("cmse_nonsecure_entry"));
282 sanitize(cx, codegen_fn_attrs.no_sanitize, llfn);
284 // Always annotate functions with the target-cpu they are compiled for.
285 // Without this, ThinLTO won't inline Rust functions into Clang generated
286 // functions (because Clang annotates functions this way too).
287 apply_target_cpu_attr(cx, llfn);
288 // tune-cpu is only conveyed through the attribute for our purpose.
289 // The target doesn't care; the subtarget reads our attribute.
290 apply_tune_cpu_attr(cx, llfn);
292 let function_features = codegen_fn_attrs
296 let feature = &f.as_str();
297 format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
299 .chain(codegen_fn_attrs.instruction_set.iter().map(|x| match x {
300 InstructionSetAttr::ArmA32 => "-thumb-mode".to_string(),
301 InstructionSetAttr::ArmT32 => "+thumb-mode".to_string(),
303 .collect::<Vec<String>>();
304 if !function_features.is_empty() {
305 let mut global_features = llvm_util::llvm_global_features(cx.tcx.sess);
306 global_features.extend(function_features.into_iter());
307 let features = global_features.join(",");
308 let val = CString::new(features).unwrap();
309 llvm::AddFunctionAttrStringValue(
311 llvm::AttributePlace::Function,
312 cstr!("target-features"),
317 // Note that currently the `wasm-import-module` doesn't do anything, but
318 // eventually LLVM 7 should read this and ferry the appropriate import
319 // module to the output file.
320 if cx.tcx.sess.target.arch == "wasm32" {
321 if let Some(module) = wasm_import_module(cx.tcx, instance.def_id()) {
322 llvm::AddFunctionAttrStringValue(
324 llvm::AttributePlace::Function,
325 cstr!("wasm-import-module"),
330 codegen_fn_attrs.link_name.unwrap_or_else(|| cx.tcx.item_name(instance.def_id()));
331 let name = CString::new(&name.as_str()[..]).unwrap();
332 llvm::AddFunctionAttrStringValue(
334 llvm::AttributePlace::Function,
335 cstr!("wasm-import-name"),
342 pub fn provide_both(providers: &mut Providers) {
343 providers.wasm_import_module_map = |tcx, cnum| {
344 // Build up a map from DefId to a `NativeLib` structure, where
345 // `NativeLib` internally contains information about
346 // `#[link(wasm_import_module = "...")]` for example.
347 let native_libs = tcx.native_libraries(cnum);
349 let def_id_to_native_lib = native_libs
351 .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
352 .collect::<FxHashMap<_, _>>();
354 let mut ret = FxHashMap::default();
355 for (def_id, lib) in tcx.foreign_modules(cnum).iter() {
356 let module = def_id_to_native_lib.get(&def_id).and_then(|s| s.wasm_import_module);
357 let module = match module {
361 ret.extend(lib.foreign_items.iter().map(|id| {
362 assert_eq!(id.krate, cnum);
363 (*id, module.to_string())
371 fn wasm_import_module(tcx: TyCtxt<'_>, id: DefId) -> Option<CString> {
372 tcx.wasm_import_module_map(id.krate).get(&id).map(|s| CString::new(&s[..]).unwrap())