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