1 //! Handling of `static`s, `const`s and promoted allocations
3 use rustc_span::DUMMY_SP;
5 use rustc_data_structures::fx::FxHashSet;
6 use rustc_errors::ErrorReported;
7 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
8 use rustc_middle::mir::interpret::{
9 read_target_uint, AllocId, Allocation, ConstValue, ErrorHandled, GlobalAlloc, Pointer, Scalar,
11 use rustc_middle::ty::{Const, ConstKind};
13 use cranelift_codegen::ir::GlobalValueData;
14 use cranelift_module::*;
16 use crate::prelude::*;
19 pub(crate) struct ConstantCx {
21 done: FxHashSet<DataId>,
24 #[derive(Copy, Clone, Debug)]
31 pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut impl Module) {
32 //println!("todo {:?}", self.todo);
33 define_all_allocs(tcx, module, &mut self);
34 //println!("done {:?}", self.done);
39 pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, impl Module>) {
40 for constant in &fx.mir.required_consts {
41 let const_ = fx.monomorphize(constant.literal);
43 ConstKind::Value(_) => {}
44 ConstKind::Unevaluated(def, ref substs, promoted) => {
47 .const_eval_resolve(ParamEnv::reveal_all(), def, substs, promoted, None)
50 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
53 .span_err(constant.span, "erroneous constant encountered");
55 ErrorHandled::TooGeneric => {
58 "codgen encountered polymorphic constant: {:?}",
67 | ConstKind::Bound(_, _)
68 | ConstKind::Placeholder(_)
69 | ConstKind::Error(_) => unreachable!("{:?}", const_),
74 pub(crate) fn codegen_static(constants_cx: &mut ConstantCx, def_id: DefId) {
75 constants_cx.todo.push(TodoItem::Static(def_id));
78 pub(crate) fn codegen_tls_ref<'tcx>(
79 fx: &mut FunctionCx<'_, 'tcx, impl Module>,
81 layout: TyAndLayout<'tcx>,
83 let data_id = data_id_for_static(fx.tcx, &mut fx.cx.module, def_id, false);
84 let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
85 #[cfg(debug_assertions)]
86 fx.add_comment(local_data_id, format!("tls {:?}", def_id));
87 let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
88 CValue::by_val(tls_ptr, layout)
91 fn codegen_static_ref<'tcx>(
92 fx: &mut FunctionCx<'_, 'tcx, impl Module>,
94 layout: TyAndLayout<'tcx>,
96 let data_id = data_id_for_static(fx.tcx, &mut fx.cx.module, def_id, false);
97 let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
98 #[cfg(debug_assertions)]
99 fx.add_comment(local_data_id, format!("{:?}", def_id));
100 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
101 assert!(!layout.is_unsized(), "unsized statics aren't supported");
104 fx.bcx.func.global_values[local_data_id],
105 GlobalValueData::Symbol { tls: false, .. }
107 "tls static referenced without Rvalue::ThreadLocalRef"
109 CPlace::for_ptr(crate::pointer::Pointer::new(global_ptr), layout)
112 pub(crate) fn codegen_constant<'tcx>(
113 fx: &mut FunctionCx<'_, 'tcx, impl Module>,
114 constant: &Constant<'tcx>,
116 let const_ = fx.monomorphize(constant.literal);
117 let const_val = match const_.val {
118 ConstKind::Value(const_val) => const_val,
119 ConstKind::Unevaluated(def, ref substs, promoted) if fx.tcx.is_static(def.did) => {
120 assert!(substs.is_empty());
121 assert!(promoted.is_none());
123 return codegen_static_ref(
126 fx.layout_of(fx.monomorphize(&constant.literal.ty)),
130 ConstKind::Unevaluated(def, ref substs, promoted) => {
133 .const_eval_resolve(ParamEnv::reveal_all(), def, substs, promoted, None)
135 Ok(const_val) => const_val,
137 if promoted.is_none() {
140 .span_err(constant.span, "erroneous constant encountered");
142 return crate::trap::trap_unreachable_ret_value(
144 fx.layout_of(const_.ty),
145 "erroneous constant encountered",
151 | ConstKind::Infer(_)
152 | ConstKind::Bound(_, _)
153 | ConstKind::Placeholder(_)
154 | ConstKind::Error(_) => unreachable!("{:?}", const_),
157 codegen_const_value(fx, const_val, const_.ty)
160 pub(crate) fn codegen_const_value<'tcx>(
161 fx: &mut FunctionCx<'_, 'tcx, impl Module>,
162 const_val: ConstValue<'tcx>,
165 let layout = fx.layout_of(ty);
166 assert!(!layout.is_unsized(), "sized const value");
169 return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
173 ConstValue::Scalar(x) => {
174 if fx.clif_type(layout.ty).is_none() {
175 let (size, align) = (layout.size, layout.align.pref);
176 let mut alloc = Allocation::from_bytes(
178 .take(size.bytes_usize())
179 .collect::<Vec<u8>>(),
182 let ptr = Pointer::new(AllocId(!0), Size::ZERO); // The alloc id is never used
183 alloc.write_scalar(fx, ptr, x.into(), size).unwrap();
184 let alloc = fx.tcx.intern_const_alloc(alloc);
185 return CValue::by_ref(pointer_for_allocation(fx, alloc), layout);
189 Scalar::Int(int) => CValue::const_val(fx, layout, int),
190 Scalar::Ptr(ptr) => {
191 let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id);
192 let base_addr = match alloc_kind {
193 Some(GlobalAlloc::Memory(alloc)) => {
194 fx.cx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
195 let data_id = data_id_for_alloc_id(
201 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
202 #[cfg(debug_assertions)]
203 fx.add_comment(local_data_id, format!("{:?}", ptr.alloc_id));
204 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
206 Some(GlobalAlloc::Function(instance)) => {
208 crate::abi::import_function(fx.tcx, &mut fx.cx.module, instance);
210 fx.cx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
211 fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
213 Some(GlobalAlloc::Static(def_id)) => {
214 assert!(fx.tcx.is_static(def_id));
216 data_id_for_static(fx.tcx, &mut fx.cx.module, def_id, false);
218 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
219 #[cfg(debug_assertions)]
220 fx.add_comment(local_data_id, format!("{:?}", def_id));
221 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
223 None => bug!("missing allocation {:?}", ptr.alloc_id),
225 let val = if ptr.offset.bytes() != 0 {
228 .iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap())
232 CValue::by_val(val, layout)
236 ConstValue::ByRef { alloc, offset } => CValue::by_ref(
237 pointer_for_allocation(fx, alloc)
238 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
241 ConstValue::Slice { data, start, end } => {
242 let ptr = pointer_for_allocation(fx, data)
243 .offset_i64(fx, i64::try_from(start).unwrap())
245 let len = fx.bcx.ins().iconst(
247 i64::try_from(end.checked_sub(start).unwrap()).unwrap(),
249 CValue::by_val_pair(ptr, len, layout)
254 fn pointer_for_allocation<'tcx>(
255 fx: &mut FunctionCx<'_, 'tcx, impl Module>,
256 alloc: &'tcx Allocation,
257 ) -> crate::pointer::Pointer {
258 let alloc_id = fx.tcx.create_memory_alloc(alloc);
259 fx.cx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
260 let data_id = data_id_for_alloc_id(&mut fx.cx.module, alloc_id, alloc.mutability);
262 let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
263 #[cfg(debug_assertions)]
264 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
265 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
266 crate::pointer::Pointer::new(global_ptr)
269 fn data_id_for_alloc_id(
270 module: &mut impl Module,
272 mutability: rustc_hir::Mutability,
276 &format!(".L__alloc_{:x}", alloc_id.0),
278 mutability == rustc_hir::Mutability::Mut,
284 fn data_id_for_static(
286 module: &mut impl Module,
290 let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
291 let linkage = if definition {
292 crate::linkage::get_static_linkage(tcx, def_id)
293 } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
294 || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
301 let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
302 let symbol_name = tcx.symbol_name(instance).name;
303 let ty = instance.ty(tcx, ParamEnv::reveal_all());
304 let is_mutable = if tcx.is_mutable_static(def_id) {
307 !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
310 .layout_of(ParamEnv::reveal_all().and(ty))
316 let attrs = tcx.codegen_fn_attrs(def_id);
323 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
327 if rlinkage.is_some() {
328 // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
329 // Declare an internal global `extern_with_linkage_foo` which
330 // is initialized with the address of `foo`. If `foo` is
331 // discarded during linking (for example, if `foo` has weak
332 // linkage and there are no definitions), then
333 // `extern_with_linkage_foo` will instead be initialized to
336 let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
337 let ref_data_id = module
338 .declare_data(&ref_name, Linkage::Local, false, false)
340 let mut data_ctx = DataContext::new();
341 data_ctx.set_align(align);
342 let data = module.declare_data_in_data(data_id, &mut data_ctx);
345 .take(pointer_ty(tcx).bytes() as usize)
348 data_ctx.write_data_addr(0, data, 0);
349 match module.define_data(ref_data_id, &data_ctx) {
350 // Every time the static is referenced there will be another definition of this global,
351 // so duplicate definitions are expected and allowed.
352 Err(ModuleError::DuplicateDefinition(_)) => {}
361 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut impl Module, cx: &mut ConstantCx) {
362 while let Some(todo_item) = cx.todo.pop() {
363 let (data_id, alloc, section_name) = match todo_item {
364 TodoItem::Alloc(alloc_id) => {
365 //println!("alloc_id {}", alloc_id);
366 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
367 GlobalAlloc::Memory(alloc) => alloc,
368 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
370 let data_id = data_id_for_alloc_id(module, alloc_id, alloc.mutability);
371 (data_id, alloc, None)
373 TodoItem::Static(def_id) => {
374 //println!("static {:?}", def_id);
376 let section_name = tcx
377 .codegen_fn_attrs(def_id)
379 .map(|s| s.as_str());
381 let alloc = tcx.eval_static_initializer(def_id).unwrap();
383 let data_id = data_id_for_static(tcx, module, def_id, true);
384 (data_id, alloc, section_name)
388 //("data_id {}", data_id);
389 if cx.done.contains(&data_id) {
393 let mut data_ctx = DataContext::new();
394 data_ctx.set_align(alloc.align.bytes());
396 if let Some(section_name) = section_name {
397 // FIXME set correct segment for Mach-O files
398 data_ctx.set_segment_section("", &*section_name);
402 .inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len())
404 data_ctx.define(bytes.into_boxed_slice());
406 for &(offset, (_tag, reloc)) in alloc.relocations().iter() {
408 let endianness = tcx.data_layout.endian;
409 let offset = offset.bytes() as usize;
410 let ptr_size = tcx.data_layout.pointer_size;
411 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
412 offset..offset + ptr_size.bytes() as usize,
414 read_target_uint(endianness, bytes).unwrap()
417 let reloc_target_alloc = tcx.get_global_alloc(reloc).unwrap();
418 let data_id = match reloc_target_alloc {
419 GlobalAlloc::Function(instance) => {
420 assert_eq!(addend, 0);
421 let func_id = crate::abi::import_function(tcx, module, instance);
422 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
423 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
426 GlobalAlloc::Memory(target_alloc) => {
427 cx.todo.push(TodoItem::Alloc(reloc));
428 data_id_for_alloc_id(module, reloc, target_alloc.mutability)
430 GlobalAlloc::Static(def_id) => {
432 .codegen_fn_attrs(def_id)
434 .contains(CodegenFnAttrFlags::THREAD_LOCAL)
436 tcx.sess.fatal(&format!(
437 "Allocation {:?} contains reference to TLS value {:?}",
442 // Don't push a `TodoItem::Static` here, as it will cause statics used by
443 // multiple crates to be duplicated between them. It isn't necessary anyway,
444 // as it will get pushed by `codegen_static` when necessary.
445 data_id_for_static(tcx, module, def_id, false)
449 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
450 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
453 // FIXME don't duplicate definitions in lazy jit mode
454 let _ = module.define_data(data_id, &data_ctx);
455 cx.done.insert(data_id);
458 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
461 pub(crate) fn mir_operand_get_const_val<'tcx>(
462 fx: &FunctionCx<'_, 'tcx, impl Module>,
463 operand: &Operand<'tcx>,
464 ) -> Option<&'tcx Const<'tcx>> {
466 Operand::Copy(_) | Operand::Move(_) => None,
467 Operand::Constant(const_) => Some(
468 fx.monomorphize(const_.literal)
469 .eval(fx.tcx, ParamEnv::reveal_all()),