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::{HasTargetSpec, RelocModel, SmallDataThresholdSupport, Target, TlsModel};
32use smallvec::SmallVec;
33
34use crate::abi::to_llvm_calling_convention;
35use crate::back::write::to_llvm_code_model;
36use crate::callee::get_fn;
37use crate::debuginfo::metadata::apply_vcall_visibility_metadata;
38use crate::llvm::{self, Metadata, MetadataKindId, Module, Type, Value};
39use crate::{attributes, common, coverageinfo, debuginfo, llvm_util};
40
41pub(crate) struct SCx<'ll> {
46 pub llmod: &'ll llvm::Module,
47 pub llcx: &'ll llvm::Context,
48 pub isize_ty: &'ll Type,
49}
50
51impl<'ll> Borrow<SCx<'ll>> for FullCx<'ll, '_> {
52 fn borrow(&self) -> &SCx<'ll> {
53 &self.scx
54 }
55}
56
57impl<'ll, 'tcx> Deref for FullCx<'ll, 'tcx> {
58 type Target = SimpleCx<'ll>;
59
60 #[inline]
61 fn deref(&self) -> &Self::Target {
62 &self.scx
63 }
64}
65
66pub(crate) struct GenericCx<'ll, T: Borrow<SCx<'ll>>>(T, PhantomData<SCx<'ll>>);
67
68impl<'ll, T: Borrow<SCx<'ll>>> Deref for GenericCx<'ll, T> {
69 type Target = T;
70
71 #[inline]
72 fn deref(&self) -> &Self::Target {
73 &self.0
74 }
75}
76
77impl<'ll, T: Borrow<SCx<'ll>>> DerefMut for GenericCx<'ll, T> {
78 #[inline]
79 fn deref_mut(&mut self) -> &mut Self::Target {
80 &mut self.0
81 }
82}
83
84pub(crate) type SimpleCx<'ll> = GenericCx<'ll, SCx<'ll>>;
85
86pub(crate) type CodegenCx<'ll, 'tcx> = GenericCx<'ll, FullCx<'ll, 'tcx>>;
90
91pub(crate) struct FullCx<'ll, 'tcx> {
92 pub tcx: TyCtxt<'tcx>,
93 pub scx: SimpleCx<'ll>,
94 pub use_dll_storage_attrs: bool,
95 pub tls_model: llvm::ThreadLocalMode,
96
97 pub codegen_unit: &'tcx CodegenUnit<'tcx>,
98
99 pub instances: RefCell<FxHashMap<Instance<'tcx>, &'ll Value>>,
101 pub vtables: RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>>,
103 pub const_str_cache: RefCell<FxHashMap<String, &'ll Value>>,
105
106 pub const_globals: RefCell<FxHashMap<&'ll Value, &'ll Value>>,
108
109 pub statics_to_rauw: RefCell<Vec<(&'ll Value, &'ll Value)>>,
114
115 pub used_statics: Vec<&'ll Value>,
118
119 pub compiler_used_statics: RefCell<Vec<&'ll Value>>,
122
123 pub type_lowering: RefCell<FxHashMap<(Ty<'tcx>, Option<VariantIdx>), &'ll Type>>,
125
126 pub scalar_lltypes: RefCell<FxHashMap<Ty<'tcx>, &'ll Type>>,
128
129 pub coverage_cx: Option<coverageinfo::CguCoverageContext<'ll, 'tcx>>,
131 pub dbg_cx: Option<debuginfo::CodegenUnitDebugContext<'ll, 'tcx>>,
132
133 eh_personality: Cell<Option<&'ll Value>>,
134 eh_catch_typeinfo: Cell<Option<&'ll Value>>,
135 pub rust_try_fn: Cell<Option<(&'ll Type, &'ll Value)>>,
136
137 intrinsics:
138 RefCell<FxHashMap<(Cow<'static, str>, SmallVec<[&'ll Type; 2]>), (&'ll Type, &'ll Value)>>,
139
140 local_gen_sym_counter: Cell<usize>,
142
143 pub renamed_statics: RefCell<FxHashMap<DefId, &'ll Value>>,
148
149 pub objc_class_t: Cell<Option<&'ll Type>>,
151
152 pub objc_classrefs: RefCell<FxHashMap<Symbol, &'ll Value>>,
154
155 pub objc_selrefs: RefCell<FxHashMap<Symbol, &'ll Value>>,
157}
158
159fn to_llvm_tls_model(tls_model: TlsModel) -> llvm::ThreadLocalMode {
160 match tls_model {
161 TlsModel::GeneralDynamic => llvm::ThreadLocalMode::GeneralDynamic,
162 TlsModel::LocalDynamic => llvm::ThreadLocalMode::LocalDynamic,
163 TlsModel::InitialExec => llvm::ThreadLocalMode::InitialExec,
164 TlsModel::LocalExec => llvm::ThreadLocalMode::LocalExec,
165 TlsModel::Emulated => llvm::ThreadLocalMode::GeneralDynamic,
166 }
167}
168
169pub(crate) unsafe fn create_module<'ll>(
170 tcx: TyCtxt<'_>,
171 llcx: &'ll llvm::Context,
172 mod_name: &str,
173) -> &'ll llvm::Module {
174 let sess = tcx.sess;
175 let mod_name = SmallCStr::new(mod_name);
176 let llmod = unsafe { llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx) };
177
178 let cx = SimpleCx::new(llmod, llcx, tcx.data_layout.pointer_size());
179
180 let mut target_data_layout = sess.target.data_layout.to_string();
181 let llvm_version = llvm_util::get_version();
182
183 if llvm_version < (21, 0, 0) {
184 if sess.target.arch == "nvptx64" {
185 target_data_layout = target_data_layout.replace("e-p6:32:32-i64", "e-i64");
187 }
188 if sess.target.arch == "amdgpu" {
189 target_data_layout = target_data_layout.replace("p8:128:128:128:48", "p8:128:128")
192 }
193 }
194 if llvm_version < (22, 0, 0) {
195 if sess.target.arch == "avr" {
196 target_data_layout = target_data_layout.replace("n8:16", "n8")
198 }
199 if sess.target.arch == "nvptx64" {
200 target_data_layout = target_data_layout.replace("-i256:256", "");
202 }
203 }
204
205 {
207 let tm = crate::back::write::create_informational_target_machine(sess, false);
208 unsafe {
209 llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm.raw());
210 }
211
212 let llvm_data_layout = unsafe { llvm::LLVMGetDataLayoutStr(llmod) };
213 let llvm_data_layout =
214 str::from_utf8(unsafe { CStr::from_ptr(llvm_data_layout) }.to_bytes())
215 .expect("got a non-UTF8 data-layout from LLVM");
216
217 if target_data_layout != llvm_data_layout {
218 tcx.dcx().emit_err(crate::errors::MismatchedDataLayout {
219 rustc_target: sess.opts.target_triple.to_string().as_str(),
220 rustc_layout: target_data_layout.as_str(),
221 llvm_target: sess.target.llvm_target.borrow(),
222 llvm_layout: llvm_data_layout,
223 });
224 }
225 }
226
227 let data_layout = SmallCStr::new(&target_data_layout);
228 unsafe {
229 llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
230 }
231
232 let llvm_target = SmallCStr::new(&versioned_llvm_target(sess));
233 unsafe {
234 llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
235 }
236
237 let reloc_model = sess.relocation_model();
238 if matches!(reloc_model, RelocModel::Pic | RelocModel::Pie) {
239 unsafe {
240 llvm::LLVMRustSetModulePICLevel(llmod);
241 }
242 if reloc_model == RelocModel::Pie
245 || tcx.crate_types().iter().all(|ty| *ty == CrateType::Executable)
246 {
247 unsafe {
248 llvm::LLVMRustSetModulePIELevel(llmod);
249 }
250 }
251 }
252
253 unsafe {
259 llvm::LLVMRustSetModuleCodeModel(llmod, to_llvm_code_model(sess.code_model()));
260 }
261
262 if !sess.needs_plt() {
265 llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "RtLibUseGOT", 1);
266 }
267
268 if sess.is_sanitizer_cfi_canonical_jump_tables_enabled() && sess.is_sanitizer_cfi_enabled() {
270 llvm::add_module_flag_u32(
271 llmod,
272 llvm::ModuleFlagMergeBehavior::Override,
273 "CFI Canonical Jump Tables",
274 1,
275 );
276 }
277
278 if sess.is_sanitizer_cfi_normalize_integers_enabled() {
281 llvm::add_module_flag_u32(
282 llmod,
283 llvm::ModuleFlagMergeBehavior::Override,
284 "cfi-normalize-integers",
285 1,
286 );
287 }
288
289 if sess.is_split_lto_unit_enabled() || sess.is_sanitizer_cfi_enabled() {
292 llvm::add_module_flag_u32(
293 llmod,
294 llvm::ModuleFlagMergeBehavior::Override,
295 "EnableSplitLTOUnit",
296 1,
297 );
298 }
299
300 if sess.is_sanitizer_kcfi_enabled() {
302 llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Override, "kcfi", 1);
303
304 let pfe =
307 PatchableFunctionEntry::from_config(sess.opts.unstable_opts.patchable_function_entry);
308 if pfe.prefix() > 0 {
309 llvm::add_module_flag_u32(
310 llmod,
311 llvm::ModuleFlagMergeBehavior::Override,
312 "kcfi-offset",
313 pfe.prefix().into(),
314 );
315 }
316
317 if sess.is_sanitizer_kcfi_arity_enabled() {
320 if llvm_version < (21, 0, 0) {
322 tcx.dcx().emit_err(crate::errors::SanitizerKcfiArityRequiresLLVM2100);
323 }
324
325 llvm::add_module_flag_u32(
326 llmod,
327 llvm::ModuleFlagMergeBehavior::Override,
328 "kcfi-arity",
329 1,
330 );
331 }
332 }
333
334 if sess.target.is_like_msvc
336 || (sess.target.options.os == "windows"
337 && sess.target.options.env == "gnu"
338 && sess.target.options.abi == "llvm")
339 {
340 match sess.opts.cg.control_flow_guard {
341 CFGuard::Disabled => {}
342 CFGuard::NoChecks => {
343 llvm::add_module_flag_u32(
345 llmod,
346 llvm::ModuleFlagMergeBehavior::Warning,
347 "cfguard",
348 1,
349 );
350 }
351 CFGuard::Checks => {
352 llvm::add_module_flag_u32(
354 llmod,
355 llvm::ModuleFlagMergeBehavior::Warning,
356 "cfguard",
357 2,
358 );
359 }
360 }
361 }
362
363 if let Some(regparm_count) = sess.opts.unstable_opts.regparm {
364 llvm::add_module_flag_u32(
365 llmod,
366 llvm::ModuleFlagMergeBehavior::Error,
367 "NumRegisterParameters",
368 regparm_count,
369 );
370 }
371
372 if let Some(BranchProtection { bti, pac_ret, gcs }) = sess.opts.unstable_opts.branch_protection
373 {
374 if sess.target.arch == "aarch64" {
375 llvm::add_module_flag_u32(
376 llmod,
377 llvm::ModuleFlagMergeBehavior::Min,
378 "branch-target-enforcement",
379 bti.into(),
380 );
381 llvm::add_module_flag_u32(
382 llmod,
383 llvm::ModuleFlagMergeBehavior::Min,
384 "sign-return-address",
385 pac_ret.is_some().into(),
386 );
387 let pac_opts = pac_ret.unwrap_or(PacRet { leaf: false, pc: false, key: PAuthKey::A });
388 llvm::add_module_flag_u32(
389 llmod,
390 llvm::ModuleFlagMergeBehavior::Min,
391 "branch-protection-pauth-lr",
392 pac_opts.pc.into(),
393 );
394 llvm::add_module_flag_u32(
395 llmod,
396 llvm::ModuleFlagMergeBehavior::Min,
397 "sign-return-address-all",
398 pac_opts.leaf.into(),
399 );
400 llvm::add_module_flag_u32(
401 llmod,
402 llvm::ModuleFlagMergeBehavior::Min,
403 "sign-return-address-with-bkey",
404 u32::from(pac_opts.key == PAuthKey::B),
405 );
406 llvm::add_module_flag_u32(
407 llmod,
408 llvm::ModuleFlagMergeBehavior::Min,
409 "guarded-control-stack",
410 gcs.into(),
411 );
412 } else {
413 bug!(
414 "branch-protection used on non-AArch64 target; \
415 this should be checked in rustc_session."
416 );
417 }
418 }
419
420 if let CFProtection::Branch | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
422 llvm::add_module_flag_u32(
423 llmod,
424 llvm::ModuleFlagMergeBehavior::Override,
425 "cf-protection-branch",
426 1,
427 );
428 }
429 if let CFProtection::Return | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
430 llvm::add_module_flag_u32(
431 llmod,
432 llvm::ModuleFlagMergeBehavior::Override,
433 "cf-protection-return",
434 1,
435 );
436 }
437
438 if sess.opts.unstable_opts.virtual_function_elimination {
439 llvm::add_module_flag_u32(
440 llmod,
441 llvm::ModuleFlagMergeBehavior::Error,
442 "Virtual Function Elim",
443 1,
444 );
445 }
446
447 if sess.opts.unstable_opts.ehcont_guard {
449 llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "ehcontguard", 1);
450 }
451
452 match sess.opts.unstable_opts.function_return {
453 FunctionReturn::Keep => {}
454 FunctionReturn::ThunkExtern => {
455 llvm::add_module_flag_u32(
456 llmod,
457 llvm::ModuleFlagMergeBehavior::Override,
458 "function_return_thunk_extern",
459 1,
460 );
461 }
462 }
463
464 if sess.opts.unstable_opts.indirect_branch_cs_prefix {
465 llvm::add_module_flag_u32(
466 llmod,
467 llvm::ModuleFlagMergeBehavior::Override,
468 "indirect_branch_cs_prefix",
469 1,
470 );
471 }
472
473 match (sess.opts.unstable_opts.small_data_threshold, sess.target.small_data_threshold_support())
474 {
475 (Some(threshold), SmallDataThresholdSupport::LlvmModuleFlag(flag)) => {
478 llvm::add_module_flag_u32(
479 llmod,
480 llvm::ModuleFlagMergeBehavior::Error,
481 &flag,
482 threshold as u32,
483 );
484 }
485 _ => (),
486 };
487
488 #[allow(clippy::option_env_unwrap)]
493 let rustc_producer =
494 format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"));
495
496 let name_metadata = cx.create_metadata(rustc_producer.as_bytes());
497 cx.module_add_named_metadata_node(llmod, c"llvm.ident", &[name_metadata]);
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: Default::default(),
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 objc_class_t: Cell::new(None),
638 objc_classrefs: Default::default(),
639 objc_selrefs: Default::default(),
640 },
641 PhantomData,
642 )
643 }
644
645 pub(crate) fn statics_to_rauw(&self) -> &RefCell<Vec<(&'ll Value, &'ll Value)>> {
646 &self.statics_to_rauw
647 }
648
649 #[inline]
651 #[track_caller]
652 pub(crate) fn coverage_cx(&self) -> &coverageinfo::CguCoverageContext<'ll, 'tcx> {
653 self.coverage_cx.as_ref().expect("only called when coverage instrumentation is enabled")
654 }
655
656 pub(crate) fn create_used_variable_impl(&self, name: &'static CStr, values: &[&'ll Value]) {
657 let array = self.const_array(self.type_ptr(), values);
658
659 let g = llvm::add_global(self.llmod, self.val_ty(array), name);
660 llvm::set_initializer(g, array);
661 llvm::set_linkage(g, llvm::Linkage::AppendingLinkage);
662 llvm::set_section(g, c"llvm.metadata");
663 }
664
665 pub(crate) fn objc_abi_version(&self) -> u32 {
669 assert!(self.tcx.sess.target.is_like_darwin);
670 if self.tcx.sess.target.arch == "x86" && self.tcx.sess.target.os == "macos" {
671 1
673 } else {
674 2
677 }
678 }
679
680 pub(crate) fn add_objc_module_flags(&self) {
684 let abi_version = self.objc_abi_version();
685
686 llvm::add_module_flag_u32(
687 self.llmod,
688 llvm::ModuleFlagMergeBehavior::Error,
689 "Objective-C Version",
690 abi_version,
691 );
692
693 llvm::add_module_flag_u32(
694 self.llmod,
695 llvm::ModuleFlagMergeBehavior::Error,
696 "Objective-C Image Info Version",
697 0,
698 );
699
700 llvm::add_module_flag_str(
701 self.llmod,
702 llvm::ModuleFlagMergeBehavior::Error,
703 "Objective-C Image Info Section",
704 match abi_version {
705 1 => "__OBJC,__image_info,regular",
706 2 => "__DATA,__objc_imageinfo,regular,no_dead_strip",
707 _ => unreachable!(),
708 },
709 );
710
711 if self.tcx.sess.target.env == "sim" {
712 llvm::add_module_flag_u32(
713 self.llmod,
714 llvm::ModuleFlagMergeBehavior::Error,
715 "Objective-C Is Simulated",
716 1 << 5,
717 );
718 }
719
720 llvm::add_module_flag_u32(
721 self.llmod,
722 llvm::ModuleFlagMergeBehavior::Error,
723 "Objective-C Class Properties",
724 1 << 6,
725 );
726 }
727}
728impl<'ll> SimpleCx<'ll> {
729 pub(crate) fn get_type_of_global(&self, val: &'ll Value) -> &'ll Type {
730 unsafe { llvm::LLVMGlobalGetValueType(val) }
731 }
732 pub(crate) fn val_ty(&self, v: &'ll Value) -> &'ll Type {
733 common::val_ty(v)
734 }
735}
736impl<'ll> SimpleCx<'ll> {
737 pub(crate) fn new(
738 llmod: &'ll llvm::Module,
739 llcx: &'ll llvm::Context,
740 pointer_size: Size,
741 ) -> Self {
742 let isize_ty = llvm::LLVMIntTypeInContext(llcx, pointer_size.bits() as c_uint);
743 Self(SCx { llmod, llcx, isize_ty }, PhantomData)
744 }
745}
746
747impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
748 pub(crate) fn get_metadata_value(&self, metadata: &'ll Metadata) -> &'ll Value {
749 llvm::LLVMMetadataAsValue(self.llcx(), metadata)
750 }
751
752 pub(crate) fn get_const_int(&self, ty: &'ll Type, val: u64) -> &'ll Value {
753 unsafe { llvm::LLVMConstInt(ty, val, llvm::FALSE) }
754 }
755
756 pub(crate) fn get_const_i64(&self, n: u64) -> &'ll Value {
757 self.get_const_int(self.type_i64(), n)
758 }
759
760 pub(crate) fn get_const_i32(&self, n: u64) -> &'ll Value {
761 self.get_const_int(self.type_i32(), n)
762 }
763
764 pub(crate) fn get_const_i16(&self, n: u64) -> &'ll Value {
765 self.get_const_int(self.type_i16(), n)
766 }
767
768 pub(crate) fn get_const_i8(&self, n: u64) -> &'ll Value {
769 self.get_const_int(self.type_i8(), n)
770 }
771
772 pub(crate) fn get_function(&self, name: &str) -> Option<&'ll Value> {
773 let name = SmallCStr::new(name);
774 unsafe { llvm::LLVMGetNamedFunction((**self).borrow().llmod, name.as_ptr()) }
775 }
776
777 pub(crate) fn get_md_kind_id(&self, name: &str) -> llvm::MetadataKindId {
778 unsafe {
779 llvm::LLVMGetMDKindIDInContext(
780 self.llcx(),
781 name.as_ptr() as *const c_char,
782 name.len() as c_uint,
783 )
784 }
785 }
786
787 pub(crate) fn create_metadata(&self, name: &[u8]) -> &'ll Metadata {
788 unsafe {
789 llvm::LLVMMDStringInContext2(self.llcx(), name.as_ptr() as *const c_char, name.len())
790 }
791 }
792}
793
794impl<'ll, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
795 fn vtables(
796 &self,
797 ) -> &RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>> {
798 &self.vtables
799 }
800
801 fn apply_vcall_visibility_metadata(
802 &self,
803 ty: Ty<'tcx>,
804 poly_trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
805 vtable: &'ll Value,
806 ) {
807 apply_vcall_visibility_metadata(self, ty, poly_trait_ref, vtable);
808 }
809
810 fn get_fn(&self, instance: Instance<'tcx>) -> &'ll Value {
811 get_fn(self, instance)
812 }
813
814 fn get_fn_addr(&self, instance: Instance<'tcx>) -> &'ll Value {
815 get_fn(self, instance)
816 }
817
818 fn eh_personality(&self) -> &'ll Value {
819 if let Some(llpersonality) = self.eh_personality.get() {
840 return llpersonality;
841 }
842
843 let name = if wants_msvc_seh(self.sess()) {
844 Some("__CxxFrameHandler3")
845 } else if wants_wasm_eh(self.sess()) {
846 Some("__gxx_wasm_personality_v0")
851 } else {
852 None
853 };
854
855 let tcx = self.tcx;
856 let llfn = match tcx.lang_items().eh_personality() {
857 Some(def_id) if name.is_none() => self.get_fn_addr(ty::Instance::expect_resolve(
858 tcx,
859 self.typing_env(),
860 def_id,
861 ty::List::empty(),
862 DUMMY_SP,
863 )),
864 _ => {
865 let name = name.unwrap_or("rust_eh_personality");
866 if let Some(llfn) = self.get_declared_value(name) {
867 llfn
868 } else {
869 let fty = self.type_variadic_func(&[], self.type_i32());
870 let llfn = self.declare_cfn(name, llvm::UnnamedAddr::Global, fty);
871 let target_cpu = attributes::target_cpu_attr(self, self.sess());
872 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[target_cpu]);
873 llfn
874 }
875 }
876 };
877 self.eh_personality.set(Some(llfn));
878 llfn
879 }
880
881 fn sess(&self) -> &Session {
882 self.tcx.sess
883 }
884
885 fn set_frame_pointer_type(&self, llfn: &'ll Value) {
886 if let Some(attr) = attributes::frame_pointer_type_attr(self, self.sess()) {
887 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[attr]);
888 }
889 }
890
891 fn apply_target_cpu_attr(&self, llfn: &'ll Value) {
892 let mut attrs = SmallVec::<[_; 2]>::new();
893 attrs.push(attributes::target_cpu_attr(self, self.sess()));
894 attrs.extend(attributes::tune_cpu_attr(self, self.sess()));
895 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &attrs);
896 }
897
898 fn declare_c_main(&self, fn_type: Self::Type) -> Option<Self::Function> {
899 let entry_name = self.sess().target.entry_name.as_ref();
900 if self.get_declared_value(entry_name).is_none() {
901 let llfn = self.declare_entry_fn(
902 entry_name,
903 to_llvm_calling_convention(self.sess(), self.sess().target.entry_abi),
904 llvm::UnnamedAddr::Global,
905 fn_type,
906 );
907 attributes::apply_to_llfn(
908 llfn,
909 llvm::AttributePlace::Function,
910 attributes::target_features_attr(self, self.tcx, vec![]).as_slice(),
911 );
912 Some(llfn)
913 } else {
914 None
917 }
918 }
919}
920
921impl<'ll> CodegenCx<'ll, '_> {
922 pub(crate) fn get_intrinsic(
923 &self,
924 base_name: Cow<'static, str>,
925 type_params: &[&'ll Type],
926 ) -> (&'ll Type, &'ll Value) {
927 *self
928 .intrinsics
929 .borrow_mut()
930 .entry((base_name, SmallVec::from_slice(type_params)))
931 .or_insert_with_key(|(base_name, type_params)| {
932 self.declare_intrinsic(base_name, type_params)
933 })
934 }
935
936 fn declare_intrinsic(
937 &self,
938 base_name: &str,
939 type_params: &[&'ll Type],
940 ) -> (&'ll Type, &'ll Value) {
941 if base_name == "memcmp" {
945 let fn_ty = self
946 .type_func(&[self.type_ptr(), self.type_ptr(), self.type_isize()], self.type_int());
947 let f = self.declare_cfn("memcmp", llvm::UnnamedAddr::No, fn_ty);
948
949 return (fn_ty, f);
950 }
951
952 let intrinsic = llvm::Intrinsic::lookup(base_name.as_bytes())
953 .unwrap_or_else(|| bug!("Unknown intrinsic: `{base_name}`"));
954 let f = intrinsic.get_declaration(self.llmod, &type_params);
955
956 (self.get_type_of_global(f), f)
957 }
958
959 pub(crate) fn eh_catch_typeinfo(&self) -> &'ll Value {
960 if let Some(eh_catch_typeinfo) = self.eh_catch_typeinfo.get() {
961 return eh_catch_typeinfo;
962 }
963 let tcx = self.tcx;
964 assert!(self.sess().target.os == "emscripten");
965 let eh_catch_typeinfo = match tcx.lang_items().eh_catch_typeinfo() {
966 Some(def_id) => self.get_static(def_id),
967 _ => {
968 let ty = self.type_struct(&[self.type_ptr(), self.type_ptr()], false);
969 self.declare_global(&mangle_internal_symbol(self.tcx, "rust_eh_catch_typeinfo"), ty)
970 }
971 };
972 self.eh_catch_typeinfo.set(Some(eh_catch_typeinfo));
973 eh_catch_typeinfo
974 }
975}
976
977impl CodegenCx<'_, '_> {
978 pub(crate) fn generate_local_symbol_name(&self, prefix: &str) -> String {
981 let idx = self.local_gen_sym_counter.get();
982 self.local_gen_sym_counter.set(idx + 1);
983 let mut name = String::with_capacity(prefix.len() + 6);
986 name.push_str(prefix);
987 name.push('.');
988 name.push_str(&(idx as u64).to_base(ALPHANUMERIC_ONLY));
989 name
990 }
991}
992
993impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
994 pub(crate) fn md_node_in_context(&self, md_list: &[&'ll Metadata]) -> &'ll Metadata {
996 unsafe { llvm::LLVMMDNodeInContext2(self.llcx(), md_list.as_ptr(), md_list.len()) }
997 }
998
999 pub(crate) fn set_metadata<'a>(
1001 &self,
1002 val: &'a Value,
1003 kind_id: MetadataKindId,
1004 md: &'ll Metadata,
1005 ) {
1006 let node = self.get_metadata_value(md);
1007 llvm::LLVMSetMetadata(val, kind_id, node);
1008 }
1009
1010 pub(crate) fn set_metadata_node(
1015 &self,
1016 instruction: &'ll Value,
1017 kind_id: MetadataKindId,
1018 md_list: &[&'ll Metadata],
1019 ) {
1020 let md = self.md_node_in_context(md_list);
1021 self.set_metadata(instruction, kind_id, md);
1022 }
1023
1024 pub(crate) fn module_add_named_metadata_node(
1029 &self,
1030 module: &'ll Module,
1031 kind_name: &CStr,
1032 md_list: &[&'ll Metadata],
1033 ) {
1034 let md = self.md_node_in_context(md_list);
1035 let md_as_val = self.get_metadata_value(md);
1036 unsafe { llvm::LLVMAddNamedMetadataOperand(module, kind_name.as_ptr(), md_as_val) };
1037 }
1038
1039 pub(crate) fn global_add_metadata_node(
1043 &self,
1044 global: &'ll Value,
1045 kind_id: MetadataKindId,
1046 md_list: &[&'ll Metadata],
1047 ) {
1048 let md = self.md_node_in_context(md_list);
1049 unsafe { llvm::LLVMRustGlobalAddMetadata(global, kind_id, md) };
1050 }
1051
1052 pub(crate) fn global_set_metadata_node(
1056 &self,
1057 global: &'ll Value,
1058 kind_id: MetadataKindId,
1059 md_list: &[&'ll Metadata],
1060 ) {
1061 let md = self.md_node_in_context(md_list);
1062 unsafe { llvm::LLVMGlobalSetMetadata(global, kind_id, md) };
1063 }
1064}
1065
1066impl HasDataLayout for CodegenCx<'_, '_> {
1067 #[inline]
1068 fn data_layout(&self) -> &TargetDataLayout {
1069 &self.tcx.data_layout
1070 }
1071}
1072
1073impl HasTargetSpec for CodegenCx<'_, '_> {
1074 #[inline]
1075 fn target_spec(&self) -> &Target {
1076 &self.tcx.sess.target
1077 }
1078}
1079
1080impl<'tcx> ty::layout::HasTyCtxt<'tcx> for CodegenCx<'_, 'tcx> {
1081 #[inline]
1082 fn tcx(&self) -> TyCtxt<'tcx> {
1083 self.tcx
1084 }
1085}
1086
1087impl<'tcx, 'll> HasTypingEnv<'tcx> for CodegenCx<'ll, 'tcx> {
1088 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
1089 ty::TypingEnv::fully_monomorphized()
1090 }
1091}
1092
1093impl<'tcx> LayoutOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
1094 #[inline]
1095 fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
1096 if let LayoutError::SizeOverflow(_)
1097 | LayoutError::ReferencesError(_)
1098 | LayoutError::InvalidSimd { .. } = err
1099 {
1100 self.tcx.dcx().emit_fatal(Spanned { span, node: err.into_diagnostic() })
1101 } else {
1102 self.tcx.dcx().emit_fatal(ssa_errors::FailedToGetLayout { span, ty, err })
1103 }
1104 }
1105}
1106
1107impl<'tcx> FnAbiOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
1108 #[inline]
1109 fn handle_fn_abi_err(
1110 &self,
1111 err: FnAbiError<'tcx>,
1112 span: Span,
1113 fn_abi_request: FnAbiRequest<'tcx>,
1114 ) -> ! {
1115 match err {
1116 FnAbiError::Layout(
1117 LayoutError::SizeOverflow(_)
1118 | LayoutError::Cycle(_)
1119 | LayoutError::InvalidSimd { .. },
1120 ) => {
1121 self.tcx.dcx().emit_fatal(Spanned { span, node: err });
1122 }
1123 _ => match fn_abi_request {
1124 FnAbiRequest::OfFnPtr { sig, extra_args } => {
1125 span_bug!(span, "`fn_abi_of_fn_ptr({sig}, {extra_args:?})` failed: {err:?}",);
1126 }
1127 FnAbiRequest::OfInstance { instance, extra_args } => {
1128 span_bug!(
1129 span,
1130 "`fn_abi_of_instance({instance}, {extra_args:?})` failed: {err:?}",
1131 );
1132 }
1133 },
1134 }
1135 }
1136}