]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/constant.rs
drive-by: Fix path spans
[rust.git] / compiler / rustc_codegen_cranelift / src / constant.rs
1 //! Handling of `static`s, `const`s and promoted allocations
2
3 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
5 use rustc_middle::mir::interpret::{
6     read_target_uint, AllocId, ConstAllocation, ConstValue, ErrorHandled, GlobalAlloc, Scalar,
7 };
8
9 use cranelift_module::*;
10
11 use crate::prelude::*;
12
13 pub(crate) struct ConstantCx {
14     todo: Vec<TodoItem>,
15     done: FxHashSet<DataId>,
16     anon_allocs: FxHashMap<AllocId, DataId>,
17 }
18
19 #[derive(Copy, Clone, Debug)]
20 enum TodoItem {
21     Alloc(AllocId),
22     Static(DefId),
23 }
24
25 impl ConstantCx {
26     pub(crate) fn new() -> Self {
27         ConstantCx { todo: vec![], done: FxHashSet::default(), anon_allocs: FxHashMap::default() }
28     }
29
30     pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut dyn Module) {
31         //println!("todo {:?}", self.todo);
32         define_all_allocs(tcx, module, &mut self);
33         //println!("done {:?}", self.done);
34         self.done.clear();
35     }
36 }
37
38 pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, '_>) -> bool {
39     let mut all_constants_ok = true;
40     for constant in &fx.mir.required_consts {
41         if eval_mir_constant(fx, constant).is_none() {
42             all_constants_ok = false;
43         }
44     }
45     all_constants_ok
46 }
47
48 pub(crate) fn codegen_static(tcx: TyCtxt<'_>, module: &mut dyn Module, def_id: DefId) {
49     let mut constants_cx = ConstantCx::new();
50     constants_cx.todo.push(TodoItem::Static(def_id));
51     constants_cx.finalize(tcx, module);
52 }
53
54 pub(crate) fn codegen_tls_ref<'tcx>(
55     fx: &mut FunctionCx<'_, '_, 'tcx>,
56     def_id: DefId,
57     layout: TyAndLayout<'tcx>,
58 ) -> CValue<'tcx> {
59     let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
60     let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
61     if fx.clif_comments.enabled() {
62         fx.add_comment(local_data_id, format!("tls {:?}", def_id));
63     }
64     let tls_ptr = fx.bcx.ins().tls_value(fx.pointer_type, local_data_id);
65     CValue::by_val(tls_ptr, layout)
66 }
67
68 pub(crate) fn eval_mir_constant<'tcx>(
69     fx: &FunctionCx<'_, '_, 'tcx>,
70     constant: &Constant<'tcx>,
71 ) -> Option<(ConstValue<'tcx>, Ty<'tcx>)> {
72     let constant_kind = fx.monomorphize(constant.literal);
73     let uv = match constant_kind {
74         ConstantKind::Ty(const_) => match const_.kind() {
75             ty::ConstKind::Unevaluated(uv) => uv.expand(),
76             ty::ConstKind::Value(val) => {
77                 return Some((fx.tcx.valtree_to_const_val((const_.ty(), val)), const_.ty()));
78             }
79             err => span_bug!(
80                 constant.span,
81                 "encountered bad ConstKind after monomorphizing: {:?}",
82                 err
83             ),
84         },
85         ConstantKind::Unevaluated(mir::UnevaluatedConst { def, .. }, _)
86             if fx.tcx.is_static(def.did) =>
87         {
88             span_bug!(constant.span, "MIR constant refers to static");
89         }
90         ConstantKind::Unevaluated(uv, _) => uv,
91         ConstantKind::Val(val, _) => return Some((val, constant_kind.ty())),
92     };
93
94     let val = fx
95         .tcx
96         .const_eval_resolve(ty::ParamEnv::reveal_all(), uv, None)
97         .map_err(|err| match err {
98             ErrorHandled::Reported(_) => {
99                 fx.tcx.sess.span_err(constant.span, "erroneous constant encountered");
100             }
101             ErrorHandled::TooGeneric => {
102                 span_bug!(constant.span, "codegen encountered polymorphic constant: {:?}", err);
103             }
104         })
105         .ok();
106     val.map(|val| (val, constant_kind.ty()))
107 }
108
109 pub(crate) fn codegen_constant_operand<'tcx>(
110     fx: &mut FunctionCx<'_, '_, 'tcx>,
111     constant: &Constant<'tcx>,
112 ) -> CValue<'tcx> {
113     let (const_val, ty) = eval_mir_constant(fx, constant).unwrap_or_else(|| {
114         span_bug!(constant.span, "erroneous constant not captured by required_consts")
115     });
116
117     codegen_const_value(fx, const_val, ty)
118 }
119
120 pub(crate) fn codegen_const_value<'tcx>(
121     fx: &mut FunctionCx<'_, '_, 'tcx>,
122     const_val: ConstValue<'tcx>,
123     ty: Ty<'tcx>,
124 ) -> CValue<'tcx> {
125     let layout = fx.layout_of(ty);
126     assert!(layout.is_sized(), "unsized const value");
127
128     if layout.is_zst() {
129         return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
130     }
131
132     match const_val {
133         ConstValue::ZeroSized => unreachable!(), // we already handles ZST above
134         ConstValue::Scalar(x) => match x {
135             Scalar::Int(int) => {
136                 if fx.clif_type(layout.ty).is_some() {
137                     return CValue::const_val(fx, layout, int);
138                 } else {
139                     let raw_val = int.to_bits(int.size()).unwrap();
140                     let val = match int.size().bytes() {
141                         1 => fx.bcx.ins().iconst(types::I8, raw_val as i64),
142                         2 => fx.bcx.ins().iconst(types::I16, raw_val as i64),
143                         4 => fx.bcx.ins().iconst(types::I32, raw_val as i64),
144                         8 => fx.bcx.ins().iconst(types::I64, raw_val as i64),
145                         16 => {
146                             let lsb = fx.bcx.ins().iconst(types::I64, raw_val as u64 as i64);
147                             let msb =
148                                 fx.bcx.ins().iconst(types::I64, (raw_val >> 64) as u64 as i64);
149                             fx.bcx.ins().iconcat(lsb, msb)
150                         }
151                         _ => unreachable!(),
152                     };
153
154                     let place = CPlace::new_stack_slot(fx, layout);
155                     place.to_ptr().store(fx, val, MemFlags::trusted());
156                     place.to_cvalue(fx)
157                 }
158             }
159             Scalar::Ptr(ptr, _size) => {
160                 let (alloc_id, offset) = ptr.into_parts(); // we know the `offset` is relative
161                 let base_addr = match fx.tcx.global_alloc(alloc_id) {
162                     GlobalAlloc::Memory(alloc) => {
163                         let data_id = data_id_for_alloc_id(
164                             &mut fx.constants_cx,
165                             fx.module,
166                             alloc_id,
167                             alloc.inner().mutability,
168                         );
169                         let local_data_id =
170                             fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
171                         if fx.clif_comments.enabled() {
172                             fx.add_comment(local_data_id, format!("{:?}", alloc_id));
173                         }
174                         fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
175                     }
176                     GlobalAlloc::Function(instance) => {
177                         let func_id = crate::abi::import_function(fx.tcx, fx.module, instance);
178                         let local_func_id =
179                             fx.module.declare_func_in_func(func_id, &mut fx.bcx.func);
180                         fx.bcx.ins().func_addr(fx.pointer_type, local_func_id)
181                     }
182                     GlobalAlloc::VTable(ty, trait_ref) => {
183                         let alloc_id = fx.tcx.vtable_allocation((ty, trait_ref));
184                         let alloc = fx.tcx.global_alloc(alloc_id).unwrap_memory();
185                         // FIXME: factor this common code with the `Memory` arm into a function?
186                         let data_id = data_id_for_alloc_id(
187                             &mut fx.constants_cx,
188                             fx.module,
189                             alloc_id,
190                             alloc.inner().mutability,
191                         );
192                         let local_data_id =
193                             fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
194                         fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
195                     }
196                     GlobalAlloc::Static(def_id) => {
197                         assert!(fx.tcx.is_static(def_id));
198                         let data_id = data_id_for_static(fx.tcx, fx.module, def_id, false);
199                         let local_data_id =
200                             fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
201                         if fx.clif_comments.enabled() {
202                             fx.add_comment(local_data_id, format!("{:?}", def_id));
203                         }
204                         fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
205                     }
206                 };
207                 let val = if offset.bytes() != 0 {
208                     fx.bcx.ins().iadd_imm(base_addr, i64::try_from(offset.bytes()).unwrap())
209                 } else {
210                     base_addr
211                 };
212                 CValue::by_val(val, layout)
213             }
214         },
215         ConstValue::ByRef { alloc, offset } => CValue::by_ref(
216             pointer_for_allocation(fx, alloc)
217                 .offset_i64(fx, i64::try_from(offset.bytes()).unwrap()),
218             layout,
219         ),
220         ConstValue::Slice { data, start, end } => {
221             let ptr = pointer_for_allocation(fx, data)
222                 .offset_i64(fx, i64::try_from(start).unwrap())
223                 .get_addr(fx);
224             let len = fx
225                 .bcx
226                 .ins()
227                 .iconst(fx.pointer_type, i64::try_from(end.checked_sub(start).unwrap()).unwrap());
228             CValue::by_val_pair(ptr, len, layout)
229         }
230     }
231 }
232
233 fn pointer_for_allocation<'tcx>(
234     fx: &mut FunctionCx<'_, '_, 'tcx>,
235     alloc: ConstAllocation<'tcx>,
236 ) -> crate::pointer::Pointer {
237     let alloc_id = fx.tcx.create_memory_alloc(alloc);
238     let data_id = data_id_for_alloc_id(
239         &mut fx.constants_cx,
240         &mut *fx.module,
241         alloc_id,
242         alloc.inner().mutability,
243     );
244
245     let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
246     if fx.clif_comments.enabled() {
247         fx.add_comment(local_data_id, format!("{:?}", alloc_id));
248     }
249     let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
250     crate::pointer::Pointer::new(global_ptr)
251 }
252
253 pub(crate) fn data_id_for_alloc_id(
254     cx: &mut ConstantCx,
255     module: &mut dyn Module,
256     alloc_id: AllocId,
257     mutability: rustc_hir::Mutability,
258 ) -> DataId {
259     cx.todo.push(TodoItem::Alloc(alloc_id));
260     *cx.anon_allocs
261         .entry(alloc_id)
262         .or_insert_with(|| module.declare_anonymous_data(mutability.is_mut(), false).unwrap())
263 }
264
265 fn data_id_for_static(
266     tcx: TyCtxt<'_>,
267     module: &mut dyn Module,
268     def_id: DefId,
269     definition: bool,
270 ) -> DataId {
271     let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
272     let linkage = if definition {
273         crate::linkage::get_static_linkage(tcx, def_id)
274     } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
275         || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
276     {
277         Linkage::Preemptible
278     } else {
279         Linkage::Import
280     };
281
282     let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
283     let symbol_name = tcx.symbol_name(instance).name;
284     let ty = instance.ty(tcx, ParamEnv::reveal_all());
285     let is_mutable = if tcx.is_mutable_static(def_id) {
286         true
287     } else {
288         !ty.is_freeze(tcx, ParamEnv::reveal_all())
289     };
290     let align = tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().align.pref.bytes();
291
292     let attrs = tcx.codegen_fn_attrs(def_id);
293
294     let data_id = match module.declare_data(
295         &*symbol_name,
296         linkage,
297         is_mutable,
298         attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
299     ) {
300         Ok(data_id) => data_id,
301         Err(ModuleError::IncompatibleDeclaration(_)) => tcx.sess.fatal(&format!(
302             "attempt to declare `{symbol_name}` as static, but it was already declared as function"
303         )),
304         Err(err) => Err::<_, _>(err).unwrap(),
305     };
306
307     if rlinkage.is_some() {
308         // Comment copied from https://github.com/rust-lang/rust/blob/45060c2a66dfd667f88bd8b94261b28a58d85bd5/src/librustc_codegen_llvm/consts.rs#L141
309         // Declare an internal global `extern_with_linkage_foo` which
310         // is initialized with the address of `foo`.  If `foo` is
311         // discarded during linking (for example, if `foo` has weak
312         // linkage and there are no definitions), then
313         // `extern_with_linkage_foo` will instead be initialized to
314         // zero.
315
316         let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
317         let ref_data_id = module.declare_data(&ref_name, Linkage::Local, false, false).unwrap();
318         let mut data_ctx = DataContext::new();
319         data_ctx.set_align(align);
320         let data = module.declare_data_in_data(data_id, &mut data_ctx);
321         data_ctx.define(std::iter::repeat(0).take(pointer_ty(tcx).bytes() as usize).collect());
322         data_ctx.write_data_addr(0, data, 0);
323         match module.define_data(ref_data_id, &data_ctx) {
324             // Every time the static is referenced there will be another definition of this global,
325             // so duplicate definitions are expected and allowed.
326             Err(ModuleError::DuplicateDefinition(_)) => {}
327             res => res.unwrap(),
328         }
329         ref_data_id
330     } else {
331         data_id
332     }
333 }
334
335 fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut ConstantCx) {
336     while let Some(todo_item) = cx.todo.pop() {
337         let (data_id, alloc, section_name) = match todo_item {
338             TodoItem::Alloc(alloc_id) => {
339                 let alloc = match tcx.global_alloc(alloc_id) {
340                     GlobalAlloc::Memory(alloc) => alloc,
341                     GlobalAlloc::Function(_) | GlobalAlloc::Static(_) | GlobalAlloc::VTable(..) => {
342                         unreachable!()
343                     }
344                 };
345                 let data_id = *cx.anon_allocs.entry(alloc_id).or_insert_with(|| {
346                     module.declare_anonymous_data(alloc.inner().mutability.is_mut(), false).unwrap()
347                 });
348                 (data_id, alloc, None)
349             }
350             TodoItem::Static(def_id) => {
351                 //println!("static {:?}", def_id);
352
353                 let section_name = tcx.codegen_fn_attrs(def_id).link_section;
354
355                 let alloc = tcx.eval_static_initializer(def_id).unwrap();
356
357                 let data_id = data_id_for_static(tcx, module, def_id, true);
358                 (data_id, alloc, section_name)
359             }
360         };
361
362         //("data_id {}", data_id);
363         if cx.done.contains(&data_id) {
364             continue;
365         }
366
367         let mut data_ctx = DataContext::new();
368         let alloc = alloc.inner();
369         data_ctx.set_align(alloc.align.bytes());
370
371         if let Some(section_name) = section_name {
372             let (segment_name, section_name) = if tcx.sess.target.is_like_osx {
373                 let section_name = section_name.as_str();
374                 if let Some(names) = section_name.split_once(',') {
375                     names
376                 } else {
377                     tcx.sess.fatal(&format!(
378                         "#[link_section = \"{}\"] is not valid for macos target: must be segment and section separated by comma",
379                         section_name
380                     ));
381                 }
382             } else {
383                 ("", section_name.as_str())
384             };
385             data_ctx.set_segment_section(segment_name, section_name);
386         }
387
388         let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len()).to_vec();
389         data_ctx.define(bytes.into_boxed_slice());
390
391         for &(offset, alloc_id) in alloc.provenance().ptrs().iter() {
392             let addend = {
393                 let endianness = tcx.data_layout.endian;
394                 let offset = offset.bytes() as usize;
395                 let ptr_size = tcx.data_layout.pointer_size;
396                 let bytes = &alloc.inspect_with_uninit_and_ptr_outside_interpreter(
397                     offset..offset + ptr_size.bytes() as usize,
398                 );
399                 read_target_uint(endianness, bytes).unwrap()
400             };
401
402             let reloc_target_alloc = tcx.global_alloc(alloc_id);
403             let data_id = match reloc_target_alloc {
404                 GlobalAlloc::Function(instance) => {
405                     assert_eq!(addend, 0);
406                     let func_id =
407                         crate::abi::import_function(tcx, module, instance.polymorphize(tcx));
408                     let local_func_id = module.declare_func_in_data(func_id, &mut data_ctx);
409                     data_ctx.write_function_addr(offset.bytes() as u32, local_func_id);
410                     continue;
411                 }
412                 GlobalAlloc::Memory(target_alloc) => {
413                     data_id_for_alloc_id(cx, module, alloc_id, target_alloc.inner().mutability)
414                 }
415                 GlobalAlloc::VTable(ty, trait_ref) => {
416                     let alloc_id = tcx.vtable_allocation((ty, trait_ref));
417                     data_id_for_alloc_id(cx, module, alloc_id, Mutability::Not)
418                 }
419                 GlobalAlloc::Static(def_id) => {
420                     if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL)
421                     {
422                         tcx.sess.fatal(&format!(
423                             "Allocation {:?} contains reference to TLS value {:?}",
424                             alloc_id, def_id
425                         ));
426                     }
427
428                     // Don't push a `TodoItem::Static` here, as it will cause statics used by
429                     // multiple crates to be duplicated between them. It isn't necessary anyway,
430                     // as it will get pushed by `codegen_static` when necessary.
431                     data_id_for_static(tcx, module, def_id, false)
432                 }
433             };
434
435             let global_value = module.declare_data_in_data(data_id, &mut data_ctx);
436             data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
437         }
438
439         module.define_data(data_id, &data_ctx).unwrap();
440         cx.done.insert(data_id);
441     }
442
443     assert!(cx.todo.is_empty(), "{:?}", cx.todo);
444 }
445
446 /// Used only for intrinsic implementations that need a compile-time constant
447 pub(crate) fn mir_operand_get_const_val<'tcx>(
448     fx: &FunctionCx<'_, '_, 'tcx>,
449     operand: &Operand<'tcx>,
450 ) -> Option<ConstValue<'tcx>> {
451     match operand {
452         Operand::Constant(const_) => Some(eval_mir_constant(fx, const_).unwrap().0),
453         // FIXME(rust-lang/rust#85105): Casts like `IMM8 as u32` result in the const being stored
454         // inside a temporary before being passed to the intrinsic requiring the const argument.
455         // This code tries to find a single constant defining definition of the referenced local.
456         Operand::Copy(place) | Operand::Move(place) => {
457             if !place.projection.is_empty() {
458                 return None;
459             }
460             let mut computed_const_val = None;
461             for bb_data in fx.mir.basic_blocks.iter() {
462                 for stmt in &bb_data.statements {
463                     match &stmt.kind {
464                         StatementKind::Assign(local_and_rvalue) if &local_and_rvalue.0 == place => {
465                             match &local_and_rvalue.1 {
466                                 Rvalue::Cast(
467                                     CastKind::IntToInt
468                                     | CastKind::FloatToFloat
469                                     | CastKind::FloatToInt
470                                     | CastKind::IntToFloat
471                                     | CastKind::FnPtrToPtr
472                                     | CastKind::PtrToPtr,
473                                     operand,
474                                     ty,
475                                 ) => {
476                                     if computed_const_val.is_some() {
477                                         return None; // local assigned twice
478                                     }
479                                     if !matches!(ty.kind(), ty::Uint(_) | ty::Int(_)) {
480                                         return None;
481                                     }
482                                     let const_val = mir_operand_get_const_val(fx, operand)?;
483                                     if fx.layout_of(*ty).size
484                                         != const_val.try_to_scalar_int()?.size()
485                                     {
486                                         return None;
487                                     }
488                                     computed_const_val = Some(const_val);
489                                 }
490                                 Rvalue::Use(operand) => {
491                                     computed_const_val = mir_operand_get_const_val(fx, operand)
492                                 }
493                                 _ => return None,
494                             }
495                         }
496                         StatementKind::SetDiscriminant { place: stmt_place, variant_index: _ }
497                             if &**stmt_place == place =>
498                         {
499                             return None;
500                         }
501                         StatementKind::Intrinsic(ref intrinsic) => match **intrinsic {
502                             NonDivergingIntrinsic::CopyNonOverlapping(..) => return None,
503                             NonDivergingIntrinsic::Assume(..) => {}
504                         },
505                         // conservative handling
506                         StatementKind::Assign(_)
507                         | StatementKind::FakeRead(_)
508                         | StatementKind::SetDiscriminant { .. }
509                         | StatementKind::Deinit(_)
510                         | StatementKind::StorageLive(_)
511                         | StatementKind::StorageDead(_)
512                         | StatementKind::Retag(_, _)
513                         | StatementKind::AscribeUserType(_, _)
514                         | StatementKind::Coverage(_)
515                         | StatementKind::Nop => {}
516                     }
517                 }
518                 match &bb_data.terminator().kind {
519                     TerminatorKind::Goto { .. }
520                     | TerminatorKind::SwitchInt { .. }
521                     | TerminatorKind::Resume
522                     | TerminatorKind::Abort
523                     | TerminatorKind::Return
524                     | TerminatorKind::Unreachable
525                     | TerminatorKind::Drop { .. }
526                     | TerminatorKind::Assert { .. } => {}
527                     TerminatorKind::DropAndReplace { .. }
528                     | TerminatorKind::Yield { .. }
529                     | TerminatorKind::GeneratorDrop
530                     | TerminatorKind::FalseEdge { .. }
531                     | TerminatorKind::FalseUnwind { .. } => unreachable!(),
532                     TerminatorKind::InlineAsm { .. } => return None,
533                     TerminatorKind::Call { destination, target: Some(_), .. }
534                         if destination == place =>
535                     {
536                         return None;
537                     }
538                     TerminatorKind::Call { .. } => {}
539                 }
540             }
541             computed_const_val
542         }
543     }
544 }