]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/attributes.rs
rustc: Switch `extern` functions to abort by default on panic
[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, 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::{self, TyCtxt, PolyFnSig};
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::*;
25
26 use abi::Abi;
27 use attributes;
28 use llvm::{self, Attribute};
29 use llvm::AttributePlace::Function;
30 use llvm_util;
31 pub use syntax::attr::{self, InlineAttr};
32
33 use context::CodegenCx;
34 use value::Value;
35
36 /// Mark LLVM function to use provided inline heuristic.
37 #[inline]
38 pub fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) {
39     use self::InlineAttr::*;
40     match inline {
41         Hint   => Attribute::InlineHint.apply_llfn(Function, val),
42         Always => Attribute::AlwaysInline.apply_llfn(Function, val),
43         Never  => {
44             if cx.tcx().sess.target.target.arch != "amdgpu" {
45                 Attribute::NoInline.apply_llfn(Function, val);
46             }
47         },
48         None   => {
49             Attribute::InlineHint.unapply_llfn(Function, val);
50             Attribute::AlwaysInline.unapply_llfn(Function, val);
51             Attribute::NoInline.unapply_llfn(Function, val);
52         },
53     };
54 }
55
56 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
57 #[inline]
58 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
59     Attribute::UWTable.toggle_llfn(Function, val, emit);
60 }
61
62 /// Tell LLVM whether the function can or cannot unwind.
63 #[inline]
64 fn unwind(val: &'ll Value, can_unwind: bool) {
65     Attribute::NoUnwind.toggle_llfn(Function, val, !can_unwind);
66 }
67
68 /// Tell LLVM whether it should optimize function for size.
69 #[inline]
70 #[allow(dead_code)] // possibly useful function
71 pub fn set_optimize_for_size(val: &'ll Value, optimize: bool) {
72     Attribute::OptimizeForSize.toggle_llfn(Function, val, optimize);
73 }
74
75 /// Tell LLVM if this function should be 'naked', i.e., skip the epilogue and prologue.
76 #[inline]
77 pub fn naked(val: &'ll Value, is_naked: bool) {
78     Attribute::Naked.toggle_llfn(Function, val, is_naked);
79 }
80
81 pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
82     if cx.sess().must_not_eliminate_frame_pointers() {
83         llvm::AddFunctionAttrStringValue(
84             llfn, llvm::AttributePlace::Function,
85             const_cstr!("no-frame-pointer-elim"), const_cstr!("true"));
86     }
87 }
88
89 pub fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
90     // Only use stack probes if the target specification indicates that we
91     // should be using stack probes
92     if !cx.sess().target.target.options.stack_probes {
93         return
94     }
95
96     // Currently stack probes seem somewhat incompatible with the address
97     // sanitizer. With asan we're already protected from stack overflow anyway
98     // so we don't really need stack probes regardless.
99     if let Some(Sanitizer::Address) = cx.sess().opts.debugging_opts.sanitizer {
100         return
101     }
102
103     // probestack doesn't play nice either with pgo-gen.
104     if cx.sess().opts.debugging_opts.pgo_gen.is_some() {
105         return;
106     }
107
108     // probestack doesn't play nice either with gcov profiling.
109     if cx.sess().opts.debugging_opts.profile {
110         return;
111     }
112
113     // Flag our internal `__rust_probestack` function as the stack probe symbol.
114     // This is defined in the `compiler-builtins` crate for each architecture.
115     llvm::AddFunctionAttrStringValue(
116         llfn, llvm::AttributePlace::Function,
117         const_cstr!("probe-stack"), const_cstr!("__rust_probestack"));
118 }
119
120 pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
121     const RUSTC_SPECIFIC_FEATURES: &[&str] = &[
122         "crt-static",
123     ];
124
125     let cmdline = sess.opts.cg.target_feature.split(',')
126         .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
127     sess.target.target.options.features.split(',')
128         .chain(cmdline)
129         .filter(|l| !l.is_empty())
130 }
131
132 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
133     let cpu = llvm_util::target_cpu(cx.tcx.sess);
134     let target_cpu = CString::new(cpu).unwrap();
135     llvm::AddFunctionAttrStringValue(
136             llfn,
137             llvm::AttributePlace::Function,
138             const_cstr!("target-cpu"),
139             target_cpu.as_c_str());
140 }
141
142 /// Sets the `NonLazyBind` LLVM attribute on a given function,
143 /// assuming the codegen options allow skipping the PLT.
144 pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
145     // Don't generate calls through PLT if it's not necessary
146     if !sess.needs_plt() {
147         Attribute::NonLazyBind.apply_llfn(Function, llfn);
148     }
149 }
150
151 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
152 /// attributes.
153 pub fn from_fn_attrs(
154     cx: &CodegenCx<'ll, 'tcx>,
155     llfn: &'ll Value,
156     id: Option<DefId>,
157     sig: PolyFnSig<'tcx>,
158 ) {
159     let codegen_fn_attrs = id.map(|id| cx.tcx.codegen_fn_attrs(id))
160         .unwrap_or_else(|| CodegenFnAttrs::new());
161
162     inline(cx, llfn, codegen_fn_attrs.inline);
163
164     // The `uwtable` attribute according to LLVM is:
165     //
166     //     This attribute indicates that the ABI being targeted requires that an
167     //     unwind table entry be produced for this function even if we can show
168     //     that no exceptions passes by it. This is normally the case for the
169     //     ELF x86-64 abi, but it can be disabled for some compilation units.
170     //
171     // Typically when we're compiling with `-C panic=abort` (which implies this
172     // `no_landing_pads` check) we don't need `uwtable` because we can't
173     // generate any exceptions! On Windows, however, exceptions include other
174     // events such as illegal instructions, segfaults, etc. This means that on
175     // Windows we end up still needing the `uwtable` attribute even if the `-C
176     // panic=abort` flag is passed.
177     //
178     // You can also find more info on why Windows is whitelisted here in:
179     //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
180     if !cx.sess().no_landing_pads() ||
181        cx.sess().target.target.options.requires_uwtable {
182         attributes::emit_uwtable(llfn, true);
183     }
184
185     set_frame_pointer_elimination(cx, llfn);
186     set_probestack(cx, llfn);
187
188     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
189         Attribute::Cold.apply_llfn(Function, llfn);
190     }
191     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
192         naked(llfn, true);
193     }
194     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
195         Attribute::NoAlias.apply_llfn(
196             llvm::AttributePlace::ReturnValue, llfn);
197     }
198
199     unwind(llfn, if cx.tcx.sess.panic_strategy() != PanicStrategy::Unwind {
200         // In panic=abort mode we assume nothing can unwind anywhere, so
201         // optimize based on this!
202         false
203     } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
204         // If a specific #[unwind] attribute is present, use that
205         true
206     } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
207         // Special attribute for allocator functions, which can't unwind
208         false
209     } else if let Some(id) = id {
210         let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
211         if cx.tcx.is_foreign_item(id) {
212             // Foreign items like `extern "C" { fn foo(); }` are assumed not to
213             // unwind
214             false
215         } else if sig.abi != Abi::Rust && sig.abi != Abi::RustCall {
216             // Any items defined in Rust that *don't* have the `extern` ABI are
217             // defined to not unwind. We insert shims to abort if an unwind
218             // happens to enforce this.
219             false
220         } else {
221             // Anything else defined in Rust is assumed that it can possibly
222             // unwind
223             true
224         }
225     } else {
226         // assume this can possibly unwind, avoiding the application of a
227         // `nounwind` attribute below.
228         true
229     });
230
231     // Always annotate functions with the target-cpu they are compiled for.
232     // Without this, ThinLTO won't inline Rust functions into Clang generated
233     // functions (because Clang annotates functions this way too).
234     // NOTE: For now we just apply this if -Zcross-lang-lto is specified, since
235     //       it introduce a little overhead and isn't really necessary otherwise.
236     if cx.tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() {
237         apply_target_cpu_attr(cx, llfn);
238     }
239
240     let features = llvm_target_features(cx.tcx.sess)
241         .map(|s| s.to_string())
242         .chain(
243             codegen_fn_attrs.target_features
244                 .iter()
245                 .map(|f| {
246                     let feature = &*f.as_str();
247                     format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
248                 })
249         )
250         .collect::<Vec<String>>()
251         .join(",");
252
253     if !features.is_empty() {
254         let val = CString::new(features).unwrap();
255         llvm::AddFunctionAttrStringValue(
256             llfn, llvm::AttributePlace::Function,
257             const_cstr!("target-features"), &val);
258     }
259
260     // Note that currently the `wasm-import-module` doesn't do anything, but
261     // eventually LLVM 7 should read this and ferry the appropriate import
262     // module to the output file.
263     if let Some(id) = id {
264         if cx.tcx.sess.target.target.arch == "wasm32" {
265             if let Some(module) = wasm_import_module(cx.tcx, id) {
266                 llvm::AddFunctionAttrStringValue(
267                     llfn,
268                     llvm::AttributePlace::Function,
269                     const_cstr!("wasm-import-module"),
270                     &module,
271                 );
272             }
273         }
274     }
275 }
276
277 pub fn provide(providers: &mut Providers) {
278     providers.target_features_whitelist = |tcx, cnum| {
279         assert_eq!(cnum, LOCAL_CRATE);
280         if tcx.sess.opts.actually_rustdoc {
281             // rustdoc needs to be able to document functions that use all the features, so
282             // whitelist them all
283             Lrc::new(llvm_util::all_known_features()
284                 .map(|(a, b)| (a.to_string(), b.map(|s| s.to_string())))
285                 .collect())
286         } else {
287             Lrc::new(llvm_util::target_feature_whitelist(tcx.sess)
288                 .iter()
289                 .map(|&(a, b)| (a.to_string(), b.map(|s| s.to_string())))
290                 .collect())
291         }
292     };
293
294     provide_extern(providers);
295 }
296
297 pub fn provide_extern(providers: &mut Providers) {
298     providers.wasm_import_module_map = |tcx, cnum| {
299         // Build up a map from DefId to a `NativeLibrary` structure, where
300         // `NativeLibrary` internally contains information about
301         // `#[link(wasm_import_module = "...")]` for example.
302         let native_libs = tcx.native_libraries(cnum);
303
304         let def_id_to_native_lib = native_libs.iter().filter_map(|lib|
305             if let Some(id) = lib.foreign_module {
306                 Some((id, lib))
307             } else {
308                 None
309             }
310         ).collect::<FxHashMap<_, _>>();
311
312         let mut ret = FxHashMap::default();
313         for lib in tcx.foreign_modules(cnum).iter() {
314             let module = def_id_to_native_lib
315                 .get(&lib.def_id)
316                 .and_then(|s| s.wasm_import_module);
317             let module = match module {
318                 Some(s) => s,
319                 None => continue,
320             };
321             ret.extend(lib.foreign_items.iter().map(|id| {
322                 assert_eq!(id.krate, cnum);
323                 (*id, module.to_string())
324             }));
325         }
326
327         Lrc::new(ret)
328     };
329 }
330
331 fn wasm_import_module(tcx: TyCtxt, id: DefId) -> Option<CString> {
332     tcx.wasm_import_module_map(id.krate)
333         .get(&id)
334         .map(|s| CString::new(&s[..]).unwrap())
335 }