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