]> git.lizzy.rs Git - rust.git/blob - src/common.rs
Implement some more things
[rust.git] / src / common.rs
1 use syntax::ast::{IntTy, UintTy};
2
3 use cretonne_module::{Module, Linkage, FuncId};
4
5 use prelude::*;
6
7 pub type CurrentBackend = ::cretonne_simplejit::SimpleJITBackend;
8
9 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
10 pub struct Variable(Local);
11
12 impl EntityRef for Variable {
13     fn new(u: usize) -> Self {
14         Variable(Local::new(u))
15     }
16
17     fn index(self) -> usize {
18         self.0.index()
19     }
20 }
21
22 pub fn cton_type_from_ty(ty: Ty) -> Option<types::Type> {
23     Some(match ty.sty {
24         TypeVariants::TyBool => types::I8,
25         TypeVariants::TyUint(size) => {
26             match size {
27                 UintTy::U8 => types::I8,
28                 UintTy::U16 => types::I16,
29                 UintTy::U32 => types::I32,
30                 UintTy::U64 => types::I64,
31                 UintTy::U128 => types::I64X2,
32                 UintTy::Usize => types::I64,
33             }
34         }
35         TypeVariants::TyInt(size) => {
36             match size {
37                 IntTy::I8 => types::I8,
38                 IntTy::I16 => types::I16,
39                 IntTy::I32 => types::I32,
40                 IntTy::I64 => types::I64,
41                 IntTy::I128 => types::I64X2,
42                 IntTy::Isize => types::I64,
43             }
44         }
45         TypeVariants::TyFnPtr(_) => types::I64,
46         TypeVariants::TyRef(..) | TypeVariants::TyRawPtr(..) => types::I64,
47         _ => return None,
48     })
49 }
50
51 // FIXME(cretonne) fix types smaller than I32
52 pub fn fixup_cton_ty(ty: Type) -> Type {
53     match ty {
54         types::I64X2 | types::I64 | types::I32 => ty,
55         _ => types::I32,
56     }
57 }
58
59 pub fn extend_val<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, val: Value, ty: Ty) -> Value {
60     let cton_ty = cton_type_from_ty(ty).unwrap();
61     let to_ty = match cton_ty {
62         types::I64 => return val,
63         types::I32 => return val,
64         _ => types::I32,
65     };
66     match ty.sty {
67         TypeVariants::TyBool => fx.bcx.ins().uextend(to_ty, val),
68         TypeVariants::TyUint(_) => fx.bcx.ins().uextend(to_ty, val),
69         TypeVariants::TyInt(_) => fx.bcx.ins().sextend(to_ty, val),
70         TypeVariants::TyFnPtr(_) => val,
71         _ => unimplemented!(),
72     }
73 }
74
75 // FIXME(cretonne) fix load.i8
76 fn load_workaround(fx: &mut FunctionCx, ty: Type, addr: Value, offset: i32) -> Value {
77     use cretonne::codegen::ir::types::*;
78     match ty {
79         I8 => fx.bcx.ins().uload8(I32, MemFlags::new(), addr, offset),
80         I16 => fx.bcx.ins().uload16(I32, MemFlags::new(), addr, offset),
81         // I32 and I64 work
82         _ => fx.bcx.ins().load(ty, MemFlags::new(), addr, offset),
83     }
84 }
85
86 // FIXME(cretonne) fix store.i8
87 fn store_workaround(fx: &mut FunctionCx, ty: Type, addr: Value, val: Value, offset: i32) {
88     use cretonne::codegen::ir::types::*;
89     match ty {
90         I8 => fx.bcx.ins().istore8(MemFlags::new(), val, addr, offset),
91         I16 => fx.bcx.ins().istore16(MemFlags::new(), val, addr, offset),
92         // I32 and I64 work
93         _ => fx.bcx.ins().store(MemFlags::new(), val, addr, offset),
94     };
95 }
96
97 #[derive(Debug, Copy, Clone)]
98 pub enum CValue {
99     ByRef(Value),
100     ByVal(Value),
101     Func(FuncRef),
102 }
103
104 impl CValue {
105     pub fn force_stack<'a, 'tcx: 'a>(self, fx: &mut FunctionCx<'a, 'tcx>, ty: Ty<'tcx>) -> Value {
106         match self {
107             CValue::ByRef(value) => value,
108             CValue::ByVal(value) => {
109                 let layout = fx.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap();
110                 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
111                     kind: StackSlotKind::ExplicitSlot,
112                     size: layout.size.bytes() as u32,
113                     offset: None,
114                 });
115                 fx.bcx.ins().stack_store(value, stack_slot, 0);
116                 fx.bcx.ins().stack_addr(types::I64, stack_slot, 0)
117             }
118             CValue::Func(func) => {
119                 let func = fx.bcx.ins().func_addr(types::I64, func);
120                 CValue::ByVal(func).force_stack(fx, ty)
121             }
122         }
123     }
124
125     pub fn load_value<'a, 'tcx: 'a>(self, fx: &mut FunctionCx<'a, 'tcx>, ty: Ty<'tcx>) -> Value {
126         match self {
127             CValue::ByRef(value) => {
128                 let cton_ty = cton_type_from_ty(fx.monomorphize(&ty)).expect(&format!("{:?}", ty));
129                 load_workaround(fx, cton_ty, value, 0)
130             }
131             CValue::ByVal(value) => value,
132             CValue::Func(func) => {
133                 fx.bcx.ins().func_addr(types::I64, func)
134             }
135         }
136     }
137
138     pub fn expect_byref(self) -> Value {
139         match self {
140             CValue::ByRef(value) => value,
141             CValue::ByVal(_) => bug!("Expected CValue::ByRef, found CValue::ByVal"),
142             CValue::Func(_) => bug!("Expected CValue::ByRef, found CValue::Func"),
143         }
144     }
145
146     pub fn value_field<'a, 'tcx: 'a>(self, fx: &mut FunctionCx<'a, 'tcx>, field: mir::Field, ty: Ty<'tcx>) -> CValue {
147         let base = match self {
148             CValue::ByRef(addr) => addr,
149             _ => bug!("place_field for {:?}", self),
150         };
151         let layout = fx.tcx.layout_of(ParamEnv::empty().and(fx.monomorphize(&ty))).unwrap();
152         let field_offset = layout.fields.offset(field.index());
153         if field_offset.bytes() > 0 {
154             let field_offset = fx.bcx.ins().iconst(types::I64, field_offset.bytes() as i64);
155             CValue::ByRef(fx.bcx.ins().iadd(base, field_offset))
156         } else {
157             CValue::ByRef(base)
158         }
159     }
160
161     pub fn const_val<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, ty: Ty<'tcx>, const_val: i64) -> CValue {
162         let ty = fx.monomorphize(&ty);
163         CValue::ByVal(fx.bcx.ins().iconst(cton_type_from_ty(ty).unwrap(), const_val))
164     }
165 }
166
167 #[derive(Debug, Copy, Clone)]
168 pub enum CPlace {
169     Var(Variable),
170     Addr(Value),
171 }
172
173 impl<'a, 'tcx: 'a> CPlace {
174     pub fn from_stack_slot(fx: &mut FunctionCx<'a, 'tcx>, stack_slot: StackSlot) -> CPlace {
175         CPlace::Addr(fx.bcx.ins().stack_addr(types::I64, stack_slot, 0))
176     }
177
178     pub fn to_cvalue(self, fx: &mut FunctionCx<'a, 'tcx>) -> CValue {
179         match self {
180             CPlace::Var(var) => CValue::ByVal(fx.bcx.use_var(var)),
181             CPlace::Addr(addr) => CValue::ByRef(addr),
182         }
183     }
184
185     pub fn expect_addr(self) -> Value {
186         match self {
187             CPlace::Addr(addr) => addr,
188             CPlace::Var(_) => bug!("Expected CPlace::Addr, found CPlace::Var"),
189         }
190     }
191
192     pub fn write_cvalue(self, fx: &mut FunctionCx<'a, 'tcx>, from: CValue, ty: Ty<'tcx>) {
193         let layout = fx.tcx.layout_of(ParamEnv::reveal_all().and(fx.monomorphize(&ty))).unwrap();
194         let size = layout.size.bytes() as i32;
195         match self {
196             CPlace::Var(var) => {
197                 let data = from.load_value(fx, ty);
198                 fx.bcx.def_var(var, data)
199             },
200             CPlace::Addr(addr) => {
201                 if let Some(cton_ty) = cton_type_from_ty(ty) {
202                     let data = from.load_value(fx, ty);
203                     store_workaround(fx, cton_ty, addr, data, 0);
204                 } else {
205                     for i in 0..size {
206                         let from = from.expect_byref();
207                         let byte = load_workaround(fx, types::I8, from, i);
208                         store_workaround(fx, types::I8, addr, byte, i);
209                     }
210                 }
211             }
212         }
213     }
214
215     pub fn place_field(self, fx: &mut FunctionCx<'a, 'tcx>, field: mir::Field, ty: Ty<'tcx>) -> (CPlace, layout::TyLayout<'tcx>) {
216         let base = self.expect_addr();
217         let layout = fx.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap();
218         let field_offset = layout.fields.offset(field.index());
219         if field_offset.bytes() > 0 {
220             let field_offset = fx.bcx.ins().iconst(types::I64, field_offset.bytes() as i64);
221             (CPlace::Addr(fx.bcx.ins().iadd(base, field_offset)), layout)
222         } else {
223             (CPlace::Addr(base), layout)
224         }
225     }
226 }
227
228 pub fn cton_sig_from_fn_sig<'a, 'tcx: 'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sig: PolyFnSig<'tcx>, substs: &Substs<'tcx>) -> Signature {
229     let sig = tcx.subst_and_normalize_erasing_regions(substs, ParamEnv::reveal_all(), &sig);
230     cton_sig_from_mono_fn_sig(sig)
231 }
232
233 pub fn cton_sig_from_instance<'a, 'tcx: 'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>, inst: Instance<'tcx>) -> Signature {
234     let fn_ty = inst.ty(tcx);
235     let sig = fn_ty.fn_sig(tcx);
236     cton_sig_from_mono_fn_sig(sig)
237 }
238
239 pub fn cton_sig_from_mono_fn_sig<'a ,'tcx: 'a>(sig: PolyFnSig<'tcx>) -> Signature {
240     let sig = sig.skip_binder();
241     let inputs = sig.inputs();
242     let _output = sig.output();
243     assert!(!sig.variadic, "Variadic function are not yet supported");
244     let call_conv = match sig.abi {
245         _ => CallConv::SystemV,
246     };
247     Signature {
248         params: Some(types::I64).into_iter() // First param is place to put return val
249             .chain(inputs.into_iter().map(|ty| fixup_cton_ty(cton_type_from_ty(ty).unwrap_or(types::I64))))
250             .map(AbiParam::new).collect(),
251         returns: vec![],
252         call_conv,
253         argument_bytes: None,
254     }
255 }
256
257 pub fn cton_intcast<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, val: Value, from: Ty<'tcx>, to: Ty<'tcx>, signed: bool) -> Value {
258     let from = cton_type_from_ty(from).unwrap();
259     let to = cton_type_from_ty(to).unwrap();
260     if from == to {
261         return val;
262     }
263     if from.wider_or_equal(to) {
264         if signed {
265             fx.bcx.ins().sextend(to, val)
266         } else {
267             fx.bcx.ins().uextend(to, val)
268         }
269     } else {
270         fx.bcx.ins().ireduce(to, val)
271     }
272 }
273
274 pub struct FunctionCx<'a, 'tcx: 'a> {
275     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
276     pub module: &'a mut Module<CurrentBackend>,
277     pub def_id_fn_id_map: &'a mut HashMap<Instance<'tcx>, FuncId>,
278     pub instance: Instance<'tcx>,
279     pub mir: &'tcx Mir<'tcx>,
280     pub param_substs: &'tcx Substs<'tcx>,
281     pub bcx: FunctionBuilder<'a, Variable>,
282     pub ebb_map: HashMap<BasicBlock, Ebb>,
283     pub local_map: HashMap<Local, CPlace>,
284 }
285
286 impl<'f, 'tcx> FunctionCx<'f, 'tcx> {
287     pub fn monomorphize<T>(&self, value: &T) -> T
288         where T: TypeFoldable<'tcx>
289     {
290         self.tcx.subst_and_normalize_erasing_regions(
291             self.param_substs,
292             ty::ParamEnv::reveal_all(),
293             value,
294         )
295     }
296
297     pub fn get_ebb(&self, bb: BasicBlock) -> Ebb {
298         *self.ebb_map.get(&bb).unwrap()
299     }
300
301     pub fn get_local_place(&mut self, local: Local) -> CPlace {
302         *self.local_map.get(&local).unwrap()
303     }
304
305     pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
306         let tcx = self.tcx;
307         let module = &mut self.module;
308         let func_id = *self.def_id_fn_id_map.entry(inst).or_insert_with(|| {
309             let sig = cton_sig_from_instance(tcx, inst);
310             module.declare_function(&tcx.absolute_item_path_str(inst.def_id()), Linkage::Local, &sig).unwrap()
311         });
312         module.declare_func_in_func(func_id, &mut self.bcx.func)
313     }
314 }