1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 //! Set and unset common attributes on LLVM values.
12 use std::ffi::CString;
14 use rustc::hir::{CodegenFnAttrFlags, CodegenFnAttrs};
15 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
16 use rustc::session::Session;
17 use rustc::session::config::Sanitizer;
18 use rustc::ty::TyCtxt;
19 use rustc::ty::layout::HasTyCtxt;
20 use rustc::ty::query::Providers;
21 use rustc_data_structures::sync::Lrc;
22 use rustc_data_structures::fx::FxHashMap;
23 use rustc_target::spec::PanicStrategy;
24 use rustc_codegen_ssa::traits::*;
27 use llvm::{self, Attribute};
28 use llvm::AttributePlace::Function;
30 pub use syntax::attr::{self, InlineAttr};
32 use context::CodegenCx;
35 /// Mark LLVM function to use provided inline heuristic.
37 pub fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) {
38 use self::InlineAttr::*;
40 Hint => Attribute::InlineHint.apply_llfn(Function, val),
41 Always => Attribute::AlwaysInline.apply_llfn(Function, val),
43 if cx.tcx().sess.target.target.arch != "amdgpu" {
44 Attribute::NoInline.apply_llfn(Function, val);
48 Attribute::InlineHint.unapply_llfn(Function, val);
49 Attribute::AlwaysInline.unapply_llfn(Function, val);
50 Attribute::NoInline.unapply_llfn(Function, val);
55 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
57 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
58 Attribute::UWTable.toggle_llfn(Function, val, emit);
61 /// Tell LLVM whether the function can or cannot unwind.
63 pub fn unwind(val: &'ll Value, can_unwind: bool) {
64 Attribute::NoUnwind.toggle_llfn(Function, val, !can_unwind);
67 /// Tell LLVM whether it should optimize function for size.
69 #[allow(dead_code)] // possibly useful function
70 pub fn set_optimize_for_size(val: &'ll Value, optimize: bool) {
71 Attribute::OptimizeForSize.toggle_llfn(Function, val, optimize);
74 /// Tell LLVM if this function should be 'naked', i.e., skip the epilogue and prologue.
76 pub fn naked(val: &'ll Value, is_naked: bool) {
77 Attribute::Naked.toggle_llfn(Function, val, is_naked);
80 pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
81 if cx.sess().must_not_eliminate_frame_pointers() {
82 llvm::AddFunctionAttrStringValue(
83 llfn, llvm::AttributePlace::Function,
84 const_cstr!("no-frame-pointer-elim"), const_cstr!("true"));
88 pub fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
89 // Only use stack probes if the target specification indicates that we
90 // should be using stack probes
91 if !cx.sess().target.target.options.stack_probes {
95 // Currently stack probes seem somewhat incompatible with the address
96 // sanitizer. With asan we're already protected from stack overflow anyway
97 // so we don't really need stack probes regardless.
98 if let Some(Sanitizer::Address) = cx.sess().opts.debugging_opts.sanitizer {
102 // probestack doesn't play nice either with pgo-gen.
103 if cx.sess().opts.debugging_opts.pgo_gen.is_some() {
107 // probestack doesn't play nice either with gcov profiling.
108 if cx.sess().opts.debugging_opts.profile {
112 // Flag our internal `__rust_probestack` function as the stack probe symbol.
113 // This is defined in the `compiler-builtins` crate for each architecture.
114 llvm::AddFunctionAttrStringValue(
115 llfn, llvm::AttributePlace::Function,
116 const_cstr!("probe-stack"), const_cstr!("__rust_probestack"));
119 pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
120 const RUSTC_SPECIFIC_FEATURES: &[&str] = &[
124 let cmdline = sess.opts.cg.target_feature.split(',')
125 .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
126 sess.target.target.options.features.split(',')
128 .filter(|l| !l.is_empty())
131 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
132 let cpu = llvm_util::target_cpu(cx.tcx.sess);
133 let target_cpu = CString::new(cpu).unwrap();
134 llvm::AddFunctionAttrStringValue(
136 llvm::AttributePlace::Function,
137 const_cstr!("target-cpu"),
138 target_cpu.as_c_str());
141 /// Sets the `NonLazyBind` LLVM attribute on a given function,
142 /// assuming the codegen options allow skipping the PLT.
143 pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
144 // Don't generate calls through PLT if it's not necessary
145 if !sess.needs_plt() {
146 Attribute::NonLazyBind.apply_llfn(Function, llfn);
150 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
152 pub fn from_fn_attrs(
153 cx: &CodegenCx<'ll, '_>,
157 let codegen_fn_attrs = id.map(|id| cx.tcx.codegen_fn_attrs(id))
158 .unwrap_or_else(|| CodegenFnAttrs::new());
160 inline(cx, llfn, codegen_fn_attrs.inline);
162 // The `uwtable` attribute according to LLVM is:
164 // This attribute indicates that the ABI being targeted requires that an
165 // unwind table entry be produced for this function even if we can show
166 // that no exceptions passes by it. This is normally the case for the
167 // ELF x86-64 abi, but it can be disabled for some compilation units.
169 // Typically when we're compiling with `-C panic=abort` (which implies this
170 // `no_landing_pads` check) we don't need `uwtable` because we can't
171 // generate any exceptions! On Windows, however, exceptions include other
172 // events such as illegal instructions, segfaults, etc. This means that on
173 // Windows we end up still needing the `uwtable` attribute even if the `-C
174 // panic=abort` flag is passed.
176 // You can also find more info on why Windows is whitelisted here in:
177 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
178 if !cx.sess().no_landing_pads() ||
179 cx.sess().target.target.options.requires_uwtable {
180 attributes::emit_uwtable(llfn, true);
183 set_frame_pointer_elimination(cx, llfn);
184 set_probestack(cx, llfn);
186 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
187 Attribute::Cold.apply_llfn(Function, llfn);
189 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
192 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
193 Attribute::NoAlias.apply_llfn(
194 llvm::AttributePlace::ReturnValue, llfn);
197 let can_unwind = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
199 } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
202 // Perhaps questionable, but we assume that anything defined
203 // *in Rust code* may unwind. Foreign items like `extern "C" {
204 // fn foo(); }` are assumed not to unwind **unless** they have
205 // a `#[unwind]` attribute.
206 } else if id.map(|id| !cx.tcx.is_foreign_item(id)).unwrap_or(false) {
213 Some(false) => attributes::unwind(llfn, false),
214 Some(true) if cx.tcx.sess.panic_strategy() == PanicStrategy::Unwind => {
215 attributes::unwind(llfn, true);
217 Some(true) | None => {}
220 // Always annotate functions with the target-cpu they are compiled for.
221 // Without this, ThinLTO won't inline Rust functions into Clang generated
222 // functions (because Clang annotates functions this way too).
223 // NOTE: For now we just apply this if -Zcross-lang-lto is specified, since
224 // it introduce a little overhead and isn't really necessary otherwise.
225 if cx.tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() {
226 apply_target_cpu_attr(cx, llfn);
229 let features = llvm_target_features(cx.tcx.sess)
230 .map(|s| s.to_string())
232 codegen_fn_attrs.target_features
235 let feature = &*f.as_str();
236 format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
239 .collect::<Vec<String>>()
242 if !features.is_empty() {
243 let val = CString::new(features).unwrap();
244 llvm::AddFunctionAttrStringValue(
245 llfn, llvm::AttributePlace::Function,
246 const_cstr!("target-features"), &val);
249 // Note that currently the `wasm-import-module` doesn't do anything, but
250 // eventually LLVM 7 should read this and ferry the appropriate import
251 // module to the output file.
252 if let Some(id) = id {
253 if cx.tcx.sess.target.target.arch == "wasm32" {
254 if let Some(module) = wasm_import_module(cx.tcx, id) {
255 llvm::AddFunctionAttrStringValue(
257 llvm::AttributePlace::Function,
258 const_cstr!("wasm-import-module"),
266 pub fn provide(providers: &mut Providers) {
267 providers.target_features_whitelist = |tcx, cnum| {
268 assert_eq!(cnum, LOCAL_CRATE);
269 if tcx.sess.opts.actually_rustdoc {
270 // rustdoc needs to be able to document functions that use all the features, so
271 // whitelist them all
272 Lrc::new(llvm_util::all_known_features()
273 .map(|(a, b)| (a.to_string(), b.map(|s| s.to_string())))
276 Lrc::new(llvm_util::target_feature_whitelist(tcx.sess)
278 .map(|&(a, b)| (a.to_string(), b.map(|s| s.to_string())))
283 provide_extern(providers);
286 pub fn provide_extern(providers: &mut Providers) {
287 providers.wasm_import_module_map = |tcx, cnum| {
288 // Build up a map from DefId to a `NativeLibrary` structure, where
289 // `NativeLibrary` internally contains information about
290 // `#[link(wasm_import_module = "...")]` for example.
291 let native_libs = tcx.native_libraries(cnum);
293 let def_id_to_native_lib = native_libs.iter().filter_map(|lib|
294 if let Some(id) = lib.foreign_module {
299 ).collect::<FxHashMap<_, _>>();
301 let mut ret = FxHashMap::default();
302 for lib in tcx.foreign_modules(cnum).iter() {
303 let module = def_id_to_native_lib
305 .and_then(|s| s.wasm_import_module);
306 let module = match module {
310 ret.extend(lib.foreign_items.iter().map(|id| {
311 assert_eq!(id.krate, cnum);
312 (*id, module.to_string())
320 fn wasm_import_module(tcx: TyCtxt, id: DefId) -> Option<CString> {
321 tcx.wasm_import_module_map(id.krate)
323 .map(|s| CString::new(&s[..]).unwrap())