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