attributes.rs 11.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Set and unset common attributes on LLVM values.

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::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;
24
use interfaces::*;
25

26
use attributes;
27
use llvm::{self, Attribute};
A
Ariel Ben-Yehuda 已提交
28
use llvm::AttributePlace::Function;
29
use llvm_util;
30
pub use syntax::attr::{self, InlineAttr};
31

32
use context::CodegenCx;
33
use value::Value;
34 35 36

/// Mark LLVM function to use provided inline heuristic.
#[inline]
37
pub fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) {
38
    use self::InlineAttr::*;
39
    match inline {
A
Ariel Ben-Yehuda 已提交
40 41
        Hint   => Attribute::InlineHint.apply_llfn(Function, val),
        Always => Attribute::AlwaysInline.apply_llfn(Function, val),
42 43 44 45 46
        Never  => {
            if cx.tcx().sess.target.target.arch != "amdgpu" {
                Attribute::NoInline.apply_llfn(Function, val);
            }
        },
47
        None   => {
48 49 50
            Attribute::InlineHint.unapply_llfn(Function, val);
            Attribute::AlwaysInline.unapply_llfn(Function, val);
            Attribute::NoInline.unapply_llfn(Function, val);
51 52 53 54 55 56
        },
    };
}

/// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
#[inline]
57
pub fn emit_uwtable(val: &'ll Value, emit: bool) {
A
Ariel Ben-Yehuda 已提交
58
    Attribute::UWTable.toggle_llfn(Function, val, emit);
59 60 61 62
}

/// Tell LLVM whether the function can or cannot unwind.
#[inline]
63
pub fn unwind(val: &'ll Value, can_unwind: bool) {
A
Ariel Ben-Yehuda 已提交
64
    Attribute::NoUnwind.toggle_llfn(Function, val, !can_unwind);
65 66
}

F
Fourchaux 已提交
67
/// Tell LLVM whether it should optimize function for size.
68 69
#[inline]
#[allow(dead_code)] // possibly useful function
70
pub fn set_optimize_for_size(val: &'ll Value, optimize: bool) {
A
Ariel Ben-Yehuda 已提交
71
    Attribute::OptimizeForSize.toggle_llfn(Function, val, optimize);
72 73
}

T
Ticki 已提交
74 75
/// Tell LLVM if this function should be 'naked', i.e. skip the epilogue and prologue.
#[inline]
76
pub fn naked(val: &'ll Value, is_naked: bool) {
A
Ariel Ben-Yehuda 已提交
77
    Attribute::Naked.toggle_llfn(Function, val, is_naked);
T
Ticki 已提交
78 79
}

80
pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
81
    if cx.sess().must_not_eliminate_frame_pointers() {
A
Ariel Ben-Yehuda 已提交
82
        llvm::AddFunctionAttrStringValue(
83
            llfn, llvm::AttributePlace::Function,
84
            const_cstr!("no-frame-pointer-elim"), const_cstr!("true"));
A
Alex Crichton 已提交
85
    }
86 87
}

88
pub fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
89 90
    // Only use stack probes if the target specification indicates that we
    // should be using stack probes
91
    if !cx.sess().target.target.options.stack_probes {
92 93 94 95 96 97
        return
    }

    // Currently stack probes seem somewhat incompatible with the address
    // sanitizer. With asan we're already protected from stack overflow anyway
    // so we don't really need stack probes regardless.
L
ljedrz 已提交
98 99
    if let Some(Sanitizer::Address) = cx.sess().opts.debugging_opts.sanitizer {
        return
100 101
    }

102
    // probestack doesn't play nice either with pgo-gen.
103
    if cx.sess().opts.debugging_opts.pgo_gen.is_some() {
104 105 106
        return;
    }

107 108 109 110 111
    // probestack doesn't play nice either with gcov profiling.
    if cx.sess().opts.debugging_opts.profile {
        return;
    }

112 113 114 115
    // Flag our internal `__rust_probestack` function as the stack probe symbol.
    // This is defined in the `compiler-builtins` crate for each architecture.
    llvm::AddFunctionAttrStringValue(
        llfn, llvm::AttributePlace::Function,
116
        const_cstr!("probe-stack"), const_cstr!("__rust_probestack"));
117 118
}

119 120 121 122 123 124 125 126 127 128 129 130
pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
    const RUSTC_SPECIFIC_FEATURES: &[&str] = &[
        "crt-static",
    ];

    let cmdline = sess.opts.cg.target_feature.split(',')
        .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
    sess.target.target.options.features.split(',')
        .chain(cmdline)
        .filter(|l| !l.is_empty())
}

131
pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
132 133
    let cpu = llvm_util::target_cpu(cx.tcx.sess);
    let target_cpu = CString::new(cpu).unwrap();
134 135 136
    llvm::AddFunctionAttrStringValue(
            llfn,
            llvm::AttributePlace::Function,
137
            const_cstr!("target-cpu"),
138 139 140
            target_cpu.as_c_str());
}

141 142 143 144 145 146 147 148 149
/// Sets the `NonLazyBind` LLVM attribute on a given function,
/// assuming the codegen options allow skipping the PLT.
pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
    // Don't generate calls through PLT if it's not necessary
    if !sess.needs_plt() {
        Attribute::NonLazyBind.apply_llfn(Function, llfn);
    }
}

150 151
/// Composite function which sets LLVM attributes for function depending on its AST (#[attribute])
/// attributes.
152 153 154 155 156 157
pub fn from_fn_attrs(
    cx: &CodegenCx<'ll, '_>,
    llfn: &'ll Value,
    id: Option<DefId>,
) {
    let codegen_fn_attrs = id.map(|id| cx.tcx.codegen_fn_attrs(id))
158
        .unwrap_or_else(|| CodegenFnAttrs::new());
W
Wesley Wiser 已提交
159

160
    inline(cx, llfn, codegen_fn_attrs.inline);
161

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    // The `uwtable` attribute according to LLVM is:
    //
    //     This attribute indicates that the ABI being targeted requires that an
    //     unwind table entry be produced for this function even if we can show
    //     that no exceptions passes by it. This is normally the case for the
    //     ELF x86-64 abi, but it can be disabled for some compilation units.
    //
    // Typically when we're compiling with `-C panic=abort` (which implies this
    // `no_landing_pads` check) we don't need `uwtable` because we can't
    // generate any exceptions! On Windows, however, exceptions include other
    // events such as illegal instructions, segfaults, etc. This means that on
    // Windows we end up still needing the `uwtable` attribute even if the `-C
    // panic=abort` flag is passed.
    //
    // You can also find more info on why Windows is whitelisted here in:
    //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
    if !cx.sess().no_landing_pads() ||
       cx.sess().target.target.options.requires_uwtable {
        attributes::emit_uwtable(llfn, true);
    }

183 184
    set_frame_pointer_elimination(cx, llfn);
    set_probestack(cx, llfn);
185

I
Irina Popa 已提交
186
    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
W
Wesley Wiser 已提交
187 188
        Attribute::Cold.apply_llfn(Function, llfn);
    }
I
Irina Popa 已提交
189
    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
W
Wesley Wiser 已提交
190 191
        naked(llfn, true);
    }
I
Irina Popa 已提交
192
    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
W
Wesley Wiser 已提交
193 194 195
        Attribute::NoAlias.apply_llfn(
            llvm::AttributePlace::ReturnValue, llfn);
    }
196 197 198 199 200 201 202 203 204 205

    let can_unwind = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
        Some(true)
    } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
        Some(false)

    // Perhaps questionable, but we assume that anything defined
    // *in Rust code* may unwind. Foreign items like `extern "C" {
    // fn foo(); }` are assumed not to unwind **unless** they have
    // a `#[unwind]` attribute.
206
    } else if id.map(|id| !cx.tcx.is_foreign_item(id)).unwrap_or(false) {
207 208 209 210 211 212 213 214 215 216 217
        Some(true)
    } else {
        None
    };

    match can_unwind {
        Some(false) => attributes::unwind(llfn, false),
        Some(true) if cx.tcx.sess.panic_strategy() == PanicStrategy::Unwind => {
            attributes::unwind(llfn, true);
        }
        Some(true) | None => {}
218
    }
219

220 221 222 223 224 225 226 227 228
    // Always annotate functions with the target-cpu they are compiled for.
    // Without this, ThinLTO won't inline Rust functions into Clang generated
    // functions (because Clang annotates functions this way too).
    // NOTE: For now we just apply this if -Zcross-lang-lto is specified, since
    //       it introduce a little overhead and isn't really necessary otherwise.
    if cx.tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() {
        apply_target_cpu_attr(cx, llfn);
    }

229 230 231
    let features = llvm_target_features(cx.tcx.sess)
        .map(|s| s.to_string())
        .chain(
I
Irina Popa 已提交
232
            codegen_fn_attrs.target_features
233 234 235 236 237 238
                .iter()
                .map(|f| {
                    let feature = &*f.as_str();
                    format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
                })
        )
239 240 241 242 243
        .collect::<Vec<String>>()
        .join(",");

    if !features.is_empty() {
        let val = CString::new(features).unwrap();
244 245
        llvm::AddFunctionAttrStringValue(
            llfn, llvm::AttributePlace::Function,
246
            const_cstr!("target-features"), &val);
247
    }
248 249 250 251

    // Note that currently the `wasm-import-module` doesn't do anything, but
    // eventually LLVM 7 should read this and ferry the appropriate import
    // module to the output file.
252 253 254 255 256 257 258 259 260 261
    if let Some(id) = id {
        if cx.tcx.sess.target.target.arch == "wasm32" {
            if let Some(module) = wasm_import_module(cx.tcx, id) {
                llvm::AddFunctionAttrStringValue(
                    llfn,
                    llvm::AttributePlace::Function,
                    const_cstr!("wasm-import-module"),
                    &module,
                );
            }
262 263
        }
    }
264 265
}

266 267 268
pub fn provide(providers: &mut Providers) {
    providers.target_features_whitelist = |tcx, cnum| {
        assert_eq!(cnum, LOCAL_CRATE);
269 270 271 272
        if tcx.sess.opts.actually_rustdoc {
            // rustdoc needs to be able to document functions that use all the features, so
            // whitelist them all
            Lrc::new(llvm_util::all_known_features()
273
                .map(|(a, b)| (a.to_string(), b.map(|s| s.to_string())))
274 275 276 277
                .collect())
        } else {
            Lrc::new(llvm_util::target_feature_whitelist(tcx.sess)
                .iter()
278
                .map(|&(a, b)| (a.to_string(), b.map(|s| s.to_string())))
279 280
                .collect())
        }
281
    };
282

283
    provide_extern(providers);
284 285
}

286 287
pub fn provide_extern(providers: &mut Providers) {
    providers.wasm_import_module_map = |tcx, cnum| {
288 289 290 291
        // Build up a map from DefId to a `NativeLibrary` structure, where
        // `NativeLibrary` internally contains information about
        // `#[link(wasm_import_module = "...")]` for example.
        let native_libs = tcx.native_libraries(cnum);
L
ljedrz 已提交
292 293

        let def_id_to_native_lib = native_libs.iter().filter_map(|lib|
294
            if let Some(id) = lib.foreign_module {
L
ljedrz 已提交
295 296 297
                Some((id, lib))
            } else {
                None
298
            }
L
ljedrz 已提交
299
        ).collect::<FxHashMap<_, _>>();
300

301
        let mut ret = FxHashMap::default();
302
        for lib in tcx.foreign_modules(cnum).iter() {
303 304 305
            let module = def_id_to_native_lib
                .get(&lib.def_id)
                .and_then(|s| s.wasm_import_module);
306 307 308 309
            let module = match module {
                Some(s) => s,
                None => continue,
            };
L
ljedrz 已提交
310
            ret.extend(lib.foreign_items.iter().map(|id| {
311
                assert_eq!(id.krate, cnum);
L
ljedrz 已提交
312 313
                (*id, module.to_string())
            }));
314 315 316
        }

        Lrc::new(ret)
317
    };
318 319 320 321 322 323 324
}

fn wasm_import_module(tcx: TyCtxt, id: DefId) -> Option<CString> {
    tcx.wasm_import_module_map(id.krate)
        .get(&id)
        .map(|s| CString::new(&s[..]).unwrap())
}