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