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