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,
8 use rustc_middle::ty::ConstKind;
9 use rustc_span::DUMMY_SP;
11 use cranelift_codegen::ir::GlobalValueData;
12 use cranelift_module::*;
14 use crate::prelude::*;
16 pub(crate) struct ConstantCx {
18 done: FxHashSet<DataId>,
19 anon_allocs: FxHashMap<AllocId, DataId>,
22 #[derive(Copy, Clone, Debug)]
29 pub(crate) fn new() -> Self {
30 ConstantCx { todo: vec![], done: FxHashSet::default(), anon_allocs: FxHashMap::default() }
33 pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut dyn Module) {
34 //println!("todo {:?}", self.todo);
35 define_all_allocs(tcx, module, &mut self);
36 //println!("done {:?}", self.done);
41 pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, '_>) -> bool {
42 let mut all_constants_ok = true;
43 for constant in &fx.mir.required_consts {
44 let unevaluated = match fx.monomorphize(constant.literal) {
45 ConstantKind::Ty(ct) => match ct.kind() {
46 ConstKind::Unevaluated(uv) => uv.expand(),
47 ConstKind::Value(_) => continue,
50 | ConstKind::Bound(_, _)
51 | ConstKind::Placeholder(_)
52 | ConstKind::Error(_) => unreachable!("{:?}", ct),
54 ConstantKind::Unevaluated(uv, _) => uv,
55 ConstantKind::Val(..) => continue,
58 if let Err(err) = fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None) {
59 all_constants_ok = false;
61 ErrorHandled::Reported(_) | ErrorHandled::Linted => {
62 fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
64 ErrorHandled::TooGeneric => {
65 span_bug!(constant.span, "codegen encountered polymorphic constant: {:?}", err);
73 pub(crate) fn codegen_static(tcx: TyCtxt<'_>, module: &mut dyn Module, def_id: DefId) {
74 let mut constants_cx = ConstantCx::new();
75 constants_cx.todo.push(TodoItem::Static(def_id));
76 constants_cx.finalize(tcx, module);
79 pub(crate) fn codegen_tls_ref<'tcx>(
80 fx: &mut FunctionCx<'_, '_, 'tcx>,
82 layout: TyAndLayout<'tcx>,
84 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
85 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
86 if fx.clif_comments.enabled() {
87 fx.add_comment(local_data_id, format!("tls {:?}", def_id));
89 let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
90 CValue::by_val(tls_ptr, layout)
93 fn codegen_static_ref<'tcx>(
94 fx: &mut FunctionCx<'_, '_, 'tcx>,
96 layout: TyAndLayout<'tcx>,
98 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
99 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
100 if fx.clif_comments.enabled() {
101 fx.add_comment(local_data_id, format!("{:?}", def_id));
103 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
104 assert!(!layout.is_unsized(), "unsized statics aren't supported");
107 fx.bcx.func.global_values[local_data_id],
108 GlobalValueData::Symbol { tls: false, .. }
110 "tls static referenced without Rvalue::ThreadLocalRef"
112 CPlace::for_ptr(crate::pointer::Pointer::new(global_ptr), layout)
115 pub(crate) fn codegen_constant<'tcx>(
116 fx: &mut FunctionCx<'_, '_, 'tcx>,
117 constant: &Constant<'tcx>,
119 let (const_val, ty) = match fx.monomorphize(constant.literal) {
120 ConstantKind::Ty(const_) => match const_.kind() {
121 ConstKind::Value(valtree) => {
122 (fx.tcx.valtree_to_const_val((const_.ty(), valtree)), const_.ty())
124 ConstKind::Unevaluated(ty::Unevaluated { def, substs, promoted })
125 if fx.tcx.is_static(def.did) =>
127 assert!(substs.is_empty());
128 assert_eq!(promoted, ());
129 return codegen_static_ref(fx, def.did, fx.layout_of(const_.ty())).to_cvalue(fx);
131 ConstKind::Unevaluated(unevaluated) => {
132 match fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated.expand(), None)
134 Ok(const_val) => (const_val, const_.ty()),
138 "erroneous constant not captured by required_consts"
144 | ConstKind::Infer(_)
145 | ConstKind::Bound(_, _)
146 | ConstKind::Placeholder(_)
147 | ConstKind::Error(_) => unreachable!("{:?}", const_),
149 ConstantKind::Unevaluated(ty::Unevaluated { def, substs, promoted }, ty)
150 if fx.tcx.is_static(def.did) =>
152 assert!(substs.is_empty());
153 assert!(promoted.is_none());
155 return codegen_static_ref(fx, def.did, fx.layout_of(ty)).to_cvalue(fx);
157 ConstantKind::Unevaluated(unevaluated, ty) => {
158 match fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None) {
159 Ok(const_val) => (const_val, ty),
161 span_bug!(constant.span, "erroneous constant not captured by required_consts");
165 ConstantKind::Val(val, ty) => (val, ty),
168 codegen_const_value(fx, const_val, ty)
171 pub(crate) fn codegen_const_value<'tcx>(
172 fx: &mut FunctionCx<'_, '_, 'tcx>,
173 const_val: ConstValue<'tcx>,
176 let layout = fx.layout_of(ty);
177 assert!(!layout.is_unsized(), "sized const value");
180 return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
184 ConstValue::ZeroSized => unreachable!(), // we already handles ZST above
185 ConstValue::Scalar(x) => match x {
186 Scalar::Int(int) => {
187 if fx.clif_type(layout.ty).is_some() {
188 return CValue::const_val(fx, layout, int);
190 let raw_val = int.to_bits(int.size()).unwrap();
191 let val = match int.size().bytes() {
192 1 => fx.bcx.ins().iconst(types::I8, raw_val as i64),
193 2 => fx.bcx.ins().iconst(types::I16, raw_val as i64),
194 4 => fx.bcx.ins().iconst(types::I32, raw_val as i64),
195 8 => fx.bcx.ins().iconst(types::I64, raw_val as i64),
197 let lsb = fx.bcx.ins().iconst(types::I64, raw_val as u64 as i64);
199 fx.bcx.ins().iconst(types::I64, (raw_val >> 64) as u64 as i64);
200 fx.bcx.ins().iconcat(lsb, msb)
205 let place = CPlace::new_stack_slot(fx, layout);
206 place.to_ptr().store(fx, val, MemFlags::trusted());
210 Scalar::Ptr(ptr, _size) => {
211 let (alloc_id, offset) = ptr.into_parts(); // we know the `offset` is relative
212 let base_addr = match fx.tcx.global_alloc(alloc_id) {
213 GlobalAlloc::Memory(alloc) => {
214 let data_id = data_id_for_alloc_id(
215 &mut fx.constants_cx,
218 alloc.inner().mutability,
221 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
222 if fx.clif_comments.enabled() {
223 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
225 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
227 GlobalAlloc::Function(instance) => {
228 let func_id = crate::abi::import_function(fx.tcx, fx.module, instance);
230 fx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
231 fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
233 GlobalAlloc::VTable(ty, trait_ref) => {
234 let alloc_id = fx.tcx.vtable_allocation((ty, trait_ref));
235 let alloc = fx.tcx.global_alloc(alloc_id).unwrap_memory();
236 // FIXME: factor this common code with the `Memory` arm into a function?
237 let data_id = data_id_for_alloc_id(
238 &mut fx.constants_cx,
241 alloc.inner().mutability,
244 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
245 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
247 GlobalAlloc::Static(def_id) => {
248 assert!(fx.tcx.is_static(def_id));
249 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
251 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
252 if fx.clif_comments.enabled() {
253 fx.add_comment(local_data_id, format!("{:?}", def_id));
255 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
258 let val = if offset.bytes() != 0 {
259 fx.bcx.ins().iadd_imm(base_addr, i64::try_from(offset.bytes()).unwrap())
263 CValue::by_val(val, layout)
266 ConstValue::ByRef { alloc, offset } => CValue::by_ref(
267 pointer_for_allocation(fx, alloc)
268 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
271 ConstValue::Slice { data, start, end } => {
272 let ptr = pointer_for_allocation(fx, data)
273 .offset_i64(fx, i64::try_from(start).unwrap())
278 .iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
279 CValue::by_val_pair(ptr, len, layout)
284 pub(crate) fn pointer_for_allocation<'tcx>(
285 fx: &mut FunctionCx<'_, '_, 'tcx>,
286 alloc: ConstAllocation<'tcx>,
287 ) -> crate::pointer::Pointer {
288 let alloc_id = fx.tcx.create_memory_alloc(alloc);
289 let data_id = data_id_for_alloc_id(
290 &mut fx.constants_cx,
293 alloc.inner().mutability,
296 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
297 if fx.clif_comments.enabled() {
298 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
300 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
301 crate::pointer::Pointer::new(global_ptr)
304 pub(crate) fn data_id_for_alloc_id(
306 module: &mut dyn Module,
308 mutability: rustc_hir::Mutability,
310 cx.todo.push(TodoItem::Alloc(alloc_id));
311 *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
312 module.declare_anonymous_data(mutability == rustc_hir::Mutability::Mut, false).unwrap()
316 fn data_id_for_static(
318 module: &mut dyn Module,
322 let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
323 let linkage = if definition {
324 crate::linkage::get_static_linkage(tcx, def_id)
325 } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
326 || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
333 let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
334 let symbol_name = tcx.symbol_name(instance).name;
335 let ty = instance.ty(tcx, ParamEnv::reveal_all());
336 let is_mutable = if tcx.is_mutable_static(def_id) {
339 !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
341 let align = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().align.pref.bytes();
343 let attrs = tcx.codegen_fn_attrs(def_id);
345 let data_id = match module.declare_data(
349 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
351 Ok(data_id) => data_id,
352 Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!(
353 "attempt to declare `{symbol_name}` as static, but it was already declared as function"
355 Err(err) => Err::<_, _>(err).unwrap(),
358 if rlinkage.is_some() {
359 // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
360 // Declare an internal global `extern_with_linkage_foo` which
361 // is initialized with the address of `foo`. If `foo` is
362 // discarded during linking (for example, if `foo` has weak
363 // linkage and there are no definitions), then
364 // `extern_with_linkage_foo` will instead be initialized to
367 let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
368 let ref_data_id = module.declare_data(&ref_name, Linkage::Local, false, false).unwrap();
369 let mut data_ctx = DataContext::new();
370 data_ctx.set_align(align);
371 let data = module.declare_data_in_data(data_id, &mut data_ctx);
372 data_ctx.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect());
373 data_ctx.write_data_addr(0, data, 0);
374 match module.define_data(ref_data_id, &data_ctx) {
375 // Every time the static is referenced there will be another definition of this global,
376 // so duplicate definitions are expected and allowed.
377 Err(ModuleError::DuplicateDefinition(_)) => {}
386 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) {
387 while let Some(todo_item) = cx.todo.pop() {
388 let (data_id, alloc, section_name) = match todo_item {
389 TodoItem::Alloc(alloc_id) => {
390 let alloc = match tcx.global_alloc(alloc_id) {
391 GlobalAlloc::Memory(alloc) => alloc,
392 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) | GlobalAlloc::VTable(..) => {
396 let data_id = *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
398 .declare_anonymous_data(
399 alloc.inner().mutability == rustc_hir::Mutability::Mut,
404 (data_id, alloc, None)
406 TodoItem::Static(def_id) => {
407 //println!("static {:?}", def_id);
409 let section_name = tcx.codegen_fn_attrs(def_id).link_section;
411 let alloc = tcx.eval_static_initializer(def_id).unwrap();
413 let data_id = data_id_for_static(tcx, module, def_id, true);
414 (data_id, alloc, section_name)
418 //("data_id {}", data_id);
419 if cx.done.contains(&data_id) {
423 let mut data_ctx = DataContext::new();
424 let alloc = alloc.inner();
425 data_ctx.set_align(alloc.align.bytes());
427 if let Some(section_name) = section_name {
428 let (segment_name, section_name) = if tcx.sess.target.is_like_osx {
429 let section_name = section_name.as_str();
430 if let Some(names) = section_name.split_once(',') {
433 tcx.sess.fatal(&format!(
434 "#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma",
439 ("", section_name.as_str())
441 data_ctx.set_segment_section(segment_name, section_name);
444 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
445 data_ctx.define(bytes.into_boxed_slice());
447 for &(offset, alloc_id) in alloc.provenance().iter() {
449 let endianness = tcx.data_layout.endian;
450 let offset = offset.bytes() as usize;
451 let ptr_size = tcx.data_layout.pointer_size;
452 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
453 offset..offset + ptr_size.bytes() as usize,
455 read_target_uint(endianness, bytes).unwrap()
458 let reloc_target_alloc = tcx.global_alloc(alloc_id);
459 let data_id = match reloc_target_alloc {
460 GlobalAlloc::Function(instance) => {
461 assert_eq!(addend, 0);
463 crate::abi::import_function(tcx, module, instance.polymorphize(tcx));
464 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
465 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
468 GlobalAlloc::Memory(target_alloc) => {
469 data_id_for_alloc_id(cx, module, alloc_id, target_alloc.inner().mutability)
471 GlobalAlloc::VTable(ty, trait_ref) => {
472 let alloc_id = tcx.vtable_allocation((ty, trait_ref));
473 data_id_for_alloc_id(cx, module, alloc_id, Mutability::Not)
475 GlobalAlloc::Static(def_id) => {
476 if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
478 tcx.sess.fatal(&format!(
479 "Allocation {:?} contains reference to TLS value {:?}",
484 // Don't push a `TodoItem::Static` here, as it will cause statics used by
485 // multiple crates to be duplicated between them. It isn't necessary anyway,
486 // as it will get pushed by `codegen_static` when necessary.
487 data_id_for_static(tcx, module, def_id, false)
491 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
492 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
495 module.define_data(data_id, &data_ctx).unwrap();
496 cx.done.insert(data_id);
499 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
502 pub(crate) fn mir_operand_get_const_val<'tcx>(
503 fx: &FunctionCx<'_, '_, 'tcx>,
504 operand: &Operand<'tcx>,
505 ) -> Option<ConstValue<'tcx>> {
507 Operand::Constant(const_) => match const_.literal {
508 ConstantKind::Ty(const_) => fx
509 .monomorphize(const_)
510 .eval_for_mir(fx.tcx, ParamEnv::reveal_all())
511 .try_to_value(fx.tcx),
512 ConstantKind::Val(val, _) => Some(val),
513 ConstantKind::Unevaluated(uv, _) => {
514 fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), uv, None).ok()
517 // FIXME(rust-lang/rust#85105): Casts like `IMM8 as u32` result in the const being stored
518 // inside a temporary before being passed to the intrinsic requiring the const argument.
519 // This code tries to find a single constant defining definition of the referenced local.
520 Operand::Copy(place) | Operand::Move(place) => {
521 if !place.projection.is_empty() {
524 let mut computed_const_val = None;
525 for bb_data in fx.mir.basic_blocks.iter() {
526 for stmt in &bb_data.statements {
528 StatementKind::Assign(local_and_rvalue) if &local_and_rvalue.0 == place => {
529 match &local_and_rvalue.1 {
530 Rvalue::Cast(CastKind::Misc, operand, ty) => {
531 if computed_const_val.is_some() {
532 return None; // local assigned twice
534 if !matches!(ty.kind(), ty::Uint(_) | ty::Int(_)) {
537 let const_val = mir_operand_get_const_val(fx, operand)?;
538 if fx.layout_of(*ty).size
539 != const_val.try_to_scalar_int()?.size()
543 computed_const_val = Some(const_val);
545 Rvalue::Use(operand) => {
546 computed_const_val = mir_operand_get_const_val(fx, operand)
551 StatementKind::SetDiscriminant { place: stmt_place, variant_index: _ }
552 if &**stmt_place == place =>
556 StatementKind::Intrinsic(ref intrinsic) => match **intrinsic {
557 NonDivergingIntrinsic::CopyNonOverlapping(..) => return None,
558 NonDivergingIntrinsic::Assume(..) => {}
560 // conservative handling
561 StatementKind::Assign(_)
562 | StatementKind::FakeRead(_)
563 | StatementKind::SetDiscriminant { .. }
564 | StatementKind::Deinit(_)
565 | StatementKind::StorageLive(_)
566 | StatementKind::StorageDead(_)
567 | StatementKind::Retag(_, _)
568 | StatementKind::AscribeUserType(_, _)
569 | StatementKind::Coverage(_)
570 | StatementKind::Nop => {}
573 match &bb_data.terminator().kind {
574 TerminatorKind::Goto { .. }
575 | TerminatorKind::SwitchInt { .. }
576 | TerminatorKind::Resume
577 | TerminatorKind::Abort
578 | TerminatorKind::Return
579 | TerminatorKind::Unreachable
580 | TerminatorKind::Drop { .. }
581 | TerminatorKind::Assert { .. } => {}
582 TerminatorKind::DropAndReplace { .. }
583 | TerminatorKind::Yield { .. }
584 | TerminatorKind::GeneratorDrop
585 | TerminatorKind::FalseEdge { .. }
586 | TerminatorKind::FalseUnwind { .. } => unreachable!(),
587 TerminatorKind::InlineAsm { .. } => return None,
588 TerminatorKind::Call { destination, target: Some(_), .. }
589 if destination == place =>
593 TerminatorKind::Call { .. } => {}