]> git.lizzy.rs Git - rust.git/blob - src/abi.rs
Implement some intrinsics
[rust.git] / src / abi.rs
1 use std::iter;
2
3 use rustc::hir;
4 use rustc_target::spec::abi::Abi;
5
6 use prelude::*;
7
8 pub fn cton_sig_from_fn_ty<'a, 'tcx: 'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>, fn_ty: Ty<'tcx>) -> Signature {
9     let sig = ty_fn_sig(tcx, fn_ty);
10     assert!(!sig.variadic, "Variadic function are not yet supported");
11     let (call_conv, inputs, _output): (CallConv, Vec<Ty>, Ty) = match sig.abi {
12         Abi::Rust => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
13         Abi::RustCall => {
14             println!("rust-call sig: {:?} inputs: {:?} output: {:?}", sig, sig.inputs(), sig.output());
15             let extra_args = match sig.inputs().last().unwrap().sty {
16                 ty::TyTuple(ref tupled_arguments) => tupled_arguments,
17                 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
18             };
19             let mut inputs: Vec<Ty> = sig.inputs()[0..sig.inputs().len() - 1].to_vec();
20             inputs.extend(extra_args.into_iter());
21             (
22                 CallConv::SystemV,
23                 inputs,
24                 sig.output(),
25             )
26         }
27         Abi::System => bug!("system abi should be selected elsewhere"),
28         // TODO: properly implement intrinsics
29         Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
30         _ => unimplemented!("unsupported abi {:?}", sig.abi),
31     };
32     Signature {
33         params: Some(types::I64).into_iter() // First param is place to put return val
34             .chain(inputs.into_iter().map(|ty| cton_type_from_ty(tcx, ty).unwrap_or(types::I64)))
35             .map(AbiParam::new).collect(),
36         returns: vec![],
37         call_conv,
38         argument_bytes: None,
39     }
40 }
41
42 fn ty_fn_sig<'a, 'tcx>(
43     tcx: TyCtxt<'a, 'tcx, 'tcx>,
44     ty: Ty<'tcx>
45 ) -> ty::FnSig<'tcx> {
46     let sig = match ty.sty {
47         ty::TyFnDef(..) |
48         // Shims currently have type TyFnPtr. Not sure this should remain.
49         ty::TyFnPtr(_) => ty.fn_sig(tcx),
50         ty::TyClosure(def_id, substs) => {
51             let sig = substs.closure_sig(def_id, tcx);
52
53             let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
54             sig.map_bound(|sig| tcx.mk_fn_sig(
55                 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
56                 sig.output(),
57                 sig.variadic,
58                 sig.unsafety,
59                 sig.abi
60             ))
61         }
62         ty::TyGenerator(def_id, substs, _) => {
63             let sig = substs.poly_sig(def_id, tcx);
64
65             let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
66             let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
67
68             sig.map_bound(|sig| {
69                 let state_did = tcx.lang_items().gen_state().unwrap();
70                 let state_adt_ref = tcx.adt_def(state_did);
71                 let state_substs = tcx.intern_substs(&[
72                     sig.yield_ty.into(),
73                     sig.return_ty.into(),
74                 ]);
75                 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
76
77                 tcx.mk_fn_sig(iter::once(env_ty),
78                     ret_ty,
79                     false,
80                     hir::Unsafety::Normal,
81                     Abi::Rust
82                 )
83             })
84         }
85         _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
86     };
87     tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig)
88 }
89
90 impl<'a, 'tcx: 'a> FunctionCx<'a, 'tcx> {
91     /// Instance must be monomorphized
92     pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
93         assert!(!inst.substs.needs_infer() && !inst.substs.has_param_types());
94         let tcx = self.tcx;
95         let module = &mut self.module;
96         let func_id = *self.def_id_fn_id_map.entry(inst).or_insert_with(|| {
97             let fn_ty = inst.ty(tcx);
98             let sig = cton_sig_from_fn_ty(tcx, fn_ty);
99             module.declare_function(&tcx.absolute_item_path_str(inst.def_id()), Linkage::Local, &sig).unwrap()
100         });
101         module.declare_func_in_func(func_id, &mut self.bcx.func)
102     }
103
104     fn self_sig(&self) -> FnSig<'tcx> {
105         ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
106     }
107
108     fn return_type(&self) -> Ty<'tcx> {
109         self.self_sig().output()
110     }
111 }
112
113 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, start_ebb: Ebb) {
114     let ret_param = fx.bcx.append_ebb_param(start_ebb, types::I64);
115     let _ = fx.bcx.create_stack_slot(StackSlotData {
116         kind: StackSlotKind::ExplicitSlot,
117         size: 0,
118         offset: None,
119     }); // Dummy stack slot for debugging
120
121     let func_params = fx.mir.args_iter().map(|local| {
122         let layout = fx.layout_of(fx.mir.local_decls[local].ty);
123         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
124             kind: StackSlotKind::ExplicitSlot,
125             size: layout.size.bytes() as u32,
126             offset: None,
127         });
128         let ty = fx.mir.local_decls[local].ty;
129         let cton_type = fx.cton_type(ty).unwrap_or(types::I64);
130         (local, fx.bcx.append_ebb_param(start_ebb, cton_type), ty, stack_slot)
131     }).collect::<Vec<(Local, Value, Ty, StackSlot)>>();
132
133     let ret_layout = fx.layout_of(fx.return_type());
134     fx.local_map.insert(RETURN_PLACE, CPlace::Addr(ret_param, ret_layout));
135
136     for (local, ebb_param, ty, stack_slot) in func_params {
137         let place = CPlace::from_stack_slot(fx, stack_slot, ty);
138         if fx.cton_type(ty).is_some() {
139             place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()));
140         } else {
141             place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout()));
142         }
143         fx.local_map.insert(local, place);
144     }
145
146     for local in fx.mir.vars_and_temps_iter() {
147         let ty = fx.mir.local_decls[local].ty;
148         let layout = fx.layout_of(ty);
149         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
150             kind: StackSlotKind::ExplicitSlot,
151             size: layout.size.bytes() as u32,
152             offset: None,
153         });
154         let place = CPlace::from_stack_slot(fx, stack_slot, ty);
155         fx.local_map.insert(local, place);
156     }
157 }
158
159 pub fn codegen_call<'a, 'tcx: 'a>(
160     fx: &mut FunctionCx<'a, 'tcx>,
161     func: &Operand<'tcx>,
162     args: &[Operand<'tcx>],
163     destination: &Option<(Place<'tcx>, BasicBlock)>,
164 ) {
165     let func = ::base::trans_operand(fx, func);
166     let fn_ty = func.layout().ty;
167     let sig = ty_fn_sig(fx.tcx, fn_ty);
168
169     let return_place = if let Some((place, _)) = destination {
170         Some(::base::trans_place(fx, place))
171     } else {
172         None
173     };
174
175     // Unpack arguments tuple for closures
176     let args = if sig.abi == Abi::RustCall {
177         assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
178         let self_arg = ::base::trans_operand(fx, &args[0]);
179         let pack_arg = ::base::trans_operand(fx, &args[1]);
180         let mut args = Vec::new();
181         args.push(self_arg);
182         match pack_arg.layout().ty.sty {
183             ty::TyTuple(ref tupled_arguments) => {
184                 for (i, _) in tupled_arguments.iter().enumerate() {
185                     args.push(pack_arg.value_field(fx, mir::Field::new(i)));
186                 }
187             },
188             _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
189         }
190         args
191     } else {
192         args
193             .into_iter()
194             .map(|arg| {
195                 ::base::trans_operand(fx, arg)
196             })
197             .collect::<Vec<_>>()
198     };
199
200     if let TypeVariants::TyFnDef(def_id, substs) = fn_ty.sty {
201         if sig.abi == Abi::RustIntrinsic {
202             let intrinsic = fx.tcx.item_name(def_id).as_str();
203             let intrinsic = &intrinsic[..];
204
205             let usize_layout = fx.layout_of(fx.tcx.types.usize);
206             let ret = return_place.unwrap();
207             match intrinsic {
208                 "copy" => {
209                     /*let elem_ty = substs.type_at(0);
210                     assert_eq!(args.len(), 3);
211                     let src = args[0];
212                     let dst = args[1];
213                     let count = args[2];*/
214                     unimplemented!("copy");
215                 }
216                 "size_of" => {
217                     assert_eq!(args.len(), 0);
218                     let size_of = fx.layout_of(substs.type_at(0)).size.bytes();
219                     let size_of = CValue::const_val(fx, usize_layout.ty, size_of as i64);
220                     ret.write_cvalue(fx, size_of);
221                 }
222                 _ if intrinsic.starts_with("unchecked_") => {
223                     assert_eq!(args.len(), 2);
224                     let lhs = args[0].load_value(fx);
225                     let rhs = args[1].load_value(fx);
226                     let bin_op = match intrinsic {
227                         "unchecked_div" => BinOp::Div,
228                         "unchecked_rem" => BinOp::Rem,
229                         "unchecked_shl" => BinOp::Shl,
230                         "unchecked_shr" => BinOp::Shr,
231                         _ => unimplemented!("intrinsic {}", intrinsic),
232                     };
233                     let res = match ret.layout().ty.sty {
234                         TypeVariants::TyUint(_) => {
235                             ::base::trans_int_binop(fx, bin_op, lhs, rhs, args[0].layout().ty, false, false)
236                         }
237                         TypeVariants::TyInt(_) => {
238                             ::base::trans_int_binop(fx, bin_op, lhs, rhs, args[0].layout().ty, true, false)
239                         }
240                         _ => panic!(),
241                     };
242                     ret.write_cvalue(fx, res);
243                 }
244                 "offset" => {
245                     assert_eq!(args.len(), 2);
246                     let base = args[0].load_value(fx);
247                     let offset = args[1].load_value(fx);
248                     let res = fx.bcx.ins().iadd(base, offset);
249                     ret.write_cvalue(fx, CValue::ByVal(res, args[0].layout()));
250                 }
251                 "transmute" => {
252                     assert_eq!(args.len(), 1);
253                     let src_ty = substs.type_at(0);
254                     let dst_ty = substs.type_at(1);
255                     assert_eq!(args[0].layout().ty, src_ty);
256                     let addr = args[0].force_stack(fx);
257                     let dst_layout = fx.layout_of(dst_ty);
258                     ret.write_cvalue(fx, CValue::ByRef(addr, dst_layout))
259                 }
260                 _ => fx.tcx.sess.fatal(&format!("unsupported intrinsic {}", intrinsic)),
261             }
262             if let Some((_, dest)) = *destination {
263                 let ret_ebb = fx.get_ebb(dest);
264                 fx.bcx.ins().jump(ret_ebb, &[]);
265             } else {
266                 fx.bcx.ins().trap(TrapCode::User(!0));
267             }
268             return;
269         }
270     }
271
272     let return_ptr = match return_place {
273         Some(place) => place.expect_addr(),
274         None => fx.bcx.ins().iconst(types::I64, 0),
275     };
276
277     let call_args = Some(return_ptr).into_iter().chain(args.into_iter().map(|arg| {
278         if fx.cton_type(arg.layout().ty).is_some() {
279             arg.load_value(fx)
280         } else {
281             arg.force_stack(fx)
282         }
283     })).collect::<Vec<_>>();
284
285     match func {
286         CValue::Func(func, _) => {
287             fx.bcx.ins().call(func, &call_args);
288         }
289         func => {
290             let func_ty = func.layout().ty;
291             let func = func.load_value(fx);
292             let sig = fx.bcx.import_signature(cton_sig_from_fn_ty(fx.tcx, func_ty));
293             fx.bcx.ins().call_indirect(sig, func, &call_args);
294         }
295     }
296     if let Some((_, dest)) = *destination {
297         let ret_ebb = fx.get_ebb(dest);
298         fx.bcx.ins().jump(ret_ebb, &[]);
299     } else {
300         fx.bcx.ins().trap(TrapCode::User(!0));
301     }
302 }