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