]> git.lizzy.rs Git - rust.git/blob - src/common.rs
Don't deduplicate vtables between functions
[rust.git] / src / common.rs
1 use rustc_index::vec::IndexVec;
2 use rustc_middle::ty::SymbolName;
3 use rustc_target::abi::call::FnAbi;
4 use rustc_target::abi::{Integer, Primitive};
5 use rustc_target::spec::{HasTargetSpec, Target};
6
7 use crate::prelude::*;
8
9 pub(crate) fn pointer_ty(tcx: TyCtxt<'_>) -> types::Type {
10     match tcx.data_layout.pointer_size.bits() {
11         16 => types::I16,
12         32 => types::I32,
13         64 => types::I64,
14         bits => bug!("ptr_sized_integer: unknown pointer bit size {}", bits),
15     }
16 }
17
18 pub(crate) fn scalar_to_clif_type(tcx: TyCtxt<'_>, scalar: Scalar) -> Type {
19     match scalar.value {
20         Primitive::Int(int, _sign) => match int {
21             Integer::I8 => types::I8,
22             Integer::I16 => types::I16,
23             Integer::I32 => types::I32,
24             Integer::I64 => types::I64,
25             Integer::I128 => types::I128,
26         },
27         Primitive::F32 => types::F32,
28         Primitive::F64 => types::F64,
29         Primitive::Pointer => pointer_ty(tcx),
30     }
31 }
32
33 fn clif_type_from_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<types::Type> {
34     Some(match ty.kind() {
35         ty::Bool => types::I8,
36         ty::Uint(size) => match size {
37             UintTy::U8 => types::I8,
38             UintTy::U16 => types::I16,
39             UintTy::U32 => types::I32,
40             UintTy::U64 => types::I64,
41             UintTy::U128 => types::I128,
42             UintTy::Usize => pointer_ty(tcx),
43         },
44         ty::Int(size) => match size {
45             IntTy::I8 => types::I8,
46             IntTy::I16 => types::I16,
47             IntTy::I32 => types::I32,
48             IntTy::I64 => types::I64,
49             IntTy::I128 => types::I128,
50             IntTy::Isize => pointer_ty(tcx),
51         },
52         ty::Char => types::I32,
53         ty::Float(size) => match size {
54             FloatTy::F32 => types::F32,
55             FloatTy::F64 => types::F64,
56         },
57         ty::FnPtr(_) => pointer_ty(tcx),
58         ty::RawPtr(TypeAndMut { ty: pointee_ty, mutbl: _ }) | ty::Ref(_, pointee_ty, _) => {
59             if has_ptr_meta(tcx, pointee_ty) {
60                 return None;
61             } else {
62                 pointer_ty(tcx)
63             }
64         }
65         ty::Adt(adt_def, _) if adt_def.repr.simd() => {
66             let (element, count) = match &tcx.layout_of(ParamEnv::reveal_all().and(ty)).unwrap().abi
67             {
68                 Abi::Vector { element, count } => (element.clone(), *count),
69                 _ => unreachable!(),
70             };
71
72             match scalar_to_clif_type(tcx, element).by(u16::try_from(count).unwrap()) {
73                 // Cranelift currently only implements icmp for 128bit vectors.
74                 Some(vector_ty) if vector_ty.bits() == 128 => vector_ty,
75                 _ => return None,
76             }
77         }
78         ty::Param(_) => bug!("ty param {:?}", ty),
79         _ => return None,
80     })
81 }
82
83 fn clif_pair_type_from_ty<'tcx>(
84     tcx: TyCtxt<'tcx>,
85     ty: Ty<'tcx>,
86 ) -> Option<(types::Type, types::Type)> {
87     Some(match ty.kind() {
88         ty::Tuple(substs) if substs.len() == 2 => {
89             let mut types = substs.types();
90             let a = clif_type_from_ty(tcx, types.next().unwrap())?;
91             let b = clif_type_from_ty(tcx, types.next().unwrap())?;
92             if a.is_vector() || b.is_vector() {
93                 return None;
94             }
95             (a, b)
96         }
97         ty::RawPtr(TypeAndMut { ty: pointee_ty, mutbl: _ }) | ty::Ref(_, pointee_ty, _) => {
98             if has_ptr_meta(tcx, pointee_ty) {
99                 (pointer_ty(tcx), pointer_ty(tcx))
100             } else {
101                 return None;
102             }
103         }
104         _ => return None,
105     })
106 }
107
108 /// Is a pointer to this type a fat ptr?
109 pub(crate) fn has_ptr_meta<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
110     let ptr_ty = tcx.mk_ptr(TypeAndMut { ty, mutbl: rustc_hir::Mutability::Not });
111     match &tcx.layout_of(ParamEnv::reveal_all().and(ptr_ty)).unwrap().abi {
112         Abi::Scalar(_) => false,
113         Abi::ScalarPair(_, _) => true,
114         abi => unreachable!("Abi of ptr to {:?} is {:?}???", ty, abi),
115     }
116 }
117
118 pub(crate) fn codegen_icmp_imm(
119     fx: &mut FunctionCx<'_, '_, '_>,
120     intcc: IntCC,
121     lhs: Value,
122     rhs: i128,
123 ) -> Value {
124     let lhs_ty = fx.bcx.func.dfg.value_type(lhs);
125     if lhs_ty == types::I128 {
126         // FIXME legalize `icmp_imm.i128` in Cranelift
127
128         let (lhs_lsb, lhs_msb) = fx.bcx.ins().isplit(lhs);
129         let (rhs_lsb, rhs_msb) = (rhs as u128 as u64 as i64, (rhs as u128 >> 64) as u64 as i64);
130
131         match intcc {
132             IntCC::Equal => {
133                 let lsb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_lsb, rhs_lsb);
134                 let msb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_msb, rhs_msb);
135                 fx.bcx.ins().band(lsb_eq, msb_eq)
136             }
137             IntCC::NotEqual => {
138                 let lsb_ne = fx.bcx.ins().icmp_imm(IntCC::NotEqual, lhs_lsb, rhs_lsb);
139                 let msb_ne = fx.bcx.ins().icmp_imm(IntCC::NotEqual, lhs_msb, rhs_msb);
140                 fx.bcx.ins().bor(lsb_ne, msb_ne)
141             }
142             _ => {
143                 // if msb_eq {
144                 //     lsb_cc
145                 // } else {
146                 //     msb_cc
147                 // }
148
149                 let msb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_msb, rhs_msb);
150                 let lsb_cc = fx.bcx.ins().icmp_imm(intcc, lhs_lsb, rhs_lsb);
151                 let msb_cc = fx.bcx.ins().icmp_imm(intcc, lhs_msb, rhs_msb);
152
153                 fx.bcx.ins().select(msb_eq, lsb_cc, msb_cc)
154             }
155         }
156     } else {
157         let rhs = i64::try_from(rhs).expect("codegen_icmp_imm rhs out of range for <128bit int");
158         fx.bcx.ins().icmp_imm(intcc, lhs, rhs)
159     }
160 }
161
162 pub(crate) fn type_min_max_value(
163     bcx: &mut FunctionBuilder<'_>,
164     ty: Type,
165     signed: bool,
166 ) -> (Value, Value) {
167     assert!(ty.is_int());
168
169     if ty == types::I128 {
170         if signed {
171             let min = i128::MIN as u128;
172             let min_lsb = bcx.ins().iconst(types::I64, min as u64 as i64);
173             let min_msb = bcx.ins().iconst(types::I64, (min >> 64) as u64 as i64);
174             let min = bcx.ins().iconcat(min_lsb, min_msb);
175
176             let max = i128::MAX as u128;
177             let max_lsb = bcx.ins().iconst(types::I64, max as u64 as i64);
178             let max_msb = bcx.ins().iconst(types::I64, (max >> 64) as u64 as i64);
179             let max = bcx.ins().iconcat(max_lsb, max_msb);
180
181             return (min, max);
182         } else {
183             let min_half = bcx.ins().iconst(types::I64, 0);
184             let min = bcx.ins().iconcat(min_half, min_half);
185
186             let max_half = bcx.ins().iconst(types::I64, u64::MAX as i64);
187             let max = bcx.ins().iconcat(max_half, max_half);
188
189             return (min, max);
190         }
191     }
192
193     let min = match (ty, signed) {
194         (types::I8, false) | (types::I16, false) | (types::I32, false) | (types::I64, false) => {
195             0i64
196         }
197         (types::I8, true) => i64::from(i8::MIN),
198         (types::I16, true) => i64::from(i16::MIN),
199         (types::I32, true) => i64::from(i32::MIN),
200         (types::I64, true) => i64::MIN,
201         _ => unreachable!(),
202     };
203
204     let max = match (ty, signed) {
205         (types::I8, false) => i64::from(u8::MAX),
206         (types::I16, false) => i64::from(u16::MAX),
207         (types::I32, false) => i64::from(u32::MAX),
208         (types::I64, false) => u64::MAX as i64,
209         (types::I8, true) => i64::from(i8::MAX),
210         (types::I16, true) => i64::from(i16::MAX),
211         (types::I32, true) => i64::from(i32::MAX),
212         (types::I64, true) => i64::MAX,
213         _ => unreachable!(),
214     };
215
216     let (min, max) = (bcx.ins().iconst(ty, min), bcx.ins().iconst(ty, max));
217
218     (min, max)
219 }
220
221 pub(crate) fn type_sign(ty: Ty<'_>) -> bool {
222     match ty.kind() {
223         ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
224         ty::Int(..) => true,
225         ty::Float(..) => false, // `signed` is unused for floats
226         _ => panic!("{}", ty),
227     }
228 }
229
230 pub(crate) struct FunctionCx<'m, 'clif, 'tcx> {
231     pub(crate) cx: &'clif mut crate::CodegenCx<'m, 'tcx>,
232     pub(crate) tcx: TyCtxt<'tcx>,
233     pub(crate) pointer_type: Type, // Cached from module
234     pub(crate) vtables: FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), DataId>,
235
236     pub(crate) instance: Instance<'tcx>,
237     pub(crate) symbol_name: SymbolName<'tcx>,
238     pub(crate) mir: &'tcx Body<'tcx>,
239     pub(crate) fn_abi: Option<FnAbi<'tcx, Ty<'tcx>>>,
240
241     pub(crate) bcx: FunctionBuilder<'clif>,
242     pub(crate) block_map: IndexVec<BasicBlock, Block>,
243     pub(crate) local_map: IndexVec<Local, CPlace<'tcx>>,
244
245     /// When `#[track_caller]` is used, the implicit caller location is stored in this variable.
246     pub(crate) caller_location: Option<CValue<'tcx>>,
247
248     pub(crate) clif_comments: crate::pretty_clif::CommentWriter,
249     pub(crate) source_info_set: indexmap::IndexSet<SourceInfo>,
250
251     /// This should only be accessed by `CPlace::new_var`.
252     pub(crate) next_ssa_var: u32,
253
254     pub(crate) inline_asm_index: u32,
255 }
256
257 impl<'tcx> LayoutOf for FunctionCx<'_, '_, 'tcx> {
258     type Ty = Ty<'tcx>;
259     type TyAndLayout = TyAndLayout<'tcx>;
260
261     fn layout_of(&self, ty: Ty<'tcx>) -> TyAndLayout<'tcx> {
262         RevealAllLayoutCx(self.tcx).layout_of(ty)
263     }
264 }
265
266 impl<'tcx> layout::HasTyCtxt<'tcx> for FunctionCx<'_, '_, 'tcx> {
267     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
268         self.tcx
269     }
270 }
271
272 impl<'tcx> rustc_target::abi::HasDataLayout for FunctionCx<'_, '_, 'tcx> {
273     fn data_layout(&self) -> &rustc_target::abi::TargetDataLayout {
274         &self.tcx.data_layout
275     }
276 }
277
278 impl<'tcx> layout::HasParamEnv<'tcx> for FunctionCx<'_, '_, 'tcx> {
279     fn param_env(&self) -> ParamEnv<'tcx> {
280         ParamEnv::reveal_all()
281     }
282 }
283
284 impl<'tcx> HasTargetSpec for FunctionCx<'_, '_, 'tcx> {
285     fn target_spec(&self) -> &Target {
286         &self.tcx.sess.target
287     }
288 }
289
290 impl<'tcx> FunctionCx<'_, '_, 'tcx> {
291     pub(crate) fn monomorphize<T>(&self, value: T) -> T
292     where
293         T: TypeFoldable<'tcx> + Copy,
294     {
295         self.instance.subst_mir_and_normalize_erasing_regions(
296             self.tcx,
297             ty::ParamEnv::reveal_all(),
298             value,
299         )
300     }
301
302     pub(crate) fn clif_type(&self, ty: Ty<'tcx>) -> Option<Type> {
303         clif_type_from_ty(self.tcx, ty)
304     }
305
306     pub(crate) fn clif_pair_type(&self, ty: Ty<'tcx>) -> Option<(Type, Type)> {
307         clif_pair_type_from_ty(self.tcx, ty)
308     }
309
310     pub(crate) fn get_block(&self, bb: BasicBlock) -> Block {
311         *self.block_map.get(bb).unwrap()
312     }
313
314     pub(crate) fn get_local_place(&mut self, local: Local) -> CPlace<'tcx> {
315         *self.local_map.get(local).unwrap_or_else(|| {
316             panic!("Local {:?} doesn't exist", local);
317         })
318     }
319
320     pub(crate) fn set_debug_loc(&mut self, source_info: mir::SourceInfo) {
321         let (index, _) = self.source_info_set.insert_full(source_info);
322         self.bcx.set_srcloc(SourceLoc::new(index as u32));
323     }
324
325     pub(crate) fn get_caller_location(&mut self, span: Span) -> CValue<'tcx> {
326         if let Some(loc) = self.caller_location {
327             // `#[track_caller]` is used; return caller location instead of current location.
328             return loc;
329         }
330
331         let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
332         let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
333         let const_loc = self.tcx.const_caller_location((
334             rustc_span::symbol::Symbol::intern(&caller.file.name.to_string()),
335             caller.line as u32,
336             caller.col_display as u32 + 1,
337         ));
338         crate::constant::codegen_const_value(self, const_loc, self.tcx.caller_location_ty())
339     }
340
341     pub(crate) fn triple(&self) -> &target_lexicon::Triple {
342         self.cx.module.isa().triple()
343     }
344
345     pub(crate) fn anonymous_str(&mut self, prefix: &str, msg: &str) -> Value {
346         use std::collections::hash_map::DefaultHasher;
347         use std::hash::{Hash, Hasher};
348
349         let mut hasher = DefaultHasher::new();
350         msg.hash(&mut hasher);
351         let msg_hash = hasher.finish();
352         let mut data_ctx = DataContext::new();
353         data_ctx.define(msg.as_bytes().to_vec().into_boxed_slice());
354         let msg_id = self
355             .cx
356             .module
357             .declare_data(&format!("__{}_{:08x}", prefix, msg_hash), Linkage::Local, false, false)
358             .unwrap();
359
360         // Ignore DuplicateDefinition error, as the data will be the same
361         let _ = self.cx.module.define_data(msg_id, &data_ctx);
362
363         let local_msg_id = self.cx.module.declare_data_in_func(msg_id, self.bcx.func);
364         if self.clif_comments.enabled() {
365             self.add_comment(local_msg_id, msg);
366         }
367         self.bcx.ins().global_value(self.pointer_type, local_msg_id)
368     }
369 }
370
371 pub(crate) struct RevealAllLayoutCx<'tcx>(pub(crate) TyCtxt<'tcx>);
372
373 impl<'tcx> LayoutOf for RevealAllLayoutCx<'tcx> {
374     type Ty = Ty<'tcx>;
375     type TyAndLayout = TyAndLayout<'tcx>;
376
377     fn layout_of(&self, ty: Ty<'tcx>) -> TyAndLayout<'tcx> {
378         assert!(!ty.still_further_specializable());
379         self.0.layout_of(ParamEnv::reveal_all().and(&ty)).unwrap_or_else(|e| {
380             if let layout::LayoutError::SizeOverflow(_) = e {
381                 self.0.sess.fatal(&e.to_string())
382             } else {
383                 bug!("failed to get layout for `{}`: {}", ty, e)
384             }
385         })
386     }
387 }
388
389 impl<'tcx> layout::HasTyCtxt<'tcx> for RevealAllLayoutCx<'tcx> {
390     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
391         self.0
392     }
393 }
394
395 impl<'tcx> rustc_target::abi::HasDataLayout for RevealAllLayoutCx<'tcx> {
396     fn data_layout(&self) -> &rustc_target::abi::TargetDataLayout {
397         &self.0.data_layout
398     }
399 }
400
401 impl<'tcx> layout::HasParamEnv<'tcx> for RevealAllLayoutCx<'tcx> {
402     fn param_env(&self) -> ParamEnv<'tcx> {
403         ParamEnv::reveal_all()
404     }
405 }
406
407 impl<'tcx> HasTargetSpec for RevealAllLayoutCx<'tcx> {
408     fn target_spec(&self) -> &Target {
409         &self.0.sess.target
410     }
411 }