]> git.lizzy.rs Git - rust.git/blob - src/abi.rs
Fix some small bugs
[rust.git] / src / abi.rs
1 use std::iter;
2
3 use rustc::hir;
4 use rustc_target::spec::abi::Abi;
5
6 use crate::prelude::*;
7
8 pub fn cton_sig_from_fn_ty<'a, 'tcx: 'a>(
9     tcx: TyCtxt<'a, 'tcx, 'tcx>,
10     fn_ty: Ty<'tcx>,
11 ) -> Signature {
12     let sig = ty_fn_sig(tcx, fn_ty);
13     assert!(!sig.variadic, "Variadic function are not yet supported");
14     let (call_conv, inputs, _output): (CallConv, Vec<Ty>, Ty) = match sig.abi {
15         Abi::Rust => (CallConv::Fast, sig.inputs().to_vec(), sig.output()),
16         Abi::C => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
17         Abi::RustCall => {
18             println!(
19                 "rust-call sig: {:?} inputs: {:?} output: {:?}",
20                 sig,
21                 sig.inputs(),
22                 sig.output()
23             );
24             assert_eq!(sig.inputs().len(), 2);
25             let extra_args = match sig.inputs().last().unwrap().sty {
26                 ty::TyTuple(ref tupled_arguments) => tupled_arguments,
27                 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
28             };
29             let mut inputs: Vec<Ty> = vec![sig.inputs()[0]];
30             inputs.extend(extra_args.into_iter());
31             (CallConv::Fast, inputs, sig.output())
32         }
33         Abi::System => bug!("system abi should be selected elsewhere"),
34         Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
35         _ => unimplemented!("unsupported abi {:?}", sig.abi),
36     };
37     Signature {
38         params: Some(types::I64).into_iter() // First param is place to put return val
39             .chain(inputs.into_iter().map(|ty| {
40                 let cton_ty = cton_type_from_ty(tcx, ty);
41                 if let Some(cton_ty) = cton_ty {
42                     cton_ty
43                 } else {
44                     if sig.abi == Abi::C {
45                         unimplemented!("Non scalars are not yet supported for \"C\" abi");
46                     }
47                     types::I64
48                 }
49             }))
50             .map(AbiParam::new).collect(),
51         returns: vec![],
52         call_conv,
53         argument_bytes: None,
54     }
55 }
56
57 fn ty_fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> ty::FnSig<'tcx> {
58     let sig = match ty.sty {
59         ty::TyFnDef(..) |
60         // Shims currently have type TyFnPtr. Not sure this should remain.
61         ty::TyFnPtr(_) => ty.fn_sig(tcx),
62         ty::TyClosure(def_id, substs) => {
63             let sig = substs.closure_sig(def_id, tcx);
64
65             let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
66             sig.map_bound(|sig| tcx.mk_fn_sig(
67                 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
68                 sig.output(),
69                 sig.variadic,
70                 sig.unsafety,
71                 sig.abi
72             ))
73         }
74         ty::TyGenerator(def_id, substs, _) => {
75             let sig = substs.poly_sig(def_id, tcx);
76
77             let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
78             let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
79
80             sig.map_bound(|sig| {
81                 let state_did = tcx.lang_items().gen_state().unwrap();
82                 let state_adt_ref = tcx.adt_def(state_did);
83                 let state_substs = tcx.intern_substs(&[
84                     sig.yield_ty.into(),
85                     sig.return_ty.into(),
86                 ]);
87                 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
88
89                 tcx.mk_fn_sig(iter::once(env_ty),
90                     ret_ty,
91                     false,
92                     hir::Unsafety::Normal,
93                     Abi::Rust
94                 )
95             })
96         }
97         _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
98     };
99     tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig)
100 }
101
102 impl<'a, 'tcx: 'a> FunctionCx<'a, 'tcx> {
103     /// Instance must be monomorphized
104     pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
105         assert!(!inst.substs.needs_infer() && !inst.substs.has_param_types());
106         let fn_ty = inst.ty(self.tcx);
107         let sig = cton_sig_from_fn_ty(self.tcx, fn_ty);
108         let def_path_based_names =
109             ::rustc_mir::monomorphize::item::DefPathBasedNames::new(self.tcx, false, false);
110         let mut name = String::new();
111         def_path_based_names.push_instance_as_string(inst, &mut name);
112         let func_id = self
113             .module
114             .declare_function(&name, Linkage::Import, &sig)
115             .unwrap();
116         self.module
117             .declare_func_in_func(func_id, &mut self.bcx.func)
118     }
119
120     fn lib_call(
121         &mut self,
122         name: &str,
123         input_tys: Vec<types::Type>,
124         output_ty: Option<types::Type>,
125         args: &[Value],
126     ) -> Option<Value> {
127         let sig = Signature {
128             params: input_tys.iter().cloned().map(AbiParam::new).collect(),
129             returns: vec![AbiParam::new(output_ty.unwrap_or(types::VOID))],
130             call_conv: CallConv::SystemV,
131             argument_bytes: None,
132         };
133         let func_id = self
134             .module
135             .declare_function(&name, Linkage::Import, &sig)
136             .unwrap();
137         let func_ref = self
138             .module
139             .declare_func_in_func(func_id, &mut self.bcx.func);
140         let call_inst = self.bcx.ins().call(func_ref, args);
141         if output_ty.is_none() {
142             return None;
143         }
144         let results = self.bcx.inst_results(call_inst);
145         assert_eq!(results.len(), 1);
146         Some(results[0])
147     }
148
149     pub fn easy_call(
150         &mut self,
151         name: &str,
152         args: &[CValue<'tcx>],
153         return_ty: Ty<'tcx>,
154     ) -> CValue<'tcx> {
155         let (input_tys, args): (Vec<_>, Vec<_>) = args
156             .into_iter()
157             .map(|arg| {
158                 (
159                     self.cton_type(arg.layout().ty).unwrap(),
160                     arg.load_value(self),
161                 )
162             }).unzip();
163         let return_layout = self.layout_of(return_ty);
164         let return_ty = if let TypeVariants::TyTuple(tup) = return_ty.sty {
165             if !tup.is_empty() {
166                 bug!("easy_call( (...) -> <non empty tuple> ) is not allowed");
167             }
168             None
169         } else {
170             Some(self.cton_type(return_ty).unwrap())
171         };
172         if let Some(val) = self.lib_call(name, input_tys, return_ty, &args) {
173             CValue::ByVal(val, return_layout)
174         } else {
175             CValue::ByRef(self.bcx.ins().iconst(types::I64, 0), return_layout)
176         }
177     }
178
179     fn self_sig(&self) -> FnSig<'tcx> {
180         ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
181     }
182
183     fn return_type(&self) -> Ty<'tcx> {
184         self.self_sig().output()
185     }
186 }
187
188 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(fx: &mut FunctionCx<'a, 'tcx>, start_ebb: Ebb) {
189     match fx.self_sig().abi {
190         Abi::Rust | Abi::RustCall => {}
191         _ => unimplemented!("declared function with non \"rust\" or \"rust-call\" abi"),
192     }
193
194     let ret_param = fx.bcx.append_ebb_param(start_ebb, types::I64);
195     let _ = fx.bcx.create_stack_slot(StackSlotData {
196         kind: StackSlotKind::ExplicitSlot,
197         size: 0,
198         offset: None,
199     }); // Dummy stack slot for debugging
200
201     enum ArgKind {
202         Normal(Value),
203         Spread(Vec<Value>),
204     }
205
206     let func_params = fx.mir.args_iter().map(|local| {
207         let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
208
209         // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
210         if Some(local) == fx.mir.spread_arg {
211             // This argument (e.g. the last argument in the "rust-call" ABI)
212             // is a tuple that was spread at the ABI level and now we have
213             // to reconstruct it into a tuple local variable, from multiple
214             // individual function arguments.
215
216             let tupled_arg_tys = match arg_ty.sty {
217                 ty::TyTuple(ref tys) => tys,
218                 _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
219             };
220
221             let mut ebb_params = Vec::new();
222             for arg_ty in tupled_arg_tys.iter() {
223                 let cton_type = fx.cton_type(arg_ty).unwrap_or(types::I64);
224                 ebb_params.push(fx.bcx.append_ebb_param(start_ebb, cton_type));
225             }
226
227             (local, ArgKind::Spread(ebb_params), arg_ty)
228         } else {
229             let cton_type = fx.cton_type(arg_ty).unwrap_or(types::I64);
230             (local, ArgKind::Normal(fx.bcx.append_ebb_param(start_ebb, cton_type)), arg_ty)
231         }
232     }).collect::<Vec<(Local, ArgKind, Ty)>>();
233
234     let ret_layout = fx.layout_of(fx.return_type());
235     fx.local_map
236         .insert(RETURN_PLACE, CPlace::Addr(ret_param, ret_layout));
237
238     for (local, arg_kind, ty) in func_params {
239         let layout = fx.layout_of(ty);
240         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
241             kind: StackSlotKind::ExplicitSlot,
242             size: layout.size.bytes() as u32,
243             offset: None,
244         });
245
246         let place = CPlace::from_stack_slot(fx, stack_slot, ty);
247
248         match arg_kind {
249             ArgKind::Normal(ebb_param) => {
250                 if fx.cton_type(ty).is_some() {
251                     place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()));
252                 } else {
253                     place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout()));
254                 }
255             }
256             ArgKind::Spread(ebb_params) => {
257                 for (i, ebb_param) in ebb_params.into_iter().enumerate() {
258                     let sub_place = place.place_field(fx, mir::Field::new(i));
259                     if fx.cton_type(sub_place.layout().ty).is_some() {
260                         sub_place.write_cvalue(fx, CValue::ByVal(ebb_param, sub_place.layout()));
261                     } else {
262                         sub_place.write_cvalue(fx, CValue::ByRef(ebb_param, sub_place.layout()));
263                     }
264                 }
265             }
266         }
267         fx.local_map.insert(local, place);
268     }
269
270     for local in fx.mir.vars_and_temps_iter() {
271         let ty = fx.mir.local_decls[local].ty;
272         let layout = fx.layout_of(ty);
273         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
274             kind: StackSlotKind::ExplicitSlot,
275             size: layout.size.bytes() as u32,
276             offset: None,
277         });
278         let place = CPlace::from_stack_slot(fx, stack_slot, ty);
279         fx.local_map.insert(local, place);
280     }
281 }
282
283 pub fn codegen_call<'a, 'tcx: 'a>(
284     fx: &mut FunctionCx<'a, 'tcx>,
285     func: &Operand<'tcx>,
286     args: &[Operand<'tcx>],
287     destination: &Option<(Place<'tcx>, BasicBlock)>,
288 ) {
289     let func = trans_operand(fx, func);
290     let fn_ty = func.layout().ty;
291     let sig = ty_fn_sig(fx.tcx, fn_ty);
292
293     let return_place = destination.as_ref().map(|(place, _)| trans_place(fx, place));
294
295     // Unpack arguments tuple for closures
296     let args = if sig.abi == Abi::RustCall {
297         assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
298         let self_arg = trans_operand(fx, &args[0]);
299         let pack_arg = trans_operand(fx, &args[1]);
300         let mut args = Vec::new();
301         args.push(self_arg);
302         match pack_arg.layout().ty.sty {
303             ty::TyTuple(ref tupled_arguments) => {
304                 for (i, _) in tupled_arguments.iter().enumerate() {
305                     args.push(pack_arg.value_field(fx, mir::Field::new(i)));
306                 }
307             }
308             _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
309         }
310         println!(
311             "{:?} {:?}",
312             pack_arg.layout().ty,
313             args.iter().map(|a| a.layout().ty).collect::<Vec<_>>()
314         );
315         args
316     } else {
317         args.into_iter()
318             .map(|arg| trans_operand(fx, arg))
319             .collect::<Vec<_>>()
320     };
321
322     if let TypeVariants::TyFnDef(def_id, substs) = fn_ty.sty {
323         if sig.abi == Abi::RustIntrinsic {
324             let intrinsic = fx.tcx.item_name(def_id).as_str();
325             let intrinsic = &intrinsic[..];
326
327             let nil_ty = fx.tcx.mk_nil();
328             let u64_layout = fx.layout_of(fx.tcx.types.u64);
329             let usize_layout = fx.layout_of(fx.tcx.types.usize);
330
331             let ret = match return_place {
332                 Some(ret) => ret,
333                 None => {
334                     println!("codegen_call(fx, {:?}, {:?}, {:?})", func, args, destination);
335                     // Insert non returning intrinsics here
336                     match intrinsic {
337                         "abort" => {
338                             fx.bcx.ins().trap(TrapCode::User(!0 - 1));
339                         }
340                         "unreachable" => {
341                             fx.bcx.ins().trap(TrapCode::User(!0 - 1));
342                         }
343                         _ => unimplemented!("unsupported instrinsic {}", intrinsic),
344                     }
345                     return;
346                 }
347             };
348             match intrinsic {
349                 "assume" => {
350                     assert_eq!(args.len(), 1);
351                 }
352                 "likely" | "unlikely" => {
353                     assert_eq!(args.len(), 1);
354                     ret.write_cvalue(fx, args[0]);
355                 }
356                 "copy" | "copy_nonoverlapping" => {
357                     let elem_ty = substs.type_at(0);
358                     let elem_size: u64 = fx.layout_of(elem_ty).size.bytes();
359                     let elem_size = fx.bcx.ins().iconst(types::I64, elem_size as i64);
360                     assert_eq!(args.len(), 3);
361                     let src = args[0];
362                     let dst = args[1];
363                     let count = args[2].load_value(fx);
364                     let byte_amount = fx.bcx.ins().imul(count, elem_size);
365                     fx.easy_call(
366                         "memmove",
367                         &[dst, src, CValue::ByVal(byte_amount, usize_layout)],
368                         nil_ty,
369                     );
370                 }
371                 "discriminant_value" => {
372                     assert_eq!(args.len(), 1);
373                     let discr = crate::base::trans_get_discriminant(fx, args[0], ret.layout());
374                     ret.write_cvalue(fx, discr);
375                 }
376                 "size_of" => {
377                     assert_eq!(args.len(), 0);
378                     let size_of = fx.layout_of(substs.type_at(0)).size.bytes();
379                     let size_of = CValue::const_val(fx, usize_layout.ty, size_of as i64);
380                     ret.write_cvalue(fx, size_of);
381                 }
382                 "type_id" => {
383                     assert_eq!(args.len(), 0);
384                     let type_id = fx.tcx.type_id_hash(substs.type_at(0));
385                     let type_id = CValue::const_val(fx, u64_layout.ty, type_id as i64);
386                     ret.write_cvalue(fx, type_id);
387                 }
388                 "min_align_of" => {
389                     assert_eq!(args.len(), 0);
390                     let min_align = fx.layout_of(substs.type_at(0)).align.abi();
391                     let min_align = CValue::const_val(fx, usize_layout.ty, min_align as i64);
392                     ret.write_cvalue(fx, min_align);
393                 }
394                 _ if intrinsic.starts_with("unchecked_") => {
395                     assert_eq!(args.len(), 2);
396                     let bin_op = match intrinsic {
397                         "unchecked_div" => BinOp::Div,
398                         "unchecked_rem" => BinOp::Rem,
399                         "unchecked_shl" => BinOp::Shl,
400                         "unchecked_shr" => BinOp::Shr,
401                         _ => unimplemented!("intrinsic {}", intrinsic),
402                     };
403                     let res = match ret.layout().ty.sty {
404                         TypeVariants::TyUint(_) => crate::base::trans_int_binop(
405                             fx,
406                             bin_op,
407                             args[0],
408                             args[1],
409                             ret.layout().ty,
410                             false,
411                         ),
412                         TypeVariants::TyInt(_) => crate::base::trans_int_binop(
413                             fx,
414                             bin_op,
415                             args[0],
416                             args[1],
417                             ret.layout().ty,
418                             true,
419                         ),
420                         _ => panic!(),
421                     };
422                     ret.write_cvalue(fx, res);
423                 }
424                 _ if intrinsic.ends_with("_with_overflow") => {
425                     assert_eq!(args.len(), 2);
426                     assert_eq!(args[0].layout().ty, args[1].layout().ty);
427                     let bin_op = match intrinsic {
428                         "add_with_overflow" => BinOp::Add,
429                         "sub_with_overflow" => BinOp::Sub,
430                         "mul_with_overflow" => BinOp::Mul,
431                         _ => unimplemented!("intrinsic {}", intrinsic),
432                     };
433                     let res = match args[0].layout().ty.sty {
434                         TypeVariants::TyUint(_) => crate::base::trans_checked_int_binop(
435                             fx,
436                             bin_op,
437                             args[0],
438                             args[1],
439                             ret.layout().ty,
440                             false,
441                         ),
442                         TypeVariants::TyInt(_) => crate::base::trans_checked_int_binop(
443                             fx,
444                             bin_op,
445                             args[0],
446                             args[1],
447                             ret.layout().ty,
448                             true,
449                         ),
450                         _ => panic!(),
451                     };
452                     ret.write_cvalue(fx, res);
453                 }
454                 _ if intrinsic.starts_with("overflowing_") => {
455                     assert_eq!(args.len(), 2);
456                     assert_eq!(args[0].layout().ty, args[1].layout().ty);
457                     let bin_op = match intrinsic {
458                         "overflowing_add" => BinOp::Add,
459                         "overflowing_sub" => BinOp::Sub,
460                         "overflowing_mul" => BinOp::Mul,
461                         _ => unimplemented!("intrinsic {}", intrinsic),
462                     };
463                     let res = match args[0].layout().ty.sty {
464                         TypeVariants::TyUint(_) => crate::base::trans_int_binop(
465                             fx,
466                             bin_op,
467                             args[0],
468                             args[1],
469                             ret.layout().ty,
470                             false,
471                         ),
472                         TypeVariants::TyInt(_) => crate::base::trans_int_binop(
473                             fx,
474                             bin_op,
475                             args[0],
476                             args[1],
477                             ret.layout().ty,
478                             true,
479                         ),
480                         _ => panic!(),
481                     };
482                     ret.write_cvalue(fx, res);
483                 }
484                 "offset" => {
485                     assert_eq!(args.len(), 2);
486                     let base = args[0].load_value(fx);
487                     let offset = args[1].load_value(fx);
488                     let res = fx.bcx.ins().iadd(base, offset);
489                     ret.write_cvalue(fx, CValue::ByVal(res, args[0].layout()));
490                 }
491                 "transmute" => {
492                     assert_eq!(args.len(), 1);
493                     let src_ty = substs.type_at(0);
494                     let dst_ty = substs.type_at(1);
495                     assert_eq!(args[0].layout().ty, src_ty);
496                     let addr = args[0].force_stack(fx);
497                     let dst_layout = fx.layout_of(dst_ty);
498                     ret.write_cvalue(fx, CValue::ByRef(addr, dst_layout))
499                 }
500                 "uninit" => {
501                     assert_eq!(args.len(), 0);
502                     let ty = substs.type_at(0);
503                     let layout = fx.layout_of(ty);
504                     let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
505                         kind: StackSlotKind::ExplicitSlot,
506                         size: layout.size.bytes() as u32,
507                         offset: None,
508                     });
509
510                     let uninit_place = CPlace::from_stack_slot(fx, stack_slot, ty);
511                     let uninit_val = uninit_place.to_cvalue(fx);
512                     ret.write_cvalue(fx, uninit_val);
513                 }
514                 "ctlz" | "ctlz_nonzero" => {
515                     assert_eq!(args.len(), 1);
516                     let arg = args[0].load_value(fx);
517                     let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
518                     ret.write_cvalue(fx, res);
519                 }
520                 "cttz" | "cttz_nonzero" => {
521                     assert_eq!(args.len(), 1);
522                     let arg = args[0].load_value(fx);
523                     let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
524                     ret.write_cvalue(fx, res);
525                 }
526                 "ctpop" => {
527                     assert_eq!(args.len(), 1);
528                     let arg = args[0].load_value(fx);
529                     let res = CValue::ByVal(fx.bcx.ins().popcnt(arg), args[0].layout());
530                     ret.write_cvalue(fx, res);
531                 }
532                 _ => unimpl!("unsupported intrinsic {}", intrinsic),
533             }
534             if let Some((_, dest)) = *destination {
535                 let ret_ebb = fx.get_ebb(dest);
536                 fx.bcx.ins().jump(ret_ebb, &[]);
537             } else {
538                 fx.bcx.ins().trap(TrapCode::User(!0));
539             }
540             return;
541         }
542     }
543
544     let return_ptr = match return_place {
545         Some(place) => place.expect_addr(),
546         None => fx.bcx.ins().iconst(types::I64, 0),
547     };
548
549     let call_args = Some(return_ptr)
550         .into_iter()
551         .chain(args.into_iter().map(|arg| {
552             if fx.cton_type(arg.layout().ty).is_some() {
553                 arg.load_value(fx)
554             } else {
555                 arg.force_stack(fx)
556             }
557         })).collect::<Vec<_>>();
558
559     match func {
560         CValue::Func(func, _) => {
561             fx.bcx.ins().call(func, &call_args);
562         }
563         func => {
564             let func_ty = func.layout().ty;
565             let func = func.load_value(fx);
566             let sig = fx
567                 .bcx
568                 .import_signature(cton_sig_from_fn_ty(fx.tcx, func_ty));
569             fx.bcx.ins().call_indirect(sig, func, &call_args);
570         }
571     }
572     if let Some((_, dest)) = *destination {
573         let ret_ebb = fx.get_ebb(dest);
574         fx.bcx.ins().jump(ret_ebb, &[]);
575     } else {
576         fx.bcx.ins().trap(TrapCode::User(!0));
577     }
578 }