1 //! Set and unset common attributes on LLVM values.
5 use rustc_codegen_ssa::traits::*;
6 use rustc_data_structures::const_cstr;
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_data_structures::small_c_str::SmallCStr;
9 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
10 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
11 use rustc_middle::ty::layout::HasTyCtxt;
12 use rustc_middle::ty::query::Providers;
13 use rustc_middle::ty::{self, TyCtxt};
14 use rustc_session::config::{OptLevel, Sanitizer};
15 use rustc_session::Session;
17 use crate::attributes;
18 use crate::llvm::AttributePlace::Function;
19 use crate::llvm::{self, Attribute};
21 pub use rustc_attr::{InlineAttr, OptimizeAttr};
23 use crate::context::CodegenCx;
24 use crate::value::Value;
26 /// Mark LLVM function to use provided inline heuristic.
28 fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) {
29 use self::InlineAttr::*;
31 Hint => Attribute::InlineHint.apply_llfn(Function, val),
32 Always => Attribute::AlwaysInline.apply_llfn(Function, val),
34 if cx.tcx().sess.target.target.arch != "amdgpu" {
35 Attribute::NoInline.apply_llfn(Function, val);
39 Attribute::InlineHint.unapply_llfn(Function, val);
40 Attribute::AlwaysInline.unapply_llfn(Function, val);
41 Attribute::NoInline.unapply_llfn(Function, val);
46 /// Apply LLVM sanitize attributes.
48 pub fn sanitize(cx: &CodegenCx<'ll, '_>, codegen_fn_flags: CodegenFnAttrFlags, llfn: &'ll Value) {
49 if let Some(ref sanitizer) = cx.tcx.sess.opts.debugging_opts.sanitizer {
51 Sanitizer::Address => {
52 if !codegen_fn_flags.contains(CodegenFnAttrFlags::NO_SANITIZE_ADDRESS) {
53 llvm::Attribute::SanitizeAddress.apply_llfn(Function, llfn);
56 Sanitizer::Memory => {
57 if !codegen_fn_flags.contains(CodegenFnAttrFlags::NO_SANITIZE_MEMORY) {
58 llvm::Attribute::SanitizeMemory.apply_llfn(Function, llfn);
61 Sanitizer::Thread => {
62 if !codegen_fn_flags.contains(CodegenFnAttrFlags::NO_SANITIZE_THREAD) {
63 llvm::Attribute::SanitizeThread.apply_llfn(Function, llfn);
71 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
73 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
74 Attribute::UWTable.toggle_llfn(Function, val, emit);
77 /// Tell LLVM if this function should be 'naked', i.e., skip the epilogue and prologue.
79 fn naked(val: &'ll Value, is_naked: bool) {
80 Attribute::Naked.toggle_llfn(Function, val, is_naked);
83 pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
84 if cx.sess().must_not_eliminate_frame_pointers() {
85 llvm::AddFunctionAttrStringValue(
87 llvm::AttributePlace::Function,
88 const_cstr!("frame-pointer"),
94 /// Tell LLVM what instrument function to insert.
96 fn set_instrument_function(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
97 if cx.sess().instrument_mcount() {
98 // Similar to `clang -pg` behavior. Handled by the
99 // `post-inline-ee-instrument` LLVM pass.
101 // The function name varies on platforms.
102 // See test/CodeGen/mcount.c in clang.
104 CString::new(cx.sess().target.target.options.target_mcount.as_str().as_bytes())
107 llvm::AddFunctionAttrStringValue(
109 llvm::AttributePlace::Function,
110 const_cstr!("instrument-function-entry-inlined"),
116 fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
117 // Only use stack probes if the target specification indicates that we
118 // should be using stack probes
119 if !cx.sess().target.target.options.stack_probes {
123 // Currently stack probes seem somewhat incompatible with the address
124 // sanitizer and thread sanitizer. With asan we're already protected from
125 // stack overflow anyway so we don't really need stack probes regardless.
126 match cx.sess().opts.debugging_opts.sanitizer {
127 Some(Sanitizer::Address | Sanitizer::Thread) => return,
131 // probestack doesn't play nice either with `-C profile-generate`.
132 if cx.sess().opts.cg.profile_generate.enabled() {
136 // probestack doesn't play nice either with gcov profiling.
137 if cx.sess().opts.debugging_opts.profile {
141 // Flag our internal `__rust_probestack` function as the stack probe symbol.
142 // This is defined in the `compiler-builtins` crate for each architecture.
143 llvm::AddFunctionAttrStringValue(
145 llvm::AttributePlace::Function,
146 const_cstr!("probe-stack"),
147 const_cstr!("__rust_probestack"),
151 fn translate_obsolete_target_features(feature: &str) -> &str {
152 const LLVM9_FEATURE_CHANGES: &[(&str, &str)] =
153 &[("+fp-only-sp", "-fp64"), ("-fp-only-sp", "+fp64"), ("+d16", "-d32"), ("-d16", "+d32")];
154 if llvm_util::get_major_version() >= 9 {
155 for &(old, new) in LLVM9_FEATURE_CHANGES {
161 for &(old, new) in LLVM9_FEATURE_CHANGES {
170 pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
171 const RUSTC_SPECIFIC_FEATURES: &[&str] = &["crt-static"];
178 .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
185 .filter(|l| !l.is_empty())
186 .map(translate_obsolete_target_features)
189 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
190 let target_cpu = SmallCStr::new(llvm_util::target_cpu(cx.tcx.sess));
191 llvm::AddFunctionAttrStringValue(
193 llvm::AttributePlace::Function,
194 const_cstr!("target-cpu"),
195 target_cpu.as_c_str(),
199 /// Sets the `NonLazyBind` LLVM attribute on a given function,
200 /// assuming the codegen options allow skipping the PLT.
201 pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
202 // Don't generate calls through PLT if it's not necessary
203 if !sess.needs_plt() {
204 Attribute::NonLazyBind.apply_llfn(Function, llfn);
208 pub(crate) fn default_optimisation_attrs(sess: &Session, llfn: &'ll Value) {
209 match sess.opts.optimize {
211 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
212 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
213 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
215 OptLevel::SizeMin => {
216 llvm::Attribute::MinSize.apply_llfn(Function, llfn);
217 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
218 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
221 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
222 llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
223 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
229 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
231 pub fn from_fn_attrs(cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value, instance: ty::Instance<'tcx>) {
232 let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(instance.def_id());
234 match codegen_fn_attrs.optimize {
235 OptimizeAttr::None => {
236 default_optimisation_attrs(cx.tcx.sess, llfn);
238 OptimizeAttr::Speed => {
239 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
240 llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
241 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
243 OptimizeAttr::Size => {
244 llvm::Attribute::MinSize.apply_llfn(Function, llfn);
245 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
246 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
250 // FIXME(eddyb) consolidate these two `inline` calls (and avoid overwrites).
251 if instance.def.requires_inline(cx.tcx) {
252 inline(cx, llfn, attributes::InlineAttr::Hint);
255 inline(cx, llfn, codegen_fn_attrs.inline.clone());
257 // The `uwtable` attribute according to LLVM is:
259 // This attribute indicates that the ABI being targeted requires that an
260 // unwind table entry be produced for this function even if we can show
261 // that no exceptions passes by it. This is normally the case for the
262 // ELF x86-64 abi, but it can be disabled for some compilation units.
264 // Typically when we're compiling with `-C panic=abort` (which implies this
265 // `no_landing_pads` check) we don't need `uwtable` because we can't
266 // generate any exceptions! On Windows, however, exceptions include other
267 // events such as illegal instructions, segfaults, etc. This means that on
268 // Windows we end up still needing the `uwtable` attribute even if the `-C
269 // panic=abort` flag is passed.
271 // You can also find more info on why Windows is whitelisted here in:
272 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
273 if cx.sess().must_emit_unwind_tables() {
274 attributes::emit_uwtable(llfn, true);
277 set_frame_pointer_elimination(cx, llfn);
278 set_instrument_function(cx, llfn);
279 set_probestack(cx, llfn);
281 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
282 Attribute::Cold.apply_llfn(Function, llfn);
284 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_RETURNS_TWICE) {
285 Attribute::ReturnsTwice.apply_llfn(Function, llfn);
287 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_PURE) {
288 Attribute::ReadOnly.apply_llfn(Function, llfn);
290 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_CONST) {
291 Attribute::ReadNone.apply_llfn(Function, llfn);
293 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
296 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
297 Attribute::NoAlias.apply_llfn(llvm::AttributePlace::ReturnValue, llfn);
299 sanitize(cx, codegen_fn_attrs.flags, llfn);
301 // Always annotate functions with the target-cpu they are compiled for.
302 // Without this, ThinLTO won't inline Rust functions into Clang generated
303 // functions (because Clang annotates functions this way too).
304 apply_target_cpu_attr(cx, llfn);
306 let features = llvm_target_features(cx.tcx.sess)
307 .map(|s| s.to_string())
308 .chain(codegen_fn_attrs.target_features.iter().map(|f| {
309 let feature = &f.as_str();
310 format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
312 .collect::<Vec<String>>()
315 if !features.is_empty() {
316 let val = CString::new(features).unwrap();
317 llvm::AddFunctionAttrStringValue(
319 llvm::AttributePlace::Function,
320 const_cstr!("target-features"),
325 // Note that currently the `wasm-import-module` doesn't do anything, but
326 // eventually LLVM 7 should read this and ferry the appropriate import
327 // module to the output file.
328 if cx.tcx.sess.target.target.arch == "wasm32" {
329 if let Some(module) = wasm_import_module(cx.tcx, instance.def_id()) {
330 llvm::AddFunctionAttrStringValue(
332 llvm::AttributePlace::Function,
333 const_cstr!("wasm-import-module"),
338 codegen_fn_attrs.link_name.unwrap_or_else(|| cx.tcx.item_name(instance.def_id()));
339 let name = CString::new(&name.as_str()[..]).unwrap();
340 llvm::AddFunctionAttrStringValue(
342 llvm::AttributePlace::Function,
343 const_cstr!("wasm-import-name"),
350 pub fn provide(providers: &mut Providers<'_>) {
351 providers.target_features_whitelist = |tcx, cnum| {
352 assert_eq!(cnum, LOCAL_CRATE);
353 if tcx.sess.opts.actually_rustdoc {
354 // rustdoc needs to be able to document functions that use all the features, so
355 // whitelist them all
356 llvm_util::all_known_features().map(|(a, b)| (a.to_string(), b)).collect()
358 llvm_util::target_feature_whitelist(tcx.sess)
360 .map(|&(a, b)| (a.to_string(), b))
365 provide_extern(providers);
368 pub fn provide_extern(providers: &mut Providers<'_>) {
369 providers.wasm_import_module_map = |tcx, cnum| {
370 // Build up a map from DefId to a `NativeLib` structure, where
371 // `NativeLib` internally contains information about
372 // `#[link(wasm_import_module = "...")]` for example.
373 let native_libs = tcx.native_libraries(cnum);
375 let def_id_to_native_lib = native_libs
377 .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
378 .collect::<FxHashMap<_, _>>();
380 let mut ret = FxHashMap::default();
381 for lib in tcx.foreign_modules(cnum).iter() {
382 let module = def_id_to_native_lib.get(&lib.def_id).and_then(|s| s.wasm_import_module);
383 let module = match module {
387 ret.extend(lib.foreign_items.iter().map(|id| {
388 assert_eq!(id.krate, cnum);
389 (*id, module.to_string())
397 fn wasm_import_module(tcx: TyCtxt<'_>, id: DefId) -> Option<CString> {
398 tcx.wasm_import_module_map(id.krate).get(&id).map(|s| CString::new(&s[..]).unwrap())