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