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