]> git.lizzy.rs Git - rust.git/blob - src/constant.rs
544b020b711900de19f66498d63f456c41cb22b8
[rust.git] / src / constant.rs
1 //! Handling of `static`s, `const`s and promoted allocations
2
3 use rustc_span::DUMMY_SP;
4
5 use rustc_data_structures::fx::FxHashSet;
6 use rustc_errors::ErrorReported;
7 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
8 use rustc_middle::mir::interpret::{
9     read_target_uint, AllocId, Allocation, ConstValue, ErrorHandled, GlobalAlloc, Pointer, Scalar,
10 };
11 use rustc_middle::ty::{Const, ConstKind};
12
13 use cranelift_codegen::ir::GlobalValueData;
14 use cranelift_module::*;
15
16 use crate::prelude::*;
17
18 #[derive(Default)]
19 pub(crate) struct ConstantCx {
20     todo: Vec<TodoItem>,
21     done: FxHashSet<DataId>,
22 }
23
24 #[derive(Copy, Clone, Debug)]
25 enum TodoItem {
26     Alloc(AllocId),
27     Static(DefId),
28 }
29
30 impl ConstantCx {
31     pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut impl Module) {
32         //println!("todo {:?}", self.todo);
33         define_all_allocs(tcx, module, &mut self);
34         //println!("done {:?}", self.done);
35         self.done.clear();
36     }
37 }
38
39 pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, impl Module>) {
40     for constant in &fx.mir.required_consts {
41         let const_ = fx.monomorphize(constant.literal);
42         match const_.val {
43             ConstKind::Value(_) => {}
44             ConstKind::Unevaluated(def, ref substs, promoted) => {
45                 if let Err(err) =
46                     fx.tcx
47                         .const_eval_resolve(ParamEnv::reveal_all(), def, substs, promoted, None)
48                 {
49                     match err {
50                         ErrorHandled::Reported(ErrorReported) | ErrorHandled::Linted => {
51                             fx.tcx
52                                 .sess
53                                 .span_err(constant.span, "erroneous constant encountered");
54                         }
55                         ErrorHandled::TooGeneric => {
56                             span_bug!(
57                                 constant.span,
58                                 "codgen encountered polymorphic constant: {:?}",
59                                 err
60                             );
61                         }
62                     }
63                 }
64             }
65             ConstKind::Param(_)
66             | ConstKind::Infer(_)
67             | ConstKind::Bound(_, _)
68             | ConstKind::Placeholder(_)
69             | ConstKind::Error(_) => unreachable!("{:?}", const_),
70         }
71     }
72 }
73
74 pub(crate) fn codegen_static(constants_cx: &mut ConstantCx, def_id: DefId) {
75     constants_cx.todo.push(TodoItem::Static(def_id));
76 }
77
78 pub(crate) fn codegen_tls_ref<'tcx>(
79     fx: &mut FunctionCx<'_, 'tcx, impl Module>,
80     def_id: DefId,
81     layout: TyAndLayout<'tcx>,
82 ) -> CValue<'tcx> {
83     let data_id = data_id_for_static(fx.tcx, &mut fx.cx.module, def_id, false);
84     let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
85     #[cfg(debug_assertions)]
86     fx.add_comment(local_data_id, format!("tls {:?}", def_id));
87     let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
88     CValue::by_val(tls_ptr, layout)
89 }
90
91 fn codegen_static_ref<'tcx>(
92     fx: &mut FunctionCx<'_, 'tcx, impl Module>,
93     def_id: DefId,
94     layout: TyAndLayout<'tcx>,
95 ) -> CPlace<'tcx> {
96     let data_id = data_id_for_static(fx.tcx, &mut fx.cx.module, def_id, false);
97     let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
98     #[cfg(debug_assertions)]
99     fx.add_comment(local_data_id, format!("{:?}", def_id));
100     let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
101     assert!(!layout.is_unsized(), "unsized statics aren't supported");
102     assert!(
103         matches!(fx.bcx.func.global_values[local_data_id], GlobalValueData::Symbol { tls: false, ..}),
104         "tls static referenced without Rvalue::ThreadLocalRef"
105     );
106     CPlace::for_ptr(crate::pointer::Pointer::new(global_ptr), layout)
107 }
108
109 pub(crate) fn codegen_constant<'tcx>(
110     fx: &mut FunctionCx<'_, 'tcx, impl Module>,
111     constant: &Constant<'tcx>,
112 ) -> CValue<'tcx> {
113     let const_ = fx.monomorphize(constant.literal);
114     let const_val = match const_.val {
115         ConstKind::Value(const_val) => const_val,
116         ConstKind::Unevaluated(def, ref substs, promoted) if fx.tcx.is_static(def.did) => {
117             assert!(substs.is_empty());
118             assert!(promoted.is_none());
119
120             return codegen_static_ref(
121                 fx,
122                 def.did,
123                 fx.layout_of(fx.monomorphize(&constant.literal.ty)),
124             )
125             .to_cvalue(fx);
126         }
127         ConstKind::Unevaluated(def, ref substs, promoted) => {
128             match fx
129                 .tcx
130                 .const_eval_resolve(ParamEnv::reveal_all(), def, substs, promoted, None)
131             {
132                 Ok(const_val) => const_val,
133                 Err(_) => {
134                     if promoted.is_none() {
135                         fx.tcx
136                             .sess
137                             .span_err(constant.span, "erroneous constant encountered");
138                     }
139                     return crate::trap::trap_unreachable_ret_value(
140                         fx,
141                         fx.layout_of(const_.ty),
142                         "erroneous constant encountered",
143                     );
144                 }
145             }
146         }
147         ConstKind::Param(_)
148         | ConstKind::Infer(_)
149         | ConstKind::Bound(_, _)
150         | ConstKind::Placeholder(_)
151         | ConstKind::Error(_) => unreachable!("{:?}", const_),
152     };
153
154     codegen_const_value(fx, const_val, const_.ty)
155 }
156
157 pub(crate) fn codegen_const_value<'tcx>(
158     fx: &mut FunctionCx<'_, 'tcx, impl Module>,
159     const_val: ConstValue<'tcx>,
160     ty: Ty<'tcx>,
161 ) -> CValue<'tcx> {
162     let layout = fx.layout_of(ty);
163     assert!(!layout.is_unsized(), "sized const value");
164
165     if layout.is_zst() {
166         return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
167     }
168
169     match const_val {
170         ConstValue::Scalar(x) => {
171             if fx.clif_type(layout.ty).is_none() {
172                 let (size, align) = (layout.size, layout.align.pref);
173                 let mut alloc = Allocation::from_bytes(
174                     std::iter::repeat(0)
175                         .take(size.bytes_usize())
176                         .collect::<Vec<u8>>(),
177                     align,
178                 );
179                 let ptr = Pointer::new(AllocId(!0), Size::ZERO); // The alloc id is never used
180                 alloc.write_scalar(fx, ptr, x.into(), size).unwrap();
181                 let alloc = fx.tcx.intern_const_alloc(alloc);
182                 return CValue::by_ref(pointer_for_allocation(fx, alloc), layout);
183             }
184
185             match x {
186                 Scalar::Int(int) => CValue::const_val(fx, layout, int),
187                 Scalar::Ptr(ptr) => {
188                     let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id);
189                     let base_addr = match alloc_kind {
190                         Some(GlobalAlloc::Memory(alloc)) => {
191                             fx.cx.constants_cx.todo.push(TodoItem::Alloc(ptr.alloc_id));
192                             let data_id = data_id_for_alloc_id(
193                                 &mut fx.cx.module,
194                                 ptr.alloc_id,
195                                 alloc.mutability,
196                             );
197                             let local_data_id =
198                                 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
199                             #[cfg(debug_assertions)]
200                             fx.add_comment(local_data_id, format!("{:?}", ptr.alloc_id));
201                             fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
202                         }
203                         Some(GlobalAlloc::Function(instance)) => {
204                             let func_id =
205                                 crate::abi::import_function(fx.tcx, &mut fx.cx.module, instance);
206                             let local_func_id =
207                                 fx.cx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
208                             fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
209                         }
210                         Some(GlobalAlloc::Static(def_id)) => {
211                             assert!(fx.tcx.is_static(def_id));
212                             let data_id =
213                                 data_id_for_static(fx.tcx, &mut fx.cx.module, def_id, false);
214                             let local_data_id =
215                                 fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
216                             #[cfg(debug_assertions)]
217                             fx.add_comment(local_data_id, format!("{:?}", def_id));
218                             fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
219                         }
220                         None => bug!("missing allocation {:?}", ptr.alloc_id),
221                     };
222                     let val = if ptr.offset.bytes() != 0 {
223                         fx.bcx
224                             .ins()
225                             .iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap())
226                     } else {
227                         base_addr
228                     };
229                     CValue::by_val(val, layout)
230                 }
231             }
232         }
233         ConstValue::ByRef { alloc, offset } => CValue::by_ref(
234             pointer_for_allocation(fx, alloc)
235                 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
236             layout,
237         ),
238         ConstValue::Slice { data, start, end } => {
239             let ptr = pointer_for_allocation(fx, data)
240                 .offset_i64(fx, i64::try_from(start).unwrap())
241                 .get_addr(fx);
242             let len = fx.bcx.ins().iconst(
243                 fx.pointer_type,
244                 i64::try_from(end.checked_sub(start).unwrap()).unwrap(),
245             );
246             CValue::by_val_pair(ptr, len, layout)
247         }
248     }
249 }
250
251 fn pointer_for_allocation<'tcx>(
252     fx: &mut FunctionCx<'_, 'tcx, impl Module>,
253     alloc: &'tcx Allocation,
254 ) -> crate::pointer::Pointer {
255     let alloc_id = fx.tcx.create_memory_alloc(alloc);
256     fx.cx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
257     let data_id = data_id_for_alloc_id(&mut fx.cx.module, alloc_id, alloc.mutability);
258
259     let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
260     #[cfg(debug_assertions)]
261     fx.add_comment(local_data_id, format!("{:?}", alloc_id));
262     let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
263     crate::pointer::Pointer::new(global_ptr)
264 }
265
266 fn data_id_for_alloc_id(
267     module: &mut impl Module,
268     alloc_id: AllocId,
269     mutability: rustc_hir::Mutability,
270 ) -> DataId {
271     module
272         .declare_data(
273             &format!(".L__alloc_{:x}", alloc_id.0),
274             Linkage::Local,
275             mutability == rustc_hir::Mutability::Mut,
276             false,
277         )
278         .unwrap()
279 }
280
281 fn data_id_for_static(
282     tcx: TyCtxt<'_>,
283     module: &mut impl Module,
284     def_id: DefId,
285     definition: bool,
286 ) -> DataId {
287     let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
288     let linkage = if definition {
289         crate::linkage::get_static_linkage(tcx, def_id)
290     } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
291         || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
292     {
293         Linkage::Preemptible
294     } else {
295         Linkage::Import
296     };
297
298     let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
299     let symbol_name = tcx.symbol_name(instance).name;
300     let ty = instance.ty(tcx, ParamEnv::reveal_all());
301     let is_mutable = if tcx.is_mutable_static(def_id) {
302         true
303     } else {
304         !ty.is_freeze(tcx.at(DUMMY_SP), ParamEnv::reveal_all())
305     };
306     let align = tcx
307         .layout_of(ParamEnv::reveal_all().and(ty))
308         .unwrap()
309         .align
310         .pref
311         .bytes();
312
313     let attrs = tcx.codegen_fn_attrs(def_id);
314
315     let data_id = module
316         .declare_data(
317             &*symbol_name,
318             linkage,
319             is_mutable,
320             attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
321         )
322         .unwrap();
323
324     if rlinkage.is_some() {
325         // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
326         // Declare an internal global `extern_with_linkage_foo` which
327         // is initialized with the address of `foo`.  If `foo` is
328         // discarded during linking (for example, if `foo` has weak
329         // linkage and there are no definitions), then
330         // `extern_with_linkage_foo` will instead be initialized to
331         // zero.
332
333         let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
334         let ref_data_id = module
335             .declare_data(&ref_name, Linkage::Local, false, false)
336             .unwrap();
337         let mut data_ctx = DataContext::new();
338         data_ctx.set_align(align);
339         let data = module.declare_data_in_data(data_id, &mut data_ctx);
340         data_ctx.define(
341             std::iter::repeat(0)
342                 .take(pointer_ty(tcx).bytes() as usize)
343                 .collect(),
344         );
345         data_ctx.write_data_addr(0, data, 0);
346         match module.define_data(ref_data_id, &data_ctx) {
347             // Every time the static is referenced there will be another definition of this global,
348             // so duplicate definitions are expected and allowed.
349             Err(ModuleError::DuplicateDefinition(_)) => {}
350             res => res.unwrap(),
351         }
352         ref_data_id
353     } else {
354         data_id
355     }
356 }
357
358 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut impl Module, cx: &mut ConstantCx) {
359     while let Some(todo_item) = cx.todo.pop() {
360         let (data_id, alloc, section_name) = match todo_item {
361             TodoItem::Alloc(alloc_id) => {
362                 //println!("alloc_id {}", alloc_id);
363                 let alloc = match tcx.get_global_alloc(alloc_id).unwrap() {
364                     GlobalAlloc::Memory(alloc) => alloc,
365                     GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
366                 };
367                 let data_id = data_id_for_alloc_id(module, alloc_id, alloc.mutability);
368                 (data_id, alloc, None)
369             }
370             TodoItem::Static(def_id) => {
371                 //println!("static {:?}", def_id);
372
373                 let section_name = tcx
374                     .codegen_fn_attrs(def_id)
375                     .link_section
376                     .map(|s| s.as_str());
377
378                 let alloc = tcx.eval_static_initializer(def_id).unwrap();
379
380                 let data_id = data_id_for_static(tcx, module, def_id, true);
381                 (data_id, alloc, section_name)
382             }
383         };
384
385         //("data_id {}", data_id);
386         if cx.done.contains(&data_id) {
387             continue;
388         }
389
390         let mut data_ctx = DataContext::new();
391         data_ctx.set_align(alloc.align.bytes());
392
393         if let Some(section_name) = section_name {
394             // FIXME set correct segment for Mach-O files
395             data_ctx.set_segment_section("", &*section_name);
396         }
397
398         let bytes = alloc
399             .inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len())
400             .to_vec();
401         data_ctx.define(bytes.into_boxed_slice());
402
403         for &(offset, (_tag, reloc)) in alloc.relocations().iter() {
404             let addend = {
405                 let endianness = tcx.data_layout.endian;
406                 let offset = offset.bytes() as usize;
407                 let ptr_size = tcx.data_layout.pointer_size;
408                 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
409                     offset..offset + ptr_size.bytes() as usize,
410                 );
411                 read_target_uint(endianness, bytes).unwrap()
412             };
413
414             let reloc_target_alloc = tcx.get_global_alloc(reloc).unwrap();
415             let data_id = match reloc_target_alloc {
416                 GlobalAlloc::Function(instance) => {
417                     assert_eq!(addend, 0);
418                     let func_id = crate::abi::import_function(tcx, module, instance);
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);
421                     continue;
422                 }
423                 GlobalAlloc::Memory(target_alloc) => {
424                     cx.todo.push(TodoItem::Alloc(reloc));
425                     data_id_for_alloc_id(module, reloc, target_alloc.mutability)
426                 }
427                 GlobalAlloc::Static(def_id) => {
428                     if tcx
429                         .codegen_fn_attrs(def_id)
430                         .flags
431                         .contains(CodegenFnAttrFlags::THREAD_LOCAL)
432                     {
433                         tcx.sess.fatal(&format!(
434                             "Allocation {:?} contains reference to TLS value {:?}",
435                             alloc, def_id
436                         ));
437                     }
438
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)
443                 }
444             };
445
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);
448         }
449
450         module.define_data(data_id, &data_ctx).unwrap();
451         cx.done.insert(data_id);
452     }
453
454     assert!(cx.todo.is_empty(), "{:?}", cx.todo);
455 }
456
457 pub(crate) fn mir_operand_get_const_val<'tcx>(
458     fx: &FunctionCx<'_, 'tcx, impl Module>,
459     operand: &Operand<'tcx>,
460 ) -> Option<&'tcx Const<'tcx>> {
461     match operand {
462         Operand::Copy(_) | Operand::Move(_) => None,
463         Operand::Constant(const_) => Some(
464             fx.monomorphize(const_.literal)
465                 .eval(fx.tcx, ParamEnv::reveal_all()),
466         ),
467     }
468 }