]> git.lizzy.rs Git - rust.git/blob - src/abi.rs
Move trapping to trap_code.rs
[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 #[derive(Debug)]
9 enum PassMode {
10     NoPass,
11     ByVal(Type),
12     ByRef,
13 }
14
15 impl PassMode {
16     fn get_param_ty(self, fx: &FunctionCx<impl Backend>) -> Type {
17         match self {
18             PassMode::NoPass => unimplemented!("pass mode nopass"),
19             PassMode::ByVal(clif_type) => clif_type,
20             PassMode::ByRef => fx.pointer_type,
21         }
22     }
23 }
24
25 fn get_pass_mode<'a, 'tcx: 'a>(
26     tcx: TyCtxt<'a, 'tcx, 'tcx>,
27     abi: Abi,
28     ty: Ty<'tcx>,
29     is_return: bool,
30 ) -> PassMode {
31     assert!(!tcx
32         .layout_of(ParamEnv::reveal_all().and(ty))
33         .unwrap()
34         .is_unsized());
35     if let ty::Never = ty.sty {
36         if is_return {
37             PassMode::NoPass
38         } else {
39             PassMode::ByRef
40         }
41     } else if ty.sty == tcx.mk_unit().sty {
42         if is_return {
43             PassMode::NoPass
44         } else {
45             PassMode::ByRef
46         }
47     } else if let Some(ret_ty) = crate::common::clif_type_from_ty(tcx, ty) {
48         PassMode::ByVal(ret_ty)
49     } else {
50         if abi == Abi::C {
51             unimpl!(
52                 "Non scalars are not yet supported for \"C\" abi ({:?}) is_return: {:?}",
53                 ty,
54                 is_return
55             );
56         }
57         PassMode::ByRef
58     }
59 }
60
61 fn adjust_arg_for_abi<'a, 'tcx: 'a>(
62     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
63     sig: FnSig<'tcx>,
64     arg: CValue<'tcx>,
65 ) -> Value {
66     match get_pass_mode(fx.tcx, sig.abi, arg.layout().ty, false) {
67         PassMode::NoPass => unimplemented!("pass mode nopass"),
68         PassMode::ByVal(_) => arg.load_value(fx),
69         PassMode::ByRef => arg.force_stack(fx),
70     }
71 }
72
73 pub fn clif_sig_from_fn_ty<'a, 'tcx: 'a>(
74     tcx: TyCtxt<'a, 'tcx, 'tcx>,
75     fn_ty: Ty<'tcx>,
76 ) -> Signature {
77     let sig = ty_fn_sig(tcx, fn_ty);
78     if sig.variadic {
79         unimpl!("Variadic function are not yet supported");
80     }
81     let (call_conv, inputs, output): (CallConv, Vec<Ty>, Ty) = match sig.abi {
82         Abi::Rust => (CallConv::Fast, sig.inputs().to_vec(), sig.output()),
83         Abi::C => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
84         Abi::RustCall => {
85             assert_eq!(sig.inputs().len(), 2);
86             let extra_args = match sig.inputs().last().unwrap().sty {
87                 ty::Tuple(ref tupled_arguments) => tupled_arguments,
88                 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
89             };
90             let mut inputs: Vec<Ty> = vec![sig.inputs()[0]];
91             inputs.extend(extra_args.into_iter());
92             (CallConv::Fast, inputs, sig.output())
93         }
94         Abi::System => bug!("system abi should be selected elsewhere"),
95         Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
96         _ => unimplemented!("unsupported abi {:?}", sig.abi),
97     };
98
99     let inputs = inputs
100         .into_iter()
101         .filter_map(|ty| match get_pass_mode(tcx, sig.abi, ty, false) {
102             PassMode::ByVal(clif_ty) => Some(clif_ty),
103             PassMode::NoPass => unimplemented!("pass mode nopass"),
104             PassMode::ByRef => Some(pointer_ty(tcx)),
105         });
106
107     let (params, returns) = match get_pass_mode(tcx, sig.abi, output, true) {
108         PassMode::NoPass => (inputs.map(AbiParam::new).collect(), vec![]),
109         PassMode::ByVal(ret_ty) => (
110             inputs.map(AbiParam::new).collect(),
111             vec![AbiParam::new(ret_ty)],
112         ),
113         PassMode::ByRef => {
114             (
115                 Some(pointer_ty(tcx)) // First param is place to put return val
116                     .into_iter()
117                     .chain(inputs)
118                     .map(AbiParam::new)
119                     .collect(),
120                 vec![],
121             )
122         }
123     };
124
125     Signature {
126         params,
127         returns,
128         call_conv,
129     }
130 }
131
132 fn ty_fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> ty::FnSig<'tcx> {
133     let sig = match ty.sty {
134         ty::FnDef(..) |
135         // Shims currently have type TyFnPtr. Not sure this should remain.
136         ty::FnPtr(_) => ty.fn_sig(tcx),
137         ty::Closure(def_id, substs) => {
138             let sig = substs.closure_sig(def_id, tcx);
139
140             let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
141             sig.map_bound(|sig| tcx.mk_fn_sig(
142                 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
143                 sig.output(),
144                 sig.variadic,
145                 sig.unsafety,
146                 sig.abi
147             ))
148         }
149         ty::Generator(def_id, substs, _) => {
150             let sig = substs.poly_sig(def_id, tcx);
151
152             let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
153             let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
154
155             sig.map_bound(|sig| {
156                 let state_did = tcx.lang_items().gen_state().unwrap();
157                 let state_adt_ref = tcx.adt_def(state_did);
158                 let state_substs = tcx.intern_substs(&[
159                     sig.yield_ty.into(),
160                     sig.return_ty.into(),
161                 ]);
162                 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
163
164                 tcx.mk_fn_sig(iter::once(env_ty),
165                     ret_ty,
166                     false,
167                     hir::Unsafety::Normal,
168                     Abi::Rust
169                 )
170             })
171         }
172         _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
173     };
174     tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig)
175 }
176
177 pub fn get_function_name_and_sig<'a, 'tcx>(
178     tcx: TyCtxt<'a, 'tcx, 'tcx>,
179     inst: Instance<'tcx>,
180 ) -> (String, Signature) {
181     assert!(!inst.substs.needs_infer() && !inst.substs.has_param_types());
182     let fn_ty = inst.ty(tcx);
183     let sig = clif_sig_from_fn_ty(tcx, fn_ty);
184     (tcx.symbol_name(inst).as_str().to_string(), sig)
185 }
186
187 impl<'a, 'tcx: 'a, B: Backend + 'a> FunctionCx<'a, 'tcx, B> {
188     /// Instance must be monomorphized
189     pub fn get_function_id(&mut self, inst: Instance<'tcx>) -> FuncId {
190         let (name, sig) = get_function_name_and_sig(self.tcx, inst);
191         self.module
192             .declare_function(&name, Linkage::Import, &sig)
193             .unwrap()
194     }
195
196     /// Instance must be monomorphized
197     pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
198         let func_id = self.get_function_id(inst);
199         self.module
200             .declare_func_in_func(func_id, &mut self.bcx.func)
201     }
202
203     fn lib_call(
204         &mut self,
205         name: &str,
206         input_tys: Vec<types::Type>,
207         output_ty: Option<types::Type>,
208         args: &[Value],
209     ) -> Option<Value> {
210         let sig = Signature {
211             params: input_tys.iter().cloned().map(AbiParam::new).collect(),
212             returns: output_ty
213                 .map(|output_ty| vec![AbiParam::new(output_ty)])
214                 .unwrap_or(Vec::new()),
215             call_conv: CallConv::SystemV,
216         };
217         let func_id = self
218             .module
219             .declare_function(&name, Linkage::Import, &sig)
220             .unwrap();
221         let func_ref = self
222             .module
223             .declare_func_in_func(func_id, &mut self.bcx.func);
224         let call_inst = self.bcx.ins().call(func_ref, args);
225         if output_ty.is_none() {
226             return None;
227         }
228         let results = self.bcx.inst_results(call_inst);
229         assert_eq!(results.len(), 1);
230         Some(results[0])
231     }
232
233     pub fn easy_call(
234         &mut self,
235         name: &str,
236         args: &[CValue<'tcx>],
237         return_ty: Ty<'tcx>,
238     ) -> CValue<'tcx> {
239         let (input_tys, args): (Vec<_>, Vec<_>) = args
240             .into_iter()
241             .map(|arg| {
242                 (
243                     self.clif_type(arg.layout().ty).unwrap(),
244                     arg.load_value(self),
245                 )
246             })
247             .unzip();
248         let return_layout = self.layout_of(return_ty);
249         let return_ty = if let ty::Tuple(tup) = return_ty.sty {
250             if !tup.is_empty() {
251                 bug!("easy_call( (...) -> <non empty tuple> ) is not allowed");
252             }
253             None
254         } else {
255             Some(self.clif_type(return_ty).unwrap())
256         };
257         if let Some(val) = self.lib_call(name, input_tys, return_ty, &args) {
258             CValue::ByVal(val, return_layout)
259         } else {
260             CValue::ByRef(self.bcx.ins().iconst(self.pointer_type, 0), return_layout)
261         }
262     }
263
264     fn self_sig(&self) -> FnSig<'tcx> {
265         ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
266     }
267
268     fn return_type(&self) -> Ty<'tcx> {
269         self.self_sig().output()
270     }
271 }
272
273 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(
274     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
275     start_ebb: Ebb,
276 ) {
277     let ssa_analyzed = crate::analyze::analyze(fx);
278
279     let ret_layout = fx.layout_of(fx.return_type());
280     let output_pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true);
281     let ret_param = match output_pass_mode {
282         PassMode::NoPass => None,
283         PassMode::ByVal(_) => None,
284         PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, fx.pointer_type)),
285     };
286
287     enum ArgKind {
288         Normal(Value),
289         Spread(Vec<Value>),
290     }
291
292     let func_params = fx
293         .mir
294         .args_iter()
295         .map(|local| {
296             let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
297
298             // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
299             if Some(local) == fx.mir.spread_arg {
300                 // This argument (e.g. the last argument in the "rust-call" ABI)
301                 // is a tuple that was spread at the ABI level and now we have
302                 // to reconstruct it into a tuple local variable, from multiple
303                 // individual function arguments.
304
305                 let tupled_arg_tys = match arg_ty.sty {
306                     ty::Tuple(ref tys) => tys,
307                     _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
308                 };
309
310                 let mut ebb_params = Vec::new();
311                 for arg_ty in tupled_arg_tys.iter() {
312                     let clif_type =
313                         get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
314                     ebb_params.push(fx.bcx.append_ebb_param(start_ebb, clif_type));
315                 }
316
317                 (local, ArgKind::Spread(ebb_params), arg_ty)
318             } else {
319                 let clif_type =
320                     get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
321                 (
322                     local,
323                     ArgKind::Normal(fx.bcx.append_ebb_param(start_ebb, clif_type)),
324                     arg_ty,
325                 )
326             }
327         })
328         .collect::<Vec<(Local, ArgKind, Ty)>>();
329
330     fx.bcx.switch_to_block(start_ebb);
331
332     fx.top_nop = Some(fx.bcx.ins().nop());
333     fx.add_global_comment(format!("ssa {:?}", ssa_analyzed));
334
335     for local in fx.mir.args_iter() {
336         let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
337         let pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false);
338         fx.add_global_comment(format!("pass {:?}: {:?} {:?}", local, arg_ty, pass_mode));
339     }
340
341     match output_pass_mode {
342         PassMode::NoPass => {
343             let null = fx.bcx.ins().iconst(fx.pointer_type, 0);
344             //unimplemented!("pass mode nopass");
345             fx.local_map.insert(
346                 RETURN_PLACE,
347                 CPlace::Addr(null, None, fx.layout_of(fx.return_type())),
348             );
349         }
350         PassMode::ByVal(ret_ty) => {
351             fx.bcx.declare_var(mir_var(RETURN_PLACE), ret_ty);
352             fx.local_map
353                 .insert(RETURN_PLACE, CPlace::Var(RETURN_PLACE, ret_layout));
354         }
355         PassMode::ByRef => {
356             fx.local_map.insert(
357                 RETURN_PLACE,
358                 CPlace::Addr(ret_param.unwrap(), None, ret_layout),
359             );
360         }
361     }
362
363     for (local, arg_kind, ty) in func_params {
364         let layout = fx.layout_of(ty);
365
366         if let ArgKind::Normal(ebb_param) = arg_kind {
367             if !ssa_analyzed
368                 .get(&local)
369                 .unwrap()
370                 .contains(crate::analyze::Flags::NOT_SSA)
371             {
372                 fx.bcx
373                     .declare_var(mir_var(local), fx.clif_type(ty).unwrap());
374                 match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false) {
375                     PassMode::NoPass => unimplemented!("pass mode nopass"),
376                     PassMode::ByVal(_) => fx.bcx.def_var(mir_var(local), ebb_param),
377                     PassMode::ByRef => {
378                         let val = CValue::ByRef(ebb_param, fx.layout_of(ty)).load_value(fx);
379                         fx.bcx.def_var(mir_var(local), val);
380                     }
381                 }
382                 fx.local_map.insert(local, CPlace::Var(local, layout));
383                 continue;
384             }
385         }
386
387         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
388             kind: StackSlotKind::ExplicitSlot,
389             size: layout.size.bytes() as u32,
390             offset: None,
391         });
392
393         let place = CPlace::from_stack_slot(fx, stack_slot, ty);
394
395         match arg_kind {
396             ArgKind::Normal(ebb_param) => match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false)
397             {
398                 PassMode::NoPass => unimplemented!("pass mode nopass"),
399                 PassMode::ByVal(_) => {
400                     place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()))
401                 }
402                 PassMode::ByRef => place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout())),
403             },
404             ArgKind::Spread(ebb_params) => {
405                 for (i, ebb_param) in ebb_params.into_iter().enumerate() {
406                     let sub_place = place.place_field(fx, mir::Field::new(i));
407                     match get_pass_mode(fx.tcx, fx.self_sig().abi, sub_place.layout().ty, false) {
408                         PassMode::NoPass => unimplemented!("pass mode nopass"),
409                         PassMode::ByVal(_) => {
410                             sub_place.write_cvalue(fx, CValue::ByVal(ebb_param, sub_place.layout()))
411                         }
412                         PassMode::ByRef => {
413                             sub_place.write_cvalue(fx, CValue::ByRef(ebb_param, sub_place.layout()))
414                         }
415                     }
416                 }
417             }
418         }
419         fx.local_map.insert(local, place);
420     }
421
422     for local in fx.mir.vars_and_temps_iter() {
423         let ty = fx.mir.local_decls[local].ty;
424         let layout = fx.layout_of(ty);
425
426         let place = if ssa_analyzed
427             .get(&local)
428             .unwrap()
429             .contains(crate::analyze::Flags::NOT_SSA)
430         {
431             let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
432                 kind: StackSlotKind::ExplicitSlot,
433                 size: layout.size.bytes() as u32,
434                 offset: None,
435             });
436             CPlace::from_stack_slot(fx, stack_slot, ty)
437         } else {
438             fx.bcx
439                 .declare_var(mir_var(local), fx.clif_type(ty).unwrap());
440             CPlace::Var(local, layout)
441         };
442
443         fx.local_map.insert(local, place);
444     }
445
446     fx.bcx
447         .ins()
448         .jump(*fx.ebb_map.get(&START_BLOCK).unwrap(), &[]);
449 }
450
451 pub fn codegen_terminator_call<'a, 'tcx: 'a>(
452     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
453     func: &Operand<'tcx>,
454     args: &[Operand<'tcx>],
455     destination: &Option<(Place<'tcx>, BasicBlock)>,
456 ) {
457     let fn_ty = fx.monomorphize(&func.ty(fx.mir, fx.tcx));
458     let sig = ty_fn_sig(fx.tcx, fn_ty);
459
460     // Unpack arguments tuple for closures
461     let args = if sig.abi == Abi::RustCall {
462         assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
463         let self_arg = trans_operand(fx, &args[0]);
464         let pack_arg = trans_operand(fx, &args[1]);
465         let mut args = Vec::new();
466         args.push(self_arg);
467         match pack_arg.layout().ty.sty {
468             ty::Tuple(ref tupled_arguments) => {
469                 for (i, _) in tupled_arguments.iter().enumerate() {
470                     args.push(pack_arg.value_field(fx, mir::Field::new(i)));
471                 }
472             }
473             _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
474         }
475         args
476     } else {
477         args.into_iter()
478             .map(|arg| trans_operand(fx, arg))
479             .collect::<Vec<_>>()
480     };
481
482     let destination = destination
483         .as_ref()
484         .map(|&(ref place, bb)| (trans_place(fx, place), bb));
485
486     if let ty::FnDef(def_id, substs) = fn_ty.sty {
487         let sig = ty_fn_sig(fx.tcx, fn_ty);
488
489         if sig.abi == Abi::RustIntrinsic {
490             crate::intrinsics::codegen_intrinsic_call(fx, def_id, substs, args, destination);
491             return;
492         }
493     }
494
495     codegen_call_inner(
496         fx,
497         Some(func),
498         fn_ty,
499         args,
500         destination.map(|(place, _)| place),
501     );
502
503     if let Some((_, dest)) = destination {
504         let ret_ebb = fx.get_ebb(dest);
505         fx.bcx.ins().jump(ret_ebb, &[]);
506     } else {
507         trap_unreachable(&mut fx.bcx);
508     }
509 }
510
511 pub fn codegen_call_inner<'a, 'tcx: 'a>(
512     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
513     func: Option<&Operand<'tcx>>,
514     fn_ty: Ty<'tcx>,
515     args: Vec<CValue<'tcx>>,
516     ret_place: Option<CPlace<'tcx>>,
517 ) {
518     let sig = ty_fn_sig(fx.tcx, fn_ty);
519
520     let ret_layout = fx.layout_of(sig.output());
521
522     let output_pass_mode = get_pass_mode(fx.tcx, sig.abi, sig.output(), true);
523     let return_ptr = match output_pass_mode {
524         PassMode::NoPass => None,
525         PassMode::ByRef => match ret_place {
526             Some(ret_place) => Some(ret_place.expect_addr()),
527             None => Some(fx.bcx.ins().iconst(fx.pointer_type, 0)),
528         },
529         PassMode::ByVal(_) => None,
530     };
531
532     let instance = match fn_ty.sty {
533         ty::FnDef(def_id, substs) => {
534             Some(Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap())
535         }
536         _ => None,
537     };
538
539     let func_ref: Option<Value>; // Indirect call target
540
541     let first_arg = {
542         if let Some(Instance {
543             def: InstanceDef::Virtual(_, idx),
544             ..
545         }) = instance
546         {
547             let (ptr, method) = crate::vtable::get_ptr_and_method_ref(fx, args[0], idx);
548             func_ref = Some(method);
549             Some(ptr)
550         } else {
551             func_ref = if instance.is_none() {
552                 let func = trans_operand(fx, func.expect("indirect call without func Operand"));
553                 Some(func.load_value(fx))
554             } else {
555                 None
556             };
557
558             args.get(0).map(|arg| adjust_arg_for_abi(fx, sig, *arg))
559         }
560         .into_iter()
561     };
562
563     let call_args: Vec<Value> = return_ptr
564         .into_iter()
565         .chain(first_arg)
566         .chain(
567             args.into_iter()
568                 .skip(1)
569                 .map(|arg| adjust_arg_for_abi(fx, sig, arg)),
570         )
571         .collect::<Vec<_>>();
572
573     let sig = fx.bcx.import_signature(clif_sig_from_fn_ty(fx.tcx, fn_ty));
574     let call_inst = if let Some(func_ref) = func_ref {
575         fx.bcx.ins().call_indirect(sig, func_ref, &call_args)
576     } else {
577         let func_ref = fx.get_function_ref(instance.expect("non-indirect call on non-FnDef type"));
578         fx.bcx.ins().call(func_ref, &call_args)
579     };
580
581     match output_pass_mode {
582         PassMode::NoPass => {}
583         PassMode::ByVal(_) => {
584             if let Some(ret_place) = ret_place {
585                 let results = fx.bcx.inst_results(call_inst);
586                 ret_place.write_cvalue(fx, CValue::ByVal(results[0], ret_layout));
587             }
588         }
589         PassMode::ByRef => {}
590     }
591 }
592
593 pub fn codegen_return(fx: &mut FunctionCx<impl Backend>) {
594     match get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true) {
595         PassMode::NoPass | PassMode::ByRef => {
596             fx.bcx.ins().return_(&[]);
597         }
598         PassMode::ByVal(_) => {
599             let place = fx.get_local_place(RETURN_PLACE);
600             let ret_val = place.to_cvalue(fx).load_value(fx);
601             fx.bcx.ins().return_(&[ret_val]);
602         }
603     }
604 }