]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/context.rs
Auto merge of #93154 - michaelwoerister:fix-generic-closure-and-generator-debuginfo...
[rust.git] / compiler / rustc_codegen_llvm / src / context.rs
1 use crate::attributes;
2 use crate::back::write::to_llvm_code_model;
3 use crate::callee::get_fn;
4 use crate::coverageinfo;
5 use crate::debuginfo;
6 use crate::llvm;
7 use crate::llvm_util;
8 use crate::type_::Type;
9 use crate::value::Value;
10
11 use cstr::cstr;
12 use rustc_codegen_ssa::base::wants_msvc_seh;
13 use rustc_codegen_ssa::traits::*;
14 use rustc_data_structures::base_n;
15 use rustc_data_structures::fx::FxHashMap;
16 use rustc_data_structures::small_c_str::SmallCStr;
17 use rustc_middle::mir::mono::CodegenUnit;
18 use rustc_middle::ty::layout::{
19     FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasParamEnv, LayoutError, LayoutOfHelpers,
20     TyAndLayout,
21 };
22 use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
23 use rustc_middle::{bug, span_bug};
24 use rustc_session::config::{BranchProtection, CFGuard, CrateType, DebugInfo, PAuthKey, PacRet};
25 use rustc_session::Session;
26 use rustc_span::source_map::Span;
27 use rustc_span::symbol::Symbol;
28 use rustc_target::abi::{
29     call::FnAbi, HasDataLayout, PointeeInfo, Size, TargetDataLayout, VariantIdx,
30 };
31 use rustc_target::spec::{HasTargetSpec, RelocModel, Target, TlsModel};
32 use smallvec::SmallVec;
33
34 use std::cell::{Cell, RefCell};
35 use std::ffi::CStr;
36 use std::str;
37
38 /// There is one `CodegenCx` per compilation unit. Each one has its own LLVM
39 /// `llvm::Context` so that several compilation units may be optimized in parallel.
40 /// All other LLVM data structures in the `CodegenCx` are tied to that `llvm::Context`.
41 pub struct CodegenCx<'ll, 'tcx> {
42     pub tcx: TyCtxt<'tcx>,
43     pub check_overflow: bool,
44     pub use_dll_storage_attrs: bool,
45     pub tls_model: llvm::ThreadLocalMode,
46
47     pub llmod: &'ll llvm::Module,
48     pub llcx: &'ll llvm::Context,
49     pub codegen_unit: &'tcx CodegenUnit<'tcx>,
50
51     /// Cache instances of monomorphic and polymorphic items
52     pub instances: RefCell<FxHashMap<Instance<'tcx>, &'ll Value>>,
53     /// Cache generated vtables
54     pub vtables:
55         RefCell<FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), &'ll Value>>,
56     /// Cache of constant strings,
57     pub const_cstr_cache: RefCell<FxHashMap<Symbol, &'ll Value>>,
58
59     /// Reverse-direction for const ptrs cast from globals.
60     ///
61     /// Key is a Value holding a `*T`,
62     /// Val is a Value holding a `*[T]`.
63     ///
64     /// Needed because LLVM loses pointer->pointee association
65     /// when we ptrcast, and we have to ptrcast during codegen
66     /// of a `[T]` const because we form a slice, a `(*T,usize)` pair, not
67     /// a pointer to an LLVM array type. Similar for trait objects.
68     pub const_unsized: RefCell<FxHashMap<&'ll Value, &'ll Value>>,
69
70     /// Cache of emitted const globals (value -> global)
71     pub const_globals: RefCell<FxHashMap<&'ll Value, &'ll Value>>,
72
73     /// List of globals for static variables which need to be passed to the
74     /// LLVM function ReplaceAllUsesWith (RAUW) when codegen is complete.
75     /// (We have to make sure we don't invalidate any Values referring
76     /// to constants.)
77     pub statics_to_rauw: RefCell<Vec<(&'ll Value, &'ll Value)>>,
78
79     /// Statics that will be placed in the llvm.used variable
80     /// See <https://llvm.org/docs/LangRef.html#the-llvm-used-global-variable> for details
81     pub used_statics: RefCell<Vec<&'ll Value>>,
82
83     /// Statics that will be placed in the llvm.compiler.used variable
84     /// See <https://llvm.org/docs/LangRef.html#the-llvm-compiler-used-global-variable> for details
85     pub compiler_used_statics: RefCell<Vec<&'ll Value>>,
86
87     /// Mapping of non-scalar types to llvm types and field remapping if needed.
88     pub type_lowering: RefCell<FxHashMap<(Ty<'tcx>, Option<VariantIdx>), TypeLowering<'ll>>>,
89
90     /// Mapping of scalar types to llvm types.
91     pub scalar_lltypes: RefCell<FxHashMap<Ty<'tcx>, &'ll Type>>,
92
93     pub pointee_infos: RefCell<FxHashMap<(Ty<'tcx>, Size), Option<PointeeInfo>>>,
94     pub isize_ty: &'ll Type,
95
96     pub coverage_cx: Option<coverageinfo::CrateCoverageContext<'ll, 'tcx>>,
97     pub dbg_cx: Option<debuginfo::CrateDebugContext<'ll, 'tcx>>,
98
99     eh_personality: Cell<Option<&'ll Value>>,
100     eh_catch_typeinfo: Cell<Option<&'ll Value>>,
101     pub rust_try_fn: Cell<Option<(&'ll Type, &'ll Value)>>,
102
103     intrinsics: RefCell<FxHashMap<&'static str, (&'ll Type, &'ll Value)>>,
104
105     /// A counter that is used for generating local symbol names
106     local_gen_sym_counter: Cell<usize>,
107 }
108
109 pub struct TypeLowering<'ll> {
110     /// Associated LLVM type
111     pub lltype: &'ll Type,
112
113     /// If padding is used the slice maps fields from source order
114     /// to llvm order.
115     pub field_remapping: Option<SmallVec<[u32; 4]>>,
116 }
117
118 fn to_llvm_tls_model(tls_model: TlsModel) -> llvm::ThreadLocalMode {
119     match tls_model {
120         TlsModel::GeneralDynamic => llvm::ThreadLocalMode::GeneralDynamic,
121         TlsModel::LocalDynamic => llvm::ThreadLocalMode::LocalDynamic,
122         TlsModel::InitialExec => llvm::ThreadLocalMode::InitialExec,
123         TlsModel::LocalExec => llvm::ThreadLocalMode::LocalExec,
124     }
125 }
126
127 pub unsafe fn create_module<'ll>(
128     tcx: TyCtxt<'_>,
129     llcx: &'ll llvm::Context,
130     mod_name: &str,
131 ) -> &'ll llvm::Module {
132     let sess = tcx.sess;
133     let mod_name = SmallCStr::new(mod_name);
134     let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx);
135
136     let mut target_data_layout = sess.target.data_layout.clone();
137     if llvm_util::get_version() < (13, 0, 0) {
138         if sess.target.arch == "powerpc64" {
139             target_data_layout = target_data_layout.replace("-S128", "");
140         }
141         if sess.target.arch == "wasm32" {
142             target_data_layout = "e-m:e-p:32:32-i64:64-n32:64-S128".to_string();
143         }
144         if sess.target.arch == "wasm64" {
145             target_data_layout = "e-m:e-p:64:64-i64:64-n32:64-S128".to_string();
146         }
147     }
148
149     // Ensure the data-layout values hardcoded remain the defaults.
150     if sess.target.is_builtin {
151         let tm = crate::back::write::create_informational_target_machine(tcx.sess);
152         llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm);
153         llvm::LLVMRustDisposeTargetMachine(tm);
154
155         let llvm_data_layout = llvm::LLVMGetDataLayoutStr(llmod);
156         let llvm_data_layout = str::from_utf8(CStr::from_ptr(llvm_data_layout).to_bytes())
157             .expect("got a non-UTF8 data-layout from LLVM");
158
159         // Unfortunately LLVM target specs change over time, and right now we
160         // don't have proper support to work with any more than one
161         // `data_layout` than the one that is in the rust-lang/rust repo. If
162         // this compiler is configured against a custom LLVM, we may have a
163         // differing data layout, even though we should update our own to use
164         // that one.
165         //
166         // As an interim hack, if CFG_LLVM_ROOT is not an empty string then we
167         // disable this check entirely as we may be configured with something
168         // that has a different target layout.
169         //
170         // Unsure if this will actually cause breakage when rustc is configured
171         // as such.
172         //
173         // FIXME(#34960)
174         let cfg_llvm_root = option_env!("CFG_LLVM_ROOT").unwrap_or("");
175         let custom_llvm_used = cfg_llvm_root.trim() != "";
176
177         if !custom_llvm_used && target_data_layout != llvm_data_layout {
178             bug!(
179                 "data-layout for target `{rustc_target}`, `{rustc_layout}`, \
180                   differs from LLVM target's `{llvm_target}` default layout, `{llvm_layout}`",
181                 rustc_target = sess.opts.target_triple,
182                 rustc_layout = target_data_layout,
183                 llvm_target = sess.target.llvm_target,
184                 llvm_layout = llvm_data_layout
185             );
186         }
187     }
188
189     let data_layout = SmallCStr::new(&target_data_layout);
190     llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
191
192     let llvm_target = SmallCStr::new(&sess.target.llvm_target);
193     llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
194
195     let reloc_model = sess.relocation_model();
196     if matches!(reloc_model, RelocModel::Pic | RelocModel::Pie) {
197         llvm::LLVMRustSetModulePICLevel(llmod);
198         // PIE is potentially more effective than PIC, but can only be used in executables.
199         // If all our outputs are executables, then we can relax PIC to PIE.
200         if reloc_model == RelocModel::Pie
201             || sess.crate_types().iter().all(|ty| *ty == CrateType::Executable)
202         {
203             llvm::LLVMRustSetModulePIELevel(llmod);
204         }
205     }
206
207     // Linking object files with different code models is undefined behavior
208     // because the compiler would have to generate additional code (to span
209     // longer jumps) if a larger code model is used with a smaller one.
210     //
211     // See https://reviews.llvm.org/D52322 and https://reviews.llvm.org/D52323.
212     llvm::LLVMRustSetModuleCodeModel(llmod, to_llvm_code_model(sess.code_model()));
213
214     // If skipping the PLT is enabled, we need to add some module metadata
215     // to ensure intrinsic calls don't use it.
216     if !sess.needs_plt() {
217         let avoid_plt = "RtLibUseGOT\0".as_ptr().cast();
218         llvm::LLVMRustAddModuleFlag(llmod, llvm::LLVMModFlagBehavior::Warning, avoid_plt, 1);
219     }
220
221     if sess.is_sanitizer_cfi_enabled() {
222         // FIXME(rcvalle): Add support for non canonical jump tables.
223         let canonical_jump_tables = "CFI Canonical Jump Tables\0".as_ptr().cast();
224         // FIXME(rcvalle): Add it with Override behavior flag.
225         llvm::LLVMRustAddModuleFlag(
226             llmod,
227             llvm::LLVMModFlagBehavior::Warning,
228             canonical_jump_tables,
229             1,
230         );
231     }
232
233     // Control Flow Guard is currently only supported by the MSVC linker on Windows.
234     if sess.target.is_like_msvc {
235         match sess.opts.cg.control_flow_guard {
236             CFGuard::Disabled => {}
237             CFGuard::NoChecks => {
238                 // Set `cfguard=1` module flag to emit metadata only.
239                 llvm::LLVMRustAddModuleFlag(
240                     llmod,
241                     llvm::LLVMModFlagBehavior::Warning,
242                     "cfguard\0".as_ptr() as *const _,
243                     1,
244                 )
245             }
246             CFGuard::Checks => {
247                 // Set `cfguard=2` module flag to emit metadata and checks.
248                 llvm::LLVMRustAddModuleFlag(
249                     llmod,
250                     llvm::LLVMModFlagBehavior::Warning,
251                     "cfguard\0".as_ptr() as *const _,
252                     2,
253                 )
254             }
255         }
256     }
257
258     if sess.target.arch == "aarch64" {
259         let BranchProtection { bti, pac_ret: pac } = sess.opts.debugging_opts.branch_protection;
260
261         llvm::LLVMRustAddModuleFlag(
262             llmod,
263             llvm::LLVMModFlagBehavior::Error,
264             "branch-target-enforcement\0".as_ptr().cast(),
265             bti.into(),
266         );
267
268         llvm::LLVMRustAddModuleFlag(
269             llmod,
270             llvm::LLVMModFlagBehavior::Error,
271             "sign-return-address\0".as_ptr().cast(),
272             pac.is_some().into(),
273         );
274         let pac_opts = pac.unwrap_or(PacRet { leaf: false, key: PAuthKey::A });
275         llvm::LLVMRustAddModuleFlag(
276             llmod,
277             llvm::LLVMModFlagBehavior::Error,
278             "sign-return-address-all\0".as_ptr().cast(),
279             pac_opts.leaf.into(),
280         );
281         let is_bkey = if pac_opts.key == PAuthKey::A { false } else { true };
282         llvm::LLVMRustAddModuleFlag(
283             llmod,
284             llvm::LLVMModFlagBehavior::Error,
285             "sign-return-address-with-bkey\0".as_ptr().cast(),
286             is_bkey.into(),
287         );
288     }
289
290     llmod
291 }
292
293 impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
294     crate fn new(
295         tcx: TyCtxt<'tcx>,
296         codegen_unit: &'tcx CodegenUnit<'tcx>,
297         llvm_module: &'ll crate::ModuleLlvm,
298     ) -> Self {
299         // An interesting part of Windows which MSVC forces our hand on (and
300         // apparently MinGW didn't) is the usage of `dllimport` and `dllexport`
301         // attributes in LLVM IR as well as native dependencies (in C these
302         // correspond to `__declspec(dllimport)`).
303         //
304         // LD (BFD) in MinGW mode can often correctly guess `dllexport` but
305         // relying on that can result in issues like #50176.
306         // LLD won't support that and expects symbols with proper attributes.
307         // Because of that we make MinGW target emit dllexport just like MSVC.
308         // When it comes to dllimport we use it for constants but for functions
309         // rely on the linker to do the right thing. Opposed to dllexport this
310         // task is easy for them (both LD and LLD) and allows us to easily use
311         // symbols from static libraries in shared libraries.
312         //
313         // Whenever a dynamic library is built on Windows it must have its public
314         // interface specified by functions tagged with `dllexport` or otherwise
315         // they're not available to be linked against. This poses a few problems
316         // for the compiler, some of which are somewhat fundamental, but we use
317         // the `use_dll_storage_attrs` variable below to attach the `dllexport`
318         // attribute to all LLVM functions that are exported e.g., they're
319         // already tagged with external linkage). This is suboptimal for a few
320         // reasons:
321         //
322         // * If an object file will never be included in a dynamic library,
323         //   there's no need to attach the dllexport attribute. Most object
324         //   files in Rust are not destined to become part of a dll as binaries
325         //   are statically linked by default.
326         // * If the compiler is emitting both an rlib and a dylib, the same
327         //   source object file is currently used but with MSVC this may be less
328         //   feasible. The compiler may be able to get around this, but it may
329         //   involve some invasive changes to deal with this.
330         //
331         // The flipside of this situation is that whenever you link to a dll and
332         // you import a function from it, the import should be tagged with
333         // `dllimport`. At this time, however, the compiler does not emit
334         // `dllimport` for any declarations other than constants (where it is
335         // required), which is again suboptimal for even more reasons!
336         //
337         // * Calling a function imported from another dll without using
338         //   `dllimport` causes the linker/compiler to have extra overhead (one
339         //   `jmp` instruction on x86) when calling the function.
340         // * The same object file may be used in different circumstances, so a
341         //   function may be imported from a dll if the object is linked into a
342         //   dll, but it may be just linked against if linked into an rlib.
343         // * The compiler has no knowledge about whether native functions should
344         //   be tagged dllimport or not.
345         //
346         // For now the compiler takes the perf hit (I do not have any numbers to
347         // this effect) by marking very little as `dllimport` and praying the
348         // linker will take care of everything. Fixing this problem will likely
349         // require adding a few attributes to Rust itself (feature gated at the
350         // start) and then strongly recommending static linkage on Windows!
351         let use_dll_storage_attrs = tcx.sess.target.is_like_windows;
352
353         let check_overflow = tcx.sess.overflow_checks();
354
355         let tls_model = to_llvm_tls_model(tcx.sess.tls_model());
356
357         let (llcx, llmod) = (&*llvm_module.llcx, llvm_module.llmod());
358
359         let coverage_cx = if tcx.sess.instrument_coverage() {
360             let covctx = coverageinfo::CrateCoverageContext::new();
361             Some(covctx)
362         } else {
363             None
364         };
365
366         let dbg_cx = if tcx.sess.opts.debuginfo != DebugInfo::None {
367             let dctx = debuginfo::CrateDebugContext::new(llmod);
368             debuginfo::metadata::compile_unit_metadata(tcx, codegen_unit.name().as_str(), &dctx);
369             Some(dctx)
370         } else {
371             None
372         };
373
374         let isize_ty = Type::ix_llcx(llcx, tcx.data_layout.pointer_size.bits());
375
376         CodegenCx {
377             tcx,
378             check_overflow,
379             use_dll_storage_attrs,
380             tls_model,
381             llmod,
382             llcx,
383             codegen_unit,
384             instances: Default::default(),
385             vtables: Default::default(),
386             const_cstr_cache: Default::default(),
387             const_unsized: Default::default(),
388             const_globals: Default::default(),
389             statics_to_rauw: RefCell::new(Vec::new()),
390             used_statics: RefCell::new(Vec::new()),
391             compiler_used_statics: RefCell::new(Vec::new()),
392             type_lowering: Default::default(),
393             scalar_lltypes: Default::default(),
394             pointee_infos: Default::default(),
395             isize_ty,
396             coverage_cx,
397             dbg_cx,
398             eh_personality: Cell::new(None),
399             eh_catch_typeinfo: Cell::new(None),
400             rust_try_fn: Cell::new(None),
401             intrinsics: Default::default(),
402             local_gen_sym_counter: Cell::new(0),
403         }
404     }
405
406     crate fn statics_to_rauw(&self) -> &RefCell<Vec<(&'ll Value, &'ll Value)>> {
407         &self.statics_to_rauw
408     }
409
410     #[inline]
411     pub fn coverage_context(&self) -> Option<&coverageinfo::CrateCoverageContext<'ll, 'tcx>> {
412         self.coverage_cx.as_ref()
413     }
414
415     fn create_used_variable_impl(&self, name: &'static CStr, values: &[&'ll Value]) {
416         let section = cstr!("llvm.metadata");
417         let array = self.const_array(self.type_ptr_to(self.type_i8()), values);
418
419         unsafe {
420             let g = llvm::LLVMAddGlobal(self.llmod, self.val_ty(array), name.as_ptr());
421             llvm::LLVMSetInitializer(g, array);
422             llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
423             llvm::LLVMSetSection(g, section.as_ptr());
424         }
425     }
426 }
427
428 impl<'ll, 'tcx> MiscMethods<'tcx> for CodegenCx<'ll, 'tcx> {
429     fn vtables(
430         &self,
431     ) -> &RefCell<FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), &'ll Value>>
432     {
433         &self.vtables
434     }
435
436     fn get_fn(&self, instance: Instance<'tcx>) -> &'ll Value {
437         get_fn(self, instance)
438     }
439
440     fn get_fn_addr(&self, instance: Instance<'tcx>) -> &'ll Value {
441         get_fn(self, instance)
442     }
443
444     fn eh_personality(&self) -> &'ll Value {
445         // The exception handling personality function.
446         //
447         // If our compilation unit has the `eh_personality` lang item somewhere
448         // within it, then we just need to codegen that. Otherwise, we're
449         // building an rlib which will depend on some upstream implementation of
450         // this function, so we just codegen a generic reference to it. We don't
451         // specify any of the types for the function, we just make it a symbol
452         // that LLVM can later use.
453         //
454         // Note that MSVC is a little special here in that we don't use the
455         // `eh_personality` lang item at all. Currently LLVM has support for
456         // both Dwarf and SEH unwind mechanisms for MSVC targets and uses the
457         // *name of the personality function* to decide what kind of unwind side
458         // tables/landing pads to emit. It looks like Dwarf is used by default,
459         // injecting a dependency on the `_Unwind_Resume` symbol for resuming
460         // an "exception", but for MSVC we want to force SEH. This means that we
461         // can't actually have the personality function be our standard
462         // `rust_eh_personality` function, but rather we wired it up to the
463         // CRT's custom personality function, which forces LLVM to consider
464         // landing pads as "landing pads for SEH".
465         if let Some(llpersonality) = self.eh_personality.get() {
466             return llpersonality;
467         }
468         let tcx = self.tcx;
469         let llfn = match tcx.lang_items().eh_personality() {
470             Some(def_id) if !wants_msvc_seh(self.sess()) => self.get_fn_addr(
471                 ty::Instance::resolve(
472                     tcx,
473                     ty::ParamEnv::reveal_all(),
474                     def_id,
475                     tcx.intern_substs(&[]),
476                 )
477                 .unwrap()
478                 .unwrap(),
479             ),
480             _ => {
481                 let name = if wants_msvc_seh(self.sess()) {
482                     "__CxxFrameHandler3"
483                 } else {
484                     "rust_eh_personality"
485                 };
486                 if let Some(llfn) = self.get_declared_value(name) {
487                     llfn
488                 } else {
489                     let fty = self.type_variadic_func(&[], self.type_i32());
490                     let llfn = self.declare_cfn(name, llvm::UnnamedAddr::Global, fty);
491                     attributes::apply_target_cpu_attr(self, llfn);
492                     llfn
493                 }
494             }
495         };
496         self.eh_personality.set(Some(llfn));
497         llfn
498     }
499
500     fn sess(&self) -> &Session {
501         self.tcx.sess
502     }
503
504     fn check_overflow(&self) -> bool {
505         self.check_overflow
506     }
507
508     fn codegen_unit(&self) -> &'tcx CodegenUnit<'tcx> {
509         self.codegen_unit
510     }
511
512     fn used_statics(&self) -> &RefCell<Vec<&'ll Value>> {
513         &self.used_statics
514     }
515
516     fn compiler_used_statics(&self) -> &RefCell<Vec<&'ll Value>> {
517         &self.compiler_used_statics
518     }
519
520     fn set_frame_pointer_type(&self, llfn: &'ll Value) {
521         attributes::set_frame_pointer_type(self, llfn)
522     }
523
524     fn apply_target_cpu_attr(&self, llfn: &'ll Value) {
525         attributes::apply_target_cpu_attr(self, llfn);
526         attributes::apply_tune_cpu_attr(self, llfn);
527     }
528
529     fn create_used_variable(&self) {
530         self.create_used_variable_impl(cstr!("llvm.used"), &*self.used_statics.borrow());
531     }
532
533     fn create_compiler_used_variable(&self) {
534         self.create_used_variable_impl(
535             cstr!("llvm.compiler.used"),
536             &*self.compiler_used_statics.borrow(),
537         );
538     }
539
540     fn declare_c_main(&self, fn_type: Self::Type) -> Option<Self::Function> {
541         if self.get_declared_value("main").is_none() {
542             Some(self.declare_cfn("main", llvm::UnnamedAddr::Global, fn_type))
543         } else {
544             // If the symbol already exists, it is an error: for example, the user wrote
545             // #[no_mangle] extern "C" fn main(..) {..}
546             // instead of #[start]
547             None
548         }
549     }
550 }
551
552 impl<'ll> CodegenCx<'ll, '_> {
553     crate fn get_intrinsic(&self, key: &str) -> (&'ll Type, &'ll Value) {
554         if let Some(v) = self.intrinsics.borrow().get(key).cloned() {
555             return v;
556         }
557
558         self.declare_intrinsic(key).unwrap_or_else(|| bug!("unknown intrinsic '{}'", key))
559     }
560
561     fn insert_intrinsic(
562         &self,
563         name: &'static str,
564         args: Option<&[&'ll llvm::Type]>,
565         ret: &'ll llvm::Type,
566     ) -> (&'ll llvm::Type, &'ll llvm::Value) {
567         let fn_ty = if let Some(args) = args {
568             self.type_func(args, ret)
569         } else {
570             self.type_variadic_func(&[], ret)
571         };
572         let f = self.declare_cfn(name, llvm::UnnamedAddr::No, fn_ty);
573         self.intrinsics.borrow_mut().insert(name, (fn_ty, f));
574         (fn_ty, f)
575     }
576
577     fn declare_intrinsic(&self, key: &str) -> Option<(&'ll Type, &'ll Value)> {
578         macro_rules! ifn {
579             ($name:expr, fn() -> $ret:expr) => (
580                 if key == $name {
581                     return Some(self.insert_intrinsic($name, Some(&[]), $ret));
582                 }
583             );
584             ($name:expr, fn(...) -> $ret:expr) => (
585                 if key == $name {
586                     return Some(self.insert_intrinsic($name, None, $ret));
587                 }
588             );
589             ($name:expr, fn($($arg:expr),*) -> $ret:expr) => (
590                 if key == $name {
591                     return Some(self.insert_intrinsic($name, Some(&[$($arg),*]), $ret));
592                 }
593             );
594         }
595         macro_rules! mk_struct {
596             ($($field_ty:expr),*) => (self.type_struct( &[$($field_ty),*], false))
597         }
598
599         let i8p = self.type_i8p();
600         let void = self.type_void();
601         let i1 = self.type_i1();
602         let t_i8 = self.type_i8();
603         let t_i16 = self.type_i16();
604         let t_i32 = self.type_i32();
605         let t_i64 = self.type_i64();
606         let t_i128 = self.type_i128();
607         let t_isize = self.type_isize();
608         let t_f32 = self.type_f32();
609         let t_f64 = self.type_f64();
610
611         ifn!("llvm.wasm.trunc.unsigned.i32.f32", fn(t_f32) -> t_i32);
612         ifn!("llvm.wasm.trunc.unsigned.i32.f64", fn(t_f64) -> t_i32);
613         ifn!("llvm.wasm.trunc.unsigned.i64.f32", fn(t_f32) -> t_i64);
614         ifn!("llvm.wasm.trunc.unsigned.i64.f64", fn(t_f64) -> t_i64);
615         ifn!("llvm.wasm.trunc.signed.i32.f32", fn(t_f32) -> t_i32);
616         ifn!("llvm.wasm.trunc.signed.i32.f64", fn(t_f64) -> t_i32);
617         ifn!("llvm.wasm.trunc.signed.i64.f32", fn(t_f32) -> t_i64);
618         ifn!("llvm.wasm.trunc.signed.i64.f64", fn(t_f64) -> t_i64);
619
620         ifn!("llvm.fptosi.sat.i8.f32", fn(t_f32) -> t_i8);
621         ifn!("llvm.fptosi.sat.i16.f32", fn(t_f32) -> t_i16);
622         ifn!("llvm.fptosi.sat.i32.f32", fn(t_f32) -> t_i32);
623         ifn!("llvm.fptosi.sat.i64.f32", fn(t_f32) -> t_i64);
624         ifn!("llvm.fptosi.sat.i128.f32", fn(t_f32) -> t_i128);
625         ifn!("llvm.fptosi.sat.i8.f64", fn(t_f64) -> t_i8);
626         ifn!("llvm.fptosi.sat.i16.f64", fn(t_f64) -> t_i16);
627         ifn!("llvm.fptosi.sat.i32.f64", fn(t_f64) -> t_i32);
628         ifn!("llvm.fptosi.sat.i64.f64", fn(t_f64) -> t_i64);
629         ifn!("llvm.fptosi.sat.i128.f64", fn(t_f64) -> t_i128);
630
631         ifn!("llvm.fptoui.sat.i8.f32", fn(t_f32) -> t_i8);
632         ifn!("llvm.fptoui.sat.i16.f32", fn(t_f32) -> t_i16);
633         ifn!("llvm.fptoui.sat.i32.f32", fn(t_f32) -> t_i32);
634         ifn!("llvm.fptoui.sat.i64.f32", fn(t_f32) -> t_i64);
635         ifn!("llvm.fptoui.sat.i128.f32", fn(t_f32) -> t_i128);
636         ifn!("llvm.fptoui.sat.i8.f64", fn(t_f64) -> t_i8);
637         ifn!("llvm.fptoui.sat.i16.f64", fn(t_f64) -> t_i16);
638         ifn!("llvm.fptoui.sat.i32.f64", fn(t_f64) -> t_i32);
639         ifn!("llvm.fptoui.sat.i64.f64", fn(t_f64) -> t_i64);
640         ifn!("llvm.fptoui.sat.i128.f64", fn(t_f64) -> t_i128);
641
642         ifn!("llvm.trap", fn() -> void);
643         ifn!("llvm.debugtrap", fn() -> void);
644         ifn!("llvm.frameaddress", fn(t_i32) -> i8p);
645
646         ifn!("llvm.powi.f32", fn(t_f32, t_i32) -> t_f32);
647         ifn!("llvm.powi.f64", fn(t_f64, t_i32) -> t_f64);
648
649         ifn!("llvm.pow.f32", fn(t_f32, t_f32) -> t_f32);
650         ifn!("llvm.pow.f64", fn(t_f64, t_f64) -> t_f64);
651
652         ifn!("llvm.sqrt.f32", fn(t_f32) -> t_f32);
653         ifn!("llvm.sqrt.f64", fn(t_f64) -> t_f64);
654
655         ifn!("llvm.sin.f32", fn(t_f32) -> t_f32);
656         ifn!("llvm.sin.f64", fn(t_f64) -> t_f64);
657
658         ifn!("llvm.cos.f32", fn(t_f32) -> t_f32);
659         ifn!("llvm.cos.f64", fn(t_f64) -> t_f64);
660
661         ifn!("llvm.exp.f32", fn(t_f32) -> t_f32);
662         ifn!("llvm.exp.f64", fn(t_f64) -> t_f64);
663
664         ifn!("llvm.exp2.f32", fn(t_f32) -> t_f32);
665         ifn!("llvm.exp2.f64", fn(t_f64) -> t_f64);
666
667         ifn!("llvm.log.f32", fn(t_f32) -> t_f32);
668         ifn!("llvm.log.f64", fn(t_f64) -> t_f64);
669
670         ifn!("llvm.log10.f32", fn(t_f32) -> t_f32);
671         ifn!("llvm.log10.f64", fn(t_f64) -> t_f64);
672
673         ifn!("llvm.log2.f32", fn(t_f32) -> t_f32);
674         ifn!("llvm.log2.f64", fn(t_f64) -> t_f64);
675
676         ifn!("llvm.fma.f32", fn(t_f32, t_f32, t_f32) -> t_f32);
677         ifn!("llvm.fma.f64", fn(t_f64, t_f64, t_f64) -> t_f64);
678
679         ifn!("llvm.fabs.f32", fn(t_f32) -> t_f32);
680         ifn!("llvm.fabs.f64", fn(t_f64) -> t_f64);
681
682         ifn!("llvm.minnum.f32", fn(t_f32, t_f32) -> t_f32);
683         ifn!("llvm.minnum.f64", fn(t_f64, t_f64) -> t_f64);
684         ifn!("llvm.maxnum.f32", fn(t_f32, t_f32) -> t_f32);
685         ifn!("llvm.maxnum.f64", fn(t_f64, t_f64) -> t_f64);
686
687         ifn!("llvm.floor.f32", fn(t_f32) -> t_f32);
688         ifn!("llvm.floor.f64", fn(t_f64) -> t_f64);
689
690         ifn!("llvm.ceil.f32", fn(t_f32) -> t_f32);
691         ifn!("llvm.ceil.f64", fn(t_f64) -> t_f64);
692
693         ifn!("llvm.trunc.f32", fn(t_f32) -> t_f32);
694         ifn!("llvm.trunc.f64", fn(t_f64) -> t_f64);
695
696         ifn!("llvm.copysign.f32", fn(t_f32, t_f32) -> t_f32);
697         ifn!("llvm.copysign.f64", fn(t_f64, t_f64) -> t_f64);
698         ifn!("llvm.round.f32", fn(t_f32) -> t_f32);
699         ifn!("llvm.round.f64", fn(t_f64) -> t_f64);
700
701         ifn!("llvm.rint.f32", fn(t_f32) -> t_f32);
702         ifn!("llvm.rint.f64", fn(t_f64) -> t_f64);
703         ifn!("llvm.nearbyint.f32", fn(t_f32) -> t_f32);
704         ifn!("llvm.nearbyint.f64", fn(t_f64) -> t_f64);
705
706         ifn!("llvm.ctpop.i8", fn(t_i8) -> t_i8);
707         ifn!("llvm.ctpop.i16", fn(t_i16) -> t_i16);
708         ifn!("llvm.ctpop.i32", fn(t_i32) -> t_i32);
709         ifn!("llvm.ctpop.i64", fn(t_i64) -> t_i64);
710         ifn!("llvm.ctpop.i128", fn(t_i128) -> t_i128);
711
712         ifn!("llvm.ctlz.i8", fn(t_i8, i1) -> t_i8);
713         ifn!("llvm.ctlz.i16", fn(t_i16, i1) -> t_i16);
714         ifn!("llvm.ctlz.i32", fn(t_i32, i1) -> t_i32);
715         ifn!("llvm.ctlz.i64", fn(t_i64, i1) -> t_i64);
716         ifn!("llvm.ctlz.i128", fn(t_i128, i1) -> t_i128);
717
718         ifn!("llvm.cttz.i8", fn(t_i8, i1) -> t_i8);
719         ifn!("llvm.cttz.i16", fn(t_i16, i1) -> t_i16);
720         ifn!("llvm.cttz.i32", fn(t_i32, i1) -> t_i32);
721         ifn!("llvm.cttz.i64", fn(t_i64, i1) -> t_i64);
722         ifn!("llvm.cttz.i128", fn(t_i128, i1) -> t_i128);
723
724         ifn!("llvm.bswap.i16", fn(t_i16) -> t_i16);
725         ifn!("llvm.bswap.i32", fn(t_i32) -> t_i32);
726         ifn!("llvm.bswap.i64", fn(t_i64) -> t_i64);
727         ifn!("llvm.bswap.i128", fn(t_i128) -> t_i128);
728
729         ifn!("llvm.bitreverse.i8", fn(t_i8) -> t_i8);
730         ifn!("llvm.bitreverse.i16", fn(t_i16) -> t_i16);
731         ifn!("llvm.bitreverse.i32", fn(t_i32) -> t_i32);
732         ifn!("llvm.bitreverse.i64", fn(t_i64) -> t_i64);
733         ifn!("llvm.bitreverse.i128", fn(t_i128) -> t_i128);
734
735         ifn!("llvm.fshl.i8", fn(t_i8, t_i8, t_i8) -> t_i8);
736         ifn!("llvm.fshl.i16", fn(t_i16, t_i16, t_i16) -> t_i16);
737         ifn!("llvm.fshl.i32", fn(t_i32, t_i32, t_i32) -> t_i32);
738         ifn!("llvm.fshl.i64", fn(t_i64, t_i64, t_i64) -> t_i64);
739         ifn!("llvm.fshl.i128", fn(t_i128, t_i128, t_i128) -> t_i128);
740
741         ifn!("llvm.fshr.i8", fn(t_i8, t_i8, t_i8) -> t_i8);
742         ifn!("llvm.fshr.i16", fn(t_i16, t_i16, t_i16) -> t_i16);
743         ifn!("llvm.fshr.i32", fn(t_i32, t_i32, t_i32) -> t_i32);
744         ifn!("llvm.fshr.i64", fn(t_i64, t_i64, t_i64) -> t_i64);
745         ifn!("llvm.fshr.i128", fn(t_i128, t_i128, t_i128) -> t_i128);
746
747         ifn!("llvm.sadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
748         ifn!("llvm.sadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
749         ifn!("llvm.sadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
750         ifn!("llvm.sadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
751         ifn!("llvm.sadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
752
753         ifn!("llvm.uadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
754         ifn!("llvm.uadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
755         ifn!("llvm.uadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
756         ifn!("llvm.uadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
757         ifn!("llvm.uadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
758
759         ifn!("llvm.ssub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
760         ifn!("llvm.ssub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
761         ifn!("llvm.ssub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
762         ifn!("llvm.ssub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
763         ifn!("llvm.ssub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
764
765         ifn!("llvm.usub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
766         ifn!("llvm.usub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
767         ifn!("llvm.usub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
768         ifn!("llvm.usub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
769         ifn!("llvm.usub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
770
771         ifn!("llvm.smul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
772         ifn!("llvm.smul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
773         ifn!("llvm.smul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
774         ifn!("llvm.smul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
775         ifn!("llvm.smul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
776
777         ifn!("llvm.umul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
778         ifn!("llvm.umul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
779         ifn!("llvm.umul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
780         ifn!("llvm.umul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
781         ifn!("llvm.umul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
782
783         ifn!("llvm.sadd.sat.i8", fn(t_i8, t_i8) -> t_i8);
784         ifn!("llvm.sadd.sat.i16", fn(t_i16, t_i16) -> t_i16);
785         ifn!("llvm.sadd.sat.i32", fn(t_i32, t_i32) -> t_i32);
786         ifn!("llvm.sadd.sat.i64", fn(t_i64, t_i64) -> t_i64);
787         ifn!("llvm.sadd.sat.i128", fn(t_i128, t_i128) -> t_i128);
788
789         ifn!("llvm.uadd.sat.i8", fn(t_i8, t_i8) -> t_i8);
790         ifn!("llvm.uadd.sat.i16", fn(t_i16, t_i16) -> t_i16);
791         ifn!("llvm.uadd.sat.i32", fn(t_i32, t_i32) -> t_i32);
792         ifn!("llvm.uadd.sat.i64", fn(t_i64, t_i64) -> t_i64);
793         ifn!("llvm.uadd.sat.i128", fn(t_i128, t_i128) -> t_i128);
794
795         ifn!("llvm.ssub.sat.i8", fn(t_i8, t_i8) -> t_i8);
796         ifn!("llvm.ssub.sat.i16", fn(t_i16, t_i16) -> t_i16);
797         ifn!("llvm.ssub.sat.i32", fn(t_i32, t_i32) -> t_i32);
798         ifn!("llvm.ssub.sat.i64", fn(t_i64, t_i64) -> t_i64);
799         ifn!("llvm.ssub.sat.i128", fn(t_i128, t_i128) -> t_i128);
800
801         ifn!("llvm.usub.sat.i8", fn(t_i8, t_i8) -> t_i8);
802         ifn!("llvm.usub.sat.i16", fn(t_i16, t_i16) -> t_i16);
803         ifn!("llvm.usub.sat.i32", fn(t_i32, t_i32) -> t_i32);
804         ifn!("llvm.usub.sat.i64", fn(t_i64, t_i64) -> t_i64);
805         ifn!("llvm.usub.sat.i128", fn(t_i128, t_i128) -> t_i128);
806
807         ifn!("llvm.lifetime.start.p0i8", fn(t_i64, i8p) -> void);
808         ifn!("llvm.lifetime.end.p0i8", fn(t_i64, i8p) -> void);
809
810         ifn!("llvm.expect.i1", fn(i1, i1) -> i1);
811         ifn!("llvm.eh.typeid.for", fn(i8p) -> t_i32);
812         ifn!("llvm.localescape", fn(...) -> void);
813         ifn!("llvm.localrecover", fn(i8p, i8p, t_i32) -> i8p);
814         ifn!("llvm.x86.seh.recoverfp", fn(i8p, i8p) -> i8p);
815
816         ifn!("llvm.assume", fn(i1) -> void);
817         ifn!("llvm.prefetch", fn(i8p, t_i32, t_i32, t_i32) -> void);
818
819         // This isn't an "LLVM intrinsic", but LLVM's optimization passes
820         // recognize it like one and we assume it exists in `core::slice::cmp`
821         ifn!("memcmp", fn(i8p, i8p, t_isize) -> t_i32);
822
823         // variadic intrinsics
824         ifn!("llvm.va_start", fn(i8p) -> void);
825         ifn!("llvm.va_end", fn(i8p) -> void);
826         ifn!("llvm.va_copy", fn(i8p, i8p) -> void);
827
828         if self.sess().instrument_coverage() {
829             ifn!("llvm.instrprof.increment", fn(i8p, t_i64, t_i32, t_i32) -> void);
830         }
831
832         ifn!("llvm.type.test", fn(i8p, self.type_metadata()) -> i1);
833
834         if self.sess().opts.debuginfo != DebugInfo::None {
835             ifn!("llvm.dbg.declare", fn(self.type_metadata(), self.type_metadata()) -> void);
836             ifn!("llvm.dbg.value", fn(self.type_metadata(), t_i64, self.type_metadata()) -> void);
837         }
838         None
839     }
840
841     crate fn eh_catch_typeinfo(&self) -> &'ll Value {
842         if let Some(eh_catch_typeinfo) = self.eh_catch_typeinfo.get() {
843             return eh_catch_typeinfo;
844         }
845         let tcx = self.tcx;
846         assert!(self.sess().target.is_like_emscripten);
847         let eh_catch_typeinfo = match tcx.lang_items().eh_catch_typeinfo() {
848             Some(def_id) => self.get_static(def_id),
849             _ => {
850                 let ty = self
851                     .type_struct(&[self.type_ptr_to(self.type_isize()), self.type_i8p()], false);
852                 self.declare_global("rust_eh_catch_typeinfo", ty)
853             }
854         };
855         let eh_catch_typeinfo = self.const_bitcast(eh_catch_typeinfo, self.type_i8p());
856         self.eh_catch_typeinfo.set(Some(eh_catch_typeinfo));
857         eh_catch_typeinfo
858     }
859 }
860
861 impl CodegenCx<'_, '_> {
862     /// Generates a new symbol name with the given prefix. This symbol name must
863     /// only be used for definitions with `internal` or `private` linkage.
864     pub fn generate_local_symbol_name(&self, prefix: &str) -> String {
865         let idx = self.local_gen_sym_counter.get();
866         self.local_gen_sym_counter.set(idx + 1);
867         // Include a '.' character, so there can be no accidental conflicts with
868         // user defined names
869         let mut name = String::with_capacity(prefix.len() + 6);
870         name.push_str(prefix);
871         name.push('.');
872         base_n::push_str(idx as u128, base_n::ALPHANUMERIC_ONLY, &mut name);
873         name
874     }
875 }
876
877 impl HasDataLayout for CodegenCx<'_, '_> {
878     #[inline]
879     fn data_layout(&self) -> &TargetDataLayout {
880         &self.tcx.data_layout
881     }
882 }
883
884 impl HasTargetSpec for CodegenCx<'_, '_> {
885     #[inline]
886     fn target_spec(&self) -> &Target {
887         &self.tcx.sess.target
888     }
889 }
890
891 impl<'tcx> ty::layout::HasTyCtxt<'tcx> for CodegenCx<'_, 'tcx> {
892     #[inline]
893     fn tcx(&self) -> TyCtxt<'tcx> {
894         self.tcx
895     }
896 }
897
898 impl<'tcx, 'll> HasParamEnv<'tcx> for CodegenCx<'ll, 'tcx> {
899     fn param_env(&self) -> ty::ParamEnv<'tcx> {
900         ty::ParamEnv::reveal_all()
901     }
902 }
903
904 impl<'tcx> LayoutOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
905     type LayoutOfResult = TyAndLayout<'tcx>;
906
907     #[inline]
908     fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
909         if let LayoutError::SizeOverflow(_) = err {
910             self.sess().span_fatal(span, &err.to_string())
911         } else {
912             span_bug!(span, "failed to get layout for `{}`: {}", ty, err)
913         }
914     }
915 }
916
917 impl<'tcx> FnAbiOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
918     type FnAbiOfResult = &'tcx FnAbi<'tcx, Ty<'tcx>>;
919
920     #[inline]
921     fn handle_fn_abi_err(
922         &self,
923         err: FnAbiError<'tcx>,
924         span: Span,
925         fn_abi_request: FnAbiRequest<'tcx>,
926     ) -> ! {
927         if let FnAbiError::Layout(LayoutError::SizeOverflow(_)) = err {
928             self.sess().span_fatal(span, &err.to_string())
929         } else {
930             match fn_abi_request {
931                 FnAbiRequest::OfFnPtr { sig, extra_args } => {
932                     span_bug!(
933                         span,
934                         "`fn_abi_of_fn_ptr({}, {:?})` failed: {}",
935                         sig,
936                         extra_args,
937                         err
938                     );
939                 }
940                 FnAbiRequest::OfInstance { instance, extra_args } => {
941                     span_bug!(
942                         span,
943                         "`fn_abi_of_instance({}, {:?})` failed: {}",
944                         instance,
945                         extra_args,
946                         err
947                     );
948                 }
949             }
950         }
951     }
952 }