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::errors as ssa_errors;
12use rustc_codegen_ssa::traits::*;
13use rustc_data_structures::base_n::{ALPHANUMERIC_ONLY, ToBaseN};
14use rustc_data_structures::fx::FxHashMap;
15use rustc_data_structures::small_c_str::SmallCStr;
16use rustc_hir::def_id::DefId;
17use rustc_middle::middle::codegen_fn_attrs::PatchableFunctionEntry;
18use rustc_middle::mir::mono::CodegenUnit;
19use rustc_middle::ty::layout::{
20 FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers,
21};
22use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
23use rustc_middle::{bug, span_bug};
24use rustc_session::Session;
25use rustc_session::config::{
26 BranchProtection, CFGuard, CFProtection, CrateType, DebugInfo, FunctionReturn, PAuthKey, PacRet,
27};
28use rustc_span::source_map::Spanned;
29use rustc_span::{DUMMY_SP, Span, Symbol};
30use rustc_symbol_mangling::mangle_internal_symbol;
31use rustc_target::spec::{
32 Abi, Arch, Env, HasTargetSpec, Os, RelocModel, SmallDataThresholdSupport, Target, TlsModel,
33};
34use smallvec::SmallVec;
35
36use crate::abi::to_llvm_calling_convention;
37use crate::back::write::to_llvm_code_model;
38use crate::builder::gpu_offload::{OffloadGlobals, OffloadKernelGlobals};
39use crate::callee::get_fn;
40use crate::debuginfo::metadata::apply_vcall_visibility_metadata;
41use crate::llvm::{self, Metadata, MetadataKindId, Module, Type, Value};
42use crate::{attributes, common, coverageinfo, debuginfo, llvm_util};
43
44pub(crate) struct SCx<'ll> {
49 pub llmod: &'ll llvm::Module,
50 pub llcx: &'ll llvm::Context,
51 pub isize_ty: &'ll Type,
52}
53
54impl<'ll> Borrow<SCx<'ll>> for FullCx<'ll, '_> {
55 fn borrow(&self) -> &SCx<'ll> {
56 &self.scx
57 }
58}
59
60impl<'ll, 'tcx> Deref for FullCx<'ll, 'tcx> {
61 type Target = SimpleCx<'ll>;
62
63 #[inline]
64 fn deref(&self) -> &Self::Target {
65 &self.scx
66 }
67}
68
69pub(crate) struct GenericCx<'ll, T: Borrow<SCx<'ll>>>(T, PhantomData<SCx<'ll>>);
70
71impl<'ll, T: Borrow<SCx<'ll>>> Deref for GenericCx<'ll, T> {
72 type Target = T;
73
74 #[inline]
75 fn deref(&self) -> &Self::Target {
76 &self.0
77 }
78}
79
80impl<'ll, T: Borrow<SCx<'ll>>> DerefMut for GenericCx<'ll, T> {
81 #[inline]
82 fn deref_mut(&mut self) -> &mut Self::Target {
83 &mut self.0
84 }
85}
86
87pub(crate) type SimpleCx<'ll> = GenericCx<'ll, SCx<'ll>>;
88
89pub(crate) type CodegenCx<'ll, 'tcx> = GenericCx<'ll, FullCx<'ll, 'tcx>>;
93
94pub(crate) struct FullCx<'ll, 'tcx> {
95 pub tcx: TyCtxt<'tcx>,
96 pub scx: SimpleCx<'ll>,
97 pub use_dll_storage_attrs: bool,
98 pub tls_model: llvm::ThreadLocalMode,
99
100 pub codegen_unit: &'tcx CodegenUnit<'tcx>,
101
102 pub instances: RefCell<FxHashMap<Instance<'tcx>, &'ll Value>>,
104 pub vtables: RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>>,
106 pub const_str_cache: RefCell<FxHashMap<String, &'ll Value>>,
108
109 pub const_globals: RefCell<FxHashMap<&'ll Value, &'ll Value>>,
111
112 pub statics_to_rauw: RefCell<Vec<(&'ll Value, &'ll Value)>>,
117
118 pub used_statics: Vec<&'ll Value>,
121
122 pub compiler_used_statics: RefCell<Vec<&'ll Value>>,
125
126 pub type_lowering: RefCell<FxHashMap<(Ty<'tcx>, Option<VariantIdx>), &'ll Type>>,
128
129 pub scalar_lltypes: RefCell<FxHashMap<Ty<'tcx>, &'ll Type>>,
131
132 pub coverage_cx: Option<coverageinfo::CguCoverageContext<'ll, 'tcx>>,
134 pub dbg_cx: Option<debuginfo::CodegenUnitDebugContext<'ll, 'tcx>>,
135
136 eh_personality: Cell<Option<&'ll Value>>,
137 eh_catch_typeinfo: Cell<Option<&'ll Value>>,
138 pub rust_try_fn: Cell<Option<(&'ll Type, &'ll Value)>>,
139
140 intrinsics:
141 RefCell<FxHashMap<(Cow<'static, str>, SmallVec<[&'ll Type; 2]>), (&'ll Type, &'ll Value)>>,
142
143 local_gen_sym_counter: Cell<usize>,
145
146 pub renamed_statics: RefCell<FxHashMap<DefId, &'ll Value>>,
151
152 pub objc_class_t: Cell<Option<&'ll Type>>,
154
155 pub objc_classrefs: RefCell<FxHashMap<Symbol, &'ll Value>>,
157
158 pub objc_selrefs: RefCell<FxHashMap<Symbol, &'ll Value>>,
160
161 pub offload_globals: RefCell<Option<OffloadGlobals<'ll>>>,
163
164 pub offload_kernel_cache: RefCell<FxHashMap<String, OffloadKernelGlobals<'ll>>>,
166}
167
168fn to_llvm_tls_model(tls_model: TlsModel) -> llvm::ThreadLocalMode {
169 match tls_model {
170 TlsModel::GeneralDynamic => llvm::ThreadLocalMode::GeneralDynamic,
171 TlsModel::LocalDynamic => llvm::ThreadLocalMode::LocalDynamic,
172 TlsModel::InitialExec => llvm::ThreadLocalMode::InitialExec,
173 TlsModel::LocalExec => llvm::ThreadLocalMode::LocalExec,
174 TlsModel::Emulated => llvm::ThreadLocalMode::GeneralDynamic,
175 }
176}
177
178pub(crate) unsafe fn create_module<'ll>(
179 tcx: TyCtxt<'_>,
180 llcx: &'ll llvm::Context,
181 mod_name: &str,
182) -> &'ll llvm::Module {
183 let sess = tcx.sess;
184 let mod_name = SmallCStr::new(mod_name);
185 let llmod = unsafe { llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx) };
186
187 let cx = SimpleCx::new(llmod, llcx, tcx.data_layout.pointer_size());
188
189 let mut target_data_layout = sess.target.data_layout.to_string();
190 let llvm_version = llvm_util::get_version();
191
192 if llvm_version < (21, 0, 0) {
193 if sess.target.arch == Arch::Nvptx64 {
194 target_data_layout = target_data_layout.replace("e-p6:32:32-i64", "e-i64");
196 }
197 if sess.target.arch == Arch::AmdGpu {
198 target_data_layout = target_data_layout.replace("p8:128:128:128:48", "p8:128:128")
201 }
202 }
203 if llvm_version < (22, 0, 0) {
204 if sess.target.arch == Arch::Avr {
205 target_data_layout = target_data_layout.replace("n8:16", "n8")
207 }
208 if sess.target.arch == Arch::Nvptx64 {
209 target_data_layout = target_data_layout.replace("-i256:256", "");
211 }
212 }
213
214 {
216 let tm = crate::back::write::create_informational_target_machine(sess, false);
217 unsafe {
218 llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm.raw());
219 }
220
221 let llvm_data_layout = unsafe { llvm::LLVMGetDataLayoutStr(llmod) };
222 let llvm_data_layout =
223 str::from_utf8(unsafe { CStr::from_ptr(llvm_data_layout) }.to_bytes())
224 .expect("got a non-UTF8 data-layout from LLVM");
225
226 if target_data_layout != llvm_data_layout {
227 tcx.dcx().emit_err(crate::errors::MismatchedDataLayout {
228 rustc_target: sess.opts.target_triple.to_string().as_str(),
229 rustc_layout: target_data_layout.as_str(),
230 llvm_target: sess.target.llvm_target.borrow(),
231 llvm_layout: llvm_data_layout,
232 });
233 }
234 }
235
236 let data_layout = SmallCStr::new(&target_data_layout);
237 unsafe {
238 llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
239 }
240
241 let llvm_target = SmallCStr::new(&versioned_llvm_target(sess));
242 unsafe {
243 llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
244 }
245
246 let reloc_model = sess.relocation_model();
247 if matches!(reloc_model, RelocModel::Pic | RelocModel::Pie) {
248 unsafe {
249 llvm::LLVMRustSetModulePICLevel(llmod);
250 }
251 if reloc_model == RelocModel::Pie
254 || tcx.crate_types().iter().all(|ty| *ty == CrateType::Executable)
255 {
256 unsafe {
257 llvm::LLVMRustSetModulePIELevel(llmod);
258 }
259 }
260 }
261
262 unsafe {
268 llvm::LLVMRustSetModuleCodeModel(llmod, to_llvm_code_model(sess.code_model()));
269 }
270
271 if !sess.needs_plt() {
274 llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "RtLibUseGOT", 1);
275 }
276
277 if sess.is_sanitizer_cfi_canonical_jump_tables_enabled() && sess.is_sanitizer_cfi_enabled() {
279 llvm::add_module_flag_u32(
280 llmod,
281 llvm::ModuleFlagMergeBehavior::Override,
282 "CFI Canonical Jump Tables",
283 1,
284 );
285 }
286
287 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
290 llvm::add_module_flag_u32(
291 llmod,
292 llvm::ModuleFlagMergeBehavior::Override,
293 "cfi-normalize-integers",
294 1,
295 );
296 }
297
298 if sess.is_split_lto_unit_enabled() || sess.is_sanitizer_cfi_enabled() {
301 llvm::add_module_flag_u32(
302 llmod,
303 llvm::ModuleFlagMergeBehavior::Override,
304 "EnableSplitLTOUnit",
305 1,
306 );
307 }
308
309 if sess.is_sanitizer_kcfi_enabled() {
311 llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Override, "kcfi", 1);
312
313 let pfe =
316 PatchableFunctionEntry::from_config(sess.opts.unstable_opts.patchable_function_entry);
317 if pfe.prefix() > 0 {
318 llvm::add_module_flag_u32(
319 llmod,
320 llvm::ModuleFlagMergeBehavior::Override,
321 "kcfi-offset",
322 pfe.prefix().into(),
323 );
324 }
325
326 if sess.is_sanitizer_kcfi_arity_enabled() {
329 if llvm_version < (21, 0, 0) {
331 tcx.dcx().emit_err(crate::errors::SanitizerKcfiArityRequiresLLVM2100);
332 }
333
334 llvm::add_module_flag_u32(
335 llmod,
336 llvm::ModuleFlagMergeBehavior::Override,
337 "kcfi-arity",
338 1,
339 );
340 }
341 }
342
343 if sess.target.is_like_msvc
345 || (sess.target.options.os == Os::Windows
346 && sess.target.options.env == Env::Gnu
347 && sess.target.options.abi == Abi::Llvm)
348 {
349 match sess.opts.cg.control_flow_guard {
350 CFGuard::Disabled => {}
351 CFGuard::NoChecks => {
352 llvm::add_module_flag_u32(
354 llmod,
355 llvm::ModuleFlagMergeBehavior::Warning,
356 "cfguard",
357 1,
358 );
359 }
360 CFGuard::Checks => {
361 llvm::add_module_flag_u32(
363 llmod,
364 llvm::ModuleFlagMergeBehavior::Warning,
365 "cfguard",
366 2,
367 );
368 }
369 }
370 }
371
372 if let Some(regparm_count) = sess.opts.unstable_opts.regparm {
373 llvm::add_module_flag_u32(
374 llmod,
375 llvm::ModuleFlagMergeBehavior::Error,
376 "NumRegisterParameters",
377 regparm_count,
378 );
379 }
380
381 if let Some(BranchProtection { bti, pac_ret, gcs }) = sess.opts.unstable_opts.branch_protection
382 {
383 if sess.target.arch == Arch::AArch64 {
384 llvm::add_module_flag_u32(
385 llmod,
386 llvm::ModuleFlagMergeBehavior::Min,
387 "branch-target-enforcement",
388 bti.into(),
389 );
390 llvm::add_module_flag_u32(
391 llmod,
392 llvm::ModuleFlagMergeBehavior::Min,
393 "sign-return-address",
394 pac_ret.is_some().into(),
395 );
396 let pac_opts = pac_ret.unwrap_or(PacRet { leaf: false, pc: false, key: PAuthKey::A });
397 llvm::add_module_flag_u32(
398 llmod,
399 llvm::ModuleFlagMergeBehavior::Min,
400 "branch-protection-pauth-lr",
401 pac_opts.pc.into(),
402 );
403 llvm::add_module_flag_u32(
404 llmod,
405 llvm::ModuleFlagMergeBehavior::Min,
406 "sign-return-address-all",
407 pac_opts.leaf.into(),
408 );
409 llvm::add_module_flag_u32(
410 llmod,
411 llvm::ModuleFlagMergeBehavior::Min,
412 "sign-return-address-with-bkey",
413 u32::from(pac_opts.key == PAuthKey::B),
414 );
415 llvm::add_module_flag_u32(
416 llmod,
417 llvm::ModuleFlagMergeBehavior::Min,
418 "guarded-control-stack",
419 gcs.into(),
420 );
421 } else {
422 bug!(
423 "branch-protection used on non-AArch64 target; \
424 this should be checked in rustc_session."
425 );
426 }
427 }
428
429 if let CFProtection::Branch | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
431 llvm::add_module_flag_u32(
432 llmod,
433 llvm::ModuleFlagMergeBehavior::Override,
434 "cf-protection-branch",
435 1,
436 );
437 }
438 if let CFProtection::Return | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
439 llvm::add_module_flag_u32(
440 llmod,
441 llvm::ModuleFlagMergeBehavior::Override,
442 "cf-protection-return",
443 1,
444 );
445 }
446
447 if sess.opts.unstable_opts.virtual_function_elimination {
448 llvm::add_module_flag_u32(
449 llmod,
450 llvm::ModuleFlagMergeBehavior::Error,
451 "Virtual Function Elim",
452 1,
453 );
454 }
455
456 if sess.opts.unstable_opts.ehcont_guard {
458 llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "ehcontguard", 1);
459 }
460
461 match sess.opts.unstable_opts.function_return {
462 FunctionReturn::Keep => {}
463 FunctionReturn::ThunkExtern => {
464 llvm::add_module_flag_u32(
465 llmod,
466 llvm::ModuleFlagMergeBehavior::Override,
467 "function_return_thunk_extern",
468 1,
469 );
470 }
471 }
472
473 if sess.opts.unstable_opts.indirect_branch_cs_prefix {
474 llvm::add_module_flag_u32(
475 llmod,
476 llvm::ModuleFlagMergeBehavior::Override,
477 "indirect_branch_cs_prefix",
478 1,
479 );
480 }
481
482 match (sess.opts.unstable_opts.small_data_threshold, sess.target.small_data_threshold_support())
483 {
484 (Some(threshold), SmallDataThresholdSupport::LlvmModuleFlag(flag)) => {
487 llvm::add_module_flag_u32(
488 llmod,
489 llvm::ModuleFlagMergeBehavior::Error,
490 &flag,
491 threshold as u32,
492 );
493 }
494 _ => (),
495 };
496
497 #[allow(clippy::option_env_unwrap)]
502 let rustc_producer =
503 format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"));
504
505 let name_metadata = cx.create_metadata(rustc_producer.as_bytes());
506 cx.module_add_named_metadata_node(llmod, c"llvm.ident", &[name_metadata]);
507
508 let llvm_abiname = &sess.target.options.llvm_abiname;
514 if matches!(sess.target.arch, Arch::RiscV32 | Arch::RiscV64) && !llvm_abiname.is_empty() {
515 llvm::add_module_flag_str(
516 llmod,
517 llvm::ModuleFlagMergeBehavior::Error,
518 "target-abi",
519 llvm_abiname,
520 );
521 }
522
523 for (key, value, merge_behavior) in &sess.opts.unstable_opts.llvm_module_flag {
525 let merge_behavior = match merge_behavior.as_str() {
526 "error" => llvm::ModuleFlagMergeBehavior::Error,
527 "warning" => llvm::ModuleFlagMergeBehavior::Warning,
528 "require" => llvm::ModuleFlagMergeBehavior::Require,
529 "override" => llvm::ModuleFlagMergeBehavior::Override,
530 "append" => llvm::ModuleFlagMergeBehavior::Append,
531 "appendunique" => llvm::ModuleFlagMergeBehavior::AppendUnique,
532 "max" => llvm::ModuleFlagMergeBehavior::Max,
533 "min" => llvm::ModuleFlagMergeBehavior::Min,
534 _ => unreachable!(),
536 };
537 llvm::add_module_flag_u32(llmod, merge_behavior, key, *value);
538 }
539
540 llmod
541}
542
543impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
544 pub(crate) fn new(
545 tcx: TyCtxt<'tcx>,
546 codegen_unit: &'tcx CodegenUnit<'tcx>,
547 llvm_module: &'ll crate::ModuleLlvm,
548 ) -> Self {
549 let use_dll_storage_attrs = tcx.sess.target.is_like_windows;
602
603 let tls_model = to_llvm_tls_model(tcx.sess.tls_model());
604
605 let (llcx, llmod) = (&*llvm_module.llcx, llvm_module.llmod());
606
607 let coverage_cx =
608 tcx.sess.instrument_coverage().then(coverageinfo::CguCoverageContext::new);
609
610 let dbg_cx = if tcx.sess.opts.debuginfo != DebugInfo::None {
611 let dctx = debuginfo::CodegenUnitDebugContext::new(llmod);
612 debuginfo::metadata::build_compile_unit_di_node(
613 tcx,
614 codegen_unit.name().as_str(),
615 &dctx,
616 );
617 Some(dctx)
618 } else {
619 None
620 };
621
622 GenericCx(
623 FullCx {
624 tcx,
625 scx: SimpleCx::new(llmod, llcx, tcx.data_layout.pointer_size()),
626 use_dll_storage_attrs,
627 tls_model,
628 codegen_unit,
629 instances: Default::default(),
630 vtables: Default::default(),
631 const_str_cache: Default::default(),
632 const_globals: Default::default(),
633 statics_to_rauw: RefCell::new(Vec::new()),
634 used_statics: Vec::new(),
635 compiler_used_statics: Default::default(),
636 type_lowering: Default::default(),
637 scalar_lltypes: Default::default(),
638 coverage_cx,
639 dbg_cx,
640 eh_personality: Cell::new(None),
641 eh_catch_typeinfo: Cell::new(None),
642 rust_try_fn: Cell::new(None),
643 intrinsics: Default::default(),
644 local_gen_sym_counter: Cell::new(0),
645 renamed_statics: Default::default(),
646 objc_class_t: Cell::new(None),
647 objc_classrefs: Default::default(),
648 objc_selrefs: Default::default(),
649 offload_globals: Default::default(),
650 offload_kernel_cache: Default::default(),
651 },
652 PhantomData,
653 )
654 }
655
656 pub(crate) fn statics_to_rauw(&self) -> &RefCell<Vec<(&'ll Value, &'ll Value)>> {
657 &self.statics_to_rauw
658 }
659
660 #[inline]
662 #[track_caller]
663 pub(crate) fn coverage_cx(&self) -> &coverageinfo::CguCoverageContext<'ll, 'tcx> {
664 self.coverage_cx.as_ref().expect("only called when coverage instrumentation is enabled")
665 }
666
667 pub(crate) fn create_used_variable_impl(&self, name: &'static CStr, values: &[&'ll Value]) {
668 let array = self.const_array(self.type_ptr(), values);
669
670 let g = llvm::add_global(self.llmod, self.val_ty(array), name);
671 llvm::set_initializer(g, array);
672 llvm::set_linkage(g, llvm::Linkage::AppendingLinkage);
673 llvm::set_section(g, c"llvm.metadata");
674 }
675
676 pub(crate) fn objc_abi_version(&self) -> u32 {
680 assert!(self.tcx.sess.target.is_like_darwin);
681 if self.tcx.sess.target.arch == Arch::X86 && self.tcx.sess.target.os == Os::MacOs {
682 1
684 } else {
685 2
688 }
689 }
690
691 pub(crate) fn add_objc_module_flags(&self) {
695 let abi_version = self.objc_abi_version();
696
697 llvm::add_module_flag_u32(
698 self.llmod,
699 llvm::ModuleFlagMergeBehavior::Error,
700 "Objective-C Version",
701 abi_version,
702 );
703
704 llvm::add_module_flag_u32(
705 self.llmod,
706 llvm::ModuleFlagMergeBehavior::Error,
707 "Objective-C Image Info Version",
708 0,
709 );
710
711 llvm::add_module_flag_str(
712 self.llmod,
713 llvm::ModuleFlagMergeBehavior::Error,
714 "Objective-C Image Info Section",
715 match abi_version {
716 1 => "__OBJC,__image_info,regular",
717 2 => "__DATA,__objc_imageinfo,regular,no_dead_strip",
718 _ => unreachable!(),
719 },
720 );
721
722 if self.tcx.sess.target.env == Env::Sim {
723 llvm::add_module_flag_u32(
724 self.llmod,
725 llvm::ModuleFlagMergeBehavior::Error,
726 "Objective-C Is Simulated",
727 1 << 5,
728 );
729 }
730
731 llvm::add_module_flag_u32(
732 self.llmod,
733 llvm::ModuleFlagMergeBehavior::Error,
734 "Objective-C Class Properties",
735 1 << 6,
736 );
737 }
738}
739impl<'ll> SimpleCx<'ll> {
740 pub(crate) fn get_type_of_global(&self, val: &'ll Value) -> &'ll Type {
741 unsafe { llvm::LLVMGlobalGetValueType(val) }
742 }
743 pub(crate) fn val_ty(&self, v: &'ll Value) -> &'ll Type {
744 common::val_ty(v)
745 }
746}
747impl<'ll> SimpleCx<'ll> {
748 pub(crate) fn new(
749 llmod: &'ll llvm::Module,
750 llcx: &'ll llvm::Context,
751 pointer_size: Size,
752 ) -> Self {
753 let isize_ty = llvm::LLVMIntTypeInContext(llcx, pointer_size.bits() as c_uint);
754 Self(SCx { llmod, llcx, isize_ty }, PhantomData)
755 }
756}
757
758impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
759 pub(crate) fn get_metadata_value(&self, metadata: &'ll Metadata) -> &'ll Value {
760 llvm::LLVMMetadataAsValue(self.llcx(), metadata)
761 }
762
763 pub(crate) fn get_const_int(&self, ty: &'ll Type, val: u64) -> &'ll Value {
764 unsafe { llvm::LLVMConstInt(ty, val, llvm::FALSE) }
765 }
766
767 pub(crate) fn get_const_i64(&self, n: u64) -> &'ll Value {
768 self.get_const_int(self.type_i64(), n)
769 }
770
771 pub(crate) fn get_const_i32(&self, n: u64) -> &'ll Value {
772 self.get_const_int(self.type_i32(), n)
773 }
774
775 pub(crate) fn get_const_i16(&self, n: u64) -> &'ll Value {
776 self.get_const_int(self.type_i16(), n)
777 }
778
779 pub(crate) fn get_const_i8(&self, n: u64) -> &'ll Value {
780 self.get_const_int(self.type_i8(), n)
781 }
782
783 pub(crate) fn get_function(&self, name: &str) -> Option<&'ll Value> {
784 let name = SmallCStr::new(name);
785 unsafe { llvm::LLVMGetNamedFunction((**self).borrow().llmod, name.as_ptr()) }
786 }
787
788 pub(crate) fn get_md_kind_id(&self, name: &str) -> llvm::MetadataKindId {
789 unsafe {
790 llvm::LLVMGetMDKindIDInContext(
791 self.llcx(),
792 name.as_ptr() as *const c_char,
793 name.len() as c_uint,
794 )
795 }
796 }
797
798 pub(crate) fn create_metadata(&self, name: &[u8]) -> &'ll Metadata {
799 unsafe {
800 llvm::LLVMMDStringInContext2(self.llcx(), name.as_ptr() as *const c_char, name.len())
801 }
802 }
803
804 pub(crate) fn get_functions(&self) -> Vec<&'ll Value> {
805 let mut functions = vec![];
806 let mut func = unsafe { llvm::LLVMGetFirstFunction(self.llmod()) };
807 while let Some(f) = func {
808 functions.push(f);
809 func = unsafe { llvm::LLVMGetNextFunction(f) }
810 }
811 functions
812 }
813}
814
815impl<'ll, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
816 fn vtables(
817 &self,
818 ) -> &RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>> {
819 &self.vtables
820 }
821
822 fn apply_vcall_visibility_metadata(
823 &self,
824 ty: Ty<'tcx>,
825 poly_trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
826 vtable: &'ll Value,
827 ) {
828 apply_vcall_visibility_metadata(self, ty, poly_trait_ref, vtable);
829 }
830
831 fn get_fn(&self, instance: Instance<'tcx>) -> &'ll Value {
832 get_fn(self, instance)
833 }
834
835 fn get_fn_addr(&self, instance: Instance<'tcx>) -> &'ll Value {
836 get_fn(self, instance)
837 }
838
839 fn eh_personality(&self) -> &'ll Value {
840 if let Some(llpersonality) = self.eh_personality.get() {
861 return llpersonality;
862 }
863
864 let name = if wants_msvc_seh(self.sess()) {
865 Some("__CxxFrameHandler3")
866 } else if wants_wasm_eh(self.sess()) {
867 Some("__gxx_wasm_personality_v0")
872 } else {
873 None
874 };
875
876 let tcx = self.tcx;
877 let llfn = match tcx.lang_items().eh_personality() {
878 Some(def_id) if name.is_none() => self.get_fn_addr(ty::Instance::expect_resolve(
879 tcx,
880 self.typing_env(),
881 def_id,
882 ty::List::empty(),
883 DUMMY_SP,
884 )),
885 _ => {
886 let name = name.unwrap_or("rust_eh_personality");
887 if let Some(llfn) = self.get_declared_value(name) {
888 llfn
889 } else {
890 let fty = self.type_variadic_func(&[], self.type_i32());
891 let llfn = self.declare_cfn(name, llvm::UnnamedAddr::Global, fty);
892 let target_cpu = attributes::target_cpu_attr(self, self.sess());
893 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[target_cpu]);
894 llfn
895 }
896 }
897 };
898 self.eh_personality.set(Some(llfn));
899 llfn
900 }
901
902 fn sess(&self) -> &Session {
903 self.tcx.sess
904 }
905
906 fn set_frame_pointer_type(&self, llfn: &'ll Value) {
907 if let Some(attr) = attributes::frame_pointer_type_attr(self, self.sess()) {
908 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[attr]);
909 }
910 }
911
912 fn apply_target_cpu_attr(&self, llfn: &'ll Value) {
913 let mut attrs = SmallVec::<[_; 2]>::new();
914 attrs.push(attributes::target_cpu_attr(self, self.sess()));
915 attrs.extend(attributes::tune_cpu_attr(self, self.sess()));
916 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &attrs);
917 }
918
919 fn declare_c_main(&self, fn_type: Self::Type) -> Option<Self::Function> {
920 let entry_name = self.sess().target.entry_name.as_ref();
921 if self.get_declared_value(entry_name).is_none() {
922 let llfn = self.declare_entry_fn(
923 entry_name,
924 to_llvm_calling_convention(self.sess(), self.sess().target.entry_abi),
925 llvm::UnnamedAddr::Global,
926 fn_type,
927 );
928 attributes::apply_to_llfn(
929 llfn,
930 llvm::AttributePlace::Function,
931 attributes::target_features_attr(self, self.tcx, vec![]).as_slice(),
932 );
933 Some(llfn)
934 } else {
935 None
938 }
939 }
940}
941
942impl<'ll> CodegenCx<'ll, '_> {
943 pub(crate) fn get_intrinsic(
944 &self,
945 base_name: Cow<'static, str>,
946 type_params: &[&'ll Type],
947 ) -> (&'ll Type, &'ll Value) {
948 *self
949 .intrinsics
950 .borrow_mut()
951 .entry((base_name, SmallVec::from_slice(type_params)))
952 .or_insert_with_key(|(base_name, type_params)| {
953 self.declare_intrinsic(base_name, type_params)
954 })
955 }
956
957 fn declare_intrinsic(
958 &self,
959 base_name: &str,
960 type_params: &[&'ll Type],
961 ) -> (&'ll Type, &'ll Value) {
962 if base_name == "memcmp" {
966 let fn_ty = self
967 .type_func(&[self.type_ptr(), self.type_ptr(), self.type_isize()], self.type_int());
968 let f = self.declare_cfn("memcmp", llvm::UnnamedAddr::No, fn_ty);
969
970 return (fn_ty, f);
971 }
972
973 let intrinsic = llvm::Intrinsic::lookup(base_name.as_bytes())
974 .unwrap_or_else(|| bug!("Unknown intrinsic: `{base_name}`"));
975 let f = intrinsic.get_declaration(self.llmod, &type_params);
976
977 (self.get_type_of_global(f), f)
978 }
979
980 pub(crate) fn eh_catch_typeinfo(&self) -> &'ll Value {
981 if let Some(eh_catch_typeinfo) = self.eh_catch_typeinfo.get() {
982 return eh_catch_typeinfo;
983 }
984 let tcx = self.tcx;
985 assert!(self.sess().target.os == Os::Emscripten);
986 let eh_catch_typeinfo = match tcx.lang_items().eh_catch_typeinfo() {
987 Some(def_id) => self.get_static(def_id),
988 _ => {
989 let ty = self.type_struct(&[self.type_ptr(), self.type_ptr()], false);
990 self.declare_global(&mangle_internal_symbol(self.tcx, "rust_eh_catch_typeinfo"), ty)
991 }
992 };
993 self.eh_catch_typeinfo.set(Some(eh_catch_typeinfo));
994 eh_catch_typeinfo
995 }
996}
997
998impl CodegenCx<'_, '_> {
999 pub(crate) fn generate_local_symbol_name(&self, prefix: &str) -> String {
1002 let idx = self.local_gen_sym_counter.get();
1003 self.local_gen_sym_counter.set(idx + 1);
1004 let mut name = String::with_capacity(prefix.len() + 6);
1007 name.push_str(prefix);
1008 name.push('.');
1009 name.push_str(&(idx as u64).to_base(ALPHANUMERIC_ONLY));
1010 name
1011 }
1012}
1013
1014impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
1015 pub(crate) fn md_node_in_context(&self, md_list: &[&'ll Metadata]) -> &'ll Metadata {
1017 unsafe { llvm::LLVMMDNodeInContext2(self.llcx(), md_list.as_ptr(), md_list.len()) }
1018 }
1019
1020 pub(crate) fn set_metadata<'a>(
1022 &self,
1023 val: &'a Value,
1024 kind_id: MetadataKindId,
1025 md: &'ll Metadata,
1026 ) {
1027 let node = self.get_metadata_value(md);
1028 llvm::LLVMSetMetadata(val, kind_id, node);
1029 }
1030
1031 pub(crate) fn set_metadata_node(
1036 &self,
1037 instruction: &'ll Value,
1038 kind_id: MetadataKindId,
1039 md_list: &[&'ll Metadata],
1040 ) {
1041 let md = self.md_node_in_context(md_list);
1042 self.set_metadata(instruction, kind_id, md);
1043 }
1044
1045 pub(crate) fn module_add_named_metadata_node(
1050 &self,
1051 module: &'ll Module,
1052 kind_name: &CStr,
1053 md_list: &[&'ll Metadata],
1054 ) {
1055 let md = self.md_node_in_context(md_list);
1056 let md_as_val = self.get_metadata_value(md);
1057 unsafe { llvm::LLVMAddNamedMetadataOperand(module, kind_name.as_ptr(), md_as_val) };
1058 }
1059
1060 pub(crate) fn global_add_metadata_node(
1064 &self,
1065 global: &'ll Value,
1066 kind_id: MetadataKindId,
1067 md_list: &[&'ll Metadata],
1068 ) {
1069 let md = self.md_node_in_context(md_list);
1070 unsafe { llvm::LLVMRustGlobalAddMetadata(global, kind_id, md) };
1071 }
1072
1073 pub(crate) fn global_set_metadata_node(
1077 &self,
1078 global: &'ll Value,
1079 kind_id: MetadataKindId,
1080 md_list: &[&'ll Metadata],
1081 ) {
1082 let md = self.md_node_in_context(md_list);
1083 unsafe { llvm::LLVMGlobalSetMetadata(global, kind_id, md) };
1084 }
1085}
1086
1087impl HasDataLayout for CodegenCx<'_, '_> {
1088 #[inline]
1089 fn data_layout(&self) -> &TargetDataLayout {
1090 &self.tcx.data_layout
1091 }
1092}
1093
1094impl HasTargetSpec for CodegenCx<'_, '_> {
1095 #[inline]
1096 fn target_spec(&self) -> &Target {
1097 &self.tcx.sess.target
1098 }
1099}
1100
1101impl<'tcx> ty::layout::HasTyCtxt<'tcx> for CodegenCx<'_, 'tcx> {
1102 #[inline]
1103 fn tcx(&self) -> TyCtxt<'tcx> {
1104 self.tcx
1105 }
1106}
1107
1108impl<'tcx, 'll> HasTypingEnv<'tcx> for CodegenCx<'ll, 'tcx> {
1109 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
1110 ty::TypingEnv::fully_monomorphized()
1111 }
1112}
1113
1114impl<'tcx> LayoutOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
1115 #[inline]
1116 fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
1117 if let LayoutError::SizeOverflow(_)
1118 | LayoutError::ReferencesError(_)
1119 | LayoutError::InvalidSimd { .. } = err
1120 {
1121 self.tcx.dcx().emit_fatal(Spanned { span, node: err.into_diagnostic() })
1122 } else {
1123 self.tcx.dcx().emit_fatal(ssa_errors::FailedToGetLayout { span, ty, err })
1124 }
1125 }
1126}
1127
1128impl<'tcx> FnAbiOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
1129 #[inline]
1130 fn handle_fn_abi_err(
1131 &self,
1132 err: FnAbiError<'tcx>,
1133 span: Span,
1134 fn_abi_request: FnAbiRequest<'tcx>,
1135 ) -> ! {
1136 match err {
1137 FnAbiError::Layout(
1138 LayoutError::SizeOverflow(_)
1139 | LayoutError::Cycle(_)
1140 | LayoutError::InvalidSimd { .. },
1141 ) => {
1142 self.tcx.dcx().emit_fatal(Spanned { span, node: err });
1143 }
1144 _ => match fn_abi_request {
1145 FnAbiRequest::OfFnPtr { sig, extra_args } => {
1146 span_bug!(span, "`fn_abi_of_fn_ptr({sig}, {extra_args:?})` failed: {err:?}",);
1147 }
1148 FnAbiRequest::OfInstance { instance, extra_args } => {
1149 span_bug!(
1150 span,
1151 "`fn_abi_of_instance({instance}, {extra_args:?})` failed: {err:?}",
1152 );
1153 }
1154 },
1155 }
1156 }
1157}