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_span::DUMMY_SP;
10 use cranelift_module::*;
12 use crate::prelude::*;
14 pub(crate) struct ConstantCx {
16 done: FxHashSet<DataId>,
17 anon_allocs: FxHashMap<AllocId, DataId>,
20 #[derive(Copy, Clone, Debug)]
27 pub(crate) fn new() -> Self {
28 ConstantCx { todo: vec![], done: FxHashSet::default(), anon_allocs: FxHashMap::default() }
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 unevaluated = match fx.monomorphize(constant.literal) {
43 ConstantKind::Ty(_) => unreachable!(),
44 ConstantKind::Unevaluated(uv, _) => uv,
45 ConstantKind::Val(..) => continue,
48 if let Err(err) = fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), unevaluated, None) {
49 all_constants_ok = false;
51 ErrorHandled::Reported(_) | ErrorHandled::Linted => {
52 fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
54 ErrorHandled::TooGeneric => {
55 span_bug!(constant.span, "codegen encountered polymorphic constant: {:?}", err);
63 pub(crate) fn codegen_static(tcx: TyCtxt<'_>, module: &mut dyn Module, def_id: DefId) {
64 let mut constants_cx = ConstantCx::new();
65 constants_cx.todo.push(TodoItem::Static(def_id));
66 constants_cx.finalize(tcx, module);
69 pub(crate) fn codegen_tls_ref<'tcx>(
70 fx: &mut FunctionCx<'_, '_, 'tcx>,
72 layout: TyAndLayout<'tcx>,
74 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
75 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
76 if fx.clif_comments.enabled() {
77 fx.add_comment(local_data_id, format!("tls {:?}", def_id));
79 let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
80 CValue::by_val(tls_ptr, layout)
83 pub(crate) fn eval_mir_constant<'tcx>(
84 fx: &mut FunctionCx<'_, '_, 'tcx>,
85 constant: &Constant<'tcx>,
86 ) -> (ConstValue<'tcx>, Ty<'tcx>) {
87 let constant_kind = fx.monomorphize(constant.literal);
88 let uv = match constant_kind {
89 ConstantKind::Ty(const_) => match const_.kind() {
90 ty::ConstKind::Unevaluated(uv) => uv.expand(),
91 ty::ConstKind::Value(val) => {
92 return (fx.tcx.valtree_to_const_val((const_.ty(), val)), const_.ty());
96 "encountered bad ConstKind after monomorphizing: {:?}",
100 ConstantKind::Unevaluated(mir::UnevaluatedConst { def, .. }, _)
101 if fx.tcx.is_static(def.did) =>
103 span_bug!(constant.span, "MIR constant refers to static");
105 ConstantKind::Unevaluated(uv, _) => uv,
106 ConstantKind::Val(val, _) => return (val, constant_kind.ty()),
110 fx.tcx.const_eval_resolve(ty::ParamEnv::reveal_all(), uv, None).unwrap_or_else(|_err| {
111 span_bug!(constant.span, "erroneous constant not captured by required_consts");
117 pub(crate) fn codegen_constant_operand<'tcx>(
118 fx: &mut FunctionCx<'_, '_, 'tcx>,
119 constant: &Constant<'tcx>,
121 let (const_val, ty) = eval_mir_constant(fx, constant);
123 codegen_const_value(fx, const_val, ty)
126 pub(crate) fn codegen_const_value<'tcx>(
127 fx: &mut FunctionCx<'_, '_, 'tcx>,
128 const_val: ConstValue<'tcx>,
131 let layout = fx.layout_of(ty);
132 assert!(!layout.is_unsized(), "sized const value");
135 return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
139 ConstValue::ZeroSized => unreachable!(), // we already handles ZST above
140 ConstValue::Scalar(x) => match x {
141 Scalar::Int(int) => {
142 if fx.clif_type(layout.ty).is_some() {
143 return CValue::const_val(fx, layout, int);
145 let raw_val = int.to_bits(int.size()).unwrap();
146 let val = match int.size().bytes() {
147 1 => fx.bcx.ins().iconst(types::I8, raw_val as i64),
148 2 => fx.bcx.ins().iconst(types::I16, raw_val as i64),
149 4 => fx.bcx.ins().iconst(types::I32, raw_val as i64),
150 8 => fx.bcx.ins().iconst(types::I64, raw_val as i64),
152 let lsb = fx.bcx.ins().iconst(types::I64, raw_val as u64 as i64);
154 fx.bcx.ins().iconst(types::I64, (raw_val >> 64) as u64 as i64);
155 fx.bcx.ins().iconcat(lsb, msb)
160 let place = CPlace::new_stack_slot(fx, layout);
161 place.to_ptr().store(fx, val, MemFlags::trusted());
165 Scalar::Ptr(ptr, _size) => {
166 let (alloc_id, offset) = ptr.into_parts(); // we know the `offset` is relative
167 let base_addr = match fx.tcx.global_alloc(alloc_id) {
168 GlobalAlloc::Memory(alloc) => {
169 let data_id = data_id_for_alloc_id(
170 &mut fx.constants_cx,
173 alloc.inner().mutability,
176 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
177 if fx.clif_comments.enabled() {
178 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
180 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
182 GlobalAlloc::Function(instance) => {
183 let func_id = crate::abi::import_function(fx.tcx, fx.module, instance);
185 fx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
186 fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
188 GlobalAlloc::VTable(ty, trait_ref) => {
189 let alloc_id = fx.tcx.vtable_allocation((ty, trait_ref));
190 let alloc = fx.tcx.global_alloc(alloc_id).unwrap_memory();
191 // FIXME: factor this common code with the `Memory` arm into a function?
192 let data_id = data_id_for_alloc_id(
193 &mut fx.constants_cx,
196 alloc.inner().mutability,
199 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
200 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
202 GlobalAlloc::Static(def_id) => {
203 assert!(fx.tcx.is_static(def_id));
204 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
206 fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
207 if fx.clif_comments.enabled() {
208 fx.add_comment(local_data_id, format!("{:?}", def_id));
210 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
213 let val = if offset.bytes() != 0 {
214 fx.bcx.ins().iadd_imm(base_addr, i64::try_from(offset.bytes()).unwrap())
218 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: ConstAllocation<'tcx>,
242 ) -> crate::pointer::Pointer {
243 let alloc_id = fx.tcx.create_memory_alloc(alloc);
244 let data_id = data_id_for_alloc_id(
245 &mut fx.constants_cx,
248 alloc.inner().mutability,
251 let local_data_id = 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!("{:?}", alloc_id));
255 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
256 crate::pointer::Pointer::new(global_ptr)
259 pub(crate) fn data_id_for_alloc_id(
261 module: &mut dyn Module,
263 mutability: rustc_hir::Mutability,
265 cx.todo.push(TodoItem::Alloc(alloc_id));
266 *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
267 module.declare_anonymous_data(mutability == rustc_hir::Mutability::Mut, false).unwrap()
271 fn data_id_for_static(
273 module: &mut dyn Module,
277 let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
278 let linkage = if definition {
279 crate::linkage::get_static_linkage(tcx, def_id)
280 } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
281 || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
288 let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
289 let symbol_name = tcx.symbol_name(instance).name;
290 let ty = instance.ty(tcx, ParamEnv::reveal_all());
291 let is_mutable = if tcx.is_mutable_static(def_id) {
294 !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
296 let align = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().align.pref.bytes();
298 let attrs = tcx.codegen_fn_attrs(def_id);
300 let data_id = match module.declare_data(
304 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
306 Ok(data_id) => data_id,
307 Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!(
308 "attempt to declare `{symbol_name}` as static, but it was already declared as function"
310 Err(err) => Err::<_, _>(err).unwrap(),
313 if rlinkage.is_some() {
314 // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
315 // Declare an internal global `extern_with_linkage_foo` which
316 // is initialized with the address of `foo`. If `foo` is
317 // discarded during linking (for example, if `foo` has weak
318 // linkage and there are no definitions), then
319 // `extern_with_linkage_foo` will instead be initialized to
322 let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
323 let ref_data_id = module.declare_data(&ref_name, Linkage::Local, false, false).unwrap();
324 let mut data_ctx = DataContext::new();
325 data_ctx.set_align(align);
326 let data = module.declare_data_in_data(data_id, &mut data_ctx);
327 data_ctx.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect());
328 data_ctx.write_data_addr(0, data, 0);
329 match module.define_data(ref_data_id, &data_ctx) {
330 // Every time the static is referenced there will be another definition of this global,
331 // so duplicate definitions are expected and allowed.
332 Err(ModuleError::DuplicateDefinition(_)) => {}
341 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) {
342 while let Some(todo_item) = cx.todo.pop() {
343 let (data_id, alloc, section_name) = match todo_item {
344 TodoItem::Alloc(alloc_id) => {
345 let alloc = match tcx.global_alloc(alloc_id) {
346 GlobalAlloc::Memory(alloc) => alloc,
347 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) | GlobalAlloc::VTable(..) => {
351 let data_id = *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
353 .declare_anonymous_data(
354 alloc.inner().mutability == rustc_hir::Mutability::Mut,
359 (data_id, alloc, None)
361 TodoItem::Static(def_id) => {
362 //println!("static {:?}", def_id);
364 let section_name = tcx.codegen_fn_attrs(def_id).link_section;
366 let alloc = tcx.eval_static_initializer(def_id).unwrap();
368 let data_id = data_id_for_static(tcx, module, def_id, true);
369 (data_id, alloc, section_name)
373 //("data_id {}", data_id);
374 if cx.done.contains(&data_id) {
378 let mut data_ctx = DataContext::new();
379 let alloc = alloc.inner();
380 data_ctx.set_align(alloc.align.bytes());
382 if let Some(section_name) = section_name {
383 let (segment_name, section_name) = if tcx.sess.target.is_like_osx {
384 let section_name = section_name.as_str();
385 if let Some(names) = section_name.split_once(',') {
388 tcx.sess.fatal(&format!(
389 "#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma",
394 ("", section_name.as_str())
396 data_ctx.set_segment_section(segment_name, section_name);
399 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
400 data_ctx.define(bytes.into_boxed_slice());
402 for &(offset, alloc_id) in alloc.provenance().iter() {
404 let endianness = tcx.data_layout.endian;
405 let offset = offset.bytes() as usize;
406 let ptr_size = tcx.data_layout.pointer_size;
407 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
408 offset..offset + ptr_size.bytes() as usize,
410 read_target_uint(endianness, bytes).unwrap()
413 let reloc_target_alloc = tcx.global_alloc(alloc_id);
414 let data_id = match reloc_target_alloc {
415 GlobalAlloc::Function(instance) => {
416 assert_eq!(addend, 0);
418 crate::abi::import_function(tcx, module, instance.polymorphize(tcx));
419 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
420 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
423 GlobalAlloc::Memory(target_alloc) => {
424 data_id_for_alloc_id(cx, module, alloc_id, target_alloc.inner().mutability)
426 GlobalAlloc::VTable(ty, trait_ref) => {
427 let alloc_id = tcx.vtable_allocation((ty, trait_ref));
428 data_id_for_alloc_id(cx, module, alloc_id, Mutability::Not)
430 GlobalAlloc::Static(def_id) => {
431 if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
433 tcx.sess.fatal(&format!(
434 "Allocation {:?} contains reference to TLS value {:?}",
439 // Don't push a `TodoItem::Static` here, as it will cause statics used by
440 // multiple crates to be duplicated between them. It isn't necessary anyway,
441 // as it will get pushed by `codegen_static` when necessary.
442 data_id_for_static(tcx, module, def_id, false)
446 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
447 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
450 module.define_data(data_id, &data_ctx).unwrap();
451 cx.done.insert(data_id);
454 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
457 pub(crate) fn mir_operand_get_const_val<'tcx>(
458 fx: &FunctionCx<'_, '_, 'tcx>,
459 operand: &Operand<'tcx>,
460 ) -> Option<ConstValue<'tcx>> {
462 Operand::Constant(const_) => match fx.monomorphize(const_.literal) {
463 ConstantKind::Ty(const_) => Some(
464 const_.eval_for_mir(fx.tcx, ParamEnv::reveal_all()).try_to_value(fx.tcx).unwrap(),
466 ConstantKind::Val(val, _) => Some(val),
467 ConstantKind::Unevaluated(uv, _) => {
468 Some(fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), uv, None).unwrap())
471 // FIXME(rust-lang/rust#85105): Casts like `IMM8 as u32` result in the const being stored
472 // inside a temporary before being passed to the intrinsic requiring the const argument.
473 // This code tries to find a single constant defining definition of the referenced local.
474 Operand::Copy(place) | Operand::Move(place) => {
475 if !place.projection.is_empty() {
478 let mut computed_const_val = None;
479 for bb_data in fx.mir.basic_blocks.iter() {
480 for stmt in &bb_data.statements {
482 StatementKind::Assign(local_and_rvalue) if &local_and_rvalue.0 == place => {
483 match &local_and_rvalue.1 {
486 | CastKind::FloatToFloat
487 | CastKind::FloatToInt
488 | CastKind::IntToFloat
489 | CastKind::FnPtrToPtr
490 | CastKind::PtrToPtr,
494 if computed_const_val.is_some() {
495 return None; // local assigned twice
497 if !matches!(ty.kind(), ty::Uint(_) | ty::Int(_)) {
500 let const_val = mir_operand_get_const_val(fx, operand)?;
501 if fx.layout_of(*ty).size
502 != const_val.try_to_scalar_int()?.size()
506 computed_const_val = Some(const_val);
508 Rvalue::Use(operand) => {
509 computed_const_val = mir_operand_get_const_val(fx, operand)
514 StatementKind::SetDiscriminant { place: stmt_place, variant_index: _ }
515 if &**stmt_place == place =>
519 StatementKind::Intrinsic(ref intrinsic) => match **intrinsic {
520 NonDivergingIntrinsic::CopyNonOverlapping(..) => return None,
521 NonDivergingIntrinsic::Assume(..) => {}
523 // conservative handling
524 StatementKind::Assign(_)
525 | StatementKind::FakeRead(_)
526 | StatementKind::SetDiscriminant { .. }
527 | StatementKind::Deinit(_)
528 | StatementKind::StorageLive(_)
529 | StatementKind::StorageDead(_)
530 | StatementKind::Retag(_, _)
531 | StatementKind::AscribeUserType(_, _)
532 | StatementKind::Coverage(_)
533 | StatementKind::Nop => {}
536 match &bb_data.terminator().kind {
537 TerminatorKind::Goto { .. }
538 | TerminatorKind::SwitchInt { .. }
539 | TerminatorKind::Resume
540 | TerminatorKind::Abort
541 | TerminatorKind::Return
542 | TerminatorKind::Unreachable
543 | TerminatorKind::Drop { .. }
544 | TerminatorKind::Assert { .. } => {}
545 TerminatorKind::DropAndReplace { .. }
546 | TerminatorKind::Yield { .. }
547 | TerminatorKind::GeneratorDrop
548 | TerminatorKind::FalseEdge { .. }
549 | TerminatorKind::FalseUnwind { .. } => unreachable!(),
550 TerminatorKind::InlineAsm { .. } => return None,
551 TerminatorKind::Call { destination, target: Some(_), .. }
552 if destination == place =>
556 TerminatorKind::Call { .. } => {}