3 use rustc_target::spec::{HasTargetSpec, Target};
5 use cranelift_module::Module;
9 pub fn mir_var(loc: Local) -> Variable {
10 Variable::with_u32(loc.index() as u32)
13 pub fn pointer_ty(tcx: TyCtxt) -> types::Type {
14 match tcx.data_layout.pointer_size.bits() {
18 bits => bug!("ptr_sized_integer: unknown pointer bit size {}", bits),
22 fn scalar_to_clif_type(tcx: TyCtxt, scalar: &Scalar) -> Type {
23 match scalar.value.size(&tcx).bits() {
28 size => bug!("Unsupported scalar size {}", size),
32 pub fn clif_type_from_ty<'a, 'tcx: 'a>(
33 tcx: TyCtxt<'a, 'tcx, 'tcx>,
35 ) -> Option<types::Type> {
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 => unimpl!("u128"),
44 UintTy::Usize => pointer_ty(tcx),
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 => unimpl!("i128"),
52 IntTy::Isize => pointer_ty(tcx),
54 ty::Char => types::I32,
55 ty::Float(size) => match size {
56 FloatTy::F32 => types::F32,
57 FloatTy::F64 => types::F64,
59 ty::FnPtr(_) => pointer_ty(tcx),
60 ty::RawPtr(TypeAndMut { ty, mutbl: _ }) | ty::Ref(_, ty, _) => {
61 if ty.is_sized(tcx.at(DUMMY_SP), ParamEnv::reveal_all()) {
67 ty::Param(_) => bug!("{:?}: {:?}", ty, ty.sty),
72 pub fn codegen_select(bcx: &mut FunctionBuilder, cond: Value, lhs: Value, rhs: Value) -> Value {
73 let lhs_ty = bcx.func.dfg.value_type(lhs);
74 let rhs_ty = bcx.func.dfg.value_type(rhs);
75 assert_eq!(lhs_ty, rhs_ty);
76 if lhs_ty == types::I8 || lhs_ty == types::I16 {
77 // FIXME workaround for missing enocding for select.i8
78 let lhs = bcx.ins().uextend(types::I32, lhs);
79 let rhs = bcx.ins().uextend(types::I32, rhs);
80 let res = bcx.ins().select(cond, lhs, rhs);
81 bcx.ins().ireduce(lhs_ty, res)
83 bcx.ins().select(cond, lhs, rhs)
87 fn codegen_field<'a, 'tcx: 'a>(
88 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
90 layout: TyLayout<'tcx>,
92 ) -> (Value, TyLayout<'tcx>) {
93 let field_offset = layout.fields.offset(field.index());
94 let field_ty = layout.field(&*fx, field.index());
95 if field_offset.bytes() > 0 {
97 fx.bcx.ins().iadd_imm(base, field_offset.bytes() as i64),
105 /// A read-only value
106 #[derive(Debug, Copy, Clone)]
107 pub enum CValue<'tcx> {
108 ByRef(Value, TyLayout<'tcx>),
109 ByVal(Value, TyLayout<'tcx>),
110 ByValPair(Value, Value, TyLayout<'tcx>),
113 impl<'tcx> CValue<'tcx> {
114 pub fn layout(&self) -> TyLayout<'tcx> {
116 CValue::ByRef(_, layout)
117 | CValue::ByVal(_, layout)
118 | CValue::ByValPair(_, _, layout) => layout,
122 pub fn force_stack<'a>(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> Value
127 CValue::ByRef(value, _layout) => value,
128 CValue::ByVal(value, layout) => {
129 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
130 kind: StackSlotKind::ExplicitSlot,
131 size: layout.size.bytes() as u32,
134 let addr = fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0);
135 fx.bcx.ins().store(MemFlags::new(), value, addr, 0);
138 CValue::ByValPair(value, extra, layout) => {
139 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
140 kind: StackSlotKind::ExplicitSlot,
141 size: layout.size.bytes() as u32,
144 let base = fx.bcx.ins().stack_addr(types::I64, stack_slot, 0);
145 let a_addr = codegen_field(fx, base, layout, mir::Field::new(0)).0;
146 let b_addr = codegen_field(fx, base, layout, mir::Field::new(1)).0;
147 fx.bcx.ins().store(MemFlags::new(), value, a_addr, 0);
148 fx.bcx.ins().store(MemFlags::new(), extra, b_addr, 0);
154 /// Load a value with layout.abi of scalar
155 pub fn load_scalar<'a>(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> Value
160 CValue::ByRef(addr, layout) => {
161 let scalar = match layout.abi {
162 layout::Abi::Scalar(ref scalar) => scalar.clone(),
165 let clif_ty = crate::abi::scalar_to_clif_type(fx.tcx, scalar);
166 fx.bcx.ins().load(clif_ty, MemFlags::new(), addr, 0)
168 CValue::ByVal(value, _layout) => value,
169 CValue::ByValPair(_, _, _layout) => bug!("Please use load_scalar_pair for ByValPair"),
173 /// Load a value pair with layout.abi of scalar pair
174 pub fn load_scalar_pair<'a>(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> (Value, Value)
179 CValue::ByRef(addr, layout) => {
180 let (a, b) = match &layout.abi {
181 layout::Abi::ScalarPair(a, b) => (a.clone(), b.clone()),
184 let clif_ty1 = crate::abi::scalar_to_clif_type(fx.tcx, a.clone());
185 let clif_ty2 = crate::abi::scalar_to_clif_type(fx.tcx, b);
186 let val1 = fx.bcx.ins().load(clif_ty1, MemFlags::new(), addr, 0);
187 let val2 = fx.bcx.ins().load(
191 a.value.size(&fx.tcx).bytes() as i32,
195 CValue::ByVal(_, _layout) => bug!("Please use load_scalar for ByVal"),
196 CValue::ByValPair(val1, val2, _layout) => (val1, val2),
200 pub fn value_field<'a>(
202 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
208 let (base, layout) = match self {
209 CValue::ByRef(addr, layout) => (addr, layout),
210 _ => bug!("place_field for {:?}", self),
213 let (field_ptr, field_layout) = codegen_field(fx, base, layout, field);
214 CValue::ByRef(field_ptr, field_layout)
217 pub fn unsize_value<'a>(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>, dest: CPlace<'tcx>) {
218 crate::unsize::coerce_unsized_into(fx, self, dest);
221 pub fn const_val<'a>(
222 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
229 let clif_ty = fx.clif_type(ty).unwrap();
230 let layout = fx.layout_of(ty);
231 CValue::ByVal(fx.bcx.ins().iconst(clif_ty, const_val), layout)
234 pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
236 CValue::ByRef(addr, _) => CValue::ByRef(addr, layout),
237 CValue::ByVal(val, _) => CValue::ByVal(val, layout),
238 CValue::ByValPair(val, extra, _) => CValue::ByValPair(val, extra, layout),
243 /// A place where you can write a value to or read a value from
244 #[derive(Debug, Copy, Clone)]
245 pub enum CPlace<'tcx> {
246 Var(Local, TyLayout<'tcx>),
247 Addr(Value, Option<Value>, TyLayout<'tcx>),
248 Stack(StackSlot, TyLayout<'tcx>),
249 NoPlace(TyLayout<'tcx>),
252 impl<'a, 'tcx: 'a> CPlace<'tcx> {
253 pub fn layout(&self) -> TyLayout<'tcx> {
255 CPlace::Var(_, layout)
256 | CPlace::Addr(_, _, layout)
257 | CPlace::Stack(_, layout)
258 | CPlace::NoPlace(layout) => layout,
262 pub fn new_stack_slot(
263 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
266 let layout = fx.layout_of(ty);
267 assert!(!layout.is_unsized());
268 if layout.size.bytes() == 0 {
269 return CPlace::NoPlace(layout);
272 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
273 kind: StackSlotKind::ExplicitSlot,
274 size: layout.size.bytes() as u32,
277 CPlace::Stack(stack_slot, layout)
280 pub fn to_cvalue(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> CValue<'tcx> {
282 CPlace::Var(var, layout) => CValue::ByVal(fx.bcx.use_var(mir_var(var)), layout),
283 CPlace::Addr(addr, extra, layout) => {
284 assert!(extra.is_none(), "unsized values are not yet supported");
285 CValue::ByRef(addr, layout)
287 CPlace::Stack(stack_slot, layout) => CValue::ByRef(
288 fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0),
291 CPlace::NoPlace(layout) => CValue::ByRef(
294 .iconst(fx.pointer_type, fx.pointer_type.bytes() as i64),
300 pub fn to_addr(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> Value {
301 match self.to_addr_maybe_unsized(fx) {
302 (addr, None) => addr,
303 (_, Some(_)) => bug!("Expected sized cplace, found {:?}", self),
307 pub fn to_addr_maybe_unsized(
309 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
310 ) -> (Value, Option<Value>) {
312 CPlace::Addr(addr, extra, _layout) => (addr, extra),
313 CPlace::Stack(stack_slot, _layout) => (
314 fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0),
317 CPlace::NoPlace(_) => (fx.bcx.ins().iconst(fx.pointer_type, 45), None),
318 CPlace::Var(_, _) => bug!("Expected CPlace::Addr, found CPlace::Var"),
322 pub fn write_cvalue(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>, from: CValue<'tcx>) {
323 use rustc::hir::Mutability::*;
325 let from_ty = from.layout().ty;
326 let to_ty = self.layout().ty;
328 fn assert_assignable<'a, 'tcx: 'a>(fx: &FunctionCx<'a, 'tcx, impl Backend>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) {
329 match (&from_ty.sty, &to_ty.sty) {
330 (ty::Ref(_, t, MutImmutable), ty::Ref(_, u, MutImmutable))
331 | (ty::Ref(_, t, MutMutable), ty::Ref(_, u, MutImmutable))
332 | (ty::Ref(_, t, MutMutable), ty::Ref(_, u, MutMutable)) => {
333 assert_assignable(fx, t, u);
334 // &mut T -> &T is allowed
335 // &'a T -> &'b T is allowed
337 (ty::Ref(_, _, MutImmutable), ty::Ref(_, _, MutMutable)) => {
338 panic!("Cant assign value of type {} to place of type {}", from_ty.sty, to_ty.sty)
340 (ty::FnPtr(_), ty::FnPtr(_)) => {
341 let from_sig = fx.tcx.normalize_erasing_late_bound_regions(
342 ParamEnv::reveal_all(),
343 &from_ty.fn_sig(fx.tcx),
345 let to_sig = fx.tcx.normalize_erasing_late_bound_regions(
346 ParamEnv::reveal_all(),
347 &to_ty.fn_sig(fx.tcx),
351 "Can't write fn ptr with incompatible sig {:?} to place with sig {:?}\n\n{:#?}",
352 from_sig, to_sig, fx,
354 // fn(&T) -> for<'l> fn(&'l T) is allowed
356 (ty::Dynamic(from_traits, _), ty::Dynamic(to_traits, _)) => {
357 let from_traits = fx.tcx.normalize_erasing_late_bound_regions(
358 ParamEnv::reveal_all(),
361 let to_traits = fx.tcx.normalize_erasing_late_bound_regions(
362 ParamEnv::reveal_all(),
366 from_traits, to_traits,
367 "Can't write trait object of incompatible traits {:?} to place with traits {:?}\n\n{:#?}",
368 from_traits, to_traits, fx,
370 // dyn for<'r> Trait<'r> -> dyn Trait<'_> is allowed
376 "Can't write value with incompatible type {:?} to place with type {:?}\n\n{:#?}",
385 assert_assignable(fx, from_ty, to_ty);
387 let (addr, dst_layout) = match self {
388 CPlace::Var(var, _) => {
389 let data = from.load_scalar(fx);
390 fx.bcx.def_var(mir_var(var), data);
393 CPlace::Addr(addr, None, dst_layout) => (addr, dst_layout),
394 CPlace::Stack(stack_slot, dst_layout) => (
395 fx.bcx.ins().stack_addr(fx.pointer_type, stack_slot, 0),
398 CPlace::NoPlace(layout) => {
399 assert!(layout.size.bytes() == 0);
400 assert!(from.layout().size.bytes() == 0);
403 CPlace::Addr(_, _, _) => bug!("Can't write value to unsized place {:?}", self),
407 CValue::ByVal(val, _src_layout) => {
408 fx.bcx.ins().store(MemFlags::new(), val, addr, 0);
410 CValue::ByValPair(val1, val2, _src_layout) => {
411 let val1_offset = dst_layout.fields.offset(0).bytes() as i32;
412 let val2_offset = dst_layout.fields.offset(1).bytes() as i32;
413 fx.bcx.ins().store(MemFlags::new(), val1, addr, val1_offset);
414 fx.bcx.ins().store(MemFlags::new(), val2, addr, val2_offset);
416 CValue::ByRef(from, src_layout) => {
417 let size = dst_layout.size.bytes();
418 let src_align = src_layout.align.abi.bytes() as u8;
419 let dst_align = dst_layout.align.abi.bytes() as u8;
420 fx.bcx.emit_small_memcpy(
421 fx.module.target_config(),
434 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
437 let layout = self.layout();
438 let (base, extra) = self.to_addr_maybe_unsized(fx);
440 let (field_ptr, field_layout) = codegen_field(fx, base, layout, field);
441 let extra = if field_layout.is_unsized() {
442 assert!(extra.is_some());
447 CPlace::Addr(field_ptr, extra, field_layout)
452 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
455 let (elem_layout, addr) = match self.layout().ty.sty {
456 ty::Array(elem_ty, _) => (fx.layout_of(elem_ty), self.to_addr(fx)),
457 ty::Slice(elem_ty) => (fx.layout_of(elem_ty), self.to_addr_maybe_unsized(fx).0),
458 _ => bug!("place_index({:?})", self.layout().ty),
464 .imul_imm(index, elem_layout.size.bytes() as i64);
466 CPlace::Addr(fx.bcx.ins().iadd(addr, offset), None, elem_layout)
469 pub fn place_deref(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>) -> CPlace<'tcx> {
470 let inner_layout = fx.layout_of(self.layout().ty.builtin_deref(true).unwrap().ty);
471 if !inner_layout.is_unsized() {
472 CPlace::Addr(self.to_cvalue(fx).load_scalar(fx), None, inner_layout)
474 match self.layout().abi {
475 Abi::ScalarPair(ref a, ref b) => {
476 let addr = self.to_addr(fx);
480 .load(scalar_to_clif_type(fx.tcx, a), MemFlags::new(), addr, 0);
481 let extra = fx.bcx.ins().load(
482 scalar_to_clif_type(fx.tcx, b),
485 a.value.size(&fx.tcx).bytes() as u32 as i32,
487 CPlace::Addr(ptr, Some(extra), inner_layout)
490 "Fat ptr doesn't have abi ScalarPair, but it has {:?}",
497 pub fn write_place_ref(self, fx: &mut FunctionCx<'a, 'tcx, impl Backend>, dest: CPlace<'tcx>) {
498 if !self.layout().is_unsized() {
499 let ptr = CValue::ByVal(self.to_addr(fx), dest.layout());
500 dest.write_cvalue(fx, ptr);
502 let (value, extra) = self.to_addr_maybe_unsized(fx);
504 match dest.layout().abi {
505 Abi::ScalarPair(ref a, _) => {
506 let dest_addr = dest.to_addr(fx);
507 fx.bcx.ins().store(MemFlags::new(), value, dest_addr, 0);
510 extra.expect("unsized type without metadata"),
512 a.value.size(&fx.tcx).bytes() as u32 as i32,
516 "Non ScalarPair abi {:?} in write_place_ref dest",
523 pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
524 assert!(!self.layout().is_unsized());
526 CPlace::Var(var, _) => CPlace::Var(var, layout),
527 CPlace::Addr(addr, extra, _) => CPlace::Addr(addr, extra, layout),
528 CPlace::Stack(stack_slot, _) => CPlace::Stack(stack_slot, layout),
529 CPlace::NoPlace(_) => {
530 assert!(layout.size.bytes() == 0);
531 CPlace::NoPlace(layout)
536 pub fn downcast_variant(
538 fx: &FunctionCx<'a, 'tcx, impl Backend>,
541 let layout = self.layout().for_variant(fx, variant);
542 self.unchecked_cast_to(layout)
546 pub fn clif_intcast<'a, 'tcx: 'a>(
547 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
552 let from = fx.bcx.func.dfg.value_type(val);
556 if to.wider_or_equal(from) {
558 fx.bcx.ins().sextend(to, val)
560 fx.bcx.ins().uextend(to, val)
563 fx.bcx.ins().ireduce(to, val)
567 pub struct FunctionCx<'a, 'tcx: 'a, B: Backend> {
568 // FIXME use a reference to `CodegenCx` instead of `tcx`, `module` and `constants` and `caches`
569 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
570 pub module: &'a mut Module<B>,
571 pub pointer_type: Type, // Cached from module
573 pub instance: Instance<'tcx>,
574 pub mir: &'tcx Mir<'tcx>,
576 pub bcx: FunctionBuilder<'a>,
577 pub ebb_map: HashMap<BasicBlock, Ebb>,
578 pub local_map: HashMap<Local, CPlace<'tcx>>,
580 pub clif_comments: crate::pretty_clif::CommentWriter,
581 pub constants: &'a mut crate::constant::ConstantCx,
582 pub caches: &'a mut Caches<'tcx>,
583 pub source_info_set: indexmap::IndexSet<SourceInfo>,
586 impl<'a, 'tcx: 'a, B: Backend + 'a> fmt::Debug for FunctionCx<'a, 'tcx, B> {
587 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
588 writeln!(f, "{:?}", self.instance.substs)?;
589 writeln!(f, "{:?}", self.local_map)?;
591 let mut clif = String::new();
592 ::cranelift::codegen::write::decorate_function(
593 &mut &self.clif_comments,
599 writeln!(f, "\n{}", clif)
603 impl<'a, 'tcx: 'a, B: Backend> LayoutOf for FunctionCx<'a, 'tcx, B> {
605 type TyLayout = TyLayout<'tcx>;
607 fn layout_of(&self, ty: Ty<'tcx>) -> TyLayout<'tcx> {
608 let ty = self.monomorphize(&ty);
609 self.tcx.layout_of(ParamEnv::reveal_all().and(&ty)).unwrap()
613 impl<'a, 'tcx, B: Backend + 'a> layout::HasTyCtxt<'tcx> for FunctionCx<'a, 'tcx, B> {
614 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
619 impl<'a, 'tcx, B: Backend + 'a> layout::HasDataLayout for FunctionCx<'a, 'tcx, B> {
620 fn data_layout(&self) -> &layout::TargetDataLayout {
621 &self.tcx.data_layout
625 impl<'a, 'tcx, B: Backend + 'a> HasTargetSpec for FunctionCx<'a, 'tcx, B> {
626 fn target_spec(&self) -> &Target {
627 &self.tcx.sess.target.target
631 impl<'a, 'tcx, B: Backend> BackendTypes for FunctionCx<'a, 'tcx, B> {
633 type BasicBlock = Ebb;
639 impl<'a, 'tcx: 'a, B: Backend + 'a> FunctionCx<'a, 'tcx, B> {
640 pub fn monomorphize<T>(&self, value: &T) -> T
642 T: TypeFoldable<'tcx>,
644 self.tcx.subst_and_normalize_erasing_regions(
645 self.instance.substs,
646 ty::ParamEnv::reveal_all(),
651 pub fn clif_type(&self, ty: Ty<'tcx>) -> Option<Type> {
652 clif_type_from_ty(self.tcx, self.monomorphize(&ty))
655 pub fn get_ebb(&self, bb: BasicBlock) -> Ebb {
656 *self.ebb_map.get(&bb).unwrap()
659 pub fn get_local_place(&mut self, local: Local) -> CPlace<'tcx> {
660 *self.local_map.get(&local).unwrap()
663 pub fn set_debug_loc(&mut self, source_info: mir::SourceInfo) {
664 let (index, _) = self.source_info_set.insert_full(source_info);
665 self.bcx.set_srcloc(SourceLoc::new(index as u32));