3 use rustc::mir::interpret::{
4 read_target_uint, AllocId, Allocation, ConstValue, GlobalAlloc, GlobalId, InterpResult, Scalar,
6 use rustc::ty::{layout::Align, Const, ConstKind};
7 use rustc_mir::interpret::{
8 ImmTy, InterpCx, Machine, Memory, MemoryKind, OpTy, PlaceTy, Pointer, StackPopCleanup,
12 use cranelift_module::*;
14 use crate::prelude::*;
17 pub struct ConstantCx {
18 todo: HashSet<TodoItem>,
19 done: HashSet<DataId>,
22 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
29 pub fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut Module<impl Backend>) {
30 //println!("todo {:?}", self.todo);
31 define_all_allocs(tcx, module, &mut self);
32 //println!("done {:?}", self.done);
37 pub fn codegen_static(constants_cx: &mut ConstantCx, def_id: DefId) {
38 constants_cx.todo.insert(TodoItem::Static(def_id));
41 pub fn codegen_static_ref<'tcx>(
42 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
46 let linkage = crate::linkage::get_static_ref_linkage(fx.tcx, def_id);
47 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, linkage);
48 cplace_for_dataid(fx, ty, data_id)
51 pub fn trans_promoted<'tcx>(
52 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
53 instance: Instance<'tcx>,
57 match fx.tcx.const_eval(ParamEnv::reveal_all().and(GlobalId {
59 promoted: Some(promoted),
62 let cplace = trans_const_place(fx, const_);
63 debug_assert_eq!(cplace.layout(), fx.layout_of(dest_ty));
66 Err(_) => crate::trap::trap_unreachable_ret_place(
68 fx.layout_of(dest_ty),
69 "[panic] Tried to get value of promoted value with errored during const eval.",
74 pub fn trans_constant<'tcx>(
75 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
76 constant: &Constant<'tcx>,
78 let const_ = force_eval_const(fx, &constant.literal);
79 trans_const_value(fx, const_)
82 pub fn force_eval_const<'tcx>(
83 fx: &FunctionCx<'_, 'tcx, impl Backend>,
85 ) -> &'tcx Const<'tcx> {
87 ConstKind::Unevaluated(def_id, ref substs) => {
88 let param_env = ParamEnv::reveal_all();
89 let substs = fx.monomorphize(substs);
90 let instance = Instance::resolve(fx.tcx, param_env, def_id, substs).unwrap();
95 fx.tcx.const_eval(param_env.and(cid)).unwrap()
97 _ => fx.monomorphize(&const_),
101 pub fn trans_const_value<'tcx>(
102 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
103 const_: &'tcx Const<'tcx>,
105 let ty = fx.monomorphize(&const_.ty);
106 let layout = fx.layout_of(ty);
108 ty::Bool | ty::Uint(_) => {
109 let bits = const_.val.try_to_bits(layout.size).unwrap();
110 CValue::const_val(fx, ty, bits)
113 let bits = const_.val.try_to_bits(layout.size).unwrap();
117 rustc::mir::interpret::sign_extend(bits, layout.size),
121 let bits = const_.val.try_to_bits(layout.size).unwrap();
122 let val = match fty {
126 .f32const(Ieee32::with_bits(u32::try_from(bits).unwrap())),
130 .f64const(Ieee64::with_bits(u64::try_from(bits).unwrap())),
132 CValue::by_val(val, layout)
134 ty::FnDef(_def_id, _substs) => CValue::by_ref(
137 .iconst(fx.pointer_type, fx.pointer_type.bytes() as i64),
140 _ => trans_const_place(fx, const_).to_cvalue(fx),
144 fn trans_const_place<'tcx>(
145 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
146 const_: &'tcx Const<'tcx>,
148 // Adapted from https://github.com/rust-lang/rust/pull/53671/files#diff-e0b58bb6712edaa8595ad7237542c958L551
149 let result = || -> InterpResult<'tcx, &'tcx Allocation> {
150 let mut ecx = InterpCx::new(
152 ty::ParamEnv::reveal_all(),
153 TransPlaceInterpreter,
156 ecx.push_stack_frame(
161 StackPopCleanup::None { cleanup: false },
164 let op = ecx.eval_operand(
165 &Operand::Constant(Box::new(Constant {
172 let ptr = ecx.allocate(op.layout, MemoryKind::Stack);
173 ecx.copy_op(op, ptr.into())?;
176 .get_raw(ptr.to_ref().to_scalar()?.to_ptr()?.alloc_id)?;
177 Ok(fx.tcx.intern_const_alloc(alloc.clone()))
179 let alloc = result().expect("unable to convert ConstKind to Allocation");
181 //println!("const value: {:?} allocation: {:?}", value, alloc);
182 let alloc_id = fx.tcx.alloc_map.lock().create_memory_alloc(alloc);
183 fx.constants_cx.todo.insert(TodoItem::Alloc(alloc_id));
184 let data_id = data_id_for_alloc_id(fx.module, alloc_id, alloc.align);
185 cplace_for_dataid(fx, const_.ty, data_id)
188 fn data_id_for_alloc_id<B: Backend>(
189 module: &mut Module<B>,
195 &format!("__alloc_{}", alloc_id.0),
198 Some(align.bytes() as u8),
203 fn data_id_for_static(
205 module: &mut Module<impl Backend>,
209 let instance = Instance::mono(tcx, def_id);
210 let symbol_name = tcx.symbol_name(instance).name.as_str();
211 let ty = instance.ty(tcx);
212 let is_mutable = if tcx.is_mutable_static(def_id) {
215 !ty.is_freeze(tcx, ParamEnv::reveal_all(), DUMMY_SP)
218 .layout_of(ParamEnv::reveal_all().and(ty))
229 Some(align.try_into().unwrap()),
233 if linkage == Linkage::Preemptible {
234 if let ty::RawPtr(_) = ty.kind {
237 tcx.def_span(def_id),
238 "must have type `*const T` or `*mut T` due to `#[linkage]` attribute",
242 let mut data_ctx = DataContext::new();
243 let zero_bytes = std::iter::repeat(0)
244 .take(pointer_ty(tcx).bytes() as usize)
245 .collect::<Vec<u8>>()
247 data_ctx.define(zero_bytes);
248 match module.define_data(data_id, &data_ctx) {
249 // Everytime a weak static is referenced, there will be a zero pointer definition,
250 // so duplicate definitions are expected and allowed.
251 Err(ModuleError::DuplicateDefinition(_)) => {}
259 fn cplace_for_dataid<'tcx>(
260 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
264 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
265 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
266 let layout = fx.layout_of(fx.monomorphize(&ty));
267 assert!(!layout.is_unsized(), "unsized statics aren't supported");
268 CPlace::for_addr(global_ptr, layout)
271 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut Module<impl Backend>, cx: &mut ConstantCx) {
272 let memory = Memory::<TransPlaceInterpreter>::new(tcx.at(DUMMY_SP), ());
274 while let Some(todo_item) = pop_set(&mut cx.todo) {
275 let (data_id, alloc) = match todo_item {
276 TodoItem::Alloc(alloc_id) => {
277 //println!("alloc_id {}", alloc_id);
278 let alloc = memory.get_raw(alloc_id).unwrap();
279 let data_id = data_id_for_alloc_id(module, alloc_id, alloc.align);
282 TodoItem::Static(def_id) => {
283 //println!("static {:?}", def_id);
285 if tcx.is_foreign_item(def_id) {
289 let instance = ty::Instance::mono(tcx, def_id);
294 let const_ = tcx.const_eval(ParamEnv::reveal_all().and(cid)).unwrap();
296 let alloc = match const_.val {
297 ConstKind::Value(ConstValue::ByRef { alloc, offset }) if offset.bytes() == 0 => alloc,
298 _ => bug!("static const eval returned {:#?}", const_),
301 let data_id = data_id_for_static(
305 if tcx.is_reachable_non_generic(def_id) {
315 //("data_id {}", data_id);
316 if cx.done.contains(&data_id) {
320 let mut data_ctx = DataContext::new();
322 let mut bytes = alloc.inspect_with_undef_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
323 // The machO backend of faerie doesn't align data objects correctly unless we do this.
324 while bytes.len() as u64 % 16 != 0 {
327 data_ctx.define(bytes.into_boxed_slice());
329 for &(offset, (_tag, reloc)) in alloc.relocations().iter() {
331 let endianness = tcx.data_layout.endian;
332 let offset = offset.bytes() as usize;
333 let ptr_size = tcx.data_layout.pointer_size;
334 let bytes = &alloc.inspect_with_undef_and_ptr_outside_interpreter(offset..offset + ptr_size.bytes() as usize);
335 read_target_uint(endianness, bytes).unwrap()
338 // Don't inline `reloc_target_alloc` into the match. That would cause `tcx.alloc_map`
339 // to be locked for the duration of the match. `data_id_for_static` however may try
340 // to lock `tcx.alloc_map` itself while calculating the layout of the target static.
341 // This would cause a panic in single threaded rustc and a deadlock for parallel rustc.
342 let reloc_target_alloc = tcx.alloc_map.lock().get(reloc).unwrap();
343 let data_id = match reloc_target_alloc {
344 GlobalAlloc::Function(instance) => {
345 assert_eq!(addend, 0);
346 let func_id = crate::abi::import_function(tcx, module, instance);
347 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
348 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
351 GlobalAlloc::Memory(_) => {
352 cx.todo.insert(TodoItem::Alloc(reloc));
353 data_id_for_alloc_id(module, reloc, alloc.align)
355 GlobalAlloc::Static(def_id) => {
356 // Don't push a `TodoItem::Static` here, as it will cause statics used by
357 // multiple crates to be duplicated between them. It isn't necessary anyway,
358 // as it will get pushed by `codegen_static` when necessary.
359 data_id_for_static(tcx, module, def_id, Linkage::Import)
363 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
364 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
367 module.define_data(data_id, &data_ctx).unwrap();
368 cx.done.insert(data_id);
371 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
374 fn pop_set<T: Copy + Eq + ::std::hash::Hash>(set: &mut HashSet<T>) -> Option<T> {
375 if let Some(elem) = set.iter().next().map(|elem| *elem) {
383 struct TransPlaceInterpreter;
385 impl<'mir, 'tcx> Machine<'mir, 'tcx> for TransPlaceInterpreter {
386 type MemoryKinds = !;
388 type PointerTag = ();
389 type AllocExtra = ();
390 type MemoryExtra = ();
391 type FrameExtra = ();
392 type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation<()>)>;
394 const CHECK_ALIGN: bool = true;
395 const STATIC_KIND: Option<!> = None;
397 fn enforce_validity(_: &InterpCx<'mir, 'tcx, Self>) -> bool {
401 fn before_terminator(_: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
406 _: &mut InterpCx<'mir, 'tcx, Self>,
409 _: Option<PlaceTy<'tcx>>,
410 _: Option<BasicBlock>,
411 _: Option<BasicBlock>,
412 ) -> InterpResult<'tcx, Option<&'mir Body<'tcx>>> {
417 _: &mut InterpCx<'mir, 'tcx, Self>,
421 _: Option<PlaceTy<'tcx>>,
422 _: Option<BasicBlock>,
423 _: Option<BasicBlock>,
424 ) -> InterpResult<'tcx> {
428 fn find_foreign_static(_: TyCtxt<'tcx>, _: DefId) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
433 _: &InterpCx<'mir, 'tcx, Self>,
437 ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
441 fn ptr_to_int(_: &Memory<'mir, 'tcx, Self>, _: Pointer<()>) -> InterpResult<'tcx, u64> {
445 fn box_alloc(_: &mut InterpCx<'mir, 'tcx, Self>, _: PlaceTy<'tcx>) -> InterpResult<'tcx> {
449 fn tag_allocation<'b>(
452 alloc: Cow<'b, Allocation>,
453 _: Option<MemoryKind<!>>,
454 ) -> (Cow<'b, Allocation<(), ()>>, ()) {
458 fn tag_static_base_pointer(_: &(), _: AllocId) -> Self::PointerTag {
463 _: &mut InterpCx<'mir, 'tcx, Self>,
465 _: &[OpTy<'tcx, ()>],
466 _: Option<PlaceTy<'tcx, ()>>,
467 _: Option<BasicBlock>,
468 ) -> InterpResult<'tcx> {
472 fn stack_push(_: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
476 fn stack_pop(_: &mut InterpCx<'mir, 'tcx, Self>, _: (), _: bool) -> InterpResult<'tcx, StackPopInfo> {
477 Ok(StackPopInfo::Normal)
481 pub fn mir_operand_get_const_val<'tcx>(
482 fx: &FunctionCx<'_, 'tcx, impl Backend>,
483 operand: &Operand<'tcx>,
484 ) -> Option<&'tcx Const<'tcx>> {
485 let place = match operand {
486 Operand::Copy(place) | Operand::Move(place) => place,
487 Operand::Constant(const_) => return Some(force_eval_const(fx, const_.literal)),
490 assert!(place.projection.is_empty());
491 let static_ = match &place.base {
492 PlaceBase::Static(static_) => static_,
493 PlaceBase::Local(_) => return None,
496 Some(match &static_.kind {
497 StaticKind::Static => unimplemented!(),
498 StaticKind::Promoted(promoted, substs) => {
499 let instance = Instance::new(static_.def_id, fx.monomorphize(substs));
501 .const_eval(ParamEnv::reveal_all().and(GlobalId {
503 promoted: Some(*promoted),