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