1 //! Set and unset common attributes on LLVM values.
5 use rustc::hir::{CodegenFnAttrFlags, CodegenFnAttrs};
6 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
7 use rustc::session::Session;
8 use rustc::session::config::{Sanitizer, OptLevel};
9 use rustc::ty::{self, TyCtxt, PolyFnSig};
10 use rustc::ty::layout::HasTyCtxt;
11 use rustc::ty::query::Providers;
12 use rustc_data_structures::small_c_str::SmallCStr;
13 use rustc_data_structures::sync::Lrc;
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_target::spec::PanicStrategy;
16 use rustc_codegen_ssa::traits::*;
19 use crate::attributes;
20 use crate::llvm::{self, Attribute};
21 use crate::llvm::AttributePlace::Function;
23 pub use syntax::attr::{self, InlineAttr, OptimizeAttr};
25 use crate::context::CodegenCx;
26 use crate::value::Value;
28 /// Mark LLVM function to use provided inline heuristic.
30 pub 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.target.arch != "amdgpu" {
37 Attribute::NoInline.apply_llfn(Function, val);
41 Attribute::InlineHint.unapply_llfn(Function, val);
42 Attribute::AlwaysInline.unapply_llfn(Function, val);
43 Attribute::NoInline.unapply_llfn(Function, val);
48 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
50 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
51 Attribute::UWTable.toggle_llfn(Function, val, emit);
54 /// Tell LLVM whether the function can or cannot unwind.
56 fn unwind(val: &'ll Value, can_unwind: bool) {
57 Attribute::NoUnwind.toggle_llfn(Function, val, !can_unwind);
60 /// Tell LLVM if this function should be 'naked', i.e., skip the epilogue and prologue.
62 pub fn naked(val: &'ll Value, is_naked: bool) {
63 Attribute::Naked.toggle_llfn(Function, val, is_naked);
66 pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
67 if cx.sess().must_not_eliminate_frame_pointers() {
68 llvm::AddFunctionAttrStringValue(
69 llfn, llvm::AttributePlace::Function,
70 const_cstr!("no-frame-pointer-elim"), const_cstr!("true"));
74 /// Tell LLVM what instrument function to insert.
76 pub fn set_instrument_function(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
77 if cx.sess().instrument_mcount() {
78 // Similar to `clang -pg` behavior. Handled by the
79 // `post-inline-ee-instrument` LLVM pass.
81 // The function name varies on platforms.
82 // See test/CodeGen/mcount.c in clang.
83 let mcount_name = CString::new(
84 cx.sess().target.target.options.target_mcount.as_str().as_bytes()).unwrap();
86 llvm::AddFunctionAttrStringValue(
87 llfn, llvm::AttributePlace::Function,
88 const_cstr!("instrument-function-entry-inlined"), &mcount_name);
92 pub fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
93 // Only use stack probes if the target specification indicates that we
94 // should be using stack probes
95 if !cx.sess().target.target.options.stack_probes {
99 // Currently stack probes seem somewhat incompatible with the address
100 // sanitizer. With asan we're already protected from stack overflow anyway
101 // so we don't really need stack probes regardless.
102 if let Some(Sanitizer::Address) = cx.sess().opts.debugging_opts.sanitizer {
106 // probestack doesn't play nice either with pgo-gen.
107 if cx.sess().opts.debugging_opts.pgo_gen.enabled() {
111 // probestack doesn't play nice either with gcov profiling.
112 if cx.sess().opts.debugging_opts.profile {
116 // Flag our internal `__rust_probestack` function as the stack probe symbol.
117 // This is defined in the `compiler-builtins` crate for each architecture.
118 llvm::AddFunctionAttrStringValue(
119 llfn, llvm::AttributePlace::Function,
120 const_cstr!("probe-stack"), const_cstr!("__rust_probestack"));
123 pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
124 const RUSTC_SPECIFIC_FEATURES: &[&str] = &[
128 let cmdline = sess.opts.cg.target_feature.split(',')
129 .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
130 sess.target.target.options.features.split(',')
132 .filter(|l| !l.is_empty())
135 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
136 let target_cpu = SmallCStr::new(llvm_util::target_cpu(cx.tcx.sess));
137 llvm::AddFunctionAttrStringValue(
139 llvm::AttributePlace::Function,
140 const_cstr!("target-cpu"),
141 target_cpu.as_c_str());
144 /// Sets the `NonLazyBind` LLVM attribute on a given function,
145 /// assuming the codegen options allow skipping the PLT.
146 pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
147 // Don't generate calls through PLT if it's not necessary
148 if !sess.needs_plt() {
149 Attribute::NonLazyBind.apply_llfn(Function, llfn);
153 pub(crate) fn default_optimisation_attrs(sess: &Session, llfn: &'ll Value) {
154 match sess.opts.optimize {
156 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
157 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
158 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
160 OptLevel::SizeMin => {
161 llvm::Attribute::MinSize.apply_llfn(Function, llfn);
162 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
163 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
166 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
167 llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
168 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
175 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
177 pub fn from_fn_attrs(
178 cx: &CodegenCx<'ll, 'tcx>,
181 sig: PolyFnSig<'tcx>,
183 let codegen_fn_attrs = id.map(|id| cx.tcx.codegen_fn_attrs(id))
184 .unwrap_or_else(|| CodegenFnAttrs::new());
186 match codegen_fn_attrs.optimize {
187 OptimizeAttr::None => {
188 default_optimisation_attrs(cx.tcx.sess, llfn);
190 OptimizeAttr::Speed => {
191 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
192 llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
193 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
195 OptimizeAttr::Size => {
196 llvm::Attribute::MinSize.apply_llfn(Function, llfn);
197 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
198 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
202 inline(cx, llfn, codegen_fn_attrs.inline);
204 // The `uwtable` attribute according to LLVM is:
206 // This attribute indicates that the ABI being targeted requires that an
207 // unwind table entry be produced for this function even if we can show
208 // that no exceptions passes by it. This is normally the case for the
209 // ELF x86-64 abi, but it can be disabled for some compilation units.
211 // Typically when we're compiling with `-C panic=abort` (which implies this
212 // `no_landing_pads` check) we don't need `uwtable` because we can't
213 // generate any exceptions! On Windows, however, exceptions include other
214 // events such as illegal instructions, segfaults, etc. This means that on
215 // Windows we end up still needing the `uwtable` attribute even if the `-C
216 // panic=abort` flag is passed.
218 // You can also find more info on why Windows is whitelisted here in:
219 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
220 if !cx.sess().no_landing_pads() ||
221 cx.sess().target.target.options.requires_uwtable {
222 attributes::emit_uwtable(llfn, true);
225 set_frame_pointer_elimination(cx, llfn);
226 set_instrument_function(cx, llfn);
227 set_probestack(cx, llfn);
229 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
230 Attribute::Cold.apply_llfn(Function, llfn);
232 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_RETURNS_TWICE) {
233 Attribute::ReturnsTwice.apply_llfn(Function, llfn);
235 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
238 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
239 Attribute::NoAlias.apply_llfn(
240 llvm::AttributePlace::ReturnValue, llfn);
243 unwind(llfn, if cx.tcx.sess.panic_strategy() != PanicStrategy::Unwind {
244 // In panic=abort mode we assume nothing can unwind anywhere, so
245 // optimize based on this!
247 } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
248 // If a specific #[unwind] attribute is present, use that
250 } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
251 // Special attribute for allocator functions, which can't unwind
253 } else if let Some(id) = id {
254 let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
255 if cx.tcx.is_foreign_item(id) {
256 // Foreign items like `extern "C" { fn foo(); }` are assumed not to
259 } else if sig.abi != Abi::Rust && sig.abi != Abi::RustCall {
260 // Any items defined in Rust that *don't* have the `extern` ABI are
261 // defined to not unwind. We insert shims to abort if an unwind
262 // happens to enforce this.
265 // Anything else defined in Rust is assumed that it can possibly
270 // assume this can possibly unwind, avoiding the application of a
271 // `nounwind` attribute below.
275 // Always annotate functions with the target-cpu they are compiled for.
276 // Without this, ThinLTO won't inline Rust functions into Clang generated
277 // functions (because Clang annotates functions this way too).
278 apply_target_cpu_attr(cx, llfn);
280 let features = llvm_target_features(cx.tcx.sess)
281 .map(|s| s.to_string())
283 codegen_fn_attrs.target_features
286 let feature = &*f.as_str();
287 format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
290 .collect::<Vec<String>>()
293 if !features.is_empty() {
294 let val = CString::new(features).unwrap();
295 llvm::AddFunctionAttrStringValue(
296 llfn, llvm::AttributePlace::Function,
297 const_cstr!("target-features"), &val);
300 // Note that currently the `wasm-import-module` doesn't do anything, but
301 // eventually LLVM 7 should read this and ferry the appropriate import
302 // module to the output file.
303 if let Some(id) = id {
304 if cx.tcx.sess.target.target.arch == "wasm32" {
305 if let Some(module) = wasm_import_module(cx.tcx, id) {
306 llvm::AddFunctionAttrStringValue(
308 llvm::AttributePlace::Function,
309 const_cstr!("wasm-import-module"),
317 pub fn provide(providers: &mut Providers<'_>) {
318 providers.target_features_whitelist = |tcx, cnum| {
319 assert_eq!(cnum, LOCAL_CRATE);
320 if tcx.sess.opts.actually_rustdoc {
321 // rustdoc needs to be able to document functions that use all the features, so
322 // whitelist them all
323 Lrc::new(llvm_util::all_known_features()
324 .map(|(a, b)| (a.to_string(), b))
327 Lrc::new(llvm_util::target_feature_whitelist(tcx.sess)
329 .map(|&(a, b)| (a.to_string(), b))
334 provide_extern(providers);
337 pub fn provide_extern(providers: &mut Providers<'_>) {
338 providers.wasm_import_module_map = |tcx, cnum| {
339 // Build up a map from DefId to a `NativeLibrary` structure, where
340 // `NativeLibrary` internally contains information about
341 // `#[link(wasm_import_module = "...")]` for example.
342 let native_libs = tcx.native_libraries(cnum);
344 let def_id_to_native_lib = native_libs.iter().filter_map(|lib|
345 if let Some(id) = lib.foreign_module {
350 ).collect::<FxHashMap<_, _>>();
352 let mut ret = FxHashMap::default();
353 for lib in tcx.foreign_modules(cnum).iter() {
354 let module = def_id_to_native_lib
356 .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)
374 .map(|s| CString::new(&s[..]).unwrap())