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 dyn 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<'_, '_, '_>) -> bool {
40 let mut all_constants_ok = true;
41 for constant in &fx.mir.required_consts {
42 let const_ = fx.monomorphize(constant.literal);
44 ConstKind::Value(_) => {}
45 ConstKind::Unevaluated(def, ref substs, promoted) => {
47 fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), def, substs, promoted, None)
49 all_constants_ok = false;
51 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
52 fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
54 ErrorHandled::TooGeneric => {
57 "codgen encountered polymorphic constant: {:?}",
66 | ConstKind::Bound(_, _)
67 | ConstKind::Placeholder(_)
68 | 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>,
81 layout: TyAndLayout<'tcx>,
83 let data_id = data_id_for_static(fx.tcx, 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>,
94 layout: TyAndLayout<'tcx>,
96 let data_id = data_id_for_static(fx.tcx, 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>,
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) => {
131 match fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), def, substs, promoted, None) {
132 Ok(const_val) => const_val,
134 span_bug!(constant.span, "erroneous constant not captured by required_consts");
139 | ConstKind::Infer(_)
140 | ConstKind::Bound(_, _)
141 | ConstKind::Placeholder(_)
142 | ConstKind::Error(_) => unreachable!("{:?}", const_),
145 codegen_const_value(fx, const_val, const_.ty)
148 pub(crate) fn codegen_const_value<'tcx>(
149 fx: &mut FunctionCx<'_, '_, 'tcx>,
150 const_val: ConstValue<'tcx>,
153 let layout = fx.layout_of(ty);
154 assert!(!layout.is_unsized(), "sized const value");
157 return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
161 ConstValue::Scalar(x) => {
162 if fx.clif_type(layout.ty).is_none() {
163 let (size, align) = (layout.size, layout.align.pref);
164 let mut alloc = Allocation::from_bytes(
165 std::iter::repeat(0).take(size.bytes_usize()).collect::<Vec<u8>>(),
168 let ptr = Pointer::new(AllocId(!0), Size::ZERO); // The alloc id is never used
169 alloc.write_scalar(fx, ptr, x.into(), size).unwrap();
170 let alloc = fx.tcx.intern_const_alloc(alloc);
171 return CValue::by_ref(pointer_for_allocation(fx, alloc), layout);
175 Scalar::Int(int) => CValue::const_val(fx, layout, int),
176 Scalar::Ptr(ptr) => {
177 let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id);
178 let base_addr = match alloc_kind {
179 Some(GlobalAlloc::Memory(alloc)) => {
180 fx.cx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
182 data_id_for_alloc_id(fx.cx.module, ptr.alloc_id, alloc.mutability);
184 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
185 #[cfg(debug_assertions)]
186 fx.add_comment(local_data_id, format!("{:?}", ptr.alloc_id));
187 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
189 Some(GlobalAlloc::Function(instance)) => {
191 crate::abi::import_function(fx.tcx, fx.cx.module, instance);
193 fx.cx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
194 fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
196 Some(GlobalAlloc::Static(def_id)) => {
197 assert!(fx.tcx.is_static(def_id));
198 let data_id = data_id_for_static(fx.tcx, fx.cx.module, def_id, false);
200 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
201 #[cfg(debug_assertions)]
202 fx.add_comment(local_data_id, format!("{:?}", def_id));
203 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
205 None => bug!("missing allocation {:?}", ptr.alloc_id),
207 let val = if ptr.offset.bytes() != 0 {
208 fx.bcx.ins().iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap())
212 CValue::by_val(val, layout)
216 ConstValue::ByRef { alloc, offset } => CValue::by_ref(
217 pointer_for_allocation(fx, alloc)
218 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
221 ConstValue::Slice { data, start, end } => {
222 let ptr = pointer_for_allocation(fx, data)
223 .offset_i64(fx, i64::try_from(start).unwrap())
228 .iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
229 CValue::by_val_pair(ptr, len, layout)
234 fn pointer_for_allocation<'tcx>(
235 fx: &mut FunctionCx<'_, '_, 'tcx>,
236 alloc: &'tcx Allocation,
237 ) -> crate::pointer::Pointer {
238 let alloc_id = fx.tcx.create_memory_alloc(alloc);
239 fx.cx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
240 let data_id = data_id_for_alloc_id(fx.cx.module, alloc_id, alloc.mutability);
242 let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
243 #[cfg(debug_assertions)]
244 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
245 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
246 crate::pointer::Pointer::new(global_ptr)
249 fn data_id_for_alloc_id(
250 module: &mut dyn Module,
252 mutability: rustc_hir::Mutability,
256 &format!(".L__alloc_{:x}", alloc_id.0),
258 mutability == rustc_hir::Mutability::Mut,
264 fn data_id_for_static(
266 module: &mut dyn Module,
270 let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
271 let linkage = if definition {
272 crate::linkage::get_static_linkage(tcx, def_id)
273 } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
274 || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
281 let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
282 let symbol_name = tcx.symbol_name(instance).name;
283 let ty = instance.ty(tcx, ParamEnv::reveal_all());
284 let is_mutable = if tcx.is_mutable_static(def_id) {
287 !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
289 let align = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().align.pref.bytes();
291 let attrs = tcx.codegen_fn_attrs(def_id);
298 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
302 if rlinkage.is_some() {
303 // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
304 // Declare an internal global `extern_with_linkage_foo` which
305 // is initialized with the address of `foo`. If `foo` is
306 // discarded during linking (for example, if `foo` has weak
307 // linkage and there are no definitions), then
308 // `extern_with_linkage_foo` will instead be initialized to
311 let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
312 let ref_data_id = module.declare_data(&ref_name, Linkage::Local, false, false).unwrap();
313 let mut data_ctx = DataContext::new();
314 data_ctx.set_align(align);
315 let data = module.declare_data_in_data(data_id, &mut data_ctx);
316 data_ctx.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect());
317 data_ctx.write_data_addr(0, data, 0);
318 match module.define_data(ref_data_id, &data_ctx) {
319 // Every time the static is referenced there will be another definition of this global,
320 // so duplicate definitions are expected and allowed.
321 Err(ModuleError::DuplicateDefinition(_)) => {}
330 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) {
331 while let Some(todo_item) = cx.todo.pop() {
332 let (data_id, alloc, section_name) = match todo_item {
333 TodoItem::Alloc(alloc_id) => {
334 //println!("alloc_id {}", alloc_id);
335 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
336 GlobalAlloc::Memory(alloc) => alloc,
337 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
339 let data_id = data_id_for_alloc_id(module, alloc_id, alloc.mutability);
340 (data_id, alloc, None)
342 TodoItem::Static(def_id) => {
343 //println!("static {:?}", def_id);
345 let section_name = tcx.codegen_fn_attrs(def_id).link_section.map(|s| s.as_str());
347 let alloc = tcx.eval_static_initializer(def_id).unwrap();
349 let data_id = data_id_for_static(tcx, module, def_id, true);
350 (data_id, alloc, section_name)
354 //("data_id {}", data_id);
355 if cx.done.contains(&data_id) {
359 let mut data_ctx = DataContext::new();
360 data_ctx.set_align(alloc.align.bytes());
362 if let Some(section_name) = section_name {
363 // FIXME set correct segment for Mach-O files
364 data_ctx.set_segment_section("", &*section_name);
367 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
368 data_ctx.define(bytes.into_boxed_slice());
370 for &(offset, (_tag, reloc)) in alloc.relocations().iter() {
372 let endianness = tcx.data_layout.endian;
373 let offset = offset.bytes() as usize;
374 let ptr_size = tcx.data_layout.pointer_size;
375 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
376 offset..offset + ptr_size.bytes() as usize,
378 read_target_uint(endianness, bytes).unwrap()
381 let reloc_target_alloc = tcx.get_global_alloc(reloc).unwrap();
382 let data_id = match reloc_target_alloc {
383 GlobalAlloc::Function(instance) => {
384 assert_eq!(addend, 0);
385 let func_id = crate::abi::import_function(tcx, module, instance);
386 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
387 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
390 GlobalAlloc::Memory(target_alloc) => {
391 cx.todo.push(TodoItem::Alloc(reloc));
392 data_id_for_alloc_id(module, reloc, target_alloc.mutability)
394 GlobalAlloc::Static(def_id) => {
395 if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
397 tcx.sess.fatal(&format!(
398 "Allocation {:?} contains reference to TLS value {:?}",
403 // Don't push a `TodoItem::Static` here, as it will cause statics used by
404 // multiple crates to be duplicated between them. It isn't necessary anyway,
405 // as it will get pushed by `codegen_static` when necessary.
406 data_id_for_static(tcx, module, def_id, false)
410 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
411 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
414 // FIXME don't duplicate definitions in lazy jit mode
415 let _ = module.define_data(data_id, &data_ctx);
416 cx.done.insert(data_id);
419 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
422 pub(crate) fn mir_operand_get_const_val<'tcx>(
423 fx: &FunctionCx<'_, '_, 'tcx>,
424 operand: &Operand<'tcx>,
425 ) -> Option<&'tcx Const<'tcx>> {
427 Operand::Copy(_) | Operand::Move(_) => None,
428 Operand::Constant(const_) => {
429 Some(fx.monomorphize(const_.literal).eval(fx.tcx, ParamEnv::reveal_all()))