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