]> git.lizzy.rs Git - rust.git/blob - src/common.rs
Remove some workarounds for missing inst legalizations
[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_icmp(
84     fx: &mut FunctionCx<'_, '_, impl Backend>,
85     intcc: IntCC,
86     lhs: Value,
87     rhs: Value,
88 ) -> Value {
89     let lhs_ty = fx.bcx.func.dfg.value_type(lhs);
90     let rhs_ty = fx.bcx.func.dfg.value_type(rhs);
91     assert_eq!(lhs_ty, rhs_ty);
92     if lhs_ty == types::I128 {
93         // FIXME legalize `icmp.i128` in Cranelift
94
95         let (lhs_lsb, lhs_msb) = fx.bcx.ins().isplit(lhs);
96         let (rhs_lsb, rhs_msb) = fx.bcx.ins().isplit(rhs);
97
98         match intcc {
99             IntCC::Equal => {
100                 let lsb_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_lsb, rhs_lsb);
101                 let msb_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_msb, rhs_msb);
102                 fx.bcx.ins().band(lsb_eq, msb_eq)
103             }
104             IntCC::NotEqual => {
105                 let lsb_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_lsb, rhs_lsb);
106                 let msb_ne = fx.bcx.ins().icmp(IntCC::NotEqual, lhs_msb, rhs_msb);
107                 fx.bcx.ins().bor(lsb_ne, msb_ne)
108             }
109             _ => {
110                 // if msb_eq {
111                 //     lsb_cc
112                 // } else {
113                 //     msb_cc
114                 // }
115
116                 let msb_eq = fx.bcx.ins().icmp(IntCC::Equal, lhs_msb, rhs_msb);
117                 let lsb_cc = fx.bcx.ins().icmp(intcc, lhs_lsb, rhs_lsb);
118                 let msb_cc = fx.bcx.ins().icmp(intcc, lhs_msb, rhs_msb);
119
120                 fx.bcx.ins().select(msb_eq, lsb_cc, msb_cc)
121             }
122         }
123     } else {
124         fx.bcx.ins().icmp(intcc, lhs, rhs)
125     }
126 }
127
128 pub fn codegen_icmp_imm(
129     fx: &mut FunctionCx<'_, '_, impl Backend>,
130     intcc: IntCC,
131     lhs: Value,
132     rhs: i128,
133 ) -> Value {
134     let lhs_ty = fx.bcx.func.dfg.value_type(lhs);
135     if lhs_ty == types::I128 {
136         // FIXME legalize `icmp_imm.i128` in Cranelift
137
138         let (lhs_lsb, lhs_msb) = fx.bcx.ins().isplit(lhs);
139         let (rhs_lsb, rhs_msb) = (rhs as u128 as u64 as i64, (rhs as u128 >> 64) as u64 as i64);
140
141         match intcc {
142             IntCC::Equal => {
143                 let lsb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_lsb, rhs_lsb);
144                 let msb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_msb, rhs_msb);
145                 fx.bcx.ins().band(lsb_eq, msb_eq)
146             }
147             IntCC::NotEqual => {
148                 let lsb_ne = fx.bcx.ins().icmp_imm(IntCC::NotEqual, lhs_lsb, rhs_lsb);
149                 let msb_ne = fx.bcx.ins().icmp_imm(IntCC::NotEqual, lhs_msb, rhs_msb);
150                 fx.bcx.ins().bor(lsb_ne, msb_ne)
151             }
152             _ => {
153                 // if msb_eq {
154                 //     lsb_cc
155                 // } else {
156                 //     msb_cc
157                 // }
158
159                 let msb_eq = fx.bcx.ins().icmp_imm(IntCC::Equal, lhs_msb, rhs_msb);
160                 let lsb_cc = fx.bcx.ins().icmp_imm(intcc, lhs_lsb, rhs_lsb);
161                 let msb_cc = fx.bcx.ins().icmp_imm(intcc, lhs_msb, rhs_msb);
162
163                 fx.bcx.ins().select(msb_eq, lsb_cc, msb_cc)
164             }
165         }
166     } else {
167         let rhs = i64::try_from(rhs).expect("codegen_icmp_imm rhs out of range for <128bit int");
168         fx.bcx.ins().icmp_imm(intcc, lhs, rhs)
169     }
170 }
171
172 fn resolve_normal_value_imm(func: &Function, val: Value) -> Option<i64> {
173     if let ValueDef::Result(inst, 0 /*param*/) = func.dfg.value_def(val) {
174         if let InstructionData::UnaryImm {
175             opcode: Opcode::Iconst,
176             imm,
177         } = func.dfg[inst]
178         {
179             Some(imm.into())
180         } else {
181             None
182         }
183     } else {
184         None
185     }
186 }
187
188 fn resolve_128bit_value_imm(func: &Function, val: Value) -> Option<u128> {
189     let (lsb, msb) = if let ValueDef::Result(inst, 0 /*param*/) = func.dfg.value_def(val) {
190         if let InstructionData::Binary {
191             opcode: Opcode::Iconcat,
192             args: [lsb, msb],
193         } = func.dfg[inst]
194         {
195             (lsb, msb)
196         } else {
197             return None;
198         }
199     } else {
200         return None;
201     };
202
203     let lsb = resolve_normal_value_imm(func, lsb)? as u64 as u128;
204     let msb = resolve_normal_value_imm(func, msb)? as u64 as u128;
205
206     Some(msb << 64 | lsb)
207 }
208
209 pub fn resolve_value_imm(func: &Function, val: Value) -> Option<u128> {
210     if func.dfg.value_type(val) == types::I128 {
211         resolve_128bit_value_imm(func, val)
212     } else {
213         resolve_normal_value_imm(func, val).map(|imm| imm as u64 as u128)
214     }
215 }
216
217 pub fn type_min_max_value(ty: Type, signed: bool) -> (i64, i64) {
218     assert!(ty.is_int());
219     let min = match (ty, signed) {
220         (types::I8, false) | (types::I16, false) | (types::I32, false) | (types::I64, false) => {
221             0i64
222         }
223         (types::I8, true) => i8::min_value() as i64,
224         (types::I16, true) => i16::min_value() as i64,
225         (types::I32, true) => i32::min_value() as i64,
226         (types::I64, true) => i64::min_value(),
227         (types::I128, _) => unimplemented!(),
228         _ => unreachable!(),
229     };
230
231     let max = match (ty, signed) {
232         (types::I8, false) => u8::max_value() as i64,
233         (types::I16, false) => u16::max_value() as i64,
234         (types::I32, false) => u32::max_value() as i64,
235         (types::I64, false) => u64::max_value() as i64,
236         (types::I8, true) => i8::max_value() as i64,
237         (types::I16, true) => i16::max_value() as i64,
238         (types::I32, true) => i32::max_value() as i64,
239         (types::I64, true) => i64::max_value(),
240         (types::I128, _) => unimplemented!(),
241         _ => unreachable!(),
242     };
243
244     (min, max)
245 }
246
247 pub fn type_sign(ty: Ty<'_>) -> bool {
248     match ty.kind {
249         ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Char | ty::Uint(..) | ty::Bool => false,
250         ty::Int(..) => true,
251         ty::Float(..) => false, // `signed` is unused for floats
252         _ => panic!("{}", ty),
253     }
254 }
255
256 pub struct FunctionCx<'clif, 'tcx, B: Backend + 'static> {
257     // FIXME use a reference to `CodegenCx` instead of `tcx`, `module` and `constants` and `caches`
258     pub tcx: TyCtxt<'tcx>,
259     pub module: &'clif mut Module<B>,
260     pub pointer_type: Type, // Cached from module
261
262     pub instance: Instance<'tcx>,
263     pub mir: &'tcx Body<'tcx>,
264
265     pub bcx: FunctionBuilder<'clif>,
266     pub ebb_map: HashMap<BasicBlock, Ebb>,
267     pub local_map: HashMap<Local, CPlace<'tcx>>,
268
269     pub clif_comments: crate::pretty_clif::CommentWriter,
270     pub constants_cx: &'clif mut crate::constant::ConstantCx,
271     pub caches: &'clif mut Caches<'tcx>,
272
273     // FIXME switch back to `SourceInfo`, once it derives `Eq` and `Hash` again.
274     pub source_info_set: indexmap::IndexSet<(Span, mir::SourceScope)>,
275 }
276
277 impl<'tcx, B: Backend> LayoutOf for FunctionCx<'_, 'tcx, B> {
278     type Ty = Ty<'tcx>;
279     type TyLayout = TyLayout<'tcx>;
280
281     fn layout_of(&self, ty: Ty<'tcx>) -> TyLayout<'tcx> {
282         let ty = self.monomorphize(&ty);
283         self.tcx
284             .layout_of(ParamEnv::reveal_all().and(&ty))
285             .unwrap_or_else(|e| {
286                 if let layout::LayoutError::SizeOverflow(_) = e {
287                     self.tcx.sess.fatal(&e.to_string())
288                 } else {
289                     bug!("failed to get layout for `{}`: {}", ty, e)
290                 }
291             })
292     }
293 }
294
295 impl<'tcx, B: Backend + 'static> layout::HasTyCtxt<'tcx> for FunctionCx<'_, 'tcx, B> {
296     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
297         self.tcx
298     }
299 }
300
301 impl<'tcx, B: Backend + 'static> layout::HasDataLayout for FunctionCx<'_, 'tcx, B> {
302     fn data_layout(&self) -> &layout::TargetDataLayout {
303         &self.tcx.data_layout
304     }
305 }
306
307 impl<'tcx, B: Backend + 'static> layout::HasParamEnv<'tcx> for FunctionCx<'_, 'tcx, B> {
308     fn param_env(&self) -> ParamEnv<'tcx> {
309         ParamEnv::reveal_all()
310     }
311 }
312
313 impl<'tcx, B: Backend + 'static> HasTargetSpec for FunctionCx<'_, 'tcx, B> {
314     fn target_spec(&self) -> &Target {
315         &self.tcx.sess.target.target
316     }
317 }
318
319 impl<'tcx, B: Backend> BackendTypes for FunctionCx<'_, 'tcx, B> {
320     type Value = Value;
321     type Function = Value;
322     type BasicBlock = Ebb;
323     type Type = Type;
324     type Funclet = !;
325     type DIScope = !;
326 }
327
328 impl<'tcx, B: Backend + 'static> FunctionCx<'_, 'tcx, B> {
329     pub fn monomorphize<T>(&self, value: &T) -> T
330     where
331         T: TypeFoldable<'tcx>,
332     {
333         self.tcx.subst_and_normalize_erasing_regions(
334             self.instance.substs,
335             ty::ParamEnv::reveal_all(),
336             value,
337         )
338     }
339
340     pub fn clif_type(&self, ty: Ty<'tcx>) -> Option<Type> {
341         clif_type_from_ty(self.tcx, self.monomorphize(&ty))
342     }
343
344     pub fn get_ebb(&self, bb: BasicBlock) -> Ebb {
345         *self.ebb_map.get(&bb).unwrap()
346     }
347
348     pub fn get_local_place(&mut self, local: Local) -> CPlace<'tcx> {
349         *self.local_map.get(&local).unwrap()
350     }
351
352     pub fn set_debug_loc(&mut self, source_info: mir::SourceInfo) {
353         let (index, _) = self.source_info_set.insert_full((source_info.span, source_info.scope));
354         self.bcx.set_srcloc(SourceLoc::new(index as u32));
355     }
356
357     pub fn get_caller_location(&mut self, span: Span) -> CValue<'tcx> {
358         let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
359         let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
360         let const_loc = self.tcx.const_caller_location((
361             syntax::symbol::Symbol::intern(&caller.file.name.to_string()),
362             caller.line as u32,
363             caller.col_display as u32 + 1,
364         ));
365         crate::constant::trans_const_value(self, const_loc)
366     }
367 }