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