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::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_ = match fx.monomorphize(constant.literal) {
43 ConstantKind::Ty(ct) => ct,
44 ConstantKind::Val(..) => continue,
47 ConstKind::Value(_) => {}
48 ConstKind::Unevaluated(unevaluated) => {
50 fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None)
52 all_constants_ok = false;
54 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
55 fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
57 ErrorHandled::TooGeneric => {
60 "codgen encountered polymorphic constant: {:?}",
69 | ConstKind::Bound(_, _)
70 | ConstKind::Placeholder(_)
71 | ConstKind::Error(_) => unreachable!("{:?}", const_),
77 pub(crate) fn codegen_static(constants_cx: &mut ConstantCx, def_id: DefId) {
78 constants_cx.todo.push(TodoItem::Static(def_id));
81 pub(crate) fn codegen_tls_ref<'tcx>(
82 fx: &mut FunctionCx<'_, '_, 'tcx>,
84 layout: TyAndLayout<'tcx>,
86 let data_id = data_id_for_static(fx.tcx, fx.cx.module, def_id, false);
87 let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
88 if fx.clif_comments.enabled() {
89 fx.add_comment(local_data_id, format!("tls {:?}", def_id));
91 let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
92 CValue::by_val(tls_ptr, layout)
95 fn codegen_static_ref<'tcx>(
96 fx: &mut FunctionCx<'_, '_, 'tcx>,
98 layout: TyAndLayout<'tcx>,
100 let data_id = data_id_for_static(fx.tcx, fx.cx.module, def_id, false);
101 let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
102 if fx.clif_comments.enabled() {
103 fx.add_comment(local_data_id, format!("{:?}", def_id));
105 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
106 assert!(!layout.is_unsized(), "unsized statics aren't supported");
109 fx.bcx.func.global_values[local_data_id],
110 GlobalValueData::Symbol { tls: false, .. }
112 "tls static referenced without Rvalue::ThreadLocalRef"
114 CPlace::for_ptr(crate::pointer::Pointer::new(global_ptr), layout)
117 pub(crate) fn codegen_constant<'tcx>(
118 fx: &mut FunctionCx<'_, '_, 'tcx>,
119 constant: &Constant<'tcx>,
121 let const_ = match fx.monomorphize(constant.literal) {
122 ConstantKind::Ty(ct) => ct,
123 ConstantKind::Val(val, ty) => return codegen_const_value(fx, val, ty),
125 let const_val = match const_.val {
126 ConstKind::Value(const_val) => const_val,
127 ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted }) if fx.tcx.is_static(def.did) => {
128 assert!(substs.is_empty());
129 assert!(promoted.is_none());
131 return codegen_static_ref(fx, def.did, fx.layout_of(const_.ty)).to_cvalue(fx);
133 ConstKind::Unevaluated(unevaluated) => {
134 match fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None) {
135 Ok(const_val) => const_val,
137 span_bug!(constant.span, "erroneous constant not captured by required_consts");
142 | ConstKind::Infer(_)
143 | ConstKind::Bound(_, _)
144 | ConstKind::Placeholder(_)
145 | ConstKind::Error(_) => unreachable!("{:?}", const_),
148 codegen_const_value(fx, const_val, const_.ty)
151 pub(crate) fn codegen_const_value<'tcx>(
152 fx: &mut FunctionCx<'_, '_, 'tcx>,
153 const_val: ConstValue<'tcx>,
156 let layout = fx.layout_of(ty);
157 assert!(!layout.is_unsized(), "sized const value");
160 return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
164 ConstValue::Scalar(x) => {
165 if fx.clif_type(layout.ty).is_none() {
166 let (size, align) = (layout.size, layout.align.pref);
167 let mut alloc = Allocation::from_bytes(
168 std::iter::repeat(0).take(size.bytes_usize()).collect::<Vec<u8>>(),
171 let ptr = Pointer::new(AllocId(!0), Size::ZERO); // The alloc id is never used
172 alloc.write_scalar(fx, ptr, x.into(), size).unwrap();
173 let alloc = fx.tcx.intern_const_alloc(alloc);
174 return CValue::by_ref(pointer_for_allocation(fx, alloc), layout);
178 Scalar::Int(int) => CValue::const_val(fx, layout, int),
179 Scalar::Ptr(ptr) => {
180 let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id);
181 let base_addr = match alloc_kind {
182 Some(GlobalAlloc::Memory(alloc)) => {
183 fx.cx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
185 data_id_for_alloc_id(fx.cx.module, ptr.alloc_id, alloc.mutability);
187 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
188 if fx.clif_comments.enabled() {
189 fx.add_comment(local_data_id, format!("{:?}", ptr.alloc_id));
191 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
193 Some(GlobalAlloc::Function(instance)) => {
195 crate::abi::import_function(fx.tcx, fx.cx.module, instance);
197 fx.cx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
198 fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
200 Some(GlobalAlloc::Static(def_id)) => {
201 assert!(fx.tcx.is_static(def_id));
202 let data_id = data_id_for_static(fx.tcx, fx.cx.module, def_id, false);
204 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
205 if fx.clif_comments.enabled() {
206 fx.add_comment(local_data_id, format!("{:?}", def_id));
208 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
210 None => bug!("missing allocation {:?}", ptr.alloc_id),
212 let val = if ptr.offset.bytes() != 0 {
213 fx.bcx.ins().iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap())
217 CValue::by_val(val, layout)
221 ConstValue::ByRef { alloc, offset } => CValue::by_ref(
222 pointer_for_allocation(fx, alloc)
223 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
226 ConstValue::Slice { data, start, end } => {
227 let ptr = pointer_for_allocation(fx, data)
228 .offset_i64(fx, i64::try_from(start).unwrap())
233 .iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
234 CValue::by_val_pair(ptr, len, layout)
239 fn pointer_for_allocation<'tcx>(
240 fx: &mut FunctionCx<'_, '_, 'tcx>,
241 alloc: &'tcx Allocation,
242 ) -> crate::pointer::Pointer {
243 let alloc_id = fx.tcx.create_memory_alloc(alloc);
244 fx.cx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
245 let data_id = data_id_for_alloc_id(fx.cx.module, alloc_id, alloc.mutability);
247 let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
248 if fx.clif_comments.enabled() {
249 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
251 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
252 crate::pointer::Pointer::new(global_ptr)
255 fn data_id_for_alloc_id(
256 module: &mut dyn Module,
258 mutability: rustc_hir::Mutability,
262 &format!(".L__alloc_{:x}", alloc_id.0),
264 mutability == rustc_hir::Mutability::Mut,
270 fn data_id_for_static(
272 module: &mut dyn Module,
276 let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
277 let linkage = if definition {
278 crate::linkage::get_static_linkage(tcx, def_id)
279 } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
280 || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
287 let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
288 let symbol_name = tcx.symbol_name(instance).name;
289 let ty = instance.ty(tcx, ParamEnv::reveal_all());
290 let is_mutable = if tcx.is_mutable_static(def_id) {
293 !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
295 let align = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().align.pref.bytes();
297 let attrs = tcx.codegen_fn_attrs(def_id);
304 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
308 if rlinkage.is_some() {
309 // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
310 // Declare an internal global `extern_with_linkage_foo` which
311 // is initialized with the address of `foo`. If `foo` is
312 // discarded during linking (for example, if `foo` has weak
313 // linkage and there are no definitions), then
314 // `extern_with_linkage_foo` will instead be initialized to
317 let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
318 let ref_data_id = module.declare_data(&ref_name, Linkage::Local, false, false).unwrap();
319 let mut data_ctx = DataContext::new();
320 data_ctx.set_align(align);
321 let data = module.declare_data_in_data(data_id, &mut data_ctx);
322 data_ctx.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect());
323 data_ctx.write_data_addr(0, data, 0);
324 match module.define_data(ref_data_id, &data_ctx) {
325 // Every time the static is referenced there will be another definition of this global,
326 // so duplicate definitions are expected and allowed.
327 Err(ModuleError::DuplicateDefinition(_)) => {}
336 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) {
337 while let Some(todo_item) = cx.todo.pop() {
338 let (data_id, alloc, section_name) = match todo_item {
339 TodoItem::Alloc(alloc_id) => {
340 //println!("alloc_id {}", alloc_id);
341 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
342 GlobalAlloc::Memory(alloc) => alloc,
343 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
345 let data_id = data_id_for_alloc_id(module, alloc_id, alloc.mutability);
346 (data_id, alloc, None)
348 TodoItem::Static(def_id) => {
349 //println!("static {:?}", def_id);
351 let section_name = tcx.codegen_fn_attrs(def_id).link_section.map(|s| s.as_str());
353 let alloc = tcx.eval_static_initializer(def_id).unwrap();
355 let data_id = data_id_for_static(tcx, module, def_id, true);
356 (data_id, alloc, section_name)
360 //("data_id {}", data_id);
361 if cx.done.contains(&data_id) {
365 let mut data_ctx = DataContext::new();
366 data_ctx.set_align(alloc.align.bytes());
368 if let Some(section_name) = section_name {
369 // FIXME set correct segment for Mach-O files
370 data_ctx.set_segment_section("", &*section_name);
373 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
374 data_ctx.define(bytes.into_boxed_slice());
376 for &(offset, (_tag, reloc)) in alloc.relocations().iter() {
378 let endianness = tcx.data_layout.endian;
379 let offset = offset.bytes() as usize;
380 let ptr_size = tcx.data_layout.pointer_size;
381 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
382 offset..offset + ptr_size.bytes() as usize,
384 read_target_uint(endianness, bytes).unwrap()
387 let reloc_target_alloc = tcx.get_global_alloc(reloc).unwrap();
388 let data_id = match reloc_target_alloc {
389 GlobalAlloc::Function(instance) => {
390 assert_eq!(addend, 0);
391 let func_id = crate::abi::import_function(tcx, module, instance);
392 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
393 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
396 GlobalAlloc::Memory(target_alloc) => {
397 cx.todo.push(TodoItem::Alloc(reloc));
398 data_id_for_alloc_id(module, reloc, target_alloc.mutability)
400 GlobalAlloc::Static(def_id) => {
401 if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
403 tcx.sess.fatal(&format!(
404 "Allocation {:?} contains reference to TLS value {:?}",
409 // Don't push a `TodoItem::Static` here, as it will cause statics used by
410 // multiple crates to be duplicated between them. It isn't necessary anyway,
411 // as it will get pushed by `codegen_static` when necessary.
412 data_id_for_static(tcx, module, def_id, false)
416 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
417 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
420 // FIXME don't duplicate definitions in lazy jit mode
421 let _ = module.define_data(data_id, &data_ctx);
422 cx.done.insert(data_id);
425 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
428 pub(crate) fn mir_operand_get_const_val<'tcx>(
429 fx: &FunctionCx<'_, '_, 'tcx>,
430 operand: &Operand<'tcx>,
431 ) -> Option<ConstValue<'tcx>> {
433 Operand::Copy(_) | Operand::Move(_) => None,
434 Operand::Constant(const_) => match const_.literal {
435 ConstantKind::Ty(const_) => {
436 fx.monomorphize(const_).eval(fx.tcx, ParamEnv::reveal_all()).val.try_to_value()
438 ConstantKind::Val(val, _) => Some(val),