1 //! Handling of `static`s, `const`s and promoted allocations
3 use rustc_span::DUMMY_SP;
5 use rustc_data_structures::fx::{FxHashMap, 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::*, CodegenCx};
18 pub(crate) struct ConstantCx {
20 done: FxHashSet<DataId>,
21 anon_allocs: FxHashMap<AllocId, DataId>,
24 #[derive(Copy, Clone, Debug)]
31 pub(crate) fn new() -> Self {
32 ConstantCx { todo: vec![], done: FxHashSet::default(), anon_allocs: FxHashMap::default() }
35 pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut dyn Module) {
36 //println!("todo {:?}", self.todo);
37 define_all_allocs(tcx, module, &mut self);
38 //println!("done {:?}", self.done);
43 pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, '_>) -> bool {
44 let mut all_constants_ok = true;
45 for constant in &fx.mir.required_consts {
46 let const_ = match fx.monomorphize(constant.literal) {
47 ConstantKind::Ty(ct) => ct,
48 ConstantKind::Val(..) => continue,
51 ConstKind::Value(_) => {}
52 ConstKind::Unevaluated(unevaluated) => {
54 fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None)
56 all_constants_ok = false;
58 ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
59 fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
61 ErrorHandled::TooGeneric => {
64 "codgen encountered polymorphic constant: {:?}",
73 | ConstKind::Bound(_, _)
74 | ConstKind::Placeholder(_)
75 | ConstKind::Error(_) => unreachable!("{:?}", const_),
81 pub(crate) fn codegen_static(cx: &mut CodegenCx<'_, '_>, def_id: DefId) {
82 let mut constants_cx = ConstantCx::new();
83 constants_cx.todo.push(TodoItem::Static(def_id));
84 constants_cx.finalize(cx.tcx, &mut *cx.module);
87 pub(crate) fn codegen_tls_ref<'tcx>(
88 fx: &mut FunctionCx<'_, '_, 'tcx>,
90 layout: TyAndLayout<'tcx>,
92 let data_id = data_id_for_static(fx.tcx, fx.cx.module, def_id, false);
93 let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
94 if fx.clif_comments.enabled() {
95 fx.add_comment(local_data_id, format!("tls {:?}", def_id));
97 let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
98 CValue::by_val(tls_ptr, layout)
101 fn codegen_static_ref<'tcx>(
102 fx: &mut FunctionCx<'_, '_, 'tcx>,
104 layout: TyAndLayout<'tcx>,
106 let data_id = data_id_for_static(fx.tcx, fx.cx.module, def_id, false);
107 let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
108 if fx.clif_comments.enabled() {
109 fx.add_comment(local_data_id, format!("{:?}", def_id));
111 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
112 assert!(!layout.is_unsized(), "unsized statics aren't supported");
115 fx.bcx.func.global_values[local_data_id],
116 GlobalValueData::Symbol { tls: false, .. }
118 "tls static referenced without Rvalue::ThreadLocalRef"
120 CPlace::for_ptr(crate::pointer::Pointer::new(global_ptr), layout)
123 pub(crate) fn codegen_constant<'tcx>(
124 fx: &mut FunctionCx<'_, '_, 'tcx>,
125 constant: &Constant<'tcx>,
127 let const_ = match fx.monomorphize(constant.literal) {
128 ConstantKind::Ty(ct) => ct,
129 ConstantKind::Val(val, ty) => return codegen_const_value(fx, val, ty),
131 let const_val = match const_.val {
132 ConstKind::Value(const_val) => const_val,
133 ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted })
134 if fx.tcx.is_static(def.did) =>
136 assert!(substs.is_empty());
137 assert!(promoted.is_none());
139 return codegen_static_ref(fx, def.did, fx.layout_of(const_.ty)).to_cvalue(fx);
141 ConstKind::Unevaluated(unevaluated) => {
142 match fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None) {
143 Ok(const_val) => const_val,
145 span_bug!(constant.span, "erroneous constant not captured by required_consts");
150 | ConstKind::Infer(_)
151 | ConstKind::Bound(_, _)
152 | ConstKind::Placeholder(_)
153 | ConstKind::Error(_) => unreachable!("{:?}", const_),
156 codegen_const_value(fx, const_val, const_.ty)
159 pub(crate) fn codegen_const_value<'tcx>(
160 fx: &mut FunctionCx<'_, '_, 'tcx>,
161 const_val: ConstValue<'tcx>,
164 let layout = fx.layout_of(ty);
165 assert!(!layout.is_unsized(), "sized const value");
168 return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
172 ConstValue::Scalar(x) => {
173 if fx.clif_type(layout.ty).is_none() {
174 let (size, align) = (layout.size, layout.align.pref);
175 let mut alloc = Allocation::from_bytes(
176 std::iter::repeat(0).take(size.bytes_usize()).collect::<Vec<u8>>(),
179 let ptr = Pointer::new(AllocId(!0), Size::ZERO); // The alloc id is never used
180 alloc.write_scalar(fx, ptr, x.into(), size).unwrap();
181 let alloc = fx.tcx.intern_const_alloc(alloc);
182 return CValue::by_ref(pointer_for_allocation(fx, alloc), layout);
186 Scalar::Int(int) => CValue::const_val(fx, layout, int),
187 Scalar::Ptr(ptr) => {
188 let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id);
189 let base_addr = match alloc_kind {
190 Some(GlobalAlloc::Memory(alloc)) => {
191 fx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
192 let data_id = data_id_for_alloc_id(
193 &mut fx.constants_cx,
199 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
200 if fx.clif_comments.enabled() {
201 fx.add_comment(local_data_id, format!("{:?}", ptr.alloc_id));
203 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
205 Some(GlobalAlloc::Function(instance)) => {
207 crate::abi::import_function(fx.tcx, fx.cx.module, instance);
209 fx.cx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
210 fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
212 Some(GlobalAlloc::Static(def_id)) => {
213 assert!(fx.tcx.is_static(def_id));
214 let data_id = data_id_for_static(fx.tcx, fx.cx.module, def_id, false);
216 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
217 if fx.clif_comments.enabled() {
218 fx.add_comment(local_data_id, format!("{:?}", def_id));
220 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
222 None => bug!("missing allocation {:?}", ptr.alloc_id),
224 let val = if ptr.offset.bytes() != 0 {
225 fx.bcx.ins().iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap())
229 CValue::by_val(val, layout)
233 ConstValue::ByRef { alloc, offset } => CValue::by_ref(
234 pointer_for_allocation(fx, alloc)
235 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
238 ConstValue::Slice { data, start, end } => {
239 let ptr = pointer_for_allocation(fx, data)
240 .offset_i64(fx, i64::try_from(start).unwrap())
245 .iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
246 CValue::by_val_pair(ptr, len, layout)
251 fn pointer_for_allocation<'tcx>(
252 fx: &mut FunctionCx<'_, '_, 'tcx>,
253 alloc: &'tcx Allocation,
254 ) -> crate::pointer::Pointer {
255 let alloc_id = fx.tcx.create_memory_alloc(alloc);
256 fx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
258 data_id_for_alloc_id(&mut fx.constants_cx, &mut *fx.cx.module, alloc_id, alloc.mutability);
260 let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
261 if fx.clif_comments.enabled() {
262 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
264 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
265 crate::pointer::Pointer::new(global_ptr)
268 fn data_id_for_alloc_id(
270 module: &mut dyn Module,
272 mutability: rustc_hir::Mutability,
274 *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
275 module.declare_anonymous_data(mutability == rustc_hir::Mutability::Mut, false).unwrap()
279 fn data_id_for_static(
281 module: &mut dyn Module,
285 let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
286 let linkage = if definition {
287 crate::linkage::get_static_linkage(tcx, def_id)
288 } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
289 || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
296 let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
297 let symbol_name = tcx.symbol_name(instance).name;
298 let ty = instance.ty(tcx, ParamEnv::reveal_all());
299 let is_mutable = if tcx.is_mutable_static(def_id) {
302 !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
304 let align = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().align.pref.bytes();
306 let attrs = tcx.codegen_fn_attrs(def_id);
313 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
317 if rlinkage.is_some() {
318 // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
319 // Declare an internal global `extern_with_linkage_foo` which
320 // is initialized with the address of `foo`. If `foo` is
321 // discarded during linking (for example, if `foo` has weak
322 // linkage and there are no definitions), then
323 // `extern_with_linkage_foo` will instead be initialized to
326 let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
327 let ref_data_id = module.declare_data(&ref_name, Linkage::Local, false, false).unwrap();
328 let mut data_ctx = DataContext::new();
329 data_ctx.set_align(align);
330 let data = module.declare_data_in_data(data_id, &mut data_ctx);
331 data_ctx.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect());
332 data_ctx.write_data_addr(0, data, 0);
333 match module.define_data(ref_data_id, &data_ctx) {
334 // Every time the static is referenced there will be another definition of this global,
335 // so duplicate definitions are expected and allowed.
336 Err(ModuleError::DuplicateDefinition(_)) => {}
345 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) {
346 while let Some(todo_item) = cx.todo.pop() {
347 let (data_id, alloc, section_name) = match todo_item {
348 TodoItem::Alloc(alloc_id) => {
349 //println!("alloc_id {}", alloc_id);
350 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
351 GlobalAlloc::Memory(alloc) => alloc,
352 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
354 let data_id = data_id_for_alloc_id(cx, module, alloc_id, alloc.mutability);
355 (data_id, alloc, None)
357 TodoItem::Static(def_id) => {
358 //println!("static {:?}", def_id);
360 let section_name = tcx.codegen_fn_attrs(def_id).link_section.map(|s| s.as_str());
362 let alloc = tcx.eval_static_initializer(def_id).unwrap();
364 let data_id = data_id_for_static(tcx, module, def_id, true);
365 (data_id, alloc, section_name)
369 //("data_id {}", data_id);
370 if cx.done.contains(&data_id) {
374 let mut data_ctx = DataContext::new();
375 data_ctx.set_align(alloc.align.bytes());
377 if let Some(section_name) = section_name {
378 // FIXME set correct segment for Mach-O files
379 data_ctx.set_segment_section("", &*section_name);
382 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
383 data_ctx.define(bytes.into_boxed_slice());
385 for &(offset, (_tag, reloc)) in alloc.relocations().iter() {
387 let endianness = tcx.data_layout.endian;
388 let offset = offset.bytes() as usize;
389 let ptr_size = tcx.data_layout.pointer_size;
390 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
391 offset..offset + ptr_size.bytes() as usize,
393 read_target_uint(endianness, bytes).unwrap()
396 let reloc_target_alloc = tcx.get_global_alloc(reloc).unwrap();
397 let data_id = match reloc_target_alloc {
398 GlobalAlloc::Function(instance) => {
399 assert_eq!(addend, 0);
400 let func_id = crate::abi::import_function(tcx, module, instance);
401 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
402 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
405 GlobalAlloc::Memory(target_alloc) => {
406 cx.todo.push(TodoItem::Alloc(reloc));
407 data_id_for_alloc_id(cx, module, reloc, target_alloc.mutability)
409 GlobalAlloc::Static(def_id) => {
410 if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
412 tcx.sess.fatal(&format!(
413 "Allocation {:?} contains reference to TLS value {:?}",
418 // Don't push a `TodoItem::Static` here, as it will cause statics used by
419 // multiple crates to be duplicated between them. It isn't necessary anyway,
420 // as it will get pushed by `codegen_static` when necessary.
421 data_id_for_static(tcx, module, def_id, false)
425 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
426 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
429 module.define_data(data_id, &data_ctx).unwrap();
430 cx.done.insert(data_id);
433 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
436 pub(crate) fn mir_operand_get_const_val<'tcx>(
437 fx: &FunctionCx<'_, '_, 'tcx>,
438 operand: &Operand<'tcx>,
439 ) -> Option<ConstValue<'tcx>> {
441 Operand::Copy(_) | Operand::Move(_) => None,
442 Operand::Constant(const_) => match const_.literal {
443 ConstantKind::Ty(const_) => {
444 fx.monomorphize(const_).eval(fx.tcx, ParamEnv::reveal_all()).val.try_to_value()
446 ConstantKind::Val(val, _) => Some(val),