]> git.lizzy.rs Git - rust.git/blob - src/constant.rs
8a22ddefbb27a721dce3aa9582ce70332ed1ef7e
[rust.git] / src / constant.rs
1 use rustc_span::DUMMY_SP;
2
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,
6 };
7 use rustc_middle::ty::{Const, ConstKind};
8 use rustc_target::abi::Align;
9 use rustc_data_structures::fx::FxHashSet;
10
11 use cranelift_codegen::ir::GlobalValueData;
12 use cranelift_module::*;
13
14 use crate::prelude::*;
15
16 #[derive(Default)]
17 pub(crate) struct ConstantCx {
18     todo: Vec<TodoItem>,
19     done: FxHashSet<DataId>,
20 }
21
22 #[derive(Copy, Clone, Debug)]
23 enum TodoItem {
24     Alloc(AllocId),
25     Static(DefId),
26 }
27
28 impl ConstantCx {
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);
33         self.done.clear();
34     }
35 }
36
37 pub(crate) fn codegen_static(constants_cx: &mut ConstantCx, def_id: DefId) {
38     constants_cx.todo.push(TodoItem::Static(def_id));
39 }
40
41 pub(crate) fn codegen_tls_ref<'tcx>(
42     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
43     def_id: DefId,
44     layout: TyAndLayout<'tcx>,
45 ) -> CValue<'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)
53 }
54
55 fn codegen_static_ref<'tcx>(
56     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
57     def_id: DefId,
58     layout: TyAndLayout<'tcx>,
59 ) -> CPlace<'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)
69 }
70
71 pub(crate) fn trans_constant<'tcx>(
72     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
73     constant: &Constant<'tcx>,
74 ) -> CValue<'tcx> {
75     let const_ = fx.monomorphize(&constant.literal);
76     let const_val = match const_.val {
77         ConstKind::Value(const_val) => const_val,
78         ConstKind::Unevaluated(def_id, ref substs, promoted) if fx.tcx.is_static(def_id) => {
79             assert!(substs.is_empty());
80             assert!(promoted.is_none());
81
82             return codegen_static_ref(
83                 fx,
84                 def_id,
85                 fx.layout_of(fx.monomorphize(&constant.literal.ty)),
86             ).to_cvalue(fx);
87         }
88         ConstKind::Unevaluated(def_id, ref substs, promoted) => {
89             match fx.tcx.const_eval_resolve(ParamEnv::reveal_all(), def_id, substs, promoted, None) {
90                 Ok(const_val) => const_val,
91                 Err(_) => {
92                     if promoted.is_none() {
93                         fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
94                     }
95                     return crate::trap::trap_unreachable_ret_value(
96                         fx,
97                         fx.layout_of(const_.ty),
98                         "erroneous constant encountered",
99                     );
100                 }
101             }
102         }
103         ConstKind::Param(_) | ConstKind::Infer(_) | ConstKind::Bound(_, _)
104         | ConstKind::Placeholder(_) | ConstKind::Error(_) => unreachable!("{:?}", const_),
105     };
106
107     trans_const_value(fx, const_val, const_.ty)
108 }
109
110 pub(crate) fn trans_const_value<'tcx>(
111     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
112     const_val: ConstValue<'tcx>,
113     ty: Ty<'tcx>
114 ) -> CValue<'tcx> {
115     let layout = fx.layout_of(ty);
116     assert!(!layout.is_unsized(), "sized const value");
117
118     if layout.is_zst() {
119         return CValue::by_ref(
120             crate::Pointer::const_addr(fx, i64::try_from(layout.align.pref.bytes()).unwrap()),
121             layout,
122         );
123     }
124
125     match const_val {
126         ConstValue::Scalar(x) => {
127             if fx.clif_type(layout.ty).is_none() {
128                 let (size, align) = (layout.size, layout.align.pref);
129                 let mut alloc = Allocation::from_bytes(
130                     std::iter::repeat(0).take(size.bytes_usize()).collect::<Vec<u8>>(),
131                     align,
132                 );
133                 let ptr = Pointer::new(AllocId(!0), Size::ZERO); // The alloc id is never used
134                 alloc.write_scalar(fx, ptr, x.into(), size).unwrap();
135                 let alloc = fx.tcx.intern_const_alloc(alloc);
136                 return CValue::by_ref(pointer_for_allocation(fx, alloc), layout);
137             }
138
139             match x {
140                 Scalar::Raw { data, size } => {
141                     assert_eq!(u64::from(size), layout.size.bytes());
142                     return CValue::const_val(fx, layout, data);
143                 }
144                 Scalar::Ptr(ptr) => {
145                     let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id);
146                     let base_addr = match alloc_kind {
147                         Some(GlobalAlloc::Memory(alloc)) => {
148                             fx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
149                             let data_id = data_id_for_alloc_id(fx.module, ptr.alloc_id, alloc.align, alloc.mutability);
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!("{:?}", ptr.alloc_id));
153                             fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
154                         }
155                         Some(GlobalAlloc::Function(instance)) => {
156                             let func_id = crate::abi::import_function(fx.tcx, fx.module, instance);
157                             let local_func_id = fx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
158                             fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
159                         }
160                         Some(GlobalAlloc::Static(def_id)) => {
161                             assert!(fx.tcx.is_static(def_id));
162                             let linkage = crate::linkage::get_static_ref_linkage(fx.tcx, def_id);
163                             let data_id = data_id_for_static(fx.tcx, fx.module, def_id, linkage);
164                             let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
165                             #[cfg(debug_assertions)]
166                             fx.add_comment(local_data_id, format!("{:?}", def_id));
167                             fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
168                         }
169                         None => bug!("missing allocation {:?}", ptr.alloc_id),
170                     };
171                     let val = fx.bcx.ins().iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap());
172                     return CValue::by_val(val, layout);
173                 }
174             }
175         }
176         ConstValue::ByRef { alloc, offset } => {
177             CValue::by_ref(
178                 pointer_for_allocation(fx, alloc)
179                     .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
180                 layout,
181             )
182         }
183         ConstValue::Slice { data, start, end } => {
184             let ptr = pointer_for_allocation(fx, data)
185                 .offset_i64(fx, i64::try_from(start).unwrap())
186                 .get_addr(fx);
187             let len = fx.bcx.ins().iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
188             CValue::by_val_pair(ptr, len, layout)
189         }
190     }
191 }
192
193 fn pointer_for_allocation<'tcx>(
194     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
195     alloc: &'tcx Allocation,
196 ) -> crate::pointer::Pointer {
197     let alloc_id = fx.tcx.create_memory_alloc(alloc);
198     fx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
199     let data_id = data_id_for_alloc_id(fx.module, alloc_id, alloc.align, alloc.mutability);
200
201     let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
202     #[cfg(debug_assertions)]
203     fx.add_comment(local_data_id, format!("{:?}", alloc_id));
204     let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
205     crate::pointer::Pointer::new(global_ptr)
206 }
207
208 fn data_id_for_alloc_id<B: Backend>(
209     module: &mut Module<B>,
210     alloc_id: AllocId,
211     align: Align,
212     mutability: rustc_hir::Mutability,
213 ) -> DataId {
214     module
215         .declare_data(
216             &format!("__alloc_{}", alloc_id.0),
217             Linkage::Local,
218             mutability == rustc_hir::Mutability::Mut,
219             false,
220             Some(align.bytes() as u8),
221         )
222         .unwrap()
223 }
224
225 fn data_id_for_static(
226     tcx: TyCtxt<'_>,
227     module: &mut Module<impl Backend>,
228     def_id: DefId,
229     linkage: Linkage,
230 ) -> DataId {
231     let instance = Instance::mono(tcx, def_id);
232     let symbol_name = tcx.symbol_name(instance).name.as_str();
233     let ty = instance.monomorphic_ty(tcx);
234     let is_mutable = if tcx.is_mutable_static(def_id) {
235         true
236     } else {
237         !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
238     };
239     let align = tcx
240         .layout_of(ParamEnv::reveal_all().and(ty))
241         .unwrap()
242         .align
243         .pref
244         .bytes();
245
246     let attrs = tcx.codegen_fn_attrs(def_id);
247
248     let data_id = module
249         .declare_data(
250             &*symbol_name,
251             linkage,
252             is_mutable,
253             attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
254             Some(align.try_into().unwrap()),
255         )
256         .unwrap();
257
258     if linkage == Linkage::Preemptible {
259         if let ty::RawPtr(_) = ty.kind {
260         } else {
261             tcx.sess.span_fatal(
262                 tcx.def_span(def_id),
263                 "must have type `*const T` or `*mut T` due to `#[linkage]` attribute",
264             )
265         }
266
267         let mut data_ctx = DataContext::new();
268         data_ctx.define_zeroinit(pointer_ty(tcx).bytes() as usize);
269         match module.define_data(data_id, &data_ctx) {
270             // Everytime a weak static is referenced, there will be a zero pointer definition,
271             // so duplicate definitions are expected and allowed.
272             Err(ModuleError::DuplicateDefinition(_)) => {}
273             res => res.unwrap(),
274         }
275     }
276
277     data_id
278 }
279
280 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut Module<impl Backend>, cx: &mut ConstantCx) {
281     while let Some(todo_item) = cx.todo.pop() {
282         let (data_id, alloc, section_name) = match todo_item {
283             TodoItem::Alloc(alloc_id) => {
284                 //println!("alloc_id {}", alloc_id);
285                 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
286                     GlobalAlloc::Memory(alloc) => alloc,
287                     GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
288                 };
289                 let data_id = data_id_for_alloc_id(module, alloc_id, alloc.align, alloc.mutability);
290                 (data_id, alloc, None)
291             }
292             TodoItem::Static(def_id) => {
293                 //println!("static {:?}", def_id);
294
295                 let section_name = tcx.codegen_fn_attrs(def_id).link_section.map(|s| s.as_str());
296
297                 let const_ = tcx.const_eval_poly(def_id).unwrap();
298
299                 let alloc = match const_ {
300                     ConstValue::ByRef { alloc, offset } if offset.bytes() == 0 => alloc,
301                     _ => bug!("static const eval returned {:#?}", const_),
302                 };
303
304                 let data_id = data_id_for_static(
305                     tcx,
306                     module,
307                     def_id,
308                     if tcx.is_reachable_non_generic(def_id) {
309                         Linkage::Export
310                     } else {
311                         Linkage::Export // FIXME Set hidden visibility
312                     },
313                 );
314                 (data_id, alloc, section_name)
315             }
316         };
317
318         //("data_id {}", data_id);
319         if cx.done.contains(&data_id) {
320             continue;
321         }
322
323         let mut data_ctx = DataContext::new();
324
325         if let Some(section_name) = section_name {
326             // FIXME set correct segment for Mach-O files
327             data_ctx.set_segment_section("", &*section_name);
328         }
329
330         let bytes = alloc.inspect_with_undef_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
331         data_ctx.define(bytes.into_boxed_slice());
332
333         for &(offset, (_tag, reloc)) in alloc.relocations().iter() {
334             let addend = {
335                 let endianness = tcx.data_layout.endian;
336                 let offset = offset.bytes() as usize;
337                 let ptr_size = tcx.data_layout.pointer_size;
338                 let bytes = &alloc.inspect_with_undef_and_ptr_outside_interpreter(offset..offset + ptr_size.bytes() as usize);
339                 read_target_uint(endianness, bytes).unwrap()
340             };
341
342             let reloc_target_alloc = tcx.get_global_alloc(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);
349                     continue;
350                 }
351                 GlobalAlloc::Memory(target_alloc) => {
352                     cx.todo.push(TodoItem::Alloc(reloc));
353                     data_id_for_alloc_id(module, reloc, target_alloc.align, target_alloc.mutability)
354                 }
355                 GlobalAlloc::Static(def_id) => {
356                     if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
357                         tcx.sess.fatal(&format!("Allocation {:?} contains reference to TLS value {:?}", alloc, def_id));
358                     }
359
360                     // Don't push a `TodoItem::Static` here, as it will cause statics used by
361                     // multiple crates to be duplicated between them. It isn't necessary anyway,
362                     // as it will get pushed by `codegen_static` when necessary.
363                     data_id_for_static(
364                         tcx,
365                         module,
366                         def_id,
367                         crate::linkage::get_static_ref_linkage(tcx, def_id),
368                     )
369                 }
370             };
371
372             let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
373             data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
374         }
375
376         module.define_data(data_id, &data_ctx).unwrap();
377         cx.done.insert(data_id);
378     }
379
380     assert!(cx.todo.is_empty(), "{:?}", cx.todo);
381 }
382
383 pub(crate) fn mir_operand_get_const_val<'tcx>(
384     fx: &FunctionCx<'_, 'tcx, impl Backend>,
385     operand: &Operand<'tcx>,
386 ) -> Option<&'tcx Const<'tcx>> {
387     match operand {
388         Operand::Copy(_) | Operand::Move(_) => None,
389         Operand::Constant(const_) => {
390             Some(fx.monomorphize(&const_.literal).eval(fx.tcx, ParamEnv::reveal_all()))
391         }
392     }
393 }