]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/attributes.rs
816242129f338e080b5061bfc424cf2f5e1c84b2
[rust.git] / src / librustc_codegen_llvm / attributes.rs
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.
4 //
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.
11
12 use std::ffi::CString;
13
14 use rustc::hir::CodegenFnAttrFlags;
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::query::Providers;
20 use rustc_data_structures::sync::Lrc;
21 use rustc_data_structures::fx::FxHashMap;
22 use rustc_target::spec::PanicStrategy;
23
24 use attributes;
25 use llvm::{self, Attribute};
26 use llvm::AttributePlace::Function;
27 use llvm_util;
28 pub use syntax::attr::{self, InlineAttr};
29
30 use context::CodegenCx;
31 use value::Value;
32
33 /// Mark LLVM function to use provided inline heuristic.
34 #[inline]
35 pub fn inline(val: &'ll Value, inline: InlineAttr) {
36     use self::InlineAttr::*;
37     match inline {
38         Hint   => Attribute::InlineHint.apply_llfn(Function, val),
39         Always => Attribute::AlwaysInline.apply_llfn(Function, val),
40         Never  => Attribute::NoInline.apply_llfn(Function, val),
41         None   => {
42             Attribute::InlineHint.unapply_llfn(Function, val);
43             Attribute::AlwaysInline.unapply_llfn(Function, val);
44             Attribute::NoInline.unapply_llfn(Function, val);
45         },
46     };
47 }
48
49 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
50 #[inline]
51 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
52     Attribute::UWTable.toggle_llfn(Function, val, emit);
53 }
54
55 /// Tell LLVM whether the function can or cannot unwind.
56 #[inline]
57 pub fn unwind(val: &'ll Value, can_unwind: bool) {
58     Attribute::NoUnwind.toggle_llfn(Function, val, !can_unwind);
59 }
60
61 /// Tell LLVM whether it should optimize function for size.
62 #[inline]
63 #[allow(dead_code)] // possibly useful function
64 pub fn set_optimize_for_size(val: &'ll Value, optimize: bool) {
65     Attribute::OptimizeForSize.toggle_llfn(Function, val, optimize);
66 }
67
68 /// Tell LLVM if this function should be 'naked', i.e. skip the epilogue and prologue.
69 #[inline]
70 pub fn naked(val: &'ll Value, is_naked: bool) {
71     Attribute::Naked.toggle_llfn(Function, val, is_naked);
72 }
73
74 pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
75     if cx.sess().must_not_eliminate_frame_pointers() {
76         llvm::AddFunctionAttrStringValue(
77             llfn, llvm::AttributePlace::Function,
78             const_cstr!("no-frame-pointer-elim"), const_cstr!("true"));
79     }
80 }
81
82 pub fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
83     // Only use stack probes if the target specification indicates that we
84     // should be using stack probes
85     if !cx.sess().target.target.options.stack_probes {
86         return
87     }
88
89     // Currently stack probes seem somewhat incompatible with the address
90     // sanitizer. With asan we're already protected from stack overflow anyway
91     // so we don't really need stack probes regardless.
92     match cx.sess().opts.debugging_opts.sanitizer {
93         Some(Sanitizer::Address) => return,
94         _ => {}
95     }
96
97     // probestack doesn't play nice either with pgo-gen.
98     if cx.sess().opts.debugging_opts.pgo_gen.is_some() {
99         return;
100     }
101
102     // probestack doesn't play nice either with gcov profiling.
103     if cx.sess().opts.debugging_opts.profile {
104         return;
105     }
106
107     // Flag our internal `__rust_probestack` function as the stack probe symbol.
108     // This is defined in the `compiler-builtins` crate for each architecture.
109     llvm::AddFunctionAttrStringValue(
110         llfn, llvm::AttributePlace::Function,
111         const_cstr!("probe-stack"), const_cstr!("__rust_probestack"));
112 }
113
114 pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
115     const RUSTC_SPECIFIC_FEATURES: &[&str] = &[
116         "crt-static",
117     ];
118
119     let cmdline = sess.opts.cg.target_feature.split(',')
120         .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
121     sess.target.target.options.features.split(',')
122         .chain(cmdline)
123         .filter(|l| !l.is_empty())
124 }
125
126 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
127     let target_cpu = CString::new(cx.tcx.sess.target_cpu().to_string()).unwrap();
128     llvm::AddFunctionAttrStringValue(
129             llfn,
130             llvm::AttributePlace::Function,
131             const_cstr!("target-cpu"),
132             target_cpu.as_c_str());
133 }
134
135 /// Composite function which sets LLVM attributes for function depending on its AST (#[attribute])
136 /// attributes.
137 pub fn from_fn_attrs(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value, id: DefId) {
138     let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(id);
139
140     inline(llfn, codegen_fn_attrs.inline);
141
142     set_frame_pointer_elimination(cx, llfn);
143     set_probestack(cx, llfn);
144
145     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
146         Attribute::Cold.apply_llfn(Function, llfn);
147     }
148     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
149         naked(llfn, true);
150     }
151     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
152         Attribute::NoAlias.apply_llfn(
153             llvm::AttributePlace::ReturnValue, llfn);
154     }
155
156     let can_unwind = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
157         Some(true)
158     } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
159         Some(false)
160
161     // Perhaps questionable, but we assume that anything defined
162     // *in Rust code* may unwind. Foreign items like `extern "C" {
163     // fn foo(); }` are assumed not to unwind **unless** they have
164     // a `#[unwind]` attribute.
165     } else if !cx.tcx.is_foreign_item(id) {
166         Some(true)
167     } else {
168         None
169     };
170
171     match can_unwind {
172         Some(false) => attributes::unwind(llfn, false),
173         Some(true) if cx.tcx.sess.panic_strategy() == PanicStrategy::Unwind => {
174             attributes::unwind(llfn, true);
175         }
176         Some(true) | None => {}
177     }
178
179     // Always annotate functions with the target-cpu they are compiled for.
180     // Without this, ThinLTO won't inline Rust functions into Clang generated
181     // functions (because Clang annotates functions this way too).
182     // NOTE: For now we just apply this if -Zcross-lang-lto is specified, since
183     //       it introduce a little overhead and isn't really necessary otherwise.
184     if cx.tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() {
185         apply_target_cpu_attr(cx, llfn);
186     }
187
188     let features = llvm_target_features(cx.tcx.sess)
189         .map(|s| s.to_string())
190         .chain(
191             codegen_fn_attrs.target_features
192                 .iter()
193                 .map(|f| {
194                     let feature = &*f.as_str();
195                     format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
196                 })
197         )
198         .collect::<Vec<String>>()
199         .join(",");
200
201     if !features.is_empty() {
202         let val = CString::new(features).unwrap();
203         llvm::AddFunctionAttrStringValue(
204             llfn, llvm::AttributePlace::Function,
205             const_cstr!("target-features"), &val);
206     }
207
208     // Note that currently the `wasm-import-module` doesn't do anything, but
209     // eventually LLVM 7 should read this and ferry the appropriate import
210     // module to the output file.
211     if cx.tcx.sess.target.target.arch == "wasm32" {
212         if let Some(module) = wasm_import_module(cx.tcx, id) {
213             llvm::AddFunctionAttrStringValue(
214                 llfn,
215                 llvm::AttributePlace::Function,
216                 const_cstr!("wasm-import-module"),
217                 &module,
218             );
219         }
220     }
221 }
222
223 pub fn provide(providers: &mut Providers) {
224     providers.target_features_whitelist = |tcx, cnum| {
225         assert_eq!(cnum, LOCAL_CRATE);
226         if tcx.sess.opts.actually_rustdoc {
227             // rustdoc needs to be able to document functions that use all the features, so
228             // whitelist them all
229             Lrc::new(llvm_util::all_known_features()
230                 .map(|(a, b)| (a.to_string(), b.map(|s| s.to_string())))
231                 .collect())
232         } else {
233             Lrc::new(llvm_util::target_feature_whitelist(tcx.sess)
234                 .iter()
235                 .map(|&(a, b)| (a.to_string(), b.map(|s| s.to_string())))
236                 .collect())
237         }
238     };
239
240     provide_extern(providers);
241 }
242
243 pub fn provide_extern(providers: &mut Providers) {
244     providers.wasm_import_module_map = |tcx, cnum| {
245         // Build up a map from DefId to a `NativeLibrary` structure, where
246         // `NativeLibrary` internally contains information about
247         // `#[link(wasm_import_module = "...")]` for example.
248         let native_libs = tcx.native_libraries(cnum);
249         let mut def_id_to_native_lib = FxHashMap();
250         for lib in native_libs.iter() {
251             if let Some(id) = lib.foreign_module {
252                 def_id_to_native_lib.insert(id, lib);
253             }
254         }
255
256         let mut ret = FxHashMap();
257         for lib in tcx.foreign_modules(cnum).iter() {
258             let module = def_id_to_native_lib
259                 .get(&lib.def_id)
260                 .and_then(|s| s.wasm_import_module);
261             let module = match module {
262                 Some(s) => s,
263                 None => continue,
264             };
265             for id in lib.foreign_items.iter() {
266                 assert_eq!(id.krate, cnum);
267                 ret.insert(*id, module.to_string());
268             }
269         }
270
271         Lrc::new(ret)
272     };
273 }
274
275 fn wasm_import_module(tcx: TyCtxt, id: DefId) -> Option<CString> {
276     tcx.wasm_import_module_map(id.krate)
277         .get(&id)
278         .map(|s| CString::new(&s[..]).unwrap())
279 }