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;
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::*;
20 use llvm::{self, Attribute};
21 use llvm::AttributePlace::Function;
23 pub use syntax::attr::{self, InlineAttr};
25 use context::CodegenCx;
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 whether it should optimize function for size.
62 #[allow(dead_code)] // possibly useful function
63 pub fn set_optimize_for_size(val: &'ll Value, optimize: bool) {
64 Attribute::OptimizeForSize.toggle_llfn(Function, val, optimize);
67 /// Tell LLVM if this function should be 'naked', i.e., skip the epilogue and prologue.
69 pub 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(
76 llfn, llvm::AttributePlace::Function,
77 const_cstr!("no-frame-pointer-elim"), const_cstr!("true"));
81 pub fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
82 // Only use stack probes if the target specification indicates that we
83 // should be using stack probes
84 if !cx.sess().target.target.options.stack_probes {
88 // Currently stack probes seem somewhat incompatible with the address
89 // sanitizer. With asan we're already protected from stack overflow anyway
90 // so we don't really need stack probes regardless.
91 if let Some(Sanitizer::Address) = cx.sess().opts.debugging_opts.sanitizer {
95 // probestack doesn't play nice either with pgo-gen.
96 if cx.sess().opts.debugging_opts.pgo_gen.is_some() {
100 // probestack doesn't play nice either with gcov profiling.
101 if cx.sess().opts.debugging_opts.profile {
105 // Flag our internal `__rust_probestack` function as the stack probe symbol.
106 // This is defined in the `compiler-builtins` crate for each architecture.
107 llvm::AddFunctionAttrStringValue(
108 llfn, llvm::AttributePlace::Function,
109 const_cstr!("probe-stack"), const_cstr!("__rust_probestack"));
112 pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
113 const RUSTC_SPECIFIC_FEATURES: &[&str] = &[
117 let cmdline = sess.opts.cg.target_feature.split(',')
118 .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
119 sess.target.target.options.features.split(',')
121 .filter(|l| !l.is_empty())
124 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
125 let target_cpu = SmallCStr::new(llvm_util::target_cpu(cx.tcx.sess));
126 llvm::AddFunctionAttrStringValue(
128 llvm::AttributePlace::Function,
129 const_cstr!("target-cpu"),
130 target_cpu.as_c_str());
133 /// Sets the `NonLazyBind` LLVM attribute on a given function,
134 /// assuming the codegen options allow skipping the PLT.
135 pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
136 // Don't generate calls through PLT if it's not necessary
137 if !sess.needs_plt() {
138 Attribute::NonLazyBind.apply_llfn(Function, llfn);
142 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
144 pub fn from_fn_attrs(
145 cx: &CodegenCx<'ll, 'tcx>,
148 sig: PolyFnSig<'tcx>,
150 let codegen_fn_attrs = id.map(|id| cx.tcx.codegen_fn_attrs(id))
151 .unwrap_or_else(|| CodegenFnAttrs::new());
153 inline(cx, llfn, codegen_fn_attrs.inline);
155 // The `uwtable` attribute according to LLVM is:
157 // This attribute indicates that the ABI being targeted requires that an
158 // unwind table entry be produced for this function even if we can show
159 // that no exceptions passes by it. This is normally the case for the
160 // ELF x86-64 abi, but it can be disabled for some compilation units.
162 // Typically when we're compiling with `-C panic=abort` (which implies this
163 // `no_landing_pads` check) we don't need `uwtable` because we can't
164 // generate any exceptions! On Windows, however, exceptions include other
165 // events such as illegal instructions, segfaults, etc. This means that on
166 // Windows we end up still needing the `uwtable` attribute even if the `-C
167 // panic=abort` flag is passed.
169 // You can also find more info on why Windows is whitelisted here in:
170 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
171 if !cx.sess().no_landing_pads() ||
172 cx.sess().target.target.options.requires_uwtable {
173 attributes::emit_uwtable(llfn, true);
176 set_frame_pointer_elimination(cx, llfn);
177 set_probestack(cx, llfn);
179 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
180 Attribute::Cold.apply_llfn(Function, llfn);
182 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
185 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
186 Attribute::NoAlias.apply_llfn(
187 llvm::AttributePlace::ReturnValue, llfn);
190 unwind(llfn, if cx.tcx.sess.panic_strategy() != PanicStrategy::Unwind {
191 // In panic=abort mode we assume nothing can unwind anywhere, so
192 // optimize based on this!
194 } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
195 // If a specific #[unwind] attribute is present, use that
197 } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
198 // Special attribute for allocator functions, which can't unwind
200 } else if let Some(id) = id {
201 let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
202 if cx.tcx.is_foreign_item(id) {
203 // Foreign items like `extern "C" { fn foo(); }` are assumed not to
206 } else if sig.abi != Abi::Rust && sig.abi != Abi::RustCall {
207 // Any items defined in Rust that *don't* have the `extern` ABI are
208 // defined to not unwind. We insert shims to abort if an unwind
209 // happens to enforce this.
212 // Anything else defined in Rust is assumed that it can possibly
217 // assume this can possibly unwind, avoiding the application of a
218 // `nounwind` attribute below.
222 // Always annotate functions with the target-cpu they are compiled for.
223 // Without this, ThinLTO won't inline Rust functions into Clang generated
224 // functions (because Clang annotates functions this way too).
225 apply_target_cpu_attr(cx, llfn);
227 let features = llvm_target_features(cx.tcx.sess)
228 .map(|s| s.to_string())
230 codegen_fn_attrs.target_features
233 let feature = &*f.as_str();
234 format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
237 .collect::<Vec<String>>()
240 if !features.is_empty() {
241 let val = CString::new(features).unwrap();
242 llvm::AddFunctionAttrStringValue(
243 llfn, llvm::AttributePlace::Function,
244 const_cstr!("target-features"), &val);
247 // Note that currently the `wasm-import-module` doesn't do anything, but
248 // eventually LLVM 7 should read this and ferry the appropriate import
249 // module to the output file.
250 if let Some(id) = id {
251 if cx.tcx.sess.target.target.arch == "wasm32" {
252 if let Some(module) = wasm_import_module(cx.tcx, id) {
253 llvm::AddFunctionAttrStringValue(
255 llvm::AttributePlace::Function,
256 const_cstr!("wasm-import-module"),
264 pub fn provide(providers: &mut Providers) {
265 providers.target_features_whitelist = |tcx, cnum| {
266 assert_eq!(cnum, LOCAL_CRATE);
267 if tcx.sess.opts.actually_rustdoc {
268 // rustdoc needs to be able to document functions that use all the features, so
269 // whitelist them all
270 Lrc::new(llvm_util::all_known_features()
271 .map(|(a, b)| (a.to_string(), b.map(|s| s.to_string())))
274 Lrc::new(llvm_util::target_feature_whitelist(tcx.sess)
276 .map(|&(a, b)| (a.to_string(), b.map(|s| s.to_string())))
281 provide_extern(providers);
284 pub fn provide_extern(providers: &mut Providers) {
285 providers.wasm_import_module_map = |tcx, cnum| {
286 // Build up a map from DefId to a `NativeLibrary` structure, where
287 // `NativeLibrary` internally contains information about
288 // `#[link(wasm_import_module = "...")]` for example.
289 let native_libs = tcx.native_libraries(cnum);
291 let def_id_to_native_lib = native_libs.iter().filter_map(|lib|
292 if let Some(id) = lib.foreign_module {
297 ).collect::<FxHashMap<_, _>>();
299 let mut ret = FxHashMap::default();
300 for lib in tcx.foreign_modules(cnum).iter() {
301 let module = def_id_to_native_lib
303 .and_then(|s| s.wasm_import_module);
304 let module = match module {
308 ret.extend(lib.foreign_items.iter().map(|id| {
309 assert_eq!(id.krate, cnum);
310 (*id, module.to_string())
318 fn wasm_import_module(tcx: TyCtxt, id: DefId) -> Option<CString> {
319 tcx.wasm_import_module_map(id.krate)
321 .map(|s| CString::new(&s[..]).unwrap())