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