]> git.lizzy.rs Git - rust.git/blob - src/common.rs
Rustup to rustc 1.41.0-nightly (ded5ee001 2019-11-13)
[rust.git] / src / common.rs
1 use rustc::ty::layout::{Integer, Primitive};
2 use rustc_target::spec::{HasTargetSpec, Target};
3
4 use cranelift::codegen::ir::{InstructionData, Opcode, ValueDef};
5
6 use crate::prelude::*;
7
8 pub fn mir_var(loc: Local) -> Variable {
9     Variable::with_u32(loc.index() as u32)
10 }
11
12 pub fn pointer_ty(tcx: TyCtxt) -> types::Type {
13     match tcx.data_layout.pointer_size.bits() {
14         16 => types::I16,
15         32 => types::I32,
16         64 => types::I64,
17         bits => bug!("ptr_sized_integer: unknown pointer bit size {}", bits),
18     }
19 }
20
21 pub fn scalar_to_clif_type(tcx: TyCtxt, scalar: Scalar) -> Type {
22     match scalar.value {
23         Primitive::Int(int, _sign) => match int {
24             Integer::I8 => types::I8,
25             Integer::I16 => types::I16,
26             Integer::I32 => types::I32,
27             Integer::I64 => types::I64,
28             Integer::I128 => types::I128,
29         },
30         Primitive::F32 => types::F32,
31         Primitive::F64 => types::F64,
32         Primitive::Pointer => pointer_ty(tcx),
33     }
34 }
35
36 pub fn clif_type_from_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<types::Type> {
37     Some(match ty.kind {
38         ty::Bool => types::I8,
39         ty::Uint(size) => match size {
40             UintTy::U8 => types::I8,
41             UintTy::U16 => types::I16,
42             UintTy::U32 => types::I32,
43             UintTy::U64 => types::I64,
44             UintTy::U128 => types::I128,
45             UintTy::Usize => pointer_ty(tcx),
46         },
47         ty::Int(size) => match size {
48             IntTy::I8 => types::I8,
49             IntTy::I16 => types::I16,
50             IntTy::I32 => types::I32,
51             IntTy::I64 => types::I64,
52             IntTy::I128 => types::I128,
53             IntTy::Isize => pointer_ty(tcx),
54         },
55         ty::Char => types::I32,
56         ty::Float(size) => match size {
57             FloatTy::F32 => types::F32,
58             FloatTy::F64 => types::F64,
59         },
60         ty::FnPtr(_) => pointer_ty(tcx),
61         ty::RawPtr(TypeAndMut { ty: pointee_ty, mutbl: _ }) | 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::Param(_) => bug!("ty param {:?}", ty),
69         _ => return None,
70     })
71 }
72
73 /// Is a pointer to this type a fat ptr?
74 pub fn has_ptr_meta<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
75     let ptr_ty = tcx.mk_ptr(TypeAndMut { ty, mutbl: rustc::hir::Mutability::Immutable });
76     match &tcx.layout_of(ParamEnv::reveal_all().and(ptr_ty)).unwrap().abi {
77         Abi::Scalar(_) => false,
78         Abi::ScalarPair(_, _) => true,
79         abi => unreachable!("Abi of ptr to {:?} is {:?}???", ty, abi),
80     }
81 }
82
83 pub fn codegen_select(bcx: &mut FunctionBuilder, cond: Value, lhs: Value, rhs: Value) -> Value {
84     let lhs_ty = bcx.func.dfg.value_type(lhs);
85     let rhs_ty = bcx.func.dfg.value_type(rhs);
86     assert_eq!(lhs_ty, rhs_ty);
87     if lhs_ty == types::I8 || lhs_ty == types::I16 {
88         // FIXME workaround for missing encoding for select.i8
89         let lhs = bcx.ins().uextend(types::I32, lhs);
90         let rhs = bcx.ins().uextend(types::I32, rhs);
91         let res = bcx.ins().select(cond, lhs, rhs);
92         bcx.ins().ireduce(lhs_ty, res)
93     } else {
94         bcx.ins().select(cond, lhs, rhs)
95     }
96 }
97
98 pub fn codegen_icmp(
99     fx: &mut FunctionCx<'_, '_, impl Backend>,
100     intcc: IntCC,
101     lhs: Value,
102     rhs: Value,
103 ) -> Value {
104     let lhs_ty = fx.bcx.func.dfg.value_type(lhs);
105     let rhs_ty = fx.bcx.func.dfg.value_type(rhs);
106     assert_eq!(lhs_ty, rhs_ty);
107     if lhs_ty == types::I128 {
108         // FIXME legalize `icmp.i128` in Cranelift
109
110         let (lhs_lsb, lhs_msb) = fx.bcx.ins().isplit(lhs);
111         let (rhs_lsb, rhs_msb) = fx.bcx.ins().isplit(rhs);
112
113         match intcc {
114             IntCC::Equal => {
115                 let lsb_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_lsb, rhs_lsb);
116                 let msb_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_msb, rhs_msb);
117                 fx.bcx.ins().band(lsb_eq, msb_eq)
118             }
119             IntCC::NotEqual => {
120                 let lsb_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_lsb, rhs_lsb);
121                 let msb_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_msb, rhs_msb);
122                 fx.bcx.ins().bor(lsb_ne, msb_ne)
123             }
124             _ => {
125                 // if msb_eq {
126                 //     lsb_cc
127                 // } else {
128                 //     msb_cc
129                 // }
130
131                 let msb_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_msb, rhs_msb);
132                 let lsb_cc = fx.bcx.ins().icmp(intcc, lhs_lsb, rhs_lsb);
133                 let msb_cc = fx.bcx.ins().icmp(intcc, lhs_msb, rhs_msb);
134
135                 fx.bcx.ins().select(msb_eq, lsb_cc, msb_cc)
136             }
137         }
138     } else {
139         fx.bcx.ins().icmp(intcc, lhs, rhs)
140     }
141 }
142
143 pub fn codegen_icmp_imm(
144     fx: &mut FunctionCx<'_, '_, impl Backend>,
145     intcc: IntCC,
146     lhs: Value,
147     rhs: i128,
148 ) -> Value {
149     let lhs_ty = fx.bcx.func.dfg.value_type(lhs);
150     if lhs_ty == types::I128 {
151         // FIXME legalize `icmp_imm.i128` in Cranelift
152
153         let (lhs_lsb, lhs_msb) = fx.bcx.ins().isplit(lhs);
154         let (rhs_lsb, rhs_msb) = (rhs as u128 as u64 as i64, (rhs as u128 >> 64) as u64 as i64);
155
156         match intcc {
157             IntCC::Equal => {
158                 let lsb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_lsb, rhs_lsb);
159                 let msb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_msb, rhs_msb);
160                 fx.bcx.ins().band(lsb_eq, msb_eq)
161             }
162             IntCC::NotEqual => {
163                 let lsb_ne = fx.bcx.ins().icmp_imm(IntCC::NotEqual, lhs_lsb, rhs_lsb);
164                 let msb_ne = fx.bcx.ins().icmp_imm(IntCC::NotEqual, lhs_msb, rhs_msb);
165                 fx.bcx.ins().bor(lsb_ne, msb_ne)
166             }
167             _ => {
168                 // if msb_eq {
169                 //     lsb_cc
170                 // } else {
171                 //     msb_cc
172                 // }
173
174                 let msb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_msb, rhs_msb);
175                 let lsb_cc = fx.bcx.ins().icmp_imm(intcc, lhs_lsb, rhs_lsb);
176                 let msb_cc = fx.bcx.ins().icmp_imm(intcc, lhs_msb, rhs_msb);
177
178                 fx.bcx.ins().select(msb_eq, lsb_cc, msb_cc)
179             }
180         }
181     } else {
182         let rhs = i64::try_from(rhs).expect("codegen_icmp_imm rhs out of range for <128bit int");
183         fx.bcx.ins().icmp_imm(intcc, lhs, rhs)
184     }
185 }
186
187 fn resolve_normal_value_imm(func: &Function, val: Value) -> Option<i64> {
188     if let ValueDef::Result(inst, 0 /*param*/) = func.dfg.value_def(val) {
189         if let InstructionData::UnaryImm {
190             opcode: Opcode::Iconst,
191             imm,
192         } = func.dfg[inst]
193         {
194             Some(imm.into())
195         } else {
196             None
197         }
198     } else {
199         None
200     }
201 }
202
203 fn resolve_128bit_value_imm(func: &Function, val: Value) -> Option<u128> {
204     let (lsb, msb) = if let ValueDef::Result(inst, 0 /*param*/) = func.dfg.value_def(val) {
205         if let InstructionData::Binary {
206             opcode: Opcode::Iconcat,
207             args: [lsb, msb],
208         } = func.dfg[inst]
209         {
210             (lsb, msb)
211         } else {
212             return None;
213         }
214     } else {
215         return None;
216     };
217
218     let lsb = resolve_normal_value_imm(func, lsb)? as u64 as u128;
219     let msb = resolve_normal_value_imm(func, msb)? as u64 as u128;
220
221     Some(msb << 64 | lsb)
222 }
223
224 pub fn resolve_value_imm(func: &Function, val: Value) -> Option<u128> {
225     if func.dfg.value_type(val) == types::I128 {
226         resolve_128bit_value_imm(func, val)
227     } else {
228         resolve_normal_value_imm(func, val).map(|imm| imm as u64 as u128)
229     }
230 }
231
232 pub fn type_min_max_value(ty: Type, signed: bool) -> (i64, i64) {
233     assert!(ty.is_int());
234     let min = match (ty, signed) {
235         (types::I8, false) | (types::I16, false) | (types::I32, false) | (types::I64, false) => {
236             0i64
237         }
238         (types::I8, true) => i8::min_value() as i64,
239         (types::I16, true) => i16::min_value() as i64,
240         (types::I32, true) => i32::min_value() as i64,
241         (types::I64, true) => i64::min_value(),
242         (types::I128, _) => unimplemented!(),
243         _ => unreachable!(),
244     };
245
246     let max = match (ty, signed) {
247         (types::I8, false) => u8::max_value() as i64,
248         (types::I16, false) => u16::max_value() as i64,
249         (types::I32, false) => u32::max_value() as i64,
250         (types::I64, false) => u64::max_value() as i64,
251         (types::I8, true) => i8::max_value() as i64,
252         (types::I16, true) => i16::max_value() as i64,
253         (types::I32, true) => i32::max_value() as i64,
254         (types::I64, true) => i64::max_value(),
255         (types::I128, _) => unimplemented!(),
256         _ => unreachable!(),
257     };
258
259     (min, max)
260 }
261
262 pub fn type_sign(ty: Ty<'_>) -> bool {
263     match ty.kind {
264         ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
265         ty::Int(..) => true,
266         ty::Float(..) => false, // `signed` is unused for floats
267         _ => panic!("{}", ty),
268     }
269 }
270
271 pub struct FunctionCx<'clif, 'tcx, B: Backend + 'static> {
272     // FIXME use a reference to `CodegenCx` instead of `tcx`, `module` and `constants` and `caches`
273     pub tcx: TyCtxt<'tcx>,
274     pub module: &'clif mut Module<B>,
275     pub pointer_type: Type, // Cached from module
276
277     pub instance: Instance<'tcx>,
278     pub mir: &'tcx Body<'tcx>,
279
280     pub bcx: FunctionBuilder<'clif>,
281     pub ebb_map: HashMap<BasicBlock, Ebb>,
282     pub local_map: HashMap<Local, CPlace<'tcx>>,
283
284     pub clif_comments: crate::pretty_clif::CommentWriter,
285     pub constants_cx: &'clif mut crate::constant::ConstantCx,
286     pub caches: &'clif mut Caches<'tcx>,
287
288     // FIXME switch back to `SourceInfo`, once it derives `Eq` and `Hash` again.
289     pub source_info_set: indexmap::IndexSet<(Span, mir::SourceScope)>,
290 }
291
292 impl<'tcx, B: Backend> LayoutOf for FunctionCx<'_, 'tcx, B> {
293     type Ty = Ty<'tcx>;
294     type TyLayout = TyLayout<'tcx>;
295
296     fn layout_of(&self, ty: Ty<'tcx>) -> TyLayout<'tcx> {
297         let ty = self.monomorphize(&ty);
298         self.tcx
299             .layout_of(ParamEnv::reveal_all().and(&ty))
300             .unwrap_or_else(|e| {
301                 if let layout::LayoutError::SizeOverflow(_) = e {
302                     self.tcx.sess.fatal(&e.to_string())
303                 } else {
304                     bug!("failed to get layout for `{}`: {}", ty, e)
305                 }
306             })
307     }
308 }
309
310 impl<'tcx, B: Backend + 'static> layout::HasTyCtxt<'tcx> for FunctionCx<'_, 'tcx, B> {
311     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
312         self.tcx
313     }
314 }
315
316 impl<'tcx, B: Backend + 'static> layout::HasDataLayout for FunctionCx<'_, 'tcx, B> {
317     fn data_layout(&self) -> &layout::TargetDataLayout {
318         &self.tcx.data_layout
319     }
320 }
321
322 impl<'tcx, B: Backend + 'static> layout::HasParamEnv<'tcx> for FunctionCx<'_, 'tcx, B> {
323     fn param_env(&self) -> ParamEnv<'tcx> {
324         ParamEnv::reveal_all()
325     }
326 }
327
328 impl<'tcx, B: Backend + 'static> HasTargetSpec for FunctionCx<'_, 'tcx, B> {
329     fn target_spec(&self) -> &Target {
330         &self.tcx.sess.target.target
331     }
332 }
333
334 impl<'tcx, B: Backend> BackendTypes for FunctionCx<'_, 'tcx, B> {
335     type Value = Value;
336     type Function = Value;
337     type BasicBlock = Ebb;
338     type Type = Type;
339     type Funclet = !;
340     type DIScope = !;
341 }
342
343 impl<'tcx, B: Backend + 'static> FunctionCx<'_, 'tcx, B> {
344     pub fn monomorphize<T>(&self, value: &T) -> T
345     where
346         T: TypeFoldable<'tcx>,
347     {
348         self.tcx.subst_and_normalize_erasing_regions(
349             self.instance.substs,
350             ty::ParamEnv::reveal_all(),
351             value,
352         )
353     }
354
355     pub fn clif_type(&self, ty: Ty<'tcx>) -> Option<Type> {
356         clif_type_from_ty(self.tcx, self.monomorphize(&ty))
357     }
358
359     pub fn get_ebb(&self, bb: BasicBlock) -> Ebb {
360         *self.ebb_map.get(&bb).unwrap()
361     }
362
363     pub fn get_local_place(&mut self, local: Local) -> CPlace<'tcx> {
364         *self.local_map.get(&local).unwrap()
365     }
366
367     pub fn set_debug_loc(&mut self, source_info: mir::SourceInfo) {
368         let (index, _) = self.source_info_set.insert_full((source_info.span, source_info.scope));
369         self.bcx.set_srcloc(SourceLoc::new(index as u32));
370     }
371
372     pub fn get_caller_location(&mut self, span: Span) -> CValue<'tcx> {
373         let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
374         let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
375         let const_loc = self.tcx.const_caller_location((
376             syntax::symbol::Symbol::intern(&caller.file.name.to_string()),
377             caller.line as u32,
378             caller.col_display as u32 + 1,
379         ));
380         crate::constant::trans_const_value(self, const_loc)
381     }
382 }