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