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