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