1use std::borrow::Borrow;
4
5use libc::c_uint;
6use rustc_abi::Primitive::Pointer;
7use rustc_abi::{self as abi, ExternAbi, HasDataLayout as _};
8use rustc_ast::Mutability;
9use rustc_codegen_ssa::traits::*;
10use rustc_crate_store::DllImport;
11use rustc_data_structures::stable_hash::{StableHash, StableHasher};
12use rustc_hashes::Hash128;
13use rustc_hir::def::DefKind;
14use rustc_hir::def_id::DefId;
15use rustc_middle::mir::interpret::{GlobalAlloc, PointerArithmetic, Scalar};
16use rustc_middle::ty::{Instance, TyCtxt};
17use rustc_session::{PointerAuthAddressDiscriminator, PointerAuthSchema};
18use rustc_span::bug;
19use tracing::debug;
20
21use crate::consts::{IsInitOrFini, IsStatic, const_alloc_to_llvm};
22pub(crate) use crate::context::CodegenCx;
23use crate::context::{GenericCx, SCx};
24use crate::llvm::{
25 self, BasicBlock, ConstantInt, FALSE, TRUE, ToLlvmBool, Type, TypeKind, Value, const_ptr_auth,
26};
27
28pub(crate) fn maybe_sign_fn_ptr<'ll, 'tcx>(
29 cx: &CodegenCx<'ll, '_>,
30 instance: Instance<'tcx>,
31 llfn: llvm::Value<'ll>,
32 schema: &PointerAuthSchema,
33) -> llvm::Value<'ll> {
34 if cx.tcx.sess.pointer_authentication_functions().is_none() {
35 return llfn;
36 }
37
38 let def_id = instance.def_id();
40 if !#[allow(non_exhaustive_omitted_patterns)] match cx.tcx.def_kind(def_id) {
DefKind::Fn | DefKind::AssocFn => true,
_ => false,
}matches!(cx.tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
41 return llfn;
42 }
43 let abi = cx.tcx.fn_sig(def_id).skip_binder().abi();
45 if !#[allow(non_exhaustive_omitted_patterns)] match abi {
ExternAbi::C { .. } | ExternAbi::System { .. } => true,
_ => false,
}matches!(abi, ExternAbi::C { .. } | ExternAbi::System { .. }) {
46 return llfn;
47 }
48 if llvm::get_value_name(llfn).starts_with(b"llvm.") {
50 return llfn;
51 }
52 if Some(def_id) == cx.tcx.lang_items().eh_personality() {
53 return llfn;
54 }
55
56 let addr_diversity = match schema.is_address_discriminated {
57 PointerAuthAddressDiscriminator::HardwareAddress(true) => Some(llfn),
58 PointerAuthAddressDiscriminator::HardwareAddress(false) => None,
59 PointerAuthAddressDiscriminator::Synthetic(val) => {
60 let llval = cx.const_u64(val);
61 let llty = cx.val_ty(llfn);
62 Some(unsafe { llvm::LLVMConstIntToPtr(llval, llty) })
63 }
64 };
65 const_ptr_auth(llfn, schema.key as u32, schema.constant_discriminator as u64, addr_diversity)
66}
67
68pub(crate) struct Funclet<'ll> {
109 cleanuppad: Value<'ll>,
110 operand: llvm::OperandBundleBox<'ll>,
111}
112
113impl<'ll> Funclet<'ll> {
114 pub(crate) fn new(cleanuppad: Value<'ll>) -> Self {
115 Funclet { cleanuppad, operand: llvm::OperandBundleBox::new("funclet", &[cleanuppad]) }
116 }
117
118 pub(crate) fn cleanuppad(&self) -> Value<'ll> {
119 self.cleanuppad
120 }
121
122 pub(crate) fn bundle(&self) -> &llvm::OperandBundle<'ll> {
123 self.operand.as_ref()
124 }
125}
126
127impl<'ll, CX: Borrow<SCx<'ll>>> BackendTypes for GenericCx<'ll, CX> {
128 type Function = Value<'ll>;
130 type BasicBlock = &'ll BasicBlock;
131 type Funclet = Funclet<'ll>;
132
133 type Value = Value<'ll>;
134 type Type = Type<'ll>;
135 type FunctionSignature = Type<'ll>;
136
137 type DIScope = &'ll llvm::debuginfo::DIScope;
138 type DILocation = &'ll llvm::debuginfo::DILocation;
139 type DIVariable = &'ll llvm::debuginfo::DIVariable;
140}
141
142impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
143 pub(crate) fn const_array(&self, ty: Type<'ll>, elts: &[Value<'ll>]) -> Value<'ll> {
144 let len = u64::try_from(elts.len()).expect("LLVMConstArray2 elements len overflow");
145 unsafe { llvm::LLVMConstArray2(ty, elts.as_ptr(), len) }
146 }
147
148 pub(crate) fn const_bytes(&self, bytes: &[u8]) -> Value<'ll> {
149 bytes_in_context(self.llcx(), bytes)
150 }
151
152 pub(crate) fn null_terminate_const_bytes(&self, bytes: &[u8]) -> Value<'ll> {
153 null_terminate_bytes_in_context(self.llcx(), bytes)
154 }
155
156 pub(crate) fn const_get_elt(&self, v: Value<'ll>, idx: u64) -> Value<'ll> {
157 unsafe {
158 let idx = c_uint::try_from(idx).expect("LLVMGetAggregateElement index overflow");
159 let r = llvm::LLVMGetAggregateElement(v, idx).unwrap();
160
161 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/common.rs:161",
"rustc_codegen_llvm::common", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/common.rs"),
::tracing_core::__macro_support::Option::Some(161u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::common"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("const_get_elt(v={0:?}, idx={1}, r={2:?})",
v, idx, r) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("const_get_elt(v={:?}, idx={}, r={:?})", v, idx, r);
162
163 r
164 }
165 }
166
167 pub(crate) fn const_null(&self, t: Type<'ll>) -> Value<'ll> {
168 unsafe { llvm::LLVMConstNull(t) }
169 }
170
171 pub(crate) fn const_struct(&self, elts: &[Value<'ll>], packed: bool) -> Value<'ll> {
172 struct_in_context(self.llcx(), elts, packed)
173 }
174}
175
176impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
177 pub(crate) fn alloc_to_backend(
178 &self,
179 global_alloc: GlobalAlloc<'tcx>,
180 need_symbol_name: bool,
181 schema: Option<&PointerAuthSchema>,
182 ) -> Result<Value<'ll>, u64> {
183 let alloc = match global_alloc {
184 GlobalAlloc::Function { instance, .. } => {
185 return Ok(self.get_fn_addr(instance, schema));
186 }
187 GlobalAlloc::Static(def_id) => {
188 if !self.tcx.is_static(def_id) {
::core::panicking::panic("assertion failed: self.tcx.is_static(def_id)")
};assert!(self.tcx.is_static(def_id));
189 if !!self.tcx.is_thread_local_static(def_id) {
::core::panicking::panic("assertion failed: !self.tcx.is_thread_local_static(def_id)")
};assert!(!self.tcx.is_thread_local_static(def_id));
190 return Ok(
191 self.renamed_statics
194 .borrow()
195 .get(&def_id)
196 .copied()
197 .unwrap_or_else(|| self.get_static(def_id)),
198 );
199 }
200 GlobalAlloc::TypeId { .. } => {
201 return Err(0);
204 }
205
206 GlobalAlloc::Memory(alloc) => {
207 if alloc.inner().len() == 0 {
208 return Err(alloc.inner().align.bytes());
212 }
213
214 alloc
215 }
216 GlobalAlloc::VTable(ty, dyn_ty) => {
217 self.tcx
218 .global_alloc(self.tcx.vtable_allocation((
219 ty,
220 dyn_ty.principal().map(|principal| {
221 self.tcx.instantiate_bound_regions_with_erased(principal)
222 }),
223 )))
224 .unwrap_memory()
225 }
226 };
227
228 let init = const_alloc_to_llvm(self, alloc.inner(), IsStatic::No, IsInitOrFini::No);
229 let alloc = alloc.inner();
230
231 if need_symbol_name {
232 let value = self.static_addr_of_mut(init, alloc.align, None);
234 if alloc.mutability.is_not() {
235 llvm::set_global_constant(value, true);
236 }
237
238 let name = self.generate_global_symbol_name();
242 llvm::set_value_name(value, name.as_bytes());
243 llvm::set_linkage(value, llvm::Linkage::InternalLinkage);
244 return Ok(value);
245 }
246
247 let value = match alloc.mutability {
248 Mutability::Mut => self.static_addr_of_mut(init, alloc.align, None),
249 _ => self.static_addr_of_impl(init, alloc.align, None),
250 };
251 if !self.sess().fewer_names() && llvm::get_value_name(value).is_empty() {
252 let hash = self.tcx.with_stable_hashing_context(|mut hcx| {
253 let mut hasher = StableHasher::new();
254 alloc.stable_hash(&mut hcx, &mut hasher);
255 hasher.finish::<Hash128>()
256 });
257 llvm::set_value_name(value, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("alloc_{0:032x}", hash))
})format!("alloc_{hash:032x}").as_bytes());
258 }
259
260 Ok(value)
261 }
262}
263
264impl<'ll, 'tcx> ConstCodegenMethods for CodegenCx<'ll, 'tcx> {
265 fn const_null(&self, t: Type<'ll>) -> Value<'ll> {
266 unsafe { llvm::LLVMConstNull(t) }
267 }
268
269 fn const_undef(&self, t: Type<'ll>) -> Value<'ll> {
270 unsafe { llvm::LLVMGetUndef(t) }
271 }
272
273 fn const_poison(&self, t: Type<'ll>) -> Value<'ll> {
274 unsafe { llvm::LLVMGetPoison(t) }
275 }
276
277 fn const_bool(&self, val: bool) -> Value<'ll> {
278 self.const_uint(self.type_i1(), val as u64)
279 }
280
281 fn const_i8(&self, i: i8) -> Value<'ll> {
282 self.const_int(self.type_i8(), i as i64)
283 }
284
285 fn const_i16(&self, i: i16) -> Value<'ll> {
286 self.const_int(self.type_i16(), i as i64)
287 }
288
289 fn const_i32(&self, i: i32) -> Value<'ll> {
290 self.const_int(self.type_i32(), i as i64)
291 }
292
293 fn const_i64(&self, i: i64) -> Value<'ll> {
294 self.const_int(self.type_i64(), i)
295 }
296
297 fn const_int(&self, t: Type<'ll>, i: i64) -> Value<'ll> {
298 if true {
if !(self.type_kind(t) == TypeKind::Integer) {
{
::core::panicking::panic_fmt(format_args!("only allows integer types in const_int"));
}
};
};debug_assert!(
299 self.type_kind(t) == TypeKind::Integer,
300 "only allows integer types in const_int"
301 );
302 unsafe { llvm::LLVMConstInt(t, i as u64, TRUE) }
303 }
304
305 fn const_u8(&self, i: u8) -> Value<'ll> {
306 self.const_uint(self.type_i8(), i as u64)
307 }
308
309 fn const_u32(&self, i: u32) -> Value<'ll> {
310 self.const_uint(self.type_i32(), i as u64)
311 }
312
313 fn const_u64(&self, i: u64) -> Value<'ll> {
314 self.const_uint(self.type_i64(), i)
315 }
316
317 fn const_u128(&self, i: u128) -> Value<'ll> {
318 self.const_uint_big(self.type_i128(), i)
319 }
320
321 fn const_usize(&self, i: u64) -> Value<'ll> {
322 let bit_size = self.data_layout().pointer_size().bits();
323 if bit_size < 64 {
324 if !(i < (1 << bit_size)) {
::core::panicking::panic("assertion failed: i < (1 << bit_size)")
};assert!(i < (1 << bit_size));
326 }
327
328 self.const_uint(self.isize_ty, i)
329 }
330
331 fn const_uint(&self, t: Type<'ll>, i: u64) -> Value<'ll> {
332 if true {
if !(self.type_kind(t) == TypeKind::Integer) {
{
::core::panicking::panic_fmt(format_args!("only allows integer types in const_uint"));
}
};
};debug_assert!(
333 self.type_kind(t) == TypeKind::Integer,
334 "only allows integer types in const_uint"
335 );
336 unsafe { llvm::LLVMConstInt(t, i, FALSE) }
337 }
338
339 fn const_uint_big(&self, t: Type<'ll>, u: u128) -> Value<'ll> {
340 if true {
if !(self.type_kind(t) == TypeKind::Integer) {
{
::core::panicking::panic_fmt(format_args!("only allows integer types in const_uint_big"));
}
};
};debug_assert!(
341 self.type_kind(t) == TypeKind::Integer,
342 "only allows integer types in const_uint_big"
343 );
344 unsafe {
345 let words = [u as u64, (u >> 64) as u64];
346 llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
347 }
348 }
349
350 fn const_real(&self, t: Type<'ll>, val: f64) -> Value<'ll> {
351 unsafe { llvm::LLVMConstReal(t, val) }
352 }
353
354 fn const_str(&self, s: &str) -> (Value<'ll>, Value<'ll>) {
355 let mut const_str_cache = self.const_str_cache.borrow_mut();
356 let str_global = const_str_cache.get(s).copied().unwrap_or_else(|| {
357 let sc = self.const_bytes(s.as_bytes());
358 let sym = self.generate_local_symbol_name("str");
359 let g = self.define_global(&sym, self.val_ty(sc)).unwrap_or_else(|| {
360 ::rustc_span::macros::bug_impl(None,
format_args!("symbol `{0}` is already defined", sym), Location::caller());bug!("symbol `{}` is already defined", sym);
361 });
362 llvm::set_initializer(g, sc);
363
364 llvm::set_global_constant(g, true);
365 llvm::set_unnamed_address(g, llvm::UnnamedAddr::Global);
366
367 llvm::set_linkage(g, llvm::Linkage::InternalLinkage);
368 let g = self.const_pointercast(g, self.type_ptr());
370 const_str_cache.insert(s.to_owned(), g);
371 g
372 });
373 let len = s.len();
374 (str_global, self.const_usize(len as u64))
375 }
376
377 fn const_struct(&self, elts: &[Value<'ll>], packed: bool) -> Value<'ll> {
378 struct_in_context(self.llcx, elts, packed)
379 }
380
381 fn const_vector(&self, elts: &[Value<'ll>]) -> Value<'ll> {
382 let len = c_uint::try_from(elts.len()).expect("LLVMConstVector elements len overflow");
383 unsafe { llvm::LLVMConstVector(elts.as_ptr(), len) }
384 }
385
386 fn const_to_opt_uint(&self, v: Value<'ll>) -> Option<u64> {
387 try_as_const_integral(v).and_then(|v| unsafe {
388 let mut i = 0u64;
389 let success = llvm::LLVMRustConstIntGetZExtValue(v, &mut i);
390 success.then_some(i)
391 })
392 }
393
394 fn const_to_opt_u128(&self, v: Value<'ll>, sign_ext: bool) -> Option<u128> {
395 try_as_const_integral(v).and_then(|v| unsafe {
396 let (mut lo, mut hi) = (0u64, 0u64);
397 let success = llvm::LLVMRustConstInt128Get(v, sign_ext, &mut hi, &mut lo);
398 success.then_some(hi_lo_to_u128(lo, hi))
399 })
400 }
401
402 fn scalar_to_backend_with_pac(
403 &self,
404 cv: Scalar,
405 layout: abi::Scalar,
406 llty: Type<'ll>,
407 schema: Option<&PointerAuthSchema>,
408 ) -> Value<'ll> {
409 let bitsize = if layout.is_bool() { 1 } else { layout.size(self).bits() };
410 match cv {
411 Scalar::Int(int) => {
412 let data = int.to_bits(layout.size(self));
413 let llval = self.const_uint_big(self.type_ix(bitsize), data);
414 if #[allow(non_exhaustive_omitted_patterns)] match layout.primitive() {
Pointer(_) => true,
_ => false,
}matches!(layout.primitive(), Pointer(_)) {
415 unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
416 } else {
417 self.const_bitcast(llval, llty)
418 }
419 }
420 Scalar::Ptr(ptr, _size) => {
421 let (prov, offset) = ptr.prov_and_relative_offset();
422 let global_alloc = self.tcx.global_alloc(prov.alloc_id());
423 let base_addr_space = global_alloc.address_space(self);
424 let base_addr = match self.alloc_to_backend(global_alloc, false, schema) {
425 Ok(base_addr) => base_addr,
426 Err(base_addr) => {
427 let val = base_addr.wrapping_add(offset.bytes());
428 let llval = self.const_usize(self.tcx.truncate_to_target_usize(val));
429 return if #[allow(non_exhaustive_omitted_patterns)] match layout.primitive() {
Pointer(_) => true,
_ => false,
}matches!(layout.primitive(), Pointer(_)) {
430 unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
431 } else {
432 self.const_bitcast(llval, llty)
433 };
434 }
435 };
436 let llval = unsafe {
437 llvm::LLVMConstInBoundsGEP2(
438 self.type_i8(),
439 self.const_pointercast(base_addr, self.type_ptr_ext(base_addr_space)),
441 &self.const_usize(offset.bytes()),
442 1,
443 )
444 };
445 if !#[allow(non_exhaustive_omitted_patterns)] match layout.primitive() {
Pointer(_) => true,
_ => false,
}matches!(layout.primitive(), Pointer(_)) {
446 unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
447 } else {
448 self.const_bitcast(llval, llty)
449 }
450 }
451 }
452 }
453
454 fn const_ptr_byte_offset(&self, base_addr: Self::Value, offset: abi::Size) -> Self::Value {
455 unsafe {
456 llvm::LLVMConstInBoundsGEP2(
457 self.type_i8(),
458 base_addr,
459 &self.const_usize(offset.bytes()),
460 1,
461 )
462 }
463 }
464}
465
466pub(crate) fn val_ty<'ll>(v: Value<'ll>) -> Type<'ll> {
468 unsafe { llvm::LLVMTypeOf(v) }
469}
470
471pub(crate) fn bytes_in_context<'ll>(llcx: llvm::Context<'ll>, bytes: &[u8]) -> Value<'ll> {
472 unsafe { llvm::LLVMConstStringInContext2(llcx, bytes.as_ptr(), bytes.len(), TRUE) }
473}
474
475pub(crate) fn null_terminate_bytes_in_context<'ll>(
476 llcx: llvm::Context<'ll>,
477 bytes: &[u8],
478) -> Value<'ll> {
479 unsafe { llvm::LLVMConstStringInContext2(llcx, bytes.as_ptr(), bytes.len(), FALSE) }
480}
481
482pub(crate) fn named_struct<'ll>(ty: Type<'ll>, elts: &[Value<'ll>]) -> Value<'ll> {
483 let len = c_uint::try_from(elts.len()).expect("LLVMConstStructInContext elements len overflow");
484 unsafe { llvm::LLVMConstNamedStruct(ty, elts.as_ptr(), len) }
485}
486
487fn struct_in_context<'ll>(
488 llcx: llvm::Context<'ll>,
489 elts: &[Value<'ll>],
490 packed: bool,
491) -> Value<'ll> {
492 let len = c_uint::try_from(elts.len()).expect("LLVMConstStructInContext elements len overflow");
493 unsafe { llvm::LLVMConstStructInContext(llcx, elts.as_ptr(), len, packed.to_llvm_bool()) }
494}
495
496#[inline]
497fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
498 ((hi as u128) << 64) | (lo as u128)
499}
500
501fn try_as_const_integral<'ll>(v: Value<'ll>) -> Option<&'ll ConstantInt> {
502 unsafe { llvm::LLVMIsAConstantInt(v) }
503}
504
505pub(crate) fn get_dllimport<'tcx>(
506 tcx: TyCtxt<'tcx>,
507 id: DefId,
508 name: &str,
509) -> Option<&'tcx DllImport> {
510 tcx.native_library(id)
511 .and_then(|lib| lib.dll_imports.iter().find(|di| di.name.as_str() == name))
512}