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.
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.
12 use std::ffi::CString;
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::TyCtxt;
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;
26 use llvm::{self, Attribute};
27 use llvm::AttributePlace::Function;
29 pub use syntax::attr::{self, InlineAttr};
31 use context::CodegenCx;
34 /// Mark LLVM function to use provided inline heuristic.
36 pub fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) {
37 use self::InlineAttr::*;
39 Hint => Attribute::InlineHint.apply_llfn(Function, val),
40 Always => Attribute::AlwaysInline.apply_llfn(Function, val),
42 if cx.tcx().sess.target.target.arch != "amdgpu" {
43 Attribute::NoInline.apply_llfn(Function, val);
47 Attribute::InlineHint.unapply_llfn(Function, val);
48 Attribute::AlwaysInline.unapply_llfn(Function, val);
49 Attribute::NoInline.unapply_llfn(Function, val);
54 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
56 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
57 Attribute::UWTable.toggle_llfn(Function, val, emit);
60 /// Tell LLVM whether the function can or cannot unwind.
62 pub fn unwind(val: &'ll Value, can_unwind: bool) {
63 Attribute::NoUnwind.toggle_llfn(Function, val, !can_unwind);
66 /// Tell LLVM whether it should optimize function for size.
68 #[allow(dead_code)] // possibly useful function
69 pub fn set_optimize_for_size(val: &'ll Value, optimize: bool) {
70 Attribute::OptimizeForSize.toggle_llfn(Function, val, optimize);
73 /// Tell LLVM if this function should be 'naked', i.e. skip the epilogue and prologue.
75 pub fn naked(val: &'ll Value, is_naked: bool) {
76 Attribute::Naked.toggle_llfn(Function, val, is_naked);
79 pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
80 if cx.sess().must_not_eliminate_frame_pointers() {
81 llvm::AddFunctionAttrStringValue(
82 llfn, llvm::AttributePlace::Function,
83 const_cstr!("no-frame-pointer-elim"), const_cstr!("true"));
87 pub fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
88 // Only use stack probes if the target specification indicates that we
89 // should be using stack probes
90 if !cx.sess().target.target.options.stack_probes {
94 // Currently stack probes seem somewhat incompatible with the address
95 // sanitizer. With asan we're already protected from stack overflow anyway
96 // so we don't really need stack probes regardless.
97 if let Some(Sanitizer::Address) = cx.sess().opts.debugging_opts.sanitizer {
101 // probestack doesn't play nice either with pgo-gen.
102 if cx.sess().opts.debugging_opts.pgo_gen.is_some() {
106 // probestack doesn't play nice either with gcov profiling.
107 if cx.sess().opts.debugging_opts.profile {
111 // Flag our internal `__rust_probestack` function as the stack probe symbol.
112 // This is defined in the `compiler-builtins` crate for each architecture.
113 llvm::AddFunctionAttrStringValue(
114 llfn, llvm::AttributePlace::Function,
115 const_cstr!("probe-stack"), const_cstr!("__rust_probestack"));
118 pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
119 const RUSTC_SPECIFIC_FEATURES: &[&str] = &[
123 let cmdline = sess.opts.cg.target_feature.split(',')
124 .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
125 sess.target.target.options.features.split(',')
127 .filter(|l| !l.is_empty())
130 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_, &'ll Value>, llfn: &'ll Value) {
131 let cpu = llvm_util::target_cpu(cx.tcx.sess);
132 let target_cpu = CString::new(cpu).unwrap();
133 llvm::AddFunctionAttrStringValue(
135 llvm::AttributePlace::Function,
136 const_cstr!("target-cpu"),
137 target_cpu.as_c_str());
140 /// Sets the `NonLazyBind` LLVM attribute on a given function,
141 /// assuming the codegen options allow skipping the PLT.
142 pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
143 // Don't generate calls through PLT if it's not necessary
144 if !sess.needs_plt() {
145 Attribute::NonLazyBind.apply_llfn(Function, llfn);
149 /// Composite function which sets LLVM attributes for function depending on its AST (#[attribute])
151 pub fn from_fn_attrs(
152 cx: &CodegenCx<'ll, '_>,
156 let codegen_fn_attrs = id.map(|id| cx.tcx.codegen_fn_attrs(id))
157 .unwrap_or_else(|| CodegenFnAttrs::new());
159 inline(cx, llfn, codegen_fn_attrs.inline);
161 // The `uwtable` attribute according to LLVM is:
163 // This attribute indicates that the ABI being targeted requires that an
164 // unwind table entry be produced for this function even if we can show
165 // that no exceptions passes by it. This is normally the case for the
166 // ELF x86-64 abi, but it can be disabled for some compilation units.
168 // Typically when we're compiling with `-C panic=abort` (which implies this
169 // `no_landing_pads` check) we don't need `uwtable` because we can't
170 // generate any exceptions! On Windows, however, exceptions include other
171 // events such as illegal instructions, segfaults, etc. This means that on
172 // Windows we end up still needing the `uwtable` attribute even if the `-C
173 // panic=abort` flag is passed.
175 // You can also find more info on why Windows is whitelisted here in:
176 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
177 if !cx.sess().no_landing_pads() ||
178 cx.sess().target.target.options.requires_uwtable {
179 attributes::emit_uwtable(llfn, true);
182 set_frame_pointer_elimination(cx, llfn);
183 set_probestack(cx, llfn);
185 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
186 Attribute::Cold.apply_llfn(Function, llfn);
188 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
191 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
192 Attribute::NoAlias.apply_llfn(
193 llvm::AttributePlace::ReturnValue, llfn);
196 let can_unwind = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
198 } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
201 // Perhaps questionable, but we assume that anything defined
202 // *in Rust code* may unwind. Foreign items like `extern "C" {
203 // fn foo(); }` are assumed not to unwind **unless** they have
204 // a `#[unwind]` attribute.
205 } else if id.map(|id| !cx.tcx.is_foreign_item(id)).unwrap_or(false) {
212 Some(false) => attributes::unwind(llfn, false),
213 Some(true) if cx.tcx.sess.panic_strategy() == PanicStrategy::Unwind => {
214 attributes::unwind(llfn, true);
216 Some(true) | None => {}
219 // Always annotate functions with the target-cpu they are compiled for.
220 // Without this, ThinLTO won't inline Rust functions into Clang generated
221 // functions (because Clang annotates functions this way too).
222 // NOTE: For now we just apply this if -Zcross-lang-lto is specified, since
223 // it introduce a little overhead and isn't really necessary otherwise.
224 if cx.tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() {
225 apply_target_cpu_attr(cx, llfn);
228 let features = llvm_target_features(cx.tcx.sess)
229 .map(|s| s.to_string())
231 codegen_fn_attrs.target_features
234 let feature = &*f.as_str();
235 format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
238 .collect::<Vec<String>>()
241 if !features.is_empty() {
242 let val = CString::new(features).unwrap();
243 llvm::AddFunctionAttrStringValue(
244 llfn, llvm::AttributePlace::Function,
245 const_cstr!("target-features"), &val);
248 // Note that currently the `wasm-import-module` doesn't do anything, but
249 // eventually LLVM 7 should read this and ferry the appropriate import
250 // module to the output file.
251 if let Some(id) = id {
252 if cx.tcx.sess.target.target.arch == "wasm32" {
253 if let Some(module) = wasm_import_module(cx.tcx, id) {
254 llvm::AddFunctionAttrStringValue(
256 llvm::AttributePlace::Function,
257 const_cstr!("wasm-import-module"),
265 pub fn provide(providers: &mut Providers) {
266 providers.target_features_whitelist = |tcx, cnum| {
267 assert_eq!(cnum, LOCAL_CRATE);
268 if tcx.sess.opts.actually_rustdoc {
269 // rustdoc needs to be able to document functions that use all the features, so
270 // whitelist them all
271 Lrc::new(llvm_util::all_known_features()
272 .map(|(a, b)| (a.to_string(), b.map(|s| s.to_string())))
275 Lrc::new(llvm_util::target_feature_whitelist(tcx.sess)
277 .map(|&(a, b)| (a.to_string(), b.map(|s| s.to_string())))
282 provide_extern(providers);
285 pub fn provide_extern(providers: &mut Providers) {
286 providers.wasm_import_module_map = |tcx, cnum| {
287 // Build up a map from DefId to a `NativeLibrary` structure, where
288 // `NativeLibrary` internally contains information about
289 // `#[link(wasm_import_module = "...")]` for example.
290 let native_libs = tcx.native_libraries(cnum);
292 let def_id_to_native_lib = native_libs.iter().filter_map(|lib|
293 if let Some(id) = lib.foreign_module {
298 ).collect::<FxHashMap<_, _>>();
300 let mut ret = FxHashMap::default();
301 for lib in tcx.foreign_modules(cnum).iter() {
302 let module = def_id_to_native_lib
304 .and_then(|s| s.wasm_import_module);
305 let module = match module {
309 ret.extend(lib.foreign_items.iter().map(|id| {
310 assert_eq!(id.krate, cnum);
311 (*id, module.to_string())
319 fn wasm_import_module(tcx: TyCtxt, id: DefId) -> Option<CString> {
320 tcx.wasm_import_module_map(id.krate)
322 .map(|s| CString::new(&s[..]).unwrap())