]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/attributes.rs
Remove licenses
[rust.git] / src / librustc_codegen_llvm / attributes.rs
1 //! Set and unset common attributes on LLVM values.
2
3 use std::ffi::CString;
4
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::*;
17
18 use abi::Abi;
19 use attributes;
20 use llvm::{self, Attribute};
21 use llvm::AttributePlace::Function;
22 use llvm_util;
23 pub use syntax::attr::{self, InlineAttr};
24
25 use context::CodegenCx;
26 use value::Value;
27
28 /// Mark LLVM function to use provided inline heuristic.
29 #[inline]
30 pub fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) {
31     use self::InlineAttr::*;
32     match inline {
33         Hint   => Attribute::InlineHint.apply_llfn(Function, val),
34         Always => Attribute::AlwaysInline.apply_llfn(Function, val),
35         Never  => {
36             if cx.tcx().sess.target.target.arch != "amdgpu" {
37                 Attribute::NoInline.apply_llfn(Function, val);
38             }
39         },
40         None   => {
41             Attribute::InlineHint.unapply_llfn(Function, val);
42             Attribute::AlwaysInline.unapply_llfn(Function, val);
43             Attribute::NoInline.unapply_llfn(Function, val);
44         },
45     };
46 }
47
48 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
49 #[inline]
50 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
51     Attribute::UWTable.toggle_llfn(Function, val, emit);
52 }
53
54 /// Tell LLVM whether the function can or cannot unwind.
55 #[inline]
56 fn unwind(val: &'ll Value, can_unwind: bool) {
57     Attribute::NoUnwind.toggle_llfn(Function, val, !can_unwind);
58 }
59
60 /// Tell LLVM whether it should optimize function for size.
61 #[inline]
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);
65 }
66
67 /// Tell LLVM if this function should be 'naked', i.e., skip the epilogue and prologue.
68 #[inline]
69 pub fn naked(val: &'ll Value, is_naked: bool) {
70     Attribute::Naked.toggle_llfn(Function, val, is_naked);
71 }
72
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"));
78     }
79 }
80
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 {
85         return
86     }
87
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 {
92         return
93     }
94
95     // probestack doesn't play nice either with pgo-gen.
96     if cx.sess().opts.debugging_opts.pgo_gen.is_some() {
97         return;
98     }
99
100     // probestack doesn't play nice either with gcov profiling.
101     if cx.sess().opts.debugging_opts.profile {
102         return;
103     }
104
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"));
110 }
111
112 pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
113     const RUSTC_SPECIFIC_FEATURES: &[&str] = &[
114         "crt-static",
115     ];
116
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(',')
120         .chain(cmdline)
121         .filter(|l| !l.is_empty())
122 }
123
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(
127             llfn,
128             llvm::AttributePlace::Function,
129             const_cstr!("target-cpu"),
130             target_cpu.as_c_str());
131 }
132
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);
139     }
140 }
141
142 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
143 /// attributes.
144 pub fn from_fn_attrs(
145     cx: &CodegenCx<'ll, 'tcx>,
146     llfn: &'ll Value,
147     id: Option<DefId>,
148     sig: PolyFnSig<'tcx>,
149 ) {
150     let codegen_fn_attrs = id.map(|id| cx.tcx.codegen_fn_attrs(id))
151         .unwrap_or_else(|| CodegenFnAttrs::new());
152
153     inline(cx, llfn, codegen_fn_attrs.inline);
154
155     // The `uwtable` attribute according to LLVM is:
156     //
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.
161     //
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.
168     //
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);
174     }
175
176     set_frame_pointer_elimination(cx, llfn);
177     set_probestack(cx, llfn);
178
179     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
180         Attribute::Cold.apply_llfn(Function, llfn);
181     }
182     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
183         naked(llfn, true);
184     }
185     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
186         Attribute::NoAlias.apply_llfn(
187             llvm::AttributePlace::ReturnValue, llfn);
188     }
189
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!
193         false
194     } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
195         // If a specific #[unwind] attribute is present, use that
196         true
197     } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
198         // Special attribute for allocator functions, which can't unwind
199         false
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
204             // unwind
205             false
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.
210             false
211         } else {
212             // Anything else defined in Rust is assumed that it can possibly
213             // unwind
214             true
215         }
216     } else {
217         // assume this can possibly unwind, avoiding the application of a
218         // `nounwind` attribute below.
219         true
220     });
221
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);
226
227     let features = llvm_target_features(cx.tcx.sess)
228         .map(|s| s.to_string())
229         .chain(
230             codegen_fn_attrs.target_features
231                 .iter()
232                 .map(|f| {
233                     let feature = &*f.as_str();
234                     format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
235                 })
236         )
237         .collect::<Vec<String>>()
238         .join(",");
239
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);
245     }
246
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(
254                     llfn,
255                     llvm::AttributePlace::Function,
256                     const_cstr!("wasm-import-module"),
257                     &module,
258                 );
259             }
260         }
261     }
262 }
263
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())))
272                 .collect())
273         } else {
274             Lrc::new(llvm_util::target_feature_whitelist(tcx.sess)
275                 .iter()
276                 .map(|&(a, b)| (a.to_string(), b.map(|s| s.to_string())))
277                 .collect())
278         }
279     };
280
281     provide_extern(providers);
282 }
283
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);
290
291         let def_id_to_native_lib = native_libs.iter().filter_map(|lib|
292             if let Some(id) = lib.foreign_module {
293                 Some((id, lib))
294             } else {
295                 None
296             }
297         ).collect::<FxHashMap<_, _>>();
298
299         let mut ret = FxHashMap::default();
300         for lib in tcx.foreign_modules(cnum).iter() {
301             let module = def_id_to_native_lib
302                 .get(&lib.def_id)
303                 .and_then(|s| s.wasm_import_module);
304             let module = match module {
305                 Some(s) => s,
306                 None => continue,
307             };
308             ret.extend(lib.foreign_items.iter().map(|id| {
309                 assert_eq!(id.krate, cnum);
310                 (*id, module.to_string())
311             }));
312         }
313
314         Lrc::new(ret)
315     };
316 }
317
318 fn wasm_import_module(tcx: TyCtxt, id: DefId) -> Option<CString> {
319     tcx.wasm_import_module_map(id.krate)
320         .get(&id)
321         .map(|s| CString::new(&s[..]).unwrap())
322 }