1 use rustc_span::DUMMY_SP;
3 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
4 use rustc_middle::mir::interpret::{
5 read_target_uint, AllocId, Allocation, ConstValue, GlobalAlloc, Pointer, Scalar,
7 use rustc_middle::ty::{Const, ConstKind};
8 use rustc_target::abi::Align;
9 use rustc_data_structures::fx::FxHashSet;
11 use cranelift_codegen::ir::GlobalValueData;
12 use cranelift_module::*;
14 use crate::prelude::*;
17 pub(crate) struct ConstantCx {
19 done: FxHashSet<DataId>,
22 #[derive(Copy, Clone, Debug)]
29 pub(crate) 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(crate) fn codegen_static(constants_cx: &mut ConstantCx, def_id: DefId) {
38 constants_cx.todo.push(TodoItem::Static(def_id));
41 pub(crate) fn codegen_tls_ref<'tcx>(
42 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
44 layout: TyAndLayout<'tcx>,
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 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
49 #[cfg(debug_assertions)]
50 fx.add_comment(local_data_id, format!("tls {:?}", def_id));
51 let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
52 CValue::by_val(tls_ptr, layout)
55 fn codegen_static_ref<'tcx>(
56 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
58 layout: TyAndLayout<'tcx>,
60 let linkage = crate::linkage::get_static_ref_linkage(fx.tcx, def_id);
61 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, linkage);
62 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
63 #[cfg(debug_assertions)]
64 fx.add_comment(local_data_id, format!("{:?}", def_id));
65 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
66 assert!(!layout.is_unsized(), "unsized statics aren't supported");
67 assert!(matches!(fx.bcx.func.global_values[local_data_id], GlobalValueData::Symbol { tls: false, ..}), "tls static referenced without Rvalue::ThreadLocalRef");
68 CPlace::for_ptr(crate::pointer::Pointer::new(global_ptr), layout)
71 pub(crate) fn trans_constant<'tcx>(
72 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
73 constant: &Constant<'tcx>,
75 let const_ = match constant.literal.val {
76 ConstKind::Unevaluated(def_id, ref substs, promoted) if fx.tcx.is_static(def_id) => {
77 assert!(substs.is_empty());
78 assert!(promoted.is_none());
80 return codegen_static_ref(
83 fx.layout_of(fx.monomorphize(&constant.literal.ty)),
86 _ => fx.monomorphize(&constant.literal).eval(fx.tcx, ParamEnv::reveal_all()),
89 trans_const_value(fx, const_)
92 pub(crate) fn trans_const_value<'tcx>(
93 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
94 const_: &'tcx Const<'tcx>,
96 let ty = fx.monomorphize(&const_.ty);
97 let layout = fx.layout_of(ty);
98 assert!(!layout.is_unsized(), "sized const value");
101 return CValue::by_ref(
102 crate::Pointer::const_addr(fx, i64::try_from(layout.align.pref.bytes()).unwrap()),
106 let const_val = match const_.val {
107 ConstKind::Value(const_val) => const_val,
108 _ => unreachable!("Const {:?} should have been evaluated", const_),
112 ConstValue::Scalar(x) => {
113 if fx.clif_type(layout.ty).is_none() {
114 let (size, align) = (layout.size, layout.align.pref);
115 let mut alloc = Allocation::from_bytes(
116 std::iter::repeat(0).take(size.bytes_usize()).collect::<Vec<u8>>(),
119 let ptr = Pointer::new(AllocId(!0), Size::ZERO); // The alloc id is never used
120 alloc.write_scalar(fx, ptr, x.into(), size).unwrap();
121 let alloc = fx.tcx.intern_const_alloc(alloc);
122 return CValue::by_ref(pointer_for_allocation(fx, alloc), layout);
126 Scalar::Raw { data, size } => {
127 assert_eq!(u64::from(size), layout.size.bytes());
128 return CValue::const_val(fx, layout, data);
130 Scalar::Ptr(ptr) => {
131 let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id);
132 let base_addr = match alloc_kind {
133 Some(GlobalAlloc::Memory(alloc)) => {
134 fx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
135 let data_id = data_id_for_alloc_id(fx.module, ptr.alloc_id, alloc.align, alloc.mutability);
136 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
137 #[cfg(debug_assertions)]
138 fx.add_comment(local_data_id, format!("{:?}", ptr.alloc_id));
139 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
141 Some(GlobalAlloc::Function(instance)) => {
142 let func_id = crate::abi::import_function(fx.tcx, fx.module, instance);
143 let local_func_id = fx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
144 fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
146 Some(GlobalAlloc::Static(def_id)) => {
147 assert!(fx.tcx.is_static(def_id));
148 let linkage = crate::linkage::get_static_ref_linkage(fx.tcx, def_id);
149 let data_id = data_id_for_static(fx.tcx, fx.module, def_id, linkage);
150 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
151 #[cfg(debug_assertions)]
152 fx.add_comment(local_data_id, format!("{:?}", def_id));
153 fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
155 None => bug!("missing allocation {:?}", ptr.alloc_id),
157 let val = fx.bcx.ins().iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap());
158 return CValue::by_val(val, layout);
162 ConstValue::ByRef { alloc, offset } => {
164 pointer_for_allocation(fx, alloc)
165 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
169 ConstValue::Slice { data, start, end } => {
170 let ptr = pointer_for_allocation(fx, data)
171 .offset_i64(fx, i64::try_from(start).unwrap())
173 let len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
174 CValue::by_val_pair(ptr, len, layout)
179 fn pointer_for_allocation<'tcx>(
180 fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
181 alloc: &'tcx Allocation,
182 ) -> crate::pointer::Pointer {
183 let alloc_id = fx.tcx.create_memory_alloc(alloc);
184 fx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
185 let data_id = data_id_for_alloc_id(fx.module, alloc_id, alloc.align, alloc.mutability);
187 let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
188 #[cfg(debug_assertions)]
189 fx.add_comment(local_data_id, format!("{:?}", alloc_id));
190 let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
191 crate::pointer::Pointer::new(global_ptr)
194 fn data_id_for_alloc_id<B: Backend>(
195 module: &mut Module<B>,
198 mutability: rustc_hir::Mutability,
202 &format!("__alloc_{}", alloc_id.0),
204 mutability == rustc_hir::Mutability::Mut,
206 Some(align.bytes() as u8),
211 fn data_id_for_static(
213 module: &mut Module<impl Backend>,
217 let instance = Instance::mono(tcx, def_id);
218 let symbol_name = tcx.symbol_name(instance).name.as_str();
219 let ty = instance.monomorphic_ty(tcx);
220 let is_mutable = if tcx.is_mutable_static(def_id) {
223 !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
226 .layout_of(ParamEnv::reveal_all().and(ty))
232 let attrs = tcx.codegen_fn_attrs(def_id);
239 attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
240 Some(align.try_into().unwrap()),
244 if linkage == Linkage::Preemptible {
245 if let ty::RawPtr(_) = ty.kind {
248 tcx.def_span(def_id),
249 "must have type `*const T` or `*mut T` due to `#[linkage]` attribute",
253 let mut data_ctx = DataContext::new();
254 data_ctx.define_zeroinit(pointer_ty(tcx).bytes() as usize);
255 match module.define_data(data_id, &data_ctx) {
256 // Everytime a weak static is referenced, there will be a zero pointer definition,
257 // so duplicate definitions are expected and allowed.
258 Err(ModuleError::DuplicateDefinition(_)) => {}
266 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut Module<impl Backend>, cx: &mut ConstantCx) {
267 while let Some(todo_item) = cx.todo.pop() {
268 let (data_id, alloc, section_name) = match todo_item {
269 TodoItem::Alloc(alloc_id) => {
270 //println!("alloc_id {}", alloc_id);
271 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
272 GlobalAlloc::Memory(alloc) => alloc,
273 GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
275 let data_id = data_id_for_alloc_id(module, alloc_id, alloc.align, alloc.mutability);
276 (data_id, alloc, None)
278 TodoItem::Static(def_id) => {
279 //println!("static {:?}", def_id);
281 let section_name = tcx.codegen_fn_attrs(def_id).link_section.map(|s| s.as_str());
283 let const_ = tcx.const_eval_poly(def_id).unwrap();
285 let alloc = match const_ {
286 ConstValue::ByRef { alloc, offset } if offset.bytes() == 0 => alloc,
287 _ => bug!("static const eval returned {:#?}", const_),
290 let data_id = data_id_for_static(
294 if tcx.is_reachable_non_generic(def_id) {
297 Linkage::Export // FIXME Set hidden visibility
300 (data_id, alloc, section_name)
304 //("data_id {}", data_id);
305 if cx.done.contains(&data_id) {
309 let mut data_ctx = DataContext::new();
311 if let Some(section_name) = section_name {
312 // FIXME set correct segment for Mach-O files
313 data_ctx.set_segment_section("", &*section_name);
316 let bytes = alloc.inspect_with_undef_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
317 data_ctx.define(bytes.into_boxed_slice());
319 for &(offset, (_tag, reloc)) in alloc.relocations().iter() {
321 let endianness = tcx.data_layout.endian;
322 let offset = offset.bytes() as usize;
323 let ptr_size = tcx.data_layout.pointer_size;
324 let bytes = &alloc.inspect_with_undef_and_ptr_outside_interpreter(offset..offset + ptr_size.bytes() as usize);
325 read_target_uint(endianness, bytes).unwrap()
328 let reloc_target_alloc = tcx.get_global_alloc(reloc).unwrap();
329 let data_id = match reloc_target_alloc {
330 GlobalAlloc::Function(instance) => {
331 assert_eq!(addend, 0);
332 let func_id = crate::abi::import_function(tcx, module, instance);
333 let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
334 data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
337 GlobalAlloc::Memory(target_alloc) => {
338 cx.todo.push(TodoItem::Alloc(reloc));
339 data_id_for_alloc_id(module, reloc, target_alloc.align, target_alloc.mutability)
341 GlobalAlloc::Static(def_id) => {
342 if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
343 tcx.sess.fatal(&format!("Allocation {:?} contains reference to TLS value {:?}", alloc, def_id));
346 // Don't push a `TodoItem::Static` here, as it will cause statics used by
347 // multiple crates to be duplicated between them. It isn't necessary anyway,
348 // as it will get pushed by `codegen_static` when necessary.
353 crate::linkage::get_static_ref_linkage(tcx, def_id),
358 let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
359 data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
362 module.define_data(data_id, &data_ctx).unwrap();
363 cx.done.insert(data_id);
366 assert!(cx.todo.is_empty(), "{:?}", cx.todo);
369 pub(crate) fn mir_operand_get_const_val<'tcx>(
370 fx: &FunctionCx<'_, 'tcx, impl Backend>,
371 operand: &Operand<'tcx>,
372 ) -> Option<&'tcx Const<'tcx>> {
374 Operand::Copy(_) | Operand::Move(_) => None,
375 Operand::Constant(const_) => {
376 Some(fx.monomorphize(&const_.literal).eval(fx.tcx, ParamEnv::reveal_all()))