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