1use std::borrow::Borrow;
4
5use libc::{c_char, c_uint};
6use rustc_abi::Primitive::Pointer;
7use rustc_abi::{self as abi, HasDataLayout as _};
8use rustc_ast::Mutability;
9use rustc_codegen_ssa::common::TypeKind;
10use rustc_codegen_ssa::traits::*;
11use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
12use rustc_hashes::Hash128;
13use rustc_hir::def_id::DefId;
14use rustc_middle::bug;
15use rustc_middle::mir::interpret::{ConstAllocation, GlobalAlloc, PointerArithmetic, Scalar};
16use rustc_middle::ty::TyCtxt;
17use rustc_session::cstore::DllImport;
18use tracing::debug;
19
20use crate::consts::const_alloc_to_llvm;
21pub(crate) use crate::context::CodegenCx;
22use crate::context::{GenericCx, SCx};
23use crate::llvm::{self, BasicBlock, ConstantInt, FALSE, Metadata, TRUE, ToLlvmBool, Type, Value};
24
25pub(crate) struct Funclet<'ll> {
66 cleanuppad: &'ll Value,
67 operand: llvm::OperandBundleBox<'ll>,
68}
69
70impl<'ll> Funclet<'ll> {
71 pub(crate) fn new(cleanuppad: &'ll Value) -> Self {
72 Funclet { cleanuppad, operand: llvm::OperandBundleBox::new("funclet", &[cleanuppad]) }
73 }
74
75 pub(crate) fn cleanuppad(&self) -> &'ll Value {
76 self.cleanuppad
77 }
78
79 pub(crate) fn bundle(&self) -> &llvm::OperandBundle<'ll> {
80 self.operand.as_ref()
81 }
82}
83
84impl<'ll, CX: Borrow<SCx<'ll>>> BackendTypes for GenericCx<'ll, CX> {
85 type Value = &'ll Value;
86 type Metadata = &'ll Metadata;
87 type Function = &'ll Value;
89
90 type BasicBlock = &'ll BasicBlock;
91 type Type = &'ll Type;
92 type Funclet = Funclet<'ll>;
93
94 type DIScope = &'ll llvm::debuginfo::DIScope;
95 type DILocation = &'ll llvm::debuginfo::DILocation;
96 type DIVariable = &'ll llvm::debuginfo::DIVariable;
97}
98
99impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
100 pub(crate) fn const_array(&self, ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
101 let len = u64::try_from(elts.len()).expect("LLVMConstArray2 elements len overflow");
102 unsafe { llvm::LLVMConstArray2(ty, elts.as_ptr(), len) }
103 }
104
105 pub(crate) fn const_bytes(&self, bytes: &[u8]) -> &'ll Value {
106 bytes_in_context(self.llcx(), bytes)
107 }
108
109 pub(crate) fn null_terminate_const_bytes(&self, bytes: &[u8]) -> &'ll Value {
110 null_terminate_bytes_in_context(self.llcx(), bytes)
111 }
112
113 pub(crate) fn const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value {
114 unsafe {
115 let idx = c_uint::try_from(idx).expect("LLVMGetAggregateElement index overflow");
116 let r = llvm::LLVMGetAggregateElement(v, idx).unwrap();
117
118 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/common.rs:118",
"rustc_codegen_llvm::common", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/common.rs"),
::tracing_core::__macro_support::Option::Some(118u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("const_get_elt(v={0:?}, idx={1}, r={2:?})",
v, idx, r) as &dyn Value))])
});
} else { ; }
};debug!("const_get_elt(v={:?}, idx={}, r={:?})", v, idx, r);
119
120 r
121 }
122 }
123
124 pub(crate) fn const_null(&self, t: &'ll Type) -> &'ll Value {
125 unsafe { llvm::LLVMConstNull(t) }
126 }
127
128 pub(crate) fn const_struct(&self, elts: &[&'ll Value], packed: bool) -> &'ll Value {
129 struct_in_context(self.llcx(), elts, packed)
130 }
131}
132
133impl<'ll, 'tcx> ConstCodegenMethods for CodegenCx<'ll, 'tcx> {
134 fn const_null(&self, t: &'ll Type) -> &'ll Value {
135 unsafe { llvm::LLVMConstNull(t) }
136 }
137
138 fn const_undef(&self, t: &'ll Type) -> &'ll Value {
139 unsafe { llvm::LLVMGetUndef(t) }
140 }
141
142 fn const_poison(&self, t: &'ll Type) -> &'ll Value {
143 unsafe { llvm::LLVMGetPoison(t) }
144 }
145
146 fn const_bool(&self, val: bool) -> &'ll Value {
147 self.const_uint(self.type_i1(), val as u64)
148 }
149
150 fn const_i8(&self, i: i8) -> &'ll Value {
151 self.const_int(self.type_i8(), i as i64)
152 }
153
154 fn const_i16(&self, i: i16) -> &'ll Value {
155 self.const_int(self.type_i16(), i as i64)
156 }
157
158 fn const_i32(&self, i: i32) -> &'ll Value {
159 self.const_int(self.type_i32(), i as i64)
160 }
161
162 fn const_int(&self, t: &'ll Type, i: i64) -> &'ll Value {
163 if true {
if !(self.type_kind(t) == TypeKind::Integer) {
{
::core::panicking::panic_fmt(format_args!("only allows integer types in const_int"));
}
};
};debug_assert!(
164 self.type_kind(t) == TypeKind::Integer,
165 "only allows integer types in const_int"
166 );
167 unsafe { llvm::LLVMConstInt(t, i as u64, TRUE) }
168 }
169
170 fn const_u8(&self, i: u8) -> &'ll Value {
171 self.const_uint(self.type_i8(), i as u64)
172 }
173
174 fn const_u32(&self, i: u32) -> &'ll Value {
175 self.const_uint(self.type_i32(), i as u64)
176 }
177
178 fn const_u64(&self, i: u64) -> &'ll Value {
179 self.const_uint(self.type_i64(), i)
180 }
181
182 fn const_u128(&self, i: u128) -> &'ll Value {
183 self.const_uint_big(self.type_i128(), i)
184 }
185
186 fn const_usize(&self, i: u64) -> &'ll Value {
187 let bit_size = self.data_layout().pointer_size().bits();
188 if bit_size < 64 {
189 if !(i < (1 << bit_size)) {
::core::panicking::panic("assertion failed: i < (1 << bit_size)")
};assert!(i < (1 << bit_size));
191 }
192
193 self.const_uint(self.isize_ty, i)
194 }
195
196 fn const_uint(&self, t: &'ll Type, i: u64) -> &'ll Value {
197 if true {
if !(self.type_kind(t) == TypeKind::Integer) {
{
::core::panicking::panic_fmt(format_args!("only allows integer types in const_uint"));
}
};
};debug_assert!(
198 self.type_kind(t) == TypeKind::Integer,
199 "only allows integer types in const_uint"
200 );
201 unsafe { llvm::LLVMConstInt(t, i, FALSE) }
202 }
203
204 fn const_uint_big(&self, t: &'ll Type, u: u128) -> &'ll Value {
205 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!(
206 self.type_kind(t) == TypeKind::Integer,
207 "only allows integer types in const_uint_big"
208 );
209 unsafe {
210 let words = [u as u64, (u >> 64) as u64];
211 llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
212 }
213 }
214
215 fn const_real(&self, t: &'ll Type, val: f64) -> &'ll Value {
216 unsafe { llvm::LLVMConstReal(t, val) }
217 }
218
219 fn const_str(&self, s: &str) -> (&'ll Value, &'ll Value) {
220 let mut const_str_cache = self.const_str_cache.borrow_mut();
221 let str_global = const_str_cache.get(s).copied().unwrap_or_else(|| {
222 let sc = self.const_bytes(s.as_bytes());
223 let sym = self.generate_local_symbol_name("str");
224 let g = self.define_global(&sym, self.val_ty(sc)).unwrap_or_else(|| {
225 ::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
sym));bug!("symbol `{}` is already defined", sym);
226 });
227 llvm::set_initializer(g, sc);
228
229 llvm::set_global_constant(g, true);
230 llvm::set_unnamed_address(g, llvm::UnnamedAddr::Global);
231
232 llvm::set_linkage(g, llvm::Linkage::InternalLinkage);
233 let g = self.const_pointercast(g, self.type_ptr());
235 const_str_cache.insert(s.to_owned(), g);
236 g
237 });
238 let len = s.len();
239 (str_global, self.const_usize(len as u64))
240 }
241
242 fn const_struct(&self, elts: &[&'ll Value], packed: bool) -> &'ll Value {
243 struct_in_context(self.llcx, elts, packed)
244 }
245
246 fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
247 let len = c_uint::try_from(elts.len()).expect("LLVMConstVector elements len overflow");
248 unsafe { llvm::LLVMConstVector(elts.as_ptr(), len) }
249 }
250
251 fn const_to_opt_uint(&self, v: &'ll Value) -> Option<u64> {
252 try_as_const_integral(v).and_then(|v| unsafe {
253 let mut i = 0u64;
254 let success = llvm::LLVMRustConstIntGetZExtValue(v, &mut i);
255 success.then_some(i)
256 })
257 }
258
259 fn const_to_opt_u128(&self, v: &'ll Value, sign_ext: bool) -> Option<u128> {
260 try_as_const_integral(v).and_then(|v| unsafe {
261 let (mut lo, mut hi) = (0u64, 0u64);
262 let success = llvm::LLVMRustConstInt128Get(v, sign_ext, &mut hi, &mut lo);
263 success.then_some(hi_lo_to_u128(lo, hi))
264 })
265 }
266
267 fn scalar_to_backend(&self, cv: Scalar, layout: abi::Scalar, llty: &'ll Type) -> &'ll Value {
268 let bitsize = if layout.is_bool() { 1 } else { layout.size(self).bits() };
269 match cv {
270 Scalar::Int(int) => {
271 let data = int.to_bits(layout.size(self));
272 let llval = self.const_uint_big(self.type_ix(bitsize), data);
273 if #[allow(non_exhaustive_omitted_patterns)] match layout.primitive() {
Pointer(_) => true,
_ => false,
}matches!(layout.primitive(), Pointer(_)) {
274 unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
275 } else {
276 self.const_bitcast(llval, llty)
277 }
278 }
279 Scalar::Ptr(ptr, _size) => {
280 let (prov, offset) = ptr.prov_and_relative_offset();
281 let global_alloc = self.tcx.global_alloc(prov.alloc_id());
282 let base_addr = match global_alloc {
283 GlobalAlloc::Memory(alloc) => {
284 if alloc.inner().len() == 0 {
288 let val = alloc.inner().align.bytes().wrapping_add(offset.bytes());
289 let llval = self.const_usize(self.tcx.truncate_to_target_usize(val));
290 return if #[allow(non_exhaustive_omitted_patterns)] match layout.primitive() {
Pointer(_) => true,
_ => false,
}matches!(layout.primitive(), Pointer(_)) {
291 unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
292 } else {
293 self.const_bitcast(llval, llty)
294 };
295 } else {
296 let init =
297 const_alloc_to_llvm(self, alloc.inner(), false);
298 let alloc = alloc.inner();
299 let value = match alloc.mutability {
300 Mutability::Mut => self.static_addr_of_mut(init, alloc.align, None),
301 _ => self.static_addr_of_impl(init, alloc.align, None),
302 };
303 if !self.sess().fewer_names() && llvm::get_value_name(value).is_empty()
304 {
305 let hash = self.tcx.with_stable_hashing_context(|mut hcx| {
306 let mut hasher = StableHasher::new();
307 alloc.hash_stable(&mut hcx, &mut hasher);
308 hasher.finish::<Hash128>()
309 });
310 llvm::set_value_name(
311 value,
312 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("alloc_{0:032x}", hash))
})format!("alloc_{hash:032x}").as_bytes(),
313 );
314 }
315 value
316 }
317 }
318 GlobalAlloc::Function { instance, .. } => self.get_fn_addr(instance),
319 GlobalAlloc::VTable(ty, dyn_ty) => {
320 let alloc = self
321 .tcx
322 .global_alloc(self.tcx.vtable_allocation((
323 ty,
324 dyn_ty.principal().map(|principal| {
325 self.tcx.instantiate_bound_regions_with_erased(principal)
326 }),
327 )))
328 .unwrap_memory();
329 let init = const_alloc_to_llvm(self, alloc.inner(), false);
330 self.static_addr_of_impl(init, alloc.inner().align, None)
331 }
332 GlobalAlloc::Static(def_id) => {
333 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));
334 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));
335 self.get_static(def_id)
336 }
337 GlobalAlloc::TypeId { .. } => {
338 let llval = self.const_usize(offset.bytes());
340 return unsafe { llvm::LLVMConstIntToPtr(llval, llty) };
341 }
342 };
343 let base_addr_space = global_alloc.address_space(self);
344 let llval = unsafe {
345 llvm::LLVMConstInBoundsGEP2(
346 self.type_i8(),
347 self.const_pointercast(base_addr, self.type_ptr_ext(base_addr_space)),
349 &self.const_usize(offset.bytes()),
350 1,
351 )
352 };
353 if !#[allow(non_exhaustive_omitted_patterns)] match layout.primitive() {
Pointer(_) => true,
_ => false,
}matches!(layout.primitive(), Pointer(_)) {
354 unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
355 } else {
356 self.const_bitcast(llval, llty)
357 }
358 }
359 }
360 }
361
362 fn const_data_from_alloc(&self, alloc: ConstAllocation<'_>) -> Self::Value {
363 const_alloc_to_llvm(self, alloc.inner(), false)
364 }
365
366 fn const_ptr_byte_offset(&self, base_addr: Self::Value, offset: abi::Size) -> Self::Value {
367 unsafe {
368 llvm::LLVMConstInBoundsGEP2(
369 self.type_i8(),
370 base_addr,
371 &self.const_usize(offset.bytes()),
372 1,
373 )
374 }
375 }
376}
377
378pub(crate) fn val_ty(v: &Value) -> &Type {
380 unsafe { llvm::LLVMTypeOf(v) }
381}
382
383pub(crate) fn bytes_in_context<'ll>(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
384 unsafe {
385 let ptr = bytes.as_ptr() as *const c_char;
386 llvm::LLVMConstStringInContext2(llcx, ptr, bytes.len(), TRUE)
387 }
388}
389
390pub(crate) fn null_terminate_bytes_in_context<'ll>(
391 llcx: &'ll llvm::Context,
392 bytes: &[u8],
393) -> &'ll Value {
394 unsafe {
395 let ptr = bytes.as_ptr() as *const c_char;
396 llvm::LLVMConstStringInContext2(llcx, ptr, bytes.len(), FALSE)
397 }
398}
399
400pub(crate) fn named_struct<'ll>(ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
401 let len = c_uint::try_from(elts.len()).expect("LLVMConstStructInContext elements len overflow");
402 unsafe { llvm::LLVMConstNamedStruct(ty, elts.as_ptr(), len) }
403}
404
405fn struct_in_context<'ll>(
406 llcx: &'ll llvm::Context,
407 elts: &[&'ll Value],
408 packed: bool,
409) -> &'ll Value {
410 let len = c_uint::try_from(elts.len()).expect("LLVMConstStructInContext elements len overflow");
411 unsafe { llvm::LLVMConstStructInContext(llcx, elts.as_ptr(), len, packed.to_llvm_bool()) }
412}
413
414#[inline]
415fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
416 ((hi as u128) << 64) | (lo as u128)
417}
418
419fn try_as_const_integral(v: &Value) -> Option<&ConstantInt> {
420 unsafe { llvm::LLVMIsAConstantInt(v) }
421}
422
423pub(crate) fn get_dllimport<'tcx>(
424 tcx: TyCtxt<'tcx>,
425 id: DefId,
426 name: &str,
427) -> Option<&'tcx DllImport> {
428 tcx.native_library(id)
429 .and_then(|lib| lib.dll_imports.iter().find(|di| di.name.as_str() == name))
430}
431
432pub(crate) trait AsCCharPtr {
434 fn as_c_char_ptr(&self) -> *const c_char;
436}
437
438impl AsCCharPtr for str {
439 fn as_c_char_ptr(&self) -> *const c_char {
440 self.as_ptr().cast()
441 }
442}
443
444impl AsCCharPtr for [u8] {
445 fn as_c_char_ptr(&self) -> *const c_char {
446 self.as_ptr().cast()
447 }
448}