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