2 use crate::back::write::to_llvm_code_model;
3 use crate::callee::get_fn;
4 use crate::coverageinfo;
6 use crate::errors::BranchProtectionRequiresAArch64;
9 use crate::type_::Type;
10 use crate::value::Value;
13 use rustc_codegen_ssa::base::wants_msvc_seh;
14 use rustc_codegen_ssa::traits::*;
15 use rustc_data_structures::base_n;
16 use rustc_data_structures::fx::FxHashMap;
17 use rustc_data_structures::small_c_str::SmallCStr;
18 use rustc_hir::def_id::DefId;
19 use rustc_middle::mir::mono::CodegenUnit;
20 use rustc_middle::ty::layout::{
21 FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasParamEnv, LayoutError, LayoutOfHelpers,
24 use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
25 use rustc_middle::{bug, span_bug};
26 use rustc_session::config::{BranchProtection, CFGuard, CFProtection};
27 use rustc_session::config::{CrateType, DebugInfo, PAuthKey, PacRet};
28 use rustc_session::Session;
29 use rustc_span::source_map::Span;
30 use rustc_span::source_map::Spanned;
31 use rustc_target::abi::{
32 call::FnAbi, HasDataLayout, PointeeInfo, Size, TargetDataLayout, VariantIdx,
34 use rustc_target::spec::{HasTargetSpec, RelocModel, Target, TlsModel};
35 use smallvec::SmallVec;
37 use std::cell::{Cell, RefCell};
41 /// There is one `CodegenCx` per compilation unit. Each one has its own LLVM
42 /// `llvm::Context` so that several compilation units may be optimized in parallel.
43 /// All other LLVM data structures in the `CodegenCx` are tied to that `llvm::Context`.
44 pub struct CodegenCx<'ll, 'tcx> {
45 pub tcx: TyCtxt<'tcx>,
46 pub check_overflow: bool,
47 pub use_dll_storage_attrs: bool,
48 pub tls_model: llvm::ThreadLocalMode,
50 pub llmod: &'ll llvm::Module,
51 pub llcx: &'ll llvm::Context,
52 pub codegen_unit: &'tcx CodegenUnit<'tcx>,
54 /// Cache instances of monomorphic and polymorphic items
55 pub instances: RefCell<FxHashMap<Instance<'tcx>, &'ll Value>>,
56 /// Cache generated vtables
58 RefCell<FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), &'ll Value>>,
59 /// Cache of constant strings,
60 pub const_str_cache: RefCell<FxHashMap<String, &'ll Value>>,
62 /// Reverse-direction for const ptrs cast from globals.
64 /// Key is a Value holding a `*T`,
65 /// Val is a Value holding a `*[T]`.
67 /// Needed because LLVM loses pointer->pointee association
68 /// when we ptrcast, and we have to ptrcast during codegen
69 /// of a `[T]` const because we form a slice, a `(*T,usize)` pair, not
70 /// a pointer to an LLVM array type. Similar for trait objects.
71 pub const_unsized: RefCell<FxHashMap<&'ll Value, &'ll Value>>,
73 /// Cache of emitted const globals (value -> global)
74 pub const_globals: RefCell<FxHashMap<&'ll Value, &'ll Value>>,
76 /// List of globals for static variables which need to be passed to the
77 /// LLVM function ReplaceAllUsesWith (RAUW) when codegen is complete.
78 /// (We have to make sure we don't invalidate any Values referring
80 pub statics_to_rauw: RefCell<Vec<(&'ll Value, &'ll Value)>>,
82 /// Statics that will be placed in the llvm.used variable
83 /// See <https://llvm.org/docs/LangRef.html#the-llvm-used-global-variable> for details
84 pub used_statics: RefCell<Vec<&'ll Value>>,
86 /// Statics that will be placed in the llvm.compiler.used variable
87 /// See <https://llvm.org/docs/LangRef.html#the-llvm-compiler-used-global-variable> for details
88 pub compiler_used_statics: RefCell<Vec<&'ll Value>>,
90 /// Mapping of non-scalar types to llvm types and field remapping if needed.
91 pub type_lowering: RefCell<FxHashMap<(Ty<'tcx>, Option<VariantIdx>), TypeLowering<'ll>>>,
93 /// Mapping of scalar types to llvm types.
94 pub scalar_lltypes: RefCell<FxHashMap<Ty<'tcx>, &'ll Type>>,
96 pub pointee_infos: RefCell<FxHashMap<(Ty<'tcx>, Size), Option<PointeeInfo>>>,
97 pub isize_ty: &'ll Type,
99 pub coverage_cx: Option<coverageinfo::CrateCoverageContext<'ll, 'tcx>>,
100 pub dbg_cx: Option<debuginfo::CodegenUnitDebugContext<'ll, 'tcx>>,
102 eh_personality: Cell<Option<&'ll Value>>,
103 eh_catch_typeinfo: Cell<Option<&'ll Value>>,
104 pub rust_try_fn: Cell<Option<(&'ll Type, &'ll Value)>>,
106 intrinsics: RefCell<FxHashMap<&'static str, (&'ll Type, &'ll Value)>>,
108 /// A counter that is used for generating local symbol names
109 local_gen_sym_counter: Cell<usize>,
111 /// `codegen_static` will sometimes create a second global variable with a
112 /// different type and clear the symbol name of the original global.
113 /// `global_asm!` needs to be able to find this new global so that it can
114 /// compute the correct mangled symbol name to insert into the asm.
115 pub renamed_statics: RefCell<FxHashMap<DefId, &'ll Value>>,
118 pub struct TypeLowering<'ll> {
119 /// Associated LLVM type
120 pub lltype: &'ll Type,
122 /// If padding is used the slice maps fields from source order
124 pub field_remapping: Option<SmallVec<[u32; 4]>>,
127 fn to_llvm_tls_model(tls_model: TlsModel) -> llvm::ThreadLocalMode {
129 TlsModel::GeneralDynamic => llvm::ThreadLocalMode::GeneralDynamic,
130 TlsModel::LocalDynamic => llvm::ThreadLocalMode::LocalDynamic,
131 TlsModel::InitialExec => llvm::ThreadLocalMode::InitialExec,
132 TlsModel::LocalExec => llvm::ThreadLocalMode::LocalExec,
136 pub unsafe fn create_module<'ll>(
138 llcx: &'ll llvm::Context,
140 ) -> &'ll llvm::Module {
142 let mod_name = SmallCStr::new(mod_name);
143 let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx);
145 let mut target_data_layout = sess.target.data_layout.to_string();
146 let llvm_version = llvm_util::get_version();
147 if llvm_version < (14, 0, 0) {
148 if sess.target.llvm_target == "i686-pc-windows-msvc"
149 || sess.target.llvm_target == "i586-pc-windows-msvc"
152 "e-m:x-p:32:32-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:32-n8:16:32-a:0:32-S32"
155 if sess.target.arch == "wasm32" {
156 target_data_layout = target_data_layout.replace("-p10:8:8-p20:8:8", "");
159 if llvm_version < (16, 0, 0) {
160 if sess.target.arch == "s390x" {
161 target_data_layout = target_data_layout.replace("-v128:64", "");
164 if sess.target.arch == "riscv64" {
165 target_data_layout = target_data_layout.replace("-n32:64-", "-n64-");
169 // Ensure the data-layout values hardcoded remain the defaults.
170 if sess.target.is_builtin {
171 let tm = crate::back::write::create_informational_target_machine(tcx.sess);
172 llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm);
173 llvm::LLVMRustDisposeTargetMachine(tm);
175 let llvm_data_layout = llvm::LLVMGetDataLayoutStr(llmod);
176 let llvm_data_layout = str::from_utf8(CStr::from_ptr(llvm_data_layout).to_bytes())
177 .expect("got a non-UTF8 data-layout from LLVM");
179 // Unfortunately LLVM target specs change over time, and right now we
180 // don't have proper support to work with any more than one
181 // `data_layout` than the one that is in the rust-lang/rust repo. If
182 // this compiler is configured against a custom LLVM, we may have a
183 // differing data layout, even though we should update our own to use
186 // As an interim hack, if CFG_LLVM_ROOT is not an empty string then we
187 // disable this check entirely as we may be configured with something
188 // that has a different target layout.
190 // Unsure if this will actually cause breakage when rustc is configured
194 let cfg_llvm_root = option_env!("CFG_LLVM_ROOT").unwrap_or("");
195 let custom_llvm_used = cfg_llvm_root.trim() != "";
197 if !custom_llvm_used && target_data_layout != llvm_data_layout {
199 "data-layout for target `{rustc_target}`, `{rustc_layout}`, \
200 differs from LLVM target's `{llvm_target}` default layout, `{llvm_layout}`",
201 rustc_target = sess.opts.target_triple,
202 rustc_layout = target_data_layout,
203 llvm_target = sess.target.llvm_target,
204 llvm_layout = llvm_data_layout
209 let data_layout = SmallCStr::new(&target_data_layout);
210 llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
212 let llvm_target = SmallCStr::new(&sess.target.llvm_target);
213 llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
215 let reloc_model = sess.relocation_model();
216 if matches!(reloc_model, RelocModel::Pic | RelocModel::Pie) {
217 llvm::LLVMRustSetModulePICLevel(llmod);
218 // PIE is potentially more effective than PIC, but can only be used in executables.
219 // If all our outputs are executables, then we can relax PIC to PIE.
220 if reloc_model == RelocModel::Pie
221 || sess.crate_types().iter().all(|ty| *ty == CrateType::Executable)
223 llvm::LLVMRustSetModulePIELevel(llmod);
227 // Linking object files with different code models is undefined behavior
228 // because the compiler would have to generate additional code (to span
229 // longer jumps) if a larger code model is used with a smaller one.
231 // See https://reviews.llvm.org/D52322 and https://reviews.llvm.org/D52323.
232 llvm::LLVMRustSetModuleCodeModel(llmod, to_llvm_code_model(sess.code_model()));
234 // If skipping the PLT is enabled, we need to add some module metadata
235 // to ensure intrinsic calls don't use it.
236 if !sess.needs_plt() {
237 let avoid_plt = "RtLibUseGOT\0".as_ptr().cast();
238 llvm::LLVMRustAddModuleFlag(llmod, llvm::LLVMModFlagBehavior::Warning, avoid_plt, 1);
241 if sess.is_sanitizer_cfi_enabled() {
242 // FIXME(rcvalle): Add support for non canonical jump tables.
243 let canonical_jump_tables = "CFI Canonical Jump Tables\0".as_ptr().cast();
244 // FIXME(rcvalle): Add it with Override behavior flag.
245 llvm::LLVMRustAddModuleFlag(
247 llvm::LLVMModFlagBehavior::Warning,
248 canonical_jump_tables,
253 // Control Flow Guard is currently only supported by the MSVC linker on Windows.
254 if sess.target.is_like_msvc {
255 match sess.opts.cg.control_flow_guard {
256 CFGuard::Disabled => {}
257 CFGuard::NoChecks => {
258 // Set `cfguard=1` module flag to emit metadata only.
259 llvm::LLVMRustAddModuleFlag(
261 llvm::LLVMModFlagBehavior::Warning,
262 "cfguard\0".as_ptr() as *const _,
267 // Set `cfguard=2` module flag to emit metadata and checks.
268 llvm::LLVMRustAddModuleFlag(
270 llvm::LLVMModFlagBehavior::Warning,
271 "cfguard\0".as_ptr() as *const _,
278 if let Some(BranchProtection { bti, pac_ret }) = sess.opts.unstable_opts.branch_protection {
279 if sess.target.arch != "aarch64" {
280 sess.emit_err(BranchProtectionRequiresAArch64);
282 llvm::LLVMRustAddModuleFlag(
284 llvm::LLVMModFlagBehavior::Error,
285 "branch-target-enforcement\0".as_ptr().cast(),
288 llvm::LLVMRustAddModuleFlag(
290 llvm::LLVMModFlagBehavior::Error,
291 "sign-return-address\0".as_ptr().cast(),
292 pac_ret.is_some().into(),
294 let pac_opts = pac_ret.unwrap_or(PacRet { leaf: false, key: PAuthKey::A });
295 llvm::LLVMRustAddModuleFlag(
297 llvm::LLVMModFlagBehavior::Error,
298 "sign-return-address-all\0".as_ptr().cast(),
299 pac_opts.leaf.into(),
301 llvm::LLVMRustAddModuleFlag(
303 llvm::LLVMModFlagBehavior::Error,
304 "sign-return-address-with-bkey\0".as_ptr().cast(),
305 u32::from(pac_opts.key == PAuthKey::B),
310 // Pass on the control-flow protection flags to LLVM (equivalent to `-fcf-protection` in Clang).
311 if let CFProtection::Branch | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
312 llvm::LLVMRustAddModuleFlag(
314 llvm::LLVMModFlagBehavior::Override,
315 "cf-protection-branch\0".as_ptr().cast(),
319 if let CFProtection::Return | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
320 llvm::LLVMRustAddModuleFlag(
322 llvm::LLVMModFlagBehavior::Override,
323 "cf-protection-return\0".as_ptr().cast(),
328 if sess.opts.unstable_opts.virtual_function_elimination {
329 llvm::LLVMRustAddModuleFlag(
331 llvm::LLVMModFlagBehavior::Error,
332 "Virtual Function Elim\0".as_ptr().cast(),
340 impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
343 codegen_unit: &'tcx CodegenUnit<'tcx>,
344 llvm_module: &'ll crate::ModuleLlvm,
346 // An interesting part of Windows which MSVC forces our hand on (and
347 // apparently MinGW didn't) is the usage of `dllimport` and `dllexport`
348 // attributes in LLVM IR as well as native dependencies (in C these
349 // correspond to `__declspec(dllimport)`).
351 // LD (BFD) in MinGW mode can often correctly guess `dllexport` but
352 // relying on that can result in issues like #50176.
353 // LLD won't support that and expects symbols with proper attributes.
354 // Because of that we make MinGW target emit dllexport just like MSVC.
355 // When it comes to dllimport we use it for constants but for functions
356 // rely on the linker to do the right thing. Opposed to dllexport this
357 // task is easy for them (both LD and LLD) and allows us to easily use
358 // symbols from static libraries in shared libraries.
360 // Whenever a dynamic library is built on Windows it must have its public
361 // interface specified by functions tagged with `dllexport` or otherwise
362 // they're not available to be linked against. This poses a few problems
363 // for the compiler, some of which are somewhat fundamental, but we use
364 // the `use_dll_storage_attrs` variable below to attach the `dllexport`
365 // attribute to all LLVM functions that are exported e.g., they're
366 // already tagged with external linkage). This is suboptimal for a few
369 // * If an object file will never be included in a dynamic library,
370 // there's no need to attach the dllexport attribute. Most object
371 // files in Rust are not destined to become part of a dll as binaries
372 // are statically linked by default.
373 // * If the compiler is emitting both an rlib and a dylib, the same
374 // source object file is currently used but with MSVC this may be less
375 // feasible. The compiler may be able to get around this, but it may
376 // involve some invasive changes to deal with this.
378 // The flip side of this situation is that whenever you link to a dll and
379 // you import a function from it, the import should be tagged with
380 // `dllimport`. At this time, however, the compiler does not emit
381 // `dllimport` for any declarations other than constants (where it is
382 // required), which is again suboptimal for even more reasons!
384 // * Calling a function imported from another dll without using
385 // `dllimport` causes the linker/compiler to have extra overhead (one
386 // `jmp` instruction on x86) when calling the function.
387 // * The same object file may be used in different circumstances, so a
388 // function may be imported from a dll if the object is linked into a
389 // dll, but it may be just linked against if linked into an rlib.
390 // * The compiler has no knowledge about whether native functions should
391 // be tagged dllimport or not.
393 // For now the compiler takes the perf hit (I do not have any numbers to
394 // this effect) by marking very little as `dllimport` and praying the
395 // linker will take care of everything. Fixing this problem will likely
396 // require adding a few attributes to Rust itself (feature gated at the
397 // start) and then strongly recommending static linkage on Windows!
398 let use_dll_storage_attrs = tcx.sess.target.is_like_windows;
400 let check_overflow = tcx.sess.overflow_checks();
402 let tls_model = to_llvm_tls_model(tcx.sess.tls_model());
404 let (llcx, llmod) = (&*llvm_module.llcx, llvm_module.llmod());
406 let coverage_cx = if tcx.sess.instrument_coverage() {
407 let covctx = coverageinfo::CrateCoverageContext::new();
413 let dbg_cx = if tcx.sess.opts.debuginfo != DebugInfo::None {
414 let dctx = debuginfo::CodegenUnitDebugContext::new(llmod);
415 debuginfo::metadata::build_compile_unit_di_node(
417 codegen_unit.name().as_str(),
425 let isize_ty = Type::ix_llcx(llcx, tcx.data_layout.pointer_size.bits());
430 use_dll_storage_attrs,
435 instances: Default::default(),
436 vtables: Default::default(),
437 const_str_cache: Default::default(),
438 const_unsized: Default::default(),
439 const_globals: Default::default(),
440 statics_to_rauw: RefCell::new(Vec::new()),
441 used_statics: RefCell::new(Vec::new()),
442 compiler_used_statics: RefCell::new(Vec::new()),
443 type_lowering: Default::default(),
444 scalar_lltypes: Default::default(),
445 pointee_infos: Default::default(),
449 eh_personality: Cell::new(None),
450 eh_catch_typeinfo: Cell::new(None),
451 rust_try_fn: Cell::new(None),
452 intrinsics: Default::default(),
453 local_gen_sym_counter: Cell::new(0),
454 renamed_statics: Default::default(),
458 pub(crate) fn statics_to_rauw(&self) -> &RefCell<Vec<(&'ll Value, &'ll Value)>> {
459 &self.statics_to_rauw
463 pub fn coverage_context(&self) -> Option<&coverageinfo::CrateCoverageContext<'ll, 'tcx>> {
464 self.coverage_cx.as_ref()
467 pub(crate) fn create_used_variable_impl(&self, name: &'static CStr, values: &[&'ll Value]) {
468 let section = cstr!("llvm.metadata");
469 let array = self.const_array(self.type_ptr_to(self.type_i8()), values);
472 let g = llvm::LLVMAddGlobal(self.llmod, self.val_ty(array), name.as_ptr());
473 llvm::LLVMSetInitializer(g, array);
474 llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
475 llvm::LLVMSetSection(g, section.as_ptr());
480 impl<'ll, 'tcx> MiscMethods<'tcx> for CodegenCx<'ll, 'tcx> {
483 ) -> &RefCell<FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), &'ll Value>>
488 fn get_fn(&self, instance: Instance<'tcx>) -> &'ll Value {
489 get_fn(self, instance)
492 fn get_fn_addr(&self, instance: Instance<'tcx>) -> &'ll Value {
493 get_fn(self, instance)
496 fn eh_personality(&self) -> &'ll Value {
497 // The exception handling personality function.
499 // If our compilation unit has the `eh_personality` lang item somewhere
500 // within it, then we just need to codegen that. Otherwise, we're
501 // building an rlib which will depend on some upstream implementation of
502 // this function, so we just codegen a generic reference to it. We don't
503 // specify any of the types for the function, we just make it a symbol
504 // that LLVM can later use.
506 // Note that MSVC is a little special here in that we don't use the
507 // `eh_personality` lang item at all. Currently LLVM has support for
508 // both Dwarf and SEH unwind mechanisms for MSVC targets and uses the
509 // *name of the personality function* to decide what kind of unwind side
510 // tables/landing pads to emit. It looks like Dwarf is used by default,
511 // injecting a dependency on the `_Unwind_Resume` symbol for resuming
512 // an "exception", but for MSVC we want to force SEH. This means that we
513 // can't actually have the personality function be our standard
514 // `rust_eh_personality` function, but rather we wired it up to the
515 // CRT's custom personality function, which forces LLVM to consider
516 // landing pads as "landing pads for SEH".
517 if let Some(llpersonality) = self.eh_personality.get() {
518 return llpersonality;
521 let llfn = match tcx.lang_items().eh_personality() {
522 Some(def_id) if !wants_msvc_seh(self.sess()) => self.get_fn_addr(
523 ty::Instance::resolve(
525 ty::ParamEnv::reveal_all(),
527 tcx.intern_substs(&[]),
533 let name = if wants_msvc_seh(self.sess()) {
536 "rust_eh_personality"
538 if let Some(llfn) = self.get_declared_value(name) {
541 let fty = self.type_variadic_func(&[], self.type_i32());
542 let llfn = self.declare_cfn(name, llvm::UnnamedAddr::Global, fty);
543 let target_cpu = attributes::target_cpu_attr(self);
544 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[target_cpu]);
549 self.eh_personality.set(Some(llfn));
553 fn sess(&self) -> &Session {
557 fn check_overflow(&self) -> bool {
561 fn codegen_unit(&self) -> &'tcx CodegenUnit<'tcx> {
565 fn set_frame_pointer_type(&self, llfn: &'ll Value) {
566 if let Some(attr) = attributes::frame_pointer_type_attr(self) {
567 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[attr]);
571 fn apply_target_cpu_attr(&self, llfn: &'ll Value) {
572 let mut attrs = SmallVec::<[_; 2]>::new();
573 attrs.push(attributes::target_cpu_attr(self));
574 attrs.extend(attributes::tune_cpu_attr(self));
575 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &attrs);
578 fn declare_c_main(&self, fn_type: Self::Type) -> Option<Self::Function> {
579 let entry_name = self.sess().target.entry_name.as_ref();
580 if self.get_declared_value(entry_name).is_none() {
581 Some(self.declare_entry_fn(
583 self.sess().target.entry_abi.into(),
584 llvm::UnnamedAddr::Global,
588 // If the symbol already exists, it is an error: for example, the user wrote
589 // #[no_mangle] extern "C" fn main(..) {..}
590 // instead of #[start]
596 impl<'ll> CodegenCx<'ll, '_> {
597 pub(crate) fn get_intrinsic(&self, key: &str) -> (&'ll Type, &'ll Value) {
598 if let Some(v) = self.intrinsics.borrow().get(key).cloned() {
602 self.declare_intrinsic(key).unwrap_or_else(|| bug!("unknown intrinsic '{}'", key))
608 args: Option<&[&'ll llvm::Type]>,
609 ret: &'ll llvm::Type,
610 ) -> (&'ll llvm::Type, &'ll llvm::Value) {
611 let fn_ty = if let Some(args) = args {
612 self.type_func(args, ret)
614 self.type_variadic_func(&[], ret)
616 let f = self.declare_cfn(name, llvm::UnnamedAddr::No, fn_ty);
617 self.intrinsics.borrow_mut().insert(name, (fn_ty, f));
621 fn declare_intrinsic(&self, key: &str) -> Option<(&'ll Type, &'ll Value)> {
623 ($name:expr, fn() -> $ret:expr) => (
625 return Some(self.insert_intrinsic($name, Some(&[]), $ret));
628 ($name:expr, fn(...) -> $ret:expr) => (
630 return Some(self.insert_intrinsic($name, None, $ret));
633 ($name:expr, fn($($arg:expr),*) -> $ret:expr) => (
635 return Some(self.insert_intrinsic($name, Some(&[$($arg),*]), $ret));
639 macro_rules! mk_struct {
640 ($($field_ty:expr),*) => (self.type_struct( &[$($field_ty),*], false))
643 let i8p = self.type_i8p();
644 let void = self.type_void();
645 let i1 = self.type_i1();
646 let t_i8 = self.type_i8();
647 let t_i16 = self.type_i16();
648 let t_i32 = self.type_i32();
649 let t_i64 = self.type_i64();
650 let t_i128 = self.type_i128();
651 let t_isize = self.type_isize();
652 let t_f32 = self.type_f32();
653 let t_f64 = self.type_f64();
654 let t_metadata = self.type_metadata();
656 ifn!("llvm.wasm.trunc.unsigned.i32.f32", fn(t_f32) -> t_i32);
657 ifn!("llvm.wasm.trunc.unsigned.i32.f64", fn(t_f64) -> t_i32);
658 ifn!("llvm.wasm.trunc.unsigned.i64.f32", fn(t_f32) -> t_i64);
659 ifn!("llvm.wasm.trunc.unsigned.i64.f64", fn(t_f64) -> t_i64);
660 ifn!("llvm.wasm.trunc.signed.i32.f32", fn(t_f32) -> t_i32);
661 ifn!("llvm.wasm.trunc.signed.i32.f64", fn(t_f64) -> t_i32);
662 ifn!("llvm.wasm.trunc.signed.i64.f32", fn(t_f32) -> t_i64);
663 ifn!("llvm.wasm.trunc.signed.i64.f64", fn(t_f64) -> t_i64);
665 ifn!("llvm.fptosi.sat.i8.f32", fn(t_f32) -> t_i8);
666 ifn!("llvm.fptosi.sat.i16.f32", fn(t_f32) -> t_i16);
667 ifn!("llvm.fptosi.sat.i32.f32", fn(t_f32) -> t_i32);
668 ifn!("llvm.fptosi.sat.i64.f32", fn(t_f32) -> t_i64);
669 ifn!("llvm.fptosi.sat.i128.f32", fn(t_f32) -> t_i128);
670 ifn!("llvm.fptosi.sat.i8.f64", fn(t_f64) -> t_i8);
671 ifn!("llvm.fptosi.sat.i16.f64", fn(t_f64) -> t_i16);
672 ifn!("llvm.fptosi.sat.i32.f64", fn(t_f64) -> t_i32);
673 ifn!("llvm.fptosi.sat.i64.f64", fn(t_f64) -> t_i64);
674 ifn!("llvm.fptosi.sat.i128.f64", fn(t_f64) -> t_i128);
676 ifn!("llvm.fptoui.sat.i8.f32", fn(t_f32) -> t_i8);
677 ifn!("llvm.fptoui.sat.i16.f32", fn(t_f32) -> t_i16);
678 ifn!("llvm.fptoui.sat.i32.f32", fn(t_f32) -> t_i32);
679 ifn!("llvm.fptoui.sat.i64.f32", fn(t_f32) -> t_i64);
680 ifn!("llvm.fptoui.sat.i128.f32", fn(t_f32) -> t_i128);
681 ifn!("llvm.fptoui.sat.i8.f64", fn(t_f64) -> t_i8);
682 ifn!("llvm.fptoui.sat.i16.f64", fn(t_f64) -> t_i16);
683 ifn!("llvm.fptoui.sat.i32.f64", fn(t_f64) -> t_i32);
684 ifn!("llvm.fptoui.sat.i64.f64", fn(t_f64) -> t_i64);
685 ifn!("llvm.fptoui.sat.i128.f64", fn(t_f64) -> t_i128);
687 ifn!("llvm.trap", fn() -> void);
688 ifn!("llvm.debugtrap", fn() -> void);
689 ifn!("llvm.frameaddress", fn(t_i32) -> i8p);
691 ifn!("llvm.powi.f32", fn(t_f32, t_i32) -> t_f32);
692 ifn!("llvm.powi.f64", fn(t_f64, t_i32) -> t_f64);
694 ifn!("llvm.pow.f32", fn(t_f32, t_f32) -> t_f32);
695 ifn!("llvm.pow.f64", fn(t_f64, t_f64) -> t_f64);
697 ifn!("llvm.sqrt.f32", fn(t_f32) -> t_f32);
698 ifn!("llvm.sqrt.f64", fn(t_f64) -> t_f64);
700 ifn!("llvm.sin.f32", fn(t_f32) -> t_f32);
701 ifn!("llvm.sin.f64", fn(t_f64) -> t_f64);
703 ifn!("llvm.cos.f32", fn(t_f32) -> t_f32);
704 ifn!("llvm.cos.f64", fn(t_f64) -> t_f64);
706 ifn!("llvm.exp.f32", fn(t_f32) -> t_f32);
707 ifn!("llvm.exp.f64", fn(t_f64) -> t_f64);
709 ifn!("llvm.exp2.f32", fn(t_f32) -> t_f32);
710 ifn!("llvm.exp2.f64", fn(t_f64) -> t_f64);
712 ifn!("llvm.log.f32", fn(t_f32) -> t_f32);
713 ifn!("llvm.log.f64", fn(t_f64) -> t_f64);
715 ifn!("llvm.log10.f32", fn(t_f32) -> t_f32);
716 ifn!("llvm.log10.f64", fn(t_f64) -> t_f64);
718 ifn!("llvm.log2.f32", fn(t_f32) -> t_f32);
719 ifn!("llvm.log2.f64", fn(t_f64) -> t_f64);
721 ifn!("llvm.fma.f32", fn(t_f32, t_f32, t_f32) -> t_f32);
722 ifn!("llvm.fma.f64", fn(t_f64, t_f64, t_f64) -> t_f64);
724 ifn!("llvm.fabs.f32", fn(t_f32) -> t_f32);
725 ifn!("llvm.fabs.f64", fn(t_f64) -> t_f64);
727 ifn!("llvm.minnum.f32", fn(t_f32, t_f32) -> t_f32);
728 ifn!("llvm.minnum.f64", fn(t_f64, t_f64) -> t_f64);
729 ifn!("llvm.maxnum.f32", fn(t_f32, t_f32) -> t_f32);
730 ifn!("llvm.maxnum.f64", fn(t_f64, t_f64) -> t_f64);
732 ifn!("llvm.floor.f32", fn(t_f32) -> t_f32);
733 ifn!("llvm.floor.f64", fn(t_f64) -> t_f64);
735 ifn!("llvm.ceil.f32", fn(t_f32) -> t_f32);
736 ifn!("llvm.ceil.f64", fn(t_f64) -> t_f64);
738 ifn!("llvm.trunc.f32", fn(t_f32) -> t_f32);
739 ifn!("llvm.trunc.f64", fn(t_f64) -> t_f64);
741 ifn!("llvm.copysign.f32", fn(t_f32, t_f32) -> t_f32);
742 ifn!("llvm.copysign.f64", fn(t_f64, t_f64) -> t_f64);
743 ifn!("llvm.round.f32", fn(t_f32) -> t_f32);
744 ifn!("llvm.round.f64", fn(t_f64) -> t_f64);
746 ifn!("llvm.rint.f32", fn(t_f32) -> t_f32);
747 ifn!("llvm.rint.f64", fn(t_f64) -> t_f64);
748 ifn!("llvm.nearbyint.f32", fn(t_f32) -> t_f32);
749 ifn!("llvm.nearbyint.f64", fn(t_f64) -> t_f64);
751 ifn!("llvm.ctpop.i8", fn(t_i8) -> t_i8);
752 ifn!("llvm.ctpop.i16", fn(t_i16) -> t_i16);
753 ifn!("llvm.ctpop.i32", fn(t_i32) -> t_i32);
754 ifn!("llvm.ctpop.i64", fn(t_i64) -> t_i64);
755 ifn!("llvm.ctpop.i128", fn(t_i128) -> t_i128);
757 ifn!("llvm.ctlz.i8", fn(t_i8, i1) -> t_i8);
758 ifn!("llvm.ctlz.i16", fn(t_i16, i1) -> t_i16);
759 ifn!("llvm.ctlz.i32", fn(t_i32, i1) -> t_i32);
760 ifn!("llvm.ctlz.i64", fn(t_i64, i1) -> t_i64);
761 ifn!("llvm.ctlz.i128", fn(t_i128, i1) -> t_i128);
763 ifn!("llvm.cttz.i8", fn(t_i8, i1) -> t_i8);
764 ifn!("llvm.cttz.i16", fn(t_i16, i1) -> t_i16);
765 ifn!("llvm.cttz.i32", fn(t_i32, i1) -> t_i32);
766 ifn!("llvm.cttz.i64", fn(t_i64, i1) -> t_i64);
767 ifn!("llvm.cttz.i128", fn(t_i128, i1) -> t_i128);
769 ifn!("llvm.bswap.i16", fn(t_i16) -> t_i16);
770 ifn!("llvm.bswap.i32", fn(t_i32) -> t_i32);
771 ifn!("llvm.bswap.i64", fn(t_i64) -> t_i64);
772 ifn!("llvm.bswap.i128", fn(t_i128) -> t_i128);
774 ifn!("llvm.bitreverse.i8", fn(t_i8) -> t_i8);
775 ifn!("llvm.bitreverse.i16", fn(t_i16) -> t_i16);
776 ifn!("llvm.bitreverse.i32", fn(t_i32) -> t_i32);
777 ifn!("llvm.bitreverse.i64", fn(t_i64) -> t_i64);
778 ifn!("llvm.bitreverse.i128", fn(t_i128) -> t_i128);
780 ifn!("llvm.fshl.i8", fn(t_i8, t_i8, t_i8) -> t_i8);
781 ifn!("llvm.fshl.i16", fn(t_i16, t_i16, t_i16) -> t_i16);
782 ifn!("llvm.fshl.i32", fn(t_i32, t_i32, t_i32) -> t_i32);
783 ifn!("llvm.fshl.i64", fn(t_i64, t_i64, t_i64) -> t_i64);
784 ifn!("llvm.fshl.i128", fn(t_i128, t_i128, t_i128) -> t_i128);
786 ifn!("llvm.fshr.i8", fn(t_i8, t_i8, t_i8) -> t_i8);
787 ifn!("llvm.fshr.i16", fn(t_i16, t_i16, t_i16) -> t_i16);
788 ifn!("llvm.fshr.i32", fn(t_i32, t_i32, t_i32) -> t_i32);
789 ifn!("llvm.fshr.i64", fn(t_i64, t_i64, t_i64) -> t_i64);
790 ifn!("llvm.fshr.i128", fn(t_i128, t_i128, t_i128) -> t_i128);
792 ifn!("llvm.sadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
793 ifn!("llvm.sadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
794 ifn!("llvm.sadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
795 ifn!("llvm.sadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
796 ifn!("llvm.sadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
798 ifn!("llvm.uadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
799 ifn!("llvm.uadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
800 ifn!("llvm.uadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
801 ifn!("llvm.uadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
802 ifn!("llvm.uadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
804 ifn!("llvm.ssub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
805 ifn!("llvm.ssub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
806 ifn!("llvm.ssub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
807 ifn!("llvm.ssub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
808 ifn!("llvm.ssub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
810 ifn!("llvm.usub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
811 ifn!("llvm.usub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
812 ifn!("llvm.usub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
813 ifn!("llvm.usub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
814 ifn!("llvm.usub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
816 ifn!("llvm.smul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
817 ifn!("llvm.smul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
818 ifn!("llvm.smul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
819 ifn!("llvm.smul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
820 ifn!("llvm.smul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
822 ifn!("llvm.umul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
823 ifn!("llvm.umul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
824 ifn!("llvm.umul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
825 ifn!("llvm.umul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
826 ifn!("llvm.umul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
828 ifn!("llvm.sadd.sat.i8", fn(t_i8, t_i8) -> t_i8);
829 ifn!("llvm.sadd.sat.i16", fn(t_i16, t_i16) -> t_i16);
830 ifn!("llvm.sadd.sat.i32", fn(t_i32, t_i32) -> t_i32);
831 ifn!("llvm.sadd.sat.i64", fn(t_i64, t_i64) -> t_i64);
832 ifn!("llvm.sadd.sat.i128", fn(t_i128, t_i128) -> t_i128);
834 ifn!("llvm.uadd.sat.i8", fn(t_i8, t_i8) -> t_i8);
835 ifn!("llvm.uadd.sat.i16", fn(t_i16, t_i16) -> t_i16);
836 ifn!("llvm.uadd.sat.i32", fn(t_i32, t_i32) -> t_i32);
837 ifn!("llvm.uadd.sat.i64", fn(t_i64, t_i64) -> t_i64);
838 ifn!("llvm.uadd.sat.i128", fn(t_i128, t_i128) -> t_i128);
840 ifn!("llvm.ssub.sat.i8", fn(t_i8, t_i8) -> t_i8);
841 ifn!("llvm.ssub.sat.i16", fn(t_i16, t_i16) -> t_i16);
842 ifn!("llvm.ssub.sat.i32", fn(t_i32, t_i32) -> t_i32);
843 ifn!("llvm.ssub.sat.i64", fn(t_i64, t_i64) -> t_i64);
844 ifn!("llvm.ssub.sat.i128", fn(t_i128, t_i128) -> t_i128);
846 ifn!("llvm.usub.sat.i8", fn(t_i8, t_i8) -> t_i8);
847 ifn!("llvm.usub.sat.i16", fn(t_i16, t_i16) -> t_i16);
848 ifn!("llvm.usub.sat.i32", fn(t_i32, t_i32) -> t_i32);
849 ifn!("llvm.usub.sat.i64", fn(t_i64, t_i64) -> t_i64);
850 ifn!("llvm.usub.sat.i128", fn(t_i128, t_i128) -> t_i128);
852 ifn!("llvm.lifetime.start.p0i8", fn(t_i64, i8p) -> void);
853 ifn!("llvm.lifetime.end.p0i8", fn(t_i64, i8p) -> void);
855 ifn!("llvm.expect.i1", fn(i1, i1) -> i1);
856 ifn!("llvm.eh.typeid.for", fn(i8p) -> t_i32);
857 ifn!("llvm.localescape", fn(...) -> void);
858 ifn!("llvm.localrecover", fn(i8p, i8p, t_i32) -> i8p);
859 ifn!("llvm.x86.seh.recoverfp", fn(i8p, i8p) -> i8p);
861 ifn!("llvm.assume", fn(i1) -> void);
862 ifn!("llvm.prefetch", fn(i8p, t_i32, t_i32, t_i32) -> void);
864 // This isn't an "LLVM intrinsic", but LLVM's optimization passes
865 // recognize it like one and we assume it exists in `core::slice::cmp`
866 match self.sess().target.arch.as_ref() {
867 "avr" | "msp430" => ifn!("memcmp", fn(i8p, i8p, t_isize) -> t_i16),
868 _ => ifn!("memcmp", fn(i8p, i8p, t_isize) -> t_i32),
871 // variadic intrinsics
872 ifn!("llvm.va_start", fn(i8p) -> void);
873 ifn!("llvm.va_end", fn(i8p) -> void);
874 ifn!("llvm.va_copy", fn(i8p, i8p) -> void);
876 if self.sess().instrument_coverage() {
877 ifn!("llvm.instrprof.increment", fn(i8p, t_i64, t_i32, t_i32) -> void);
880 ifn!("llvm.type.test", fn(i8p, t_metadata) -> i1);
881 ifn!("llvm.type.checked.load", fn(i8p, t_i32, t_metadata) -> mk_struct! {i8p, i1});
883 if self.sess().opts.debuginfo != DebugInfo::None {
884 ifn!("llvm.dbg.declare", fn(t_metadata, t_metadata) -> void);
885 ifn!("llvm.dbg.value", fn(t_metadata, t_i64, t_metadata) -> void);
888 ifn!("llvm.ptrmask", fn(i8p, t_isize) -> i8p);
893 pub(crate) fn eh_catch_typeinfo(&self) -> &'ll Value {
894 if let Some(eh_catch_typeinfo) = self.eh_catch_typeinfo.get() {
895 return eh_catch_typeinfo;
898 assert!(self.sess().target.os == "emscripten");
899 let eh_catch_typeinfo = match tcx.lang_items().eh_catch_typeinfo() {
900 Some(def_id) => self.get_static(def_id),
903 .type_struct(&[self.type_ptr_to(self.type_isize()), self.type_i8p()], false);
904 self.declare_global("rust_eh_catch_typeinfo", ty)
907 let eh_catch_typeinfo = self.const_bitcast(eh_catch_typeinfo, self.type_i8p());
908 self.eh_catch_typeinfo.set(Some(eh_catch_typeinfo));
913 impl CodegenCx<'_, '_> {
914 /// Generates a new symbol name with the given prefix. This symbol name must
915 /// only be used for definitions with `internal` or `private` linkage.
916 pub fn generate_local_symbol_name(&self, prefix: &str) -> String {
917 let idx = self.local_gen_sym_counter.get();
918 self.local_gen_sym_counter.set(idx + 1);
919 // Include a '.' character, so there can be no accidental conflicts with
920 // user defined names
921 let mut name = String::with_capacity(prefix.len() + 6);
922 name.push_str(prefix);
924 base_n::push_str(idx as u128, base_n::ALPHANUMERIC_ONLY, &mut name);
929 impl HasDataLayout for CodegenCx<'_, '_> {
931 fn data_layout(&self) -> &TargetDataLayout {
932 &self.tcx.data_layout
936 impl HasTargetSpec for CodegenCx<'_, '_> {
938 fn target_spec(&self) -> &Target {
939 &self.tcx.sess.target
943 impl<'tcx> ty::layout::HasTyCtxt<'tcx> for CodegenCx<'_, 'tcx> {
945 fn tcx(&self) -> TyCtxt<'tcx> {
950 impl<'tcx, 'll> HasParamEnv<'tcx> for CodegenCx<'ll, 'tcx> {
951 fn param_env(&self) -> ty::ParamEnv<'tcx> {
952 ty::ParamEnv::reveal_all()
956 impl<'tcx> LayoutOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
957 type LayoutOfResult = TyAndLayout<'tcx>;
960 fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
961 if let LayoutError::SizeOverflow(_) = err {
962 self.sess().emit_fatal(Spanned { span, node: err })
964 span_bug!(span, "failed to get layout for `{}`: {}", ty, err)
969 impl<'tcx> FnAbiOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
970 type FnAbiOfResult = &'tcx FnAbi<'tcx, Ty<'tcx>>;
973 fn handle_fn_abi_err(
975 err: FnAbiError<'tcx>,
977 fn_abi_request: FnAbiRequest<'tcx>,
979 if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err {
980 self.sess().emit_fatal(Spanned { span, node: err })
982 match fn_abi_request {
983 FnAbiRequest::OfFnPtr { sig, extra_args } => {
986 "`fn_abi_of_fn_ptr({}, {:?})` failed: {}",
992 FnAbiRequest::OfInstance { instance, extra_args } => {
995 "`fn_abi_of_instance({}, {:?})` failed: {}",