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