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