1use std::borrow::{Borrow, Cow};
2use std::cell::{Cell, RefCell};
3use std::ffi::{CStr, c_char, c_uint};
4use std::marker::PhantomData;
5use std::ops::{Deref, DerefMut};
6use std::str;
7
8use rustc_abi::{HasDataLayout, Size, TargetDataLayout, VariantIdx};
9use rustc_codegen_ssa::back::versioned_llvm_target;
10use rustc_codegen_ssa::base::{wants_msvc_seh, wants_wasm_eh};
11use rustc_codegen_ssa::common::TypeKind;
12use rustc_codegen_ssa::errors as ssa_errors;
13use rustc_codegen_ssa::traits::*;
14use rustc_data_structures::base_n::{ALPHANUMERIC_ONLY, ToBaseN};
15use rustc_data_structures::fx::FxHashMap;
16use rustc_data_structures::small_c_str::SmallCStr;
17use rustc_hir::def_id::DefId;
18use rustc_middle::middle::codegen_fn_attrs::PatchableFunctionEntry;
19use rustc_middle::mir::mono::CodegenUnit;
20use rustc_middle::ty::layout::{
21 FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers,
22};
23use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
24use rustc_middle::{bug, span_bug};
25use rustc_session::Session;
26use rustc_session::config::{
27 BranchProtection, CFGuard, CFProtection, CrateType, DebugInfo, FunctionReturn, PAuthKey, PacRet,
28};
29use rustc_span::source_map::Spanned;
30use rustc_span::{DUMMY_SP, Span};
31use rustc_symbol_mangling::mangle_internal_symbol;
32use rustc_target::spec::{HasTargetSpec, RelocModel, SmallDataThresholdSupport, Target, TlsModel};
33use smallvec::SmallVec;
34
35use crate::back::write::to_llvm_code_model;
36use crate::callee::get_fn;
37use crate::debuginfo::metadata::apply_vcall_visibility_metadata;
38use crate::llvm::Metadata;
39use crate::type_::Type;
40use crate::value::Value;
41use crate::{attributes, common, coverageinfo, debuginfo, llvm, llvm_util};
42
43pub(crate) struct SCx<'ll> {
48 pub llmod: &'ll llvm::Module,
49 pub llcx: &'ll llvm::Context,
50 pub isize_ty: &'ll Type,
51}
52
53impl<'ll> Borrow<SCx<'ll>> for FullCx<'ll, '_> {
54 fn borrow(&self) -> &SCx<'ll> {
55 &self.scx
56 }
57}
58
59impl<'ll, 'tcx> Deref for FullCx<'ll, 'tcx> {
60 type Target = SimpleCx<'ll>;
61
62 #[inline]
63 fn deref(&self) -> &Self::Target {
64 &self.scx
65 }
66}
67
68pub(crate) struct GenericCx<'ll, T: Borrow<SCx<'ll>>>(T, PhantomData<SCx<'ll>>);
69
70impl<'ll, T: Borrow<SCx<'ll>>> Deref for GenericCx<'ll, T> {
71 type Target = T;
72
73 #[inline]
74 fn deref(&self) -> &Self::Target {
75 &self.0
76 }
77}
78
79impl<'ll, T: Borrow<SCx<'ll>>> DerefMut for GenericCx<'ll, T> {
80 #[inline]
81 fn deref_mut(&mut self) -> &mut Self::Target {
82 &mut self.0
83 }
84}
85
86pub(crate) type SimpleCx<'ll> = GenericCx<'ll, SCx<'ll>>;
87
88pub(crate) type CodegenCx<'ll, 'tcx> = GenericCx<'ll, FullCx<'ll, 'tcx>>;
92
93pub(crate) struct FullCx<'ll, 'tcx> {
94 pub tcx: TyCtxt<'tcx>,
95 pub scx: SimpleCx<'ll>,
96 pub use_dll_storage_attrs: bool,
97 pub tls_model: llvm::ThreadLocalMode,
98
99 pub codegen_unit: &'tcx CodegenUnit<'tcx>,
100
101 pub instances: RefCell<FxHashMap<Instance<'tcx>, &'ll Value>>,
103 pub vtables: RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>>,
105 pub const_str_cache: RefCell<FxHashMap<String, &'ll Value>>,
107
108 pub const_globals: RefCell<FxHashMap<&'ll Value, &'ll Value>>,
110
111 pub statics_to_rauw: RefCell<Vec<(&'ll Value, &'ll Value)>>,
116
117 pub used_statics: Vec<&'ll Value>,
120
121 pub compiler_used_statics: Vec<&'ll Value>,
124
125 pub type_lowering: RefCell<FxHashMap<(Ty<'tcx>, Option<VariantIdx>), &'ll Type>>,
127
128 pub scalar_lltypes: RefCell<FxHashMap<Ty<'tcx>, &'ll Type>>,
130
131 pub coverage_cx: Option<coverageinfo::CguCoverageContext<'ll, 'tcx>>,
133 pub dbg_cx: Option<debuginfo::CodegenUnitDebugContext<'ll, 'tcx>>,
134
135 eh_personality: Cell<Option<&'ll Value>>,
136 eh_catch_typeinfo: Cell<Option<&'ll Value>>,
137 pub rust_try_fn: Cell<Option<(&'ll Type, &'ll Value)>>,
138
139 intrinsics:
140 RefCell<FxHashMap<(Cow<'static, str>, SmallVec<[&'ll Type; 2]>), (&'ll Type, &'ll Value)>>,
141
142 local_gen_sym_counter: Cell<usize>,
144
145 pub renamed_statics: RefCell<FxHashMap<DefId, &'ll Value>>,
150}
151
152fn to_llvm_tls_model(tls_model: TlsModel) -> llvm::ThreadLocalMode {
153 match tls_model {
154 TlsModel::GeneralDynamic => llvm::ThreadLocalMode::GeneralDynamic,
155 TlsModel::LocalDynamic => llvm::ThreadLocalMode::LocalDynamic,
156 TlsModel::InitialExec => llvm::ThreadLocalMode::InitialExec,
157 TlsModel::LocalExec => llvm::ThreadLocalMode::LocalExec,
158 TlsModel::Emulated => llvm::ThreadLocalMode::GeneralDynamic,
159 }
160}
161
162pub(crate) unsafe fn create_module<'ll>(
163 tcx: TyCtxt<'_>,
164 llcx: &'ll llvm::Context,
165 mod_name: &str,
166) -> &'ll llvm::Module {
167 let sess = tcx.sess;
168 let mod_name = SmallCStr::new(mod_name);
169 let llmod = unsafe { llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx) };
170
171 let cx = SimpleCx::new(llmod, llcx, tcx.data_layout.pointer_size());
172
173 let mut target_data_layout = sess.target.data_layout.to_string();
174 let llvm_version = llvm_util::get_version();
175
176 if llvm_version < (20, 0, 0) {
177 if sess.target.arch == "aarch64" || sess.target.arch.starts_with("arm64") {
178 target_data_layout =
182 target_data_layout.replace("-p270:32:32-p271:32:32-p272:64:64", "");
183 }
184 if sess.target.arch.starts_with("sparc") {
185 target_data_layout = target_data_layout.replace("-i128:128", "");
188 }
189 if sess.target.arch.starts_with("mips64") {
190 target_data_layout = target_data_layout.replace("-i128:128", "");
193 }
194 if sess.target.arch.starts_with("powerpc64") {
195 target_data_layout = target_data_layout.replace("-i128:128", "");
198 }
199 if sess.target.arch.starts_with("wasm32") || sess.target.arch.starts_with("wasm64") {
200 target_data_layout = target_data_layout.replace("-i128:128", "");
203 }
204 }
205 if llvm_version < (21, 0, 0) {
206 if sess.target.arch == "nvptx64" {
207 target_data_layout = target_data_layout.replace("e-p6:32:32-i64", "e-i64");
209 }
210 if sess.target.arch == "amdgpu" {
211 target_data_layout = target_data_layout.replace("p8:128:128:128:48", "p8:128:128")
214 }
215 }
216 if llvm_version < (22, 0, 0) {
217 if sess.target.arch == "avr" {
218 target_data_layout = target_data_layout.replace("n8:16", "n8")
220 }
221 }
222
223 {
225 let tm = crate::back::write::create_informational_target_machine(sess, false);
226 unsafe {
227 llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm.raw());
228 }
229
230 let llvm_data_layout = unsafe { llvm::LLVMGetDataLayoutStr(llmod) };
231 let llvm_data_layout =
232 str::from_utf8(unsafe { CStr::from_ptr(llvm_data_layout) }.to_bytes())
233 .expect("got a non-UTF8 data-layout from LLVM");
234
235 if target_data_layout != llvm_data_layout {
236 tcx.dcx().emit_err(crate::errors::MismatchedDataLayout {
237 rustc_target: sess.opts.target_triple.to_string().as_str(),
238 rustc_layout: target_data_layout.as_str(),
239 llvm_target: sess.target.llvm_target.borrow(),
240 llvm_layout: llvm_data_layout,
241 });
242 }
243 }
244
245 let data_layout = SmallCStr::new(&target_data_layout);
246 unsafe {
247 llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
248 }
249
250 let llvm_target = SmallCStr::new(&versioned_llvm_target(sess));
251 unsafe {
252 llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
253 }
254
255 let reloc_model = sess.relocation_model();
256 if matches!(reloc_model, RelocModel::Pic | RelocModel::Pie) {
257 unsafe {
258 llvm::LLVMRustSetModulePICLevel(llmod);
259 }
260 if reloc_model == RelocModel::Pie
263 || tcx.crate_types().iter().all(|ty| *ty == CrateType::Executable)
264 {
265 unsafe {
266 llvm::LLVMRustSetModulePIELevel(llmod);
267 }
268 }
269 }
270
271 unsafe {
277 llvm::LLVMRustSetModuleCodeModel(llmod, to_llvm_code_model(sess.code_model()));
278 }
279
280 if !sess.needs_plt() {
283 llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "RtLibUseGOT", 1);
284 }
285
286 if sess.is_sanitizer_cfi_canonical_jump_tables_enabled() && sess.is_sanitizer_cfi_enabled() {
288 llvm::add_module_flag_u32(
289 llmod,
290 llvm::ModuleFlagMergeBehavior::Override,
291 "CFI Canonical Jump Tables",
292 1,
293 );
294 }
295
296 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
299 llvm::add_module_flag_u32(
300 llmod,
301 llvm::ModuleFlagMergeBehavior::Override,
302 "cfi-normalize-integers",
303 1,
304 );
305 }
306
307 if sess.is_split_lto_unit_enabled() || sess.is_sanitizer_cfi_enabled() {
310 llvm::add_module_flag_u32(
311 llmod,
312 llvm::ModuleFlagMergeBehavior::Override,
313 "EnableSplitLTOUnit",
314 1,
315 );
316 }
317
318 if sess.is_sanitizer_kcfi_enabled() {
320 llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Override, "kcfi", 1);
321
322 let pfe =
325 PatchableFunctionEntry::from_config(sess.opts.unstable_opts.patchable_function_entry);
326 if pfe.prefix() > 0 {
327 llvm::add_module_flag_u32(
328 llmod,
329 llvm::ModuleFlagMergeBehavior::Override,
330 "kcfi-offset",
331 pfe.prefix().into(),
332 );
333 }
334
335 if sess.is_sanitizer_kcfi_arity_enabled() {
338 if llvm_version < (21, 0, 0) {
340 tcx.dcx().emit_err(crate::errors::SanitizerKcfiArityRequiresLLVM2100);
341 }
342
343 llvm::add_module_flag_u32(
344 llmod,
345 llvm::ModuleFlagMergeBehavior::Override,
346 "kcfi-arity",
347 1,
348 );
349 }
350 }
351
352 if sess.target.is_like_msvc
354 || (sess.target.options.os == "windows"
355 && sess.target.options.env == "gnu"
356 && sess.target.options.abi == "llvm")
357 {
358 match sess.opts.cg.control_flow_guard {
359 CFGuard::Disabled => {}
360 CFGuard::NoChecks => {
361 llvm::add_module_flag_u32(
363 llmod,
364 llvm::ModuleFlagMergeBehavior::Warning,
365 "cfguard",
366 1,
367 );
368 }
369 CFGuard::Checks => {
370 llvm::add_module_flag_u32(
372 llmod,
373 llvm::ModuleFlagMergeBehavior::Warning,
374 "cfguard",
375 2,
376 );
377 }
378 }
379 }
380
381 if let Some(BranchProtection { bti, pac_ret }) = sess.opts.unstable_opts.branch_protection {
382 if sess.target.arch == "aarch64" {
383 llvm::add_module_flag_u32(
384 llmod,
385 llvm::ModuleFlagMergeBehavior::Min,
386 "branch-target-enforcement",
387 bti.into(),
388 );
389 llvm::add_module_flag_u32(
390 llmod,
391 llvm::ModuleFlagMergeBehavior::Min,
392 "sign-return-address",
393 pac_ret.is_some().into(),
394 );
395 let pac_opts = pac_ret.unwrap_or(PacRet { leaf: false, pc: false, key: PAuthKey::A });
396 llvm::add_module_flag_u32(
397 llmod,
398 llvm::ModuleFlagMergeBehavior::Min,
399 "branch-protection-pauth-lr",
400 pac_opts.pc.into(),
401 );
402 llvm::add_module_flag_u32(
403 llmod,
404 llvm::ModuleFlagMergeBehavior::Min,
405 "sign-return-address-all",
406 pac_opts.leaf.into(),
407 );
408 llvm::add_module_flag_u32(
409 llmod,
410 llvm::ModuleFlagMergeBehavior::Min,
411 "sign-return-address-with-bkey",
412 u32::from(pac_opts.key == PAuthKey::B),
413 );
414 } else {
415 bug!(
416 "branch-protection used on non-AArch64 target; \
417 this should be checked in rustc_session."
418 );
419 }
420 }
421
422 if let CFProtection::Branch | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
424 llvm::add_module_flag_u32(
425 llmod,
426 llvm::ModuleFlagMergeBehavior::Override,
427 "cf-protection-branch",
428 1,
429 );
430 }
431 if let CFProtection::Return | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
432 llvm::add_module_flag_u32(
433 llmod,
434 llvm::ModuleFlagMergeBehavior::Override,
435 "cf-protection-return",
436 1,
437 );
438 }
439
440 if sess.opts.unstable_opts.virtual_function_elimination {
441 llvm::add_module_flag_u32(
442 llmod,
443 llvm::ModuleFlagMergeBehavior::Error,
444 "Virtual Function Elim",
445 1,
446 );
447 }
448
449 if sess.opts.unstable_opts.ehcont_guard {
451 llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "ehcontguard", 1);
452 }
453
454 match sess.opts.unstable_opts.function_return {
455 FunctionReturn::Keep => {}
456 FunctionReturn::ThunkExtern => {
457 llvm::add_module_flag_u32(
458 llmod,
459 llvm::ModuleFlagMergeBehavior::Override,
460 "function_return_thunk_extern",
461 1,
462 );
463 }
464 }
465
466 match (sess.opts.unstable_opts.small_data_threshold, sess.target.small_data_threshold_support())
467 {
468 (Some(threshold), SmallDataThresholdSupport::LlvmModuleFlag(flag)) => {
471 llvm::add_module_flag_u32(
472 llmod,
473 llvm::ModuleFlagMergeBehavior::Error,
474 &flag,
475 threshold as u32,
476 );
477 }
478 _ => (),
479 };
480
481 #[allow(clippy::option_env_unwrap)]
486 let rustc_producer =
487 format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"));
488
489 let name_metadata = cx.create_metadata(rustc_producer.as_bytes());
490
491 unsafe {
492 llvm::LLVMAddNamedMetadataOperand(
493 llmod,
494 c"llvm.ident".as_ptr(),
495 &cx.get_metadata_value(llvm::LLVMMDNodeInContext2(llcx, &name_metadata, 1)),
496 );
497 }
498
499 let llvm_abiname = &sess.target.options.llvm_abiname;
505 if matches!(sess.target.arch.as_ref(), "riscv32" | "riscv64") && !llvm_abiname.is_empty() {
506 llvm::add_module_flag_str(
507 llmod,
508 llvm::ModuleFlagMergeBehavior::Error,
509 "target-abi",
510 llvm_abiname,
511 );
512 }
513
514 for (key, value, merge_behavior) in &sess.opts.unstable_opts.llvm_module_flag {
516 let merge_behavior = match merge_behavior.as_str() {
517 "error" => llvm::ModuleFlagMergeBehavior::Error,
518 "warning" => llvm::ModuleFlagMergeBehavior::Warning,
519 "require" => llvm::ModuleFlagMergeBehavior::Require,
520 "override" => llvm::ModuleFlagMergeBehavior::Override,
521 "append" => llvm::ModuleFlagMergeBehavior::Append,
522 "appendunique" => llvm::ModuleFlagMergeBehavior::AppendUnique,
523 "max" => llvm::ModuleFlagMergeBehavior::Max,
524 "min" => llvm::ModuleFlagMergeBehavior::Min,
525 _ => unreachable!(),
527 };
528 llvm::add_module_flag_u32(llmod, merge_behavior, key, *value);
529 }
530
531 llmod
532}
533
534impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
535 pub(crate) fn new(
536 tcx: TyCtxt<'tcx>,
537 codegen_unit: &'tcx CodegenUnit<'tcx>,
538 llvm_module: &'ll crate::ModuleLlvm,
539 ) -> Self {
540 let use_dll_storage_attrs = tcx.sess.target.is_like_windows;
593
594 let tls_model = to_llvm_tls_model(tcx.sess.tls_model());
595
596 let (llcx, llmod) = (&*llvm_module.llcx, llvm_module.llmod());
597
598 let coverage_cx =
599 tcx.sess.instrument_coverage().then(coverageinfo::CguCoverageContext::new);
600
601 let dbg_cx = if tcx.sess.opts.debuginfo != DebugInfo::None {
602 let dctx = debuginfo::CodegenUnitDebugContext::new(llmod);
603 debuginfo::metadata::build_compile_unit_di_node(
604 tcx,
605 codegen_unit.name().as_str(),
606 &dctx,
607 );
608 Some(dctx)
609 } else {
610 None
611 };
612
613 GenericCx(
614 FullCx {
615 tcx,
616 scx: SimpleCx::new(llmod, llcx, tcx.data_layout.pointer_size()),
617 use_dll_storage_attrs,
618 tls_model,
619 codegen_unit,
620 instances: Default::default(),
621 vtables: Default::default(),
622 const_str_cache: Default::default(),
623 const_globals: Default::default(),
624 statics_to_rauw: RefCell::new(Vec::new()),
625 used_statics: Vec::new(),
626 compiler_used_statics: Vec::new(),
627 type_lowering: Default::default(),
628 scalar_lltypes: Default::default(),
629 coverage_cx,
630 dbg_cx,
631 eh_personality: Cell::new(None),
632 eh_catch_typeinfo: Cell::new(None),
633 rust_try_fn: Cell::new(None),
634 intrinsics: Default::default(),
635 local_gen_sym_counter: Cell::new(0),
636 renamed_statics: Default::default(),
637 },
638 PhantomData,
639 )
640 }
641
642 pub(crate) fn statics_to_rauw(&self) -> &RefCell<Vec<(&'ll Value, &'ll Value)>> {
643 &self.statics_to_rauw
644 }
645
646 #[inline]
648 #[track_caller]
649 pub(crate) fn coverage_cx(&self) -> &coverageinfo::CguCoverageContext<'ll, 'tcx> {
650 self.coverage_cx.as_ref().expect("only called when coverage instrumentation is enabled")
651 }
652
653 pub(crate) fn create_used_variable_impl(&self, name: &'static CStr, values: &[&'ll Value]) {
654 let array = self.const_array(self.type_ptr(), values);
655
656 let g = llvm::add_global(self.llmod, self.val_ty(array), name);
657 llvm::set_initializer(g, array);
658 llvm::set_linkage(g, llvm::Linkage::AppendingLinkage);
659 llvm::set_section(g, c"llvm.metadata");
660 }
661}
662impl<'ll> SimpleCx<'ll> {
663 pub(crate) fn get_return_type(&self, ty: &'ll Type) -> &'ll Type {
664 assert_eq!(self.type_kind(ty), TypeKind::Function);
665 unsafe { llvm::LLVMGetReturnType(ty) }
666 }
667 pub(crate) fn get_type_of_global(&self, val: &'ll Value) -> &'ll Type {
668 unsafe { llvm::LLVMGlobalGetValueType(val) }
669 }
670 pub(crate) fn val_ty(&self, v: &'ll Value) -> &'ll Type {
671 common::val_ty(v)
672 }
673}
674impl<'ll> SimpleCx<'ll> {
675 pub(crate) fn new(
676 llmod: &'ll llvm::Module,
677 llcx: &'ll llvm::Context,
678 pointer_size: Size,
679 ) -> Self {
680 let isize_ty = llvm::Type::ix_llcx(llcx, pointer_size.bits());
681 Self(SCx { llmod, llcx, isize_ty }, PhantomData)
682 }
683}
684
685impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
686 pub(crate) fn get_metadata_value(&self, metadata: &'ll Metadata) -> &'ll Value {
687 llvm::LLVMMetadataAsValue(self.llcx(), metadata)
688 }
689
690 pub(crate) fn get_const_int(&self, ty: &'ll Type, val: u64) -> &'ll Value {
691 unsafe { llvm::LLVMConstInt(ty, val, llvm::False) }
692 }
693
694 pub(crate) fn get_const_i64(&self, n: u64) -> &'ll Value {
695 self.get_const_int(self.type_i64(), n)
696 }
697
698 pub(crate) fn get_const_i32(&self, n: u64) -> &'ll Value {
699 self.get_const_int(self.type_i32(), n)
700 }
701
702 pub(crate) fn get_const_i16(&self, n: u64) -> &'ll Value {
703 self.get_const_int(self.type_i16(), n)
704 }
705
706 pub(crate) fn get_const_i8(&self, n: u64) -> &'ll Value {
707 self.get_const_int(self.type_i8(), n)
708 }
709
710 pub(crate) fn get_function(&self, name: &str) -> Option<&'ll Value> {
711 let name = SmallCStr::new(name);
712 unsafe { llvm::LLVMGetNamedFunction((**self).borrow().llmod, name.as_ptr()) }
713 }
714
715 pub(crate) fn get_md_kind_id(&self, name: &str) -> llvm::MetadataKindId {
716 unsafe {
717 llvm::LLVMGetMDKindIDInContext(
718 self.llcx(),
719 name.as_ptr() as *const c_char,
720 name.len() as c_uint,
721 )
722 }
723 }
724
725 pub(crate) fn create_metadata(&self, name: &[u8]) -> &'ll Metadata {
726 unsafe {
727 llvm::LLVMMDStringInContext2(self.llcx(), name.as_ptr() as *const c_char, name.len())
728 }
729 }
730
731 pub(crate) fn get_functions(&self) -> Vec<&'ll Value> {
732 let mut functions = vec![];
733 let mut func = unsafe { llvm::LLVMGetFirstFunction(self.llmod()) };
734 while let Some(f) = func {
735 functions.push(f);
736 func = unsafe { llvm::LLVMGetNextFunction(f) }
737 }
738 functions
739 }
740}
741
742impl<'ll, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
743 fn vtables(
744 &self,
745 ) -> &RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>> {
746 &self.vtables
747 }
748
749 fn apply_vcall_visibility_metadata(
750 &self,
751 ty: Ty<'tcx>,
752 poly_trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
753 vtable: &'ll Value,
754 ) {
755 apply_vcall_visibility_metadata(self, ty, poly_trait_ref, vtable);
756 }
757
758 fn get_fn(&self, instance: Instance<'tcx>) -> &'ll Value {
759 get_fn(self, instance)
760 }
761
762 fn get_fn_addr(&self, instance: Instance<'tcx>) -> &'ll Value {
763 get_fn(self, instance)
764 }
765
766 fn eh_personality(&self) -> &'ll Value {
767 if let Some(llpersonality) = self.eh_personality.get() {
788 return llpersonality;
789 }
790
791 let name = if wants_msvc_seh(self.sess()) {
792 Some("__CxxFrameHandler3")
793 } else if wants_wasm_eh(self.sess()) {
794 Some("__gxx_wasm_personality_v0")
799 } else {
800 None
801 };
802
803 let tcx = self.tcx;
804 let llfn = match tcx.lang_items().eh_personality() {
805 Some(def_id) if name.is_none() => self.get_fn_addr(ty::Instance::expect_resolve(
806 tcx,
807 self.typing_env(),
808 def_id,
809 ty::List::empty(),
810 DUMMY_SP,
811 )),
812 _ => {
813 let name = name.unwrap_or("rust_eh_personality");
814 if let Some(llfn) = self.get_declared_value(name) {
815 llfn
816 } else {
817 let fty = self.type_variadic_func(&[], self.type_i32());
818 let llfn = self.declare_cfn(name, llvm::UnnamedAddr::Global, fty);
819 let target_cpu = attributes::target_cpu_attr(self);
820 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[target_cpu]);
821 llfn
822 }
823 }
824 };
825 self.eh_personality.set(Some(llfn));
826 llfn
827 }
828
829 fn sess(&self) -> &Session {
830 self.tcx.sess
831 }
832
833 fn set_frame_pointer_type(&self, llfn: &'ll Value) {
834 if let Some(attr) = attributes::frame_pointer_type_attr(self) {
835 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[attr]);
836 }
837 }
838
839 fn apply_target_cpu_attr(&self, llfn: &'ll Value) {
840 let mut attrs = SmallVec::<[_; 2]>::new();
841 attrs.push(attributes::target_cpu_attr(self));
842 attrs.extend(attributes::tune_cpu_attr(self));
843 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &attrs);
844 }
845
846 fn declare_c_main(&self, fn_type: Self::Type) -> Option<Self::Function> {
847 let entry_name = self.sess().target.entry_name.as_ref();
848 if self.get_declared_value(entry_name).is_none() {
849 Some(self.declare_entry_fn(
850 entry_name,
851 llvm::CallConv::from_conv(
852 self.sess().target.entry_abi,
853 self.sess().target.arch.borrow(),
854 ),
855 llvm::UnnamedAddr::Global,
856 fn_type,
857 ))
858 } else {
859 None
862 }
863 }
864}
865
866impl<'ll> CodegenCx<'ll, '_> {
867 pub(crate) fn get_intrinsic(
868 &self,
869 base_name: Cow<'static, str>,
870 type_params: &[&'ll Type],
871 ) -> (&'ll Type, &'ll Value) {
872 *self
873 .intrinsics
874 .borrow_mut()
875 .entry((base_name, SmallVec::from_slice(type_params)))
876 .or_insert_with_key(|(base_name, type_params)| {
877 self.declare_intrinsic(base_name, type_params)
878 })
879 }
880
881 fn declare_intrinsic(
882 &self,
883 base_name: &str,
884 type_params: &[&'ll Type],
885 ) -> (&'ll Type, &'ll Value) {
886 if base_name == "memcmp" {
890 let fn_ty = self
891 .type_func(&[self.type_ptr(), self.type_ptr(), self.type_isize()], self.type_int());
892 let f = self.declare_cfn("memcmp", llvm::UnnamedAddr::No, fn_ty);
893
894 return (fn_ty, f);
895 }
896
897 let intrinsic = llvm::Intrinsic::lookup(base_name.as_bytes())
898 .unwrap_or_else(|| bug!("Unknown intrinsic: `{base_name}`"));
899 let f = intrinsic.get_declaration(self.llmod, &type_params);
900
901 (self.get_type_of_global(f), f)
902 }
903
904 pub(crate) fn eh_catch_typeinfo(&self) -> &'ll Value {
905 if let Some(eh_catch_typeinfo) = self.eh_catch_typeinfo.get() {
906 return eh_catch_typeinfo;
907 }
908 let tcx = self.tcx;
909 assert!(self.sess().target.os == "emscripten");
910 let eh_catch_typeinfo = match tcx.lang_items().eh_catch_typeinfo() {
911 Some(def_id) => self.get_static(def_id),
912 _ => {
913 let ty = self.type_struct(&[self.type_ptr(), self.type_ptr()], false);
914 self.declare_global(&mangle_internal_symbol(self.tcx, "rust_eh_catch_typeinfo"), ty)
915 }
916 };
917 self.eh_catch_typeinfo.set(Some(eh_catch_typeinfo));
918 eh_catch_typeinfo
919 }
920}
921
922impl CodegenCx<'_, '_> {
923 pub(crate) fn generate_local_symbol_name(&self, prefix: &str) -> String {
926 let idx = self.local_gen_sym_counter.get();
927 self.local_gen_sym_counter.set(idx + 1);
928 let mut name = String::with_capacity(prefix.len() + 6);
931 name.push_str(prefix);
932 name.push('.');
933 name.push_str(&(idx as u64).to_base(ALPHANUMERIC_ONLY));
934 name
935 }
936}
937
938impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
939 pub(crate) fn set_metadata<'a>(
941 &self,
942 val: &'a Value,
943 kind_id: impl Into<llvm::MetadataKindId>,
944 md: &'ll Metadata,
945 ) {
946 let node = self.get_metadata_value(md);
947 llvm::LLVMSetMetadata(val, kind_id.into(), node);
948 }
949}
950
951impl HasDataLayout for CodegenCx<'_, '_> {
952 #[inline]
953 fn data_layout(&self) -> &TargetDataLayout {
954 &self.tcx.data_layout
955 }
956}
957
958impl HasTargetSpec for CodegenCx<'_, '_> {
959 #[inline]
960 fn target_spec(&self) -> &Target {
961 &self.tcx.sess.target
962 }
963}
964
965impl<'tcx> ty::layout::HasTyCtxt<'tcx> for CodegenCx<'_, 'tcx> {
966 #[inline]
967 fn tcx(&self) -> TyCtxt<'tcx> {
968 self.tcx
969 }
970}
971
972impl<'tcx, 'll> HasTypingEnv<'tcx> for CodegenCx<'ll, 'tcx> {
973 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
974 ty::TypingEnv::fully_monomorphized()
975 }
976}
977
978impl<'tcx> LayoutOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
979 #[inline]
980 fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
981 if let LayoutError::SizeOverflow(_) | LayoutError::ReferencesError(_) = err {
982 self.tcx.dcx().emit_fatal(Spanned { span, node: err.into_diagnostic() })
983 } else {
984 self.tcx.dcx().emit_fatal(ssa_errors::FailedToGetLayout { span, ty, err })
985 }
986 }
987}
988
989impl<'tcx> FnAbiOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
990 #[inline]
991 fn handle_fn_abi_err(
992 &self,
993 err: FnAbiError<'tcx>,
994 span: Span,
995 fn_abi_request: FnAbiRequest<'tcx>,
996 ) -> ! {
997 match err {
998 FnAbiError::Layout(LayoutError::SizeOverflow(_) | LayoutError::Cycle(_)) => {
999 self.tcx.dcx().emit_fatal(Spanned { span, node: err });
1000 }
1001 _ => match fn_abi_request {
1002 FnAbiRequest::OfFnPtr { sig, extra_args } => {
1003 span_bug!(span, "`fn_abi_of_fn_ptr({sig}, {extra_args:?})` failed: {err:?}",);
1004 }
1005 FnAbiRequest::OfInstance { instance, extra_args } => {
1006 span_bug!(
1007 span,
1008 "`fn_abi_of_instance({instance}, {extra_args:?})` failed: {err:?}",
1009 );
1010 }
1011 },
1012 }
1013 }
1014}