1 //! Handling of `static`s, `const`s and promoted allocations
3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
5 use rustc_middle::mir::interpret::{
6 read_target_uint, AllocId, ConstAllocation, ConstValue, ErrorHandled, GlobalAlloc, Scalar,
9 use cranelift_module::*;
11 use crate::prelude::*;
13 pub(crate) struct ConstantCx {
15 done: FxHashSet<DataId>,
16 anon_allocs: FxHashMap<AllocId, DataId>,
19 #[derive(Copy, Clone, Debug)]
26 pub(crate) fn new() -> Self {
27 ConstantCx { todo: vec![], done: FxHashSet::default(), anon_allocs: FxHashMap::default() }
30 pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut dyn Module) {
31 //println!("todo {:?}", self.todo);
32 define_all_allocs(tcx, module, &mut self);
33 //println!("done {:?}", self.done);
38 pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, '_>) -> bool {
39 let mut all_constants_ok = true;
40 for constant in &fx.mir.required_consts {
41 if eval_mir_constant(fx, constant).is_none() {
42 all_constants_ok = false;
48 pub(crate) fn codegen_static(tcx: TyCtxt<'_>, module: &mut dyn Module, def_id: DefId) {
49 let mut constants_cx = ConstantCx::new();
50 constants_cx.todo.push(TodoItem::Static(def_id));
51 constants_cx.finalize(tcx, module);
54 pub(crate) fn codegen_tls_ref<'tcx>(
55 fx: &mut FunctionCx<'_, '_, 'tcx>,
57 layout: TyAndLayout<'tcx>,
59 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
60 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
61 if fx.clif_comments.enabled() {
62 fx.add_comment(local_data_id, format!("tls {:?}", def_id));
64 let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
65 CValue::by_val(tls_ptr, layout)
68 pub(crate) fn eval_mir_constant<'tcx>(
69 fx: &FunctionCx<'_, '_, 'tcx>,
70 constant: &Constant<'tcx>,
71 ) -> Option<(ConstValue<'tcx>, Ty<'tcx>)> {
72 let constant_kind = fx.monomorphize(constant.literal);
73 let uv = match constant_kind {
74 ConstantKind::Ty(const_) => match const_.kind() {
75 ty::ConstKind::Unevaluated(uv) => uv.expand(),
76 ty::ConstKind::Value(val) => {
77 return Some((fx.tcx.valtree_to_const_val((const_.ty(), val)), const_.ty()));
81 "encountered bad ConstKind after monomorphizing: {:?}",
85 ConstantKind::Unevaluated(mir::UnevaluatedConst { def, .. }, _)
86 if fx.tcx.is_static(def.did) =>
88 span_bug!(constant.span, "MIR constant refers to static");
90 ConstantKind::Unevaluated(uv, _) => uv,
91 ConstantKind::Val(val, _) => return Some((val, constant_kind.ty())),
96 .const_eval_resolve(ty::ParamEnv::reveal_all(), uv, None)
97 .map_err(|err| match err {
98 ErrorHandled::Reported(_) => {
99 fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
101 ErrorHandled::TooGeneric => {
102 span_bug!(constant.span, "codegen encountered polymorphic constant: {:?}", err);
106 val.map(|val| (val, constant_kind.ty()))
109 pub(crate) fn codegen_constant_operand<'tcx>(
110 fx: &mut FunctionCx<'_, '_, 'tcx>,
111 constant: &Constant<'tcx>,
113 let (const_val, ty) = eval_mir_constant(fx, constant).unwrap_or_else(|| {
114 span_bug!(constant.span, "erroneous constant not captured by required_consts")
117 codegen_const_value(fx, const_val, ty)
120 pub(crate) fn codegen_const_value<'tcx>(
121 fx: &mut FunctionCx<'_, '_, 'tcx>,
122 const_val: ConstValue<'tcx>,
125 let layout = fx.layout_of(ty);
126 assert!(layout.is_sized(), "unsized const value");
129 return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
133 ConstValue::ZeroSized => unreachable!(), // we already handles ZST above
134 ConstValue::Scalar(x) => match x {
135 Scalar::Int(int) => {
136 if fx.clif_type(layout.ty).is_some() {
137 return CValue::const_val(fx, layout, int);
139 let raw_val = int.to_bits(int.size()).unwrap();
140 let val = match int.size().bytes() {
141 1 => fx.bcx.ins().iconst(types::I8, raw_val as i64),
142 2 => fx.bcx.ins().iconst(types::I16, raw_val as i64),
143 4 => fx.bcx.ins().iconst(types::I32, raw_val as i64),
144 8 => fx.bcx.ins().iconst(types::I64, raw_val as i64),
146 let lsb = fx.bcx.ins().iconst(types::I64, raw_val as u64 as i64);
148 fx.bcx.ins().iconst(types::I64, (raw_val >> 64) as u64 as i64);
149 fx.bcx.ins().iconcat(lsb, msb)
154 let place = CPlace::new_stack_slot(fx, layout);
155 place.to_ptr().store(fx, val, MemFlags::trusted());
159 Scalar::Ptr(ptr, _size) => {
160 let (alloc_id, offset) = ptr.into_parts(); // we know the `offset` is relative
161 let base_addr = match fx.tcx.global_alloc(alloc_id) {
162 GlobalAlloc::Memory(alloc) => {
163 let data_id = data_id_for_alloc_id(
164 &mut fx.constants_cx,
167 alloc.inner().mutability,
170 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
171 if fx.clif_comments.enabled() {
172 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
174 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
176 GlobalAlloc::Function(instance) => {
177 let func_id = crate::abi::import_function(fx.tcx, fx.module, instance);
179 fx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
180 fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
182 GlobalAlloc::VTable(ty, trait_ref) => {
183 let alloc_id = fx.tcx.vtable_allocation((ty, trait_ref));
184 let alloc = fx.tcx.global_alloc(alloc_id).unwrap_memory();
185 // FIXME: factor this common code with the `Memory` arm into a function?
186 let data_id = data_id_for_alloc_id(
187 &mut fx.constants_cx,
190 alloc.inner().mutability,
193 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
194 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
196 GlobalAlloc::Static(def_id) => {
197 assert!(fx.tcx.is_static(def_id));
198 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
200 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
201 if fx.clif_comments.enabled() {
202 fx.add_comment(local_data_id, format!("{:?}", def_id));
204 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
207 let val = if offset.bytes() != 0 {
208 fx.bcx.ins().iadd_imm(base_addr, i64::try_from(offset.bytes()).unwrap())
212 CValue::by_val(val, layout)
215 ConstValue::ByRef { alloc, offset } => CValue::by_ref(
216 pointer_for_allocation(fx, alloc)
217 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
220 ConstValue::Slice { data, start, end } => {
221 let ptr = pointer_for_allocation(fx, data)
222 .offset_i64(fx, i64::try_from(start).unwrap())
227 .iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
228 CValue::by_val_pair(ptr, len, layout)
233 fn pointer_for_allocation<'tcx>(
234 fx: &mut FunctionCx<'_, '_, 'tcx>,
235 alloc: ConstAllocation<'tcx>,
236 ) -> crate::pointer::Pointer {
237 let alloc_id = fx.tcx.create_memory_alloc(alloc);
238 let data_id = data_id_for_alloc_id(
239 &mut fx.constants_cx,
242 alloc.inner().mutability,
245 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
246 if fx.clif_comments.enabled() {
247 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
249 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
250 crate::pointer::Pointer::new(global_ptr)
253 pub(crate) fn data_id_for_alloc_id(
255 module: &mut dyn Module,
257 mutability: rustc_hir::Mutability,
259 cx.todo.push(TodoItem::Alloc(alloc_id));
260 *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
261 module.declare_anonymous_data(mutability == rustc_hir::Mutability::Mut, false).unwrap()
265 fn data_id_for_static(
267 module: &mut dyn Module,
271 let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
272 let linkage = if definition {
273 crate::linkage::get_static_linkage(tcx, def_id)
274 } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
275 || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
282 let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
283 let symbol_name = tcx.symbol_name(instance).name;
284 let ty = instance.ty(tcx, ParamEnv::reveal_all());
285 let is_mutable = if tcx.is_mutable_static(def_id) {
288 !ty.is_freeze(tcx, ParamEnv::reveal_all())
290 let align = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().align.pref.bytes();
292 let attrs = tcx.codegen_fn_attrs(def_id);
294 let data_id = match module.declare_data(
298 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
300 Ok(data_id) => data_id,
301 Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!(
302 "attempt to declare `{symbol_name}` as static, but it was already declared as function"
304 Err(err) => Err::<_, _>(err).unwrap(),
307 if rlinkage.is_some() {
308 // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
309 // Declare an internal global `extern_with_linkage_foo` which
310 // is initialized with the address of `foo`. If `foo` is
311 // discarded during linking (for example, if `foo` has weak
312 // linkage and there are no definitions), then
313 // `extern_with_linkage_foo` will instead be initialized to
316 let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
317 let ref_data_id = module.declare_data(&ref_name, Linkage::Local, false, false).unwrap();
318 let mut data_ctx = DataContext::new();
319 data_ctx.set_align(align);
320 let data = module.declare_data_in_data(data_id, &mut data_ctx);
321 data_ctx.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect());
322 data_ctx.write_data_addr(0, data, 0);
323 match module.define_data(ref_data_id, &data_ctx) {
324 // Every time the static is referenced there will be another definition of this global,
325 // so duplicate definitions are expected and allowed.
326 Err(ModuleError::DuplicateDefinition(_)) => {}
335 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) {
336 while let Some(todo_item) = cx.todo.pop() {
337 let (data_id, alloc, section_name) = match todo_item {
338 TodoItem::Alloc(alloc_id) => {
339 let alloc = match tcx.global_alloc(alloc_id) {
340 GlobalAlloc::Memory(alloc) => alloc,
341 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) | GlobalAlloc::VTable(..) => {
345 let data_id = *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
347 .declare_anonymous_data(
348 alloc.inner().mutability == rustc_hir::Mutability::Mut,
353 (data_id, alloc, None)
355 TodoItem::Static(def_id) => {
356 //println!("static {:?}", def_id);
358 let section_name = tcx.codegen_fn_attrs(def_id).link_section;
360 let alloc = tcx.eval_static_initializer(def_id).unwrap();
362 let data_id = data_id_for_static(tcx, module, def_id, true);
363 (data_id, alloc, section_name)
367 //("data_id {}", data_id);
368 if cx.done.contains(&data_id) {
372 let mut data_ctx = DataContext::new();
373 let alloc = alloc.inner();
374 data_ctx.set_align(alloc.align.bytes());
376 if let Some(section_name) = section_name {
377 let (segment_name, section_name) = if tcx.sess.target.is_like_osx {
378 let section_name = section_name.as_str();
379 if let Some(names) = section_name.split_once(',') {
382 tcx.sess.fatal(&format!(
383 "#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma",
388 ("", section_name.as_str())
390 data_ctx.set_segment_section(segment_name, section_name);
393 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
394 data_ctx.define(bytes.into_boxed_slice());
396 for &(offset, alloc_id) in alloc.provenance().ptrs().iter() {
398 let endianness = tcx.data_layout.endian;
399 let offset = offset.bytes() as usize;
400 let ptr_size = tcx.data_layout.pointer_size;
401 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
402 offset..offset + ptr_size.bytes() as usize,
404 read_target_uint(endianness, bytes).unwrap()
407 let reloc_target_alloc = tcx.global_alloc(alloc_id);
408 let data_id = match reloc_target_alloc {
409 GlobalAlloc::Function(instance) => {
410 assert_eq!(addend, 0);
412 crate::abi::import_function(tcx, module, instance.polymorphize(tcx));
413 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
414 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
417 GlobalAlloc::Memory(target_alloc) => {
418 data_id_for_alloc_id(cx, module, alloc_id, target_alloc.inner().mutability)
420 GlobalAlloc::VTable(ty, trait_ref) => {
421 let alloc_id = tcx.vtable_allocation((ty, trait_ref));
422 data_id_for_alloc_id(cx, module, alloc_id, Mutability::Not)
424 GlobalAlloc::Static(def_id) => {
425 if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
427 tcx.sess.fatal(&format!(
428 "Allocation {:?} contains reference to TLS value {:?}",
433 // Don't push a `TodoItem::Static` here, as it will cause statics used by
434 // multiple crates to be duplicated between them. It isn't necessary anyway,
435 // as it will get pushed by `codegen_static` when necessary.
436 data_id_for_static(tcx, module, def_id, false)
440 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
441 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
444 module.define_data(data_id, &data_ctx).unwrap();
445 cx.done.insert(data_id);
448 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
451 /// Used only for intrinsic implementations that need a compile-time constant
452 pub(crate) fn mir_operand_get_const_val<'tcx>(
453 fx: &FunctionCx<'_, '_, 'tcx>,
454 operand: &Operand<'tcx>,
455 ) -> Option<ConstValue<'tcx>> {
457 Operand::Constant(const_) => Some(eval_mir_constant(fx, const_).unwrap().0),
458 // FIXME(rust-lang/rust#85105): Casts like `IMM8 as u32` result in the const being stored
459 // inside a temporary before being passed to the intrinsic requiring the const argument.
460 // This code tries to find a single constant defining definition of the referenced local.
461 Operand::Copy(place) | Operand::Move(place) => {
462 if !place.projection.is_empty() {
465 let mut computed_const_val = None;
466 for bb_data in fx.mir.basic_blocks.iter() {
467 for stmt in &bb_data.statements {
469 StatementKind::Assign(local_and_rvalue) if &local_and_rvalue.0 == place => {
470 match &local_and_rvalue.1 {
473 | CastKind::FloatToFloat
474 | CastKind::FloatToInt
475 | CastKind::IntToFloat
476 | CastKind::FnPtrToPtr
477 | CastKind::PtrToPtr,
481 if computed_const_val.is_some() {
482 return None; // local assigned twice
484 if !matches!(ty.kind(), ty::Uint(_) | ty::Int(_)) {
487 let const_val = mir_operand_get_const_val(fx, operand)?;
488 if fx.layout_of(*ty).size
489 != const_val.try_to_scalar_int()?.size()
493 computed_const_val = Some(const_val);
495 Rvalue::Use(operand) => {
496 computed_const_val = mir_operand_get_const_val(fx, operand)
501 StatementKind::SetDiscriminant { place: stmt_place, variant_index: _ }
502 if &**stmt_place == place =>
506 StatementKind::Intrinsic(ref intrinsic) => match **intrinsic {
507 NonDivergingIntrinsic::CopyNonOverlapping(..) => return None,
508 NonDivergingIntrinsic::Assume(..) => {}
510 // conservative handling
511 StatementKind::Assign(_)
512 | StatementKind::FakeRead(_)
513 | StatementKind::SetDiscriminant { .. }
514 | StatementKind::Deinit(_)
515 | StatementKind::StorageLive(_)
516 | StatementKind::StorageDead(_)
517 | StatementKind::Retag(_, _)
518 | StatementKind::AscribeUserType(_, _)
519 | StatementKind::Coverage(_)
520 | StatementKind::Nop => {}
523 match &bb_data.terminator().kind {
524 TerminatorKind::Goto { .. }
525 | TerminatorKind::SwitchInt { .. }
526 | TerminatorKind::Resume
527 | TerminatorKind::Abort
528 | TerminatorKind::Return
529 | TerminatorKind::Unreachable
530 | TerminatorKind::Drop { .. }
531 | TerminatorKind::Assert { .. } => {}
532 TerminatorKind::DropAndReplace { .. }
533 | TerminatorKind::Yield { .. }
534 | TerminatorKind::GeneratorDrop
535 | TerminatorKind::FalseEdge { .. }
536 | TerminatorKind::FalseUnwind { .. } => unreachable!(),
537 TerminatorKind::InlineAsm { .. } => return None,
538 TerminatorKind::Call { destination, target: Some(_), .. }
539 if destination == place =>
543 TerminatorKind::Call { .. } => {}