1 extern crate rustc_target;
6 use syntax::ast::{IntTy, UintTy};
7 use self::rustc_target::spec::{HasTargetSpec, Target};
9 use cranelift_module::{Module, FuncId, DataId};
13 pub type CurrentBackend = ::cranelift_simplejit::SimpleJITBackend;
15 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
16 pub struct Variable(Local);
18 impl EntityRef for Variable {
19 fn new(u: usize) -> Self {
20 Variable(Local::new(u))
23 fn index(self) -> usize {
28 pub fn cton_type_from_ty<'a, 'tcx: 'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> Option<types::Type> {
30 TypeVariants::TyBool => types::I8,
31 TypeVariants::TyUint(size) => {
33 UintTy::U8 => types::I8,
34 UintTy::U16 => types::I16,
35 UintTy::U32 => types::I32,
36 UintTy::U64 => types::I64,
37 UintTy::U128 => unimplemented!("u128"),
38 UintTy::Usize => types::I64,
41 TypeVariants::TyInt(size) => {
43 IntTy::I8 => types::I8,
44 IntTy::I16 => types::I16,
45 IntTy::I32 => types::I32,
46 IntTy::I64 => types::I64,
47 IntTy::I128 => unimplemented!("i128"),
48 IntTy::Isize => types::I64,
51 TypeVariants::TyChar => types::I32,
52 TypeVariants::TyFnPtr(_) => types::I64,
53 TypeVariants::TyRawPtr(TypeAndMut { ty, mutbl: _ }) | TypeVariants::TyRef(_, ty, _) => {
54 if ty.is_sized(tcx.at(DUMMY_SP), ParamEnv::reveal_all()) {
60 TypeVariants::TyParam(_) => bug!("{:?}: {:?}", ty, ty.sty),
66 #[derive(Debug, Copy, Clone)]
67 pub enum CValue<'tcx> {
68 ByRef(Value, TyLayout<'tcx>),
69 ByVal(Value, TyLayout<'tcx>),
70 Func(FuncRef, TyLayout<'tcx>),
73 impl<'tcx> CValue<'tcx> {
74 pub fn layout(&self) -> TyLayout<'tcx> {
76 CValue::ByRef(_, layout) |
77 CValue::ByVal(_, layout) |
78 CValue::Func(_, layout) => layout
82 pub fn force_stack<'a>(self, fx: &mut FunctionCx<'a, 'tcx>) -> Value where 'tcx: 'a {
84 CValue::ByRef(value, _layout) => value,
85 CValue::ByVal(value, layout) => {
86 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
87 kind: StackSlotKind::ExplicitSlot,
88 size: layout.size.bytes() as u32,
91 fx.bcx.ins().stack_store(value, stack_slot, 0);
92 fx.bcx.ins().stack_addr(types::I64, stack_slot, 0)
94 CValue::Func(func, ty) => {
95 let func = fx.bcx.ins().func_addr(types::I64, func);
96 CValue::ByVal(func, ty).force_stack(fx)
101 pub fn load_value<'a>(self, fx: &mut FunctionCx<'a, 'tcx>) -> Value where 'tcx: 'a{
103 CValue::ByRef(addr, layout) => {
104 let cton_ty = fx.cton_type(layout.ty).expect(&format!("load_value of type {:?}", layout.ty));
105 fx.bcx.ins().load(cton_ty, MemFlags::new(), addr, 0)
107 CValue::ByVal(value, _layout) => value,
108 CValue::Func(func, _layout) => {
109 fx.bcx.ins().func_addr(types::I64, func)
114 pub fn expect_byref(self) -> (Value, TyLayout<'tcx>) {
116 CValue::ByRef(value, layout) => (value, layout),
117 CValue::ByVal(_, _) => bug!("Expected CValue::ByRef, found CValue::ByVal"),
118 CValue::Func(_, _) => bug!("Expected CValue::ByRef, found CValue::Func"),
122 pub fn value_field<'a>(self, fx: &mut FunctionCx<'a, 'tcx>, field: mir::Field) -> CValue<'tcx> where 'tcx: 'a {
123 use rustc::ty::util::IntTypeExt;
125 let (base, layout) = match self {
126 CValue::ByRef(addr, layout) => (addr, layout),
127 _ => bug!("place_field for {:?}", self),
129 let field_offset = layout.fields.offset(field.index());
130 let field_layout = if field.index() == 0 {
131 fx.layout_of(if let ty::TyAdt(adt_def, _) = layout.ty.sty {
132 adt_def.repr.discr_type().to_ty(fx.tcx)
134 // This can only be `0`, for now, so `u8` will suffice.
138 layout.field(&*fx, field.index())
140 if field_offset.bytes() > 0 {
141 let field_offset = fx.bcx.ins().iconst(types::I64, field_offset.bytes() as i64);
142 CValue::ByRef(fx.bcx.ins().iadd(base, field_offset), field_layout)
144 CValue::ByRef(base, field_layout)
148 pub fn const_val<'a>(fx: &mut FunctionCx<'a, 'tcx>, ty: Ty<'tcx>, const_val: i64) -> CValue<'tcx> where 'tcx: 'a {
149 let cton_ty = fx.cton_type(ty).unwrap();
150 let layout = fx.layout_of(ty);
151 CValue::ByVal(fx.bcx.ins().iconst(cton_ty, const_val), layout)
154 pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
156 CValue::ByRef(addr, _) => CValue::ByRef(addr, layout),
157 CValue::ByVal(val, _) => CValue::ByVal(val, layout),
158 CValue::Func(fun, _) => CValue::Func(fun, layout),
163 /// A place where you can write a value to or read a value from
164 #[derive(Debug, Copy, Clone)]
165 pub enum CPlace<'tcx> {
166 Var(Variable, TyLayout<'tcx>),
167 Addr(Value, TyLayout<'tcx>),
170 impl<'a, 'tcx: 'a> CPlace<'tcx> {
171 pub fn layout(&self) -> TyLayout<'tcx> {
173 CPlace::Var(_, layout) |
174 CPlace::Addr(_, layout) => layout
178 pub fn from_stack_slot(fx: &mut FunctionCx<'a, 'tcx>, stack_slot: StackSlot, ty: Ty<'tcx>) -> CPlace<'tcx> {
179 let layout = fx.layout_of(ty);
180 CPlace::Addr(fx.bcx.ins().stack_addr(types::I64, stack_slot, 0), layout)
183 pub fn to_cvalue(self, fx: &mut FunctionCx<'a, 'tcx>) -> CValue<'tcx> {
185 CPlace::Var(var, layout) => CValue::ByVal(fx.bcx.use_var(var), layout),
186 CPlace::Addr(addr, layout) => CValue::ByRef(addr, layout),
190 pub fn expect_addr(self) -> Value {
192 CPlace::Addr(addr, _layout) => addr,
193 CPlace::Var(_, _) => bug!("Expected CPlace::Addr, found CPlace::Var"),
197 pub fn write_cvalue(self, fx: &mut FunctionCx<'a, 'tcx>, from: CValue<'tcx>) {
198 match (&self.layout().ty.sty, &from.layout().ty.sty) {
199 (TypeVariants::TyRef(_, t, dest_mut), TypeVariants::TyRef(_, u, src_mut)) if (
200 if *dest_mut != ::rustc::hir::Mutability::MutImmutable && src_mut != dest_mut {
208 // &mut T -> &T is allowed
209 // &'a T -> &'b T is allowed
213 self.layout().ty, from.layout().ty,
214 "Can't write value of incompatible type to place {:?} {:?}\n\n{:#?}",
215 self.layout().ty.sty, from.layout().ty.sty,
222 CPlace::Var(var, _) => {
223 let data = from.load_value(fx);
224 fx.bcx.def_var(var, data)
226 CPlace::Addr(addr, layout) => {
227 let size = layout.size.bytes() as i32;
229 if let Some(_) = fx.cton_type(layout.ty) {
230 let data = from.load_value(fx);
231 fx.bcx.ins().store(MemFlags::new(), data, addr, 0);
233 let from = from.expect_byref();
235 while size - offset >= 8 {
236 let byte = fx.bcx.ins().load(types::I64, MemFlags::new(), from.0, offset);
237 fx.bcx.ins().store(MemFlags::new(), byte, addr, offset);
240 while size - offset >= 4 {
241 let byte = fx.bcx.ins().load(types::I32, MemFlags::new(), from.0, offset);
242 fx.bcx.ins().store(MemFlags::new(), byte, addr, offset);
245 while offset < size {
246 let byte = fx.bcx.ins().load(types::I8, MemFlags::new(), from.0, offset);
247 fx.bcx.ins().store(MemFlags::new(), byte, addr, offset);
255 pub fn place_field(self, fx: &mut FunctionCx<'a, 'tcx>, field: mir::Field) -> CPlace<'tcx> {
256 let base = self.expect_addr();
257 let layout = self.layout();
258 let field_offset = layout.fields.offset(field.index());
259 let field_ty = layout.field(&*fx, field.index());
260 if field_offset.bytes() > 0 {
261 let field_offset = fx.bcx.ins().iconst(types::I64, field_offset.bytes() as i64);
262 CPlace::Addr(fx.bcx.ins().iadd(base, field_offset), field_ty)
265 CPlace::Addr(base, field_ty)
269 pub fn unchecked_cast_to(self, layout: TyLayout<'tcx>) -> Self {
271 CPlace::Var(var, _) => CPlace::Var(var, layout),
272 CPlace::Addr(addr, _) => CPlace::Addr(addr, layout),
276 pub fn downcast_variant(self, fx: &FunctionCx<'a, 'tcx>, variant: usize) -> Self {
277 let layout = self.layout().for_variant(fx, variant);
278 self.unchecked_cast_to(layout)
282 pub fn cton_intcast<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, val: Value, from: Ty<'tcx>, to: Ty<'tcx>, signed: bool) -> Value {
283 let from = fx.cton_type(from).unwrap();
284 let to = fx.cton_type(to).unwrap();
288 if to.wider_or_equal(from) {
290 fx.bcx.ins().sextend(to, val)
292 fx.bcx.ins().uextend(to, val)
295 fx.bcx.ins().ireduce(to, val)
299 pub struct FunctionCx<'a, 'tcx: 'a> {
300 pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
301 pub module: &'a mut Module<CurrentBackend>,
302 pub def_id_fn_id_map: &'a mut HashMap<Instance<'tcx>, FuncId>,
303 pub instance: Instance<'tcx>,
304 pub mir: &'tcx Mir<'tcx>,
305 pub param_substs: &'tcx Substs<'tcx>,
306 pub bcx: FunctionBuilder<'a, Variable>,
307 pub ebb_map: HashMap<BasicBlock, Ebb>,
308 pub local_map: HashMap<Local, CPlace<'tcx>>,
309 pub comments: HashMap<Inst, String>,
310 pub constants: &'a mut HashMap<AllocId, DataId>,
313 impl<'a, 'tcx: 'a> fmt::Debug for FunctionCx<'a, 'tcx> {
314 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
315 writeln!(f, "{:?}", self.def_id_fn_id_map)?;
316 writeln!(f, "{:?}", self.param_substs)?;
317 writeln!(f, "{:?}", self.local_map)?;
319 let mut clif = String::new();
320 let mut writer = ::pretty_clif::CommentWriter(self.comments.clone());
321 ::cranelift::codegen::write::decorate_function(
327 writeln!(f, "\n{}", clif)
331 impl<'a, 'tcx: 'a> LayoutOf for &'a FunctionCx<'a, 'tcx> {
333 type TyLayout = TyLayout<'tcx>;
335 fn layout_of(self, ty: Ty<'tcx>) -> TyLayout<'tcx> {
336 let ty = self.monomorphize(&ty);
337 self.tcx.layout_of(ParamEnv::reveal_all().and(&ty)).unwrap()
341 impl<'a, 'tcx> layout::HasTyCtxt<'tcx> for &'a FunctionCx<'a, 'tcx> {
342 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
347 impl<'a, 'tcx> layout::HasDataLayout for &'a FunctionCx<'a, 'tcx> {
348 fn data_layout(&self) -> &layout::TargetDataLayout {
349 &self.tcx.data_layout
353 impl<'a, 'tcx> HasTargetSpec for &'a FunctionCx<'a, 'tcx> {
354 fn target_spec(&self) -> &Target {
355 &self.tcx.sess.target.target
359 impl<'a, 'tcx: 'a> FunctionCx<'a, 'tcx> {
360 pub fn monomorphize<T>(&self, value: &T) -> T
361 where T: TypeFoldable<'tcx>
363 self.tcx.subst_and_normalize_erasing_regions(
365 ty::ParamEnv::reveal_all(),
370 pub fn cton_type(&self, ty: Ty<'tcx>) -> Option<Type> {
371 cton_type_from_ty(self.tcx, self.monomorphize(&ty))
374 pub fn get_ebb(&self, bb: BasicBlock) -> Ebb {
375 *self.ebb_map.get(&bb).unwrap()
378 pub fn get_local_place(&mut self, local: Local) -> CPlace<'tcx> {
379 *self.local_map.get(&local).unwrap()
382 pub fn add_comment<'s, S: Into<Cow<'s, str>>>(&mut self, inst: Inst, comment: S) {
383 use std::collections::hash_map::Entry;
384 match self.comments.entry(inst) {
385 Entry::Occupied(mut occ) => {
386 occ.get_mut().push('\n');
387 occ.get_mut().push_str(comment.into().as_ref());
389 Entry::Vacant(vac) => {
390 vac.insert(comment.into().into_owned());