]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/attributes.rs
Fix handling of wasm import modules and names
[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;
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, Ty};
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::fx::FxHashMap;
14 use rustc_target::abi::call::Conv;
15 use rustc_target::spec::PanicStrategy;
16 use rustc_codegen_ssa::traits::*;
17
18 use crate::abi::FnAbi;
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 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 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 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 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 and thread sanitizer. With asan we're already protected from
101     // stack overflow anyway so we don't really need stack probes regardless.
102     match cx.sess().opts.debugging_opts.sanitizer {
103         Some(Sanitizer::Address) |
104         Some(Sanitizer::Thread) => return,
105         _ => {},
106     }
107
108     // probestack doesn't play nice either with `-C profile-generate`.
109     if cx.sess().opts.cg.profile_generate.enabled() {
110         return;
111     }
112
113     // probestack doesn't play nice either with gcov profiling.
114     if cx.sess().opts.debugging_opts.profile {
115         return;
116     }
117
118     // Flag our internal `__rust_probestack` function as the stack probe symbol.
119     // This is defined in the `compiler-builtins` crate for each architecture.
120     llvm::AddFunctionAttrStringValue(
121         llfn, llvm::AttributePlace::Function,
122         const_cstr!("probe-stack"), const_cstr!("__rust_probestack"));
123 }
124
125 fn translate_obsolete_target_features(feature: &str) -> &str {
126     const LLVM9_FEATURE_CHANGES: &[(&str, &str)] = &[
127         ("+fp-only-sp", "-fp64"),
128         ("-fp-only-sp", "+fp64"),
129         ("+d16", "-d32"),
130         ("-d16", "+d32"),
131     ];
132     if llvm_util::get_major_version() >= 9 {
133         for &(old, new) in LLVM9_FEATURE_CHANGES {
134             if feature == old {
135                 return new;
136             }
137         }
138     } else {
139         for &(old, new) in LLVM9_FEATURE_CHANGES {
140             if feature == new {
141                 return old;
142             }
143         }
144     }
145     feature
146 }
147
148 pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
149     const RUSTC_SPECIFIC_FEATURES: &[&str] = &[
150         "crt-static",
151     ];
152
153     let cmdline = sess.opts.cg.target_feature.split(',')
154         .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
155     sess.target.target.options.features.split(',')
156         .chain(cmdline)
157         .filter(|l| !l.is_empty())
158         .map(translate_obsolete_target_features)
159 }
160
161 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
162     let target_cpu = SmallCStr::new(llvm_util::target_cpu(cx.tcx.sess));
163     llvm::AddFunctionAttrStringValue(
164             llfn,
165             llvm::AttributePlace::Function,
166             const_cstr!("target-cpu"),
167             target_cpu.as_c_str());
168 }
169
170 /// Sets the `NonLazyBind` LLVM attribute on a given function,
171 /// assuming the codegen options allow skipping the PLT.
172 pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
173     // Don't generate calls through PLT if it's not necessary
174     if !sess.needs_plt() {
175         Attribute::NonLazyBind.apply_llfn(Function, llfn);
176     }
177 }
178
179 pub(crate) fn default_optimisation_attrs(sess: &Session, llfn: &'ll Value) {
180     match sess.opts.optimize {
181         OptLevel::Size => {
182             llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
183             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
184             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
185         },
186         OptLevel::SizeMin => {
187             llvm::Attribute::MinSize.apply_llfn(Function, llfn);
188             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
189             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
190         }
191         OptLevel::No => {
192             llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
193             llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
194             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
195         }
196         _ => {}
197     }
198 }
199
200
201 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
202 /// attributes.
203 pub fn from_fn_attrs(
204     cx: &CodegenCx<'ll, 'tcx>,
205     llfn: &'ll Value,
206     instance: ty::Instance<'tcx>,
207     fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
208 ) {
209     let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(instance.def_id());
210
211     match codegen_fn_attrs.optimize {
212         OptimizeAttr::None => {
213             default_optimisation_attrs(cx.tcx.sess, llfn);
214         }
215         OptimizeAttr::Speed => {
216             llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
217             llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
218             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
219         }
220         OptimizeAttr::Size => {
221             llvm::Attribute::MinSize.apply_llfn(Function, llfn);
222             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
223             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
224         }
225     }
226
227     // FIXME(eddyb) consolidate these two `inline` calls (and avoid overwrites).
228     if instance.def.is_inline(cx.tcx) {
229         inline(cx, llfn, attributes::InlineAttr::Hint);
230     }
231
232     inline(cx, llfn, codegen_fn_attrs.inline);
233
234     // The `uwtable` attribute according to LLVM is:
235     //
236     //     This attribute indicates that the ABI being targeted requires that an
237     //     unwind table entry be produced for this function even if we can show
238     //     that no exceptions passes by it. This is normally the case for the
239     //     ELF x86-64 abi, but it can be disabled for some compilation units.
240     //
241     // Typically when we're compiling with `-C panic=abort` (which implies this
242     // `no_landing_pads` check) we don't need `uwtable` because we can't
243     // generate any exceptions! On Windows, however, exceptions include other
244     // events such as illegal instructions, segfaults, etc. This means that on
245     // Windows we end up still needing the `uwtable` attribute even if the `-C
246     // panic=abort` flag is passed.
247     //
248     // You can also find more info on why Windows is whitelisted here in:
249     //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
250     if !cx.sess().no_landing_pads() ||
251        cx.sess().target.target.options.requires_uwtable {
252         attributes::emit_uwtable(llfn, true);
253     }
254
255     set_frame_pointer_elimination(cx, llfn);
256     set_instrument_function(cx, llfn);
257     set_probestack(cx, llfn);
258
259     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
260         Attribute::Cold.apply_llfn(Function, llfn);
261     }
262     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_RETURNS_TWICE) {
263         Attribute::ReturnsTwice.apply_llfn(Function, llfn);
264     }
265     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
266         naked(llfn, true);
267     }
268     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
269         Attribute::NoAlias.apply_llfn(
270             llvm::AttributePlace::ReturnValue, llfn);
271     }
272
273     unwind(llfn, if cx.tcx.sess.panic_strategy() != PanicStrategy::Unwind {
274         // In panic=abort mode we assume nothing can unwind anywhere, so
275         // optimize based on this!
276         false
277     } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
278         // If a specific #[unwind] attribute is present, use that.
279         true
280     } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
281         // Special attribute for allocator functions, which can't unwind.
282         false
283     } else {
284         if fn_abi.conv == Conv::Rust {
285             // Any Rust method (or `extern "Rust" fn` or `extern
286             // "rust-call" fn`) is explicitly allowed to unwind
287             // (unless it has no-unwind attribute, handled above).
288             true
289         } else {
290             // Anything else is either:
291             //
292             //  1. A foreign item using a non-Rust ABI (like `extern "C" { fn foo(); }`), or
293             //
294             //  2. A Rust item using a non-Rust ABI (like `extern "C" fn foo() { ... }`).
295             //
296             // Foreign items (case 1) are assumed to not unwind; it is
297             // UB otherwise. (At least for now; see also
298             // rust-lang/rust#63909 and Rust RFC 2753.)
299             //
300             // Items defined in Rust with non-Rust ABIs (case 2) are also
301             // not supposed to unwind. Whether this should be enforced
302             // (versus stating it is UB) and *how* it would be enforced
303             // is currently under discussion; see rust-lang/rust#58794.
304             //
305             // In either case, we mark item as explicitly nounwind.
306             false
307         }
308     });
309
310     // Always annotate functions with the target-cpu they are compiled for.
311     // Without this, ThinLTO won't inline Rust functions into Clang generated
312     // functions (because Clang annotates functions this way too).
313     apply_target_cpu_attr(cx, llfn);
314
315     let features = llvm_target_features(cx.tcx.sess)
316         .map(|s| s.to_string())
317         .chain(
318             codegen_fn_attrs.target_features
319                 .iter()
320                 .map(|f| {
321                     let feature = &f.as_str();
322                     format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
323                 })
324         )
325         .collect::<Vec<String>>()
326         .join(",");
327
328     if !features.is_empty() {
329         let val = CString::new(features).unwrap();
330         llvm::AddFunctionAttrStringValue(
331             llfn, llvm::AttributePlace::Function,
332             const_cstr!("target-features"), &val);
333     }
334
335     // Note that currently the `wasm-import-module` doesn't do anything, but
336     // eventually LLVM 7 should read this and ferry the appropriate import
337     // module to the output file.
338     if cx.tcx.sess.target.target.arch == "wasm32" {
339         if let Some(module) = wasm_import_module(cx.tcx, instance.def_id()) {
340             llvm::AddFunctionAttrStringValue(
341                 llfn,
342                 llvm::AttributePlace::Function,
343                 const_cstr!("wasm-import-module"),
344                 &module,
345             );
346
347             let name = codegen_fn_attrs.link_name.unwrap_or_else(|| {
348                 cx.tcx.item_name(instance.def_id())
349             });
350             let name = CString::new(&name.as_str()[..]).unwrap();
351             llvm::AddFunctionAttrStringValue(
352                 llfn,
353                 llvm::AttributePlace::Function,
354                 const_cstr!("wasm-import-name"),
355                 &name,
356             );
357         }
358     }
359 }
360
361 pub fn provide(providers: &mut Providers<'_>) {
362     providers.target_features_whitelist = |tcx, cnum| {
363         assert_eq!(cnum, LOCAL_CRATE);
364         if tcx.sess.opts.actually_rustdoc {
365             // rustdoc needs to be able to document functions that use all the features, so
366             // whitelist them all
367             tcx.arena.alloc(llvm_util::all_known_features()
368                 .map(|(a, b)| (a.to_string(), b))
369                 .collect())
370         } else {
371             tcx.arena.alloc(llvm_util::target_feature_whitelist(tcx.sess)
372                 .iter()
373                 .map(|&(a, b)| (a.to_string(), b))
374                 .collect())
375         }
376     };
377
378     provide_extern(providers);
379 }
380
381 pub fn provide_extern(providers: &mut Providers<'_>) {
382     providers.wasm_import_module_map = |tcx, cnum| {
383         // Build up a map from DefId to a `NativeLibrary` structure, where
384         // `NativeLibrary` internally contains information about
385         // `#[link(wasm_import_module = "...")]` for example.
386         let native_libs = tcx.native_libraries(cnum);
387
388         let def_id_to_native_lib = native_libs.iter().filter_map(|lib|
389             lib.foreign_module.map(|id| (id, lib))
390         ).collect::<FxHashMap<_, _>>();
391
392         let mut ret = FxHashMap::default();
393         for lib in tcx.foreign_modules(cnum).iter() {
394             let module = def_id_to_native_lib
395                 .get(&lib.def_id)
396                 .and_then(|s| s.wasm_import_module);
397             let module = match module {
398                 Some(s) => s,
399                 None => continue,
400             };
401             ret.extend(lib.foreign_items.iter().map(|id| {
402                 assert_eq!(id.krate, cnum);
403                 (*id, module.to_string())
404             }));
405         }
406
407         tcx.arena.alloc(ret)
408     };
409 }
410
411 fn wasm_import_module(tcx: TyCtxt<'_>, id: DefId) -> Option<CString> {
412     tcx.wasm_import_module_map(id.krate)
413         .get(&id)
414         .map(|s| CString::new(&s[..]).unwrap())
415 }