5 use rustc_target::spec::abi::Abi;
17 fn get_param_ty(self, fx: &FunctionCx<impl Backend>) -> Type {
19 PassMode::NoPass => unimplemented!("pass mode nopass"),
20 PassMode::ByVal(clif_type) => clif_type,
21 PassMode::ByRef => fx.pointer_type,
26 fn get_pass_mode<'a, 'tcx: 'a>(
27 tcx: TyCtxt<'a, 'tcx, 'tcx>,
33 .layout_of(ParamEnv::reveal_all().and(ty))
36 if let ty::Never = ty.sty {
42 } else if ty.sty == tcx.mk_unit().sty {
48 } else if let Some(ret_ty) = crate::common::clif_type_from_ty(tcx, ty) {
49 PassMode::ByVal(ret_ty)
53 "Non scalars are not yet supported for \"C\" abi ({:?}) is_return: {:?}",
62 fn adjust_arg_for_abi<'a, 'tcx: 'a>(
63 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
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),
74 fn clif_sig_from_fn_ty<'a, 'tcx: 'a>(
75 tcx: TyCtxt<'a, 'tcx, 'tcx>,
78 let sig = ty_fn_sig(tcx, fn_ty);
80 unimpl!("Variadic function are not yet supported");
82 let (call_conv, inputs, output): (CallConv, Vec<Ty>, Ty) = match sig.abi {
83 Abi::Rust => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
84 Abi::C => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
86 assert_eq!(sig.inputs().len(), 2);
87 let extra_args = match sig.inputs().last().unwrap().sty {
88 ty::Tuple(ref tupled_arguments) => tupled_arguments,
89 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
91 let mut inputs: Vec<Ty> = vec![sig.inputs()[0]];
92 inputs.extend(extra_args.into_iter());
93 (CallConv::SystemV, inputs, sig.output())
95 Abi::System => bug!("system abi should be selected elsewhere"),
96 Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
97 _ => unimplemented!("unsupported abi {:?}", sig.abi),
102 .filter_map(|ty| match get_pass_mode(tcx, sig.abi, ty, false) {
103 PassMode::ByVal(clif_ty) => Some(clif_ty),
104 PassMode::NoPass => unimplemented!("pass mode nopass"),
105 PassMode::ByRef => Some(pointer_ty(tcx)),
108 let (params, returns) = match get_pass_mode(tcx, sig.abi, output, true) {
109 PassMode::NoPass => (inputs.map(AbiParam::new).collect(), vec![]),
110 PassMode::ByVal(ret_ty) => (
111 inputs.map(AbiParam::new).collect(),
112 vec![AbiParam::new(ret_ty)],
116 Some(pointer_ty(tcx)) // First param is place to put return val
133 pub fn ty_fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> ty::FnSig<'tcx> {
134 let sig = match ty.sty {
136 // Shims currently have type TyFnPtr. Not sure this should remain.
137 ty::FnPtr(_) => ty.fn_sig(tcx),
138 ty::Closure(def_id, substs) => {
139 let sig = substs.closure_sig(def_id, tcx);
141 let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
142 sig.map_bound(|sig| tcx.mk_fn_sig(
143 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
150 ty::Generator(def_id, substs, _) => {
151 let sig = substs.poly_sig(def_id, tcx);
153 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
154 let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
156 sig.map_bound(|sig| {
157 let state_did = tcx.lang_items().gen_state().unwrap();
158 let state_adt_ref = tcx.adt_def(state_did);
159 let state_substs = tcx.intern_substs(&[
161 sig.return_ty.into(),
163 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
165 tcx.mk_fn_sig(iter::once(env_ty),
168 hir::Unsafety::Normal,
173 _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
175 tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig)
178 pub fn get_function_name_and_sig<'a, 'tcx>(
179 tcx: TyCtxt<'a, 'tcx, 'tcx>,
180 inst: Instance<'tcx>,
181 ) -> (String, Signature) {
182 assert!(!inst.substs.needs_infer() && !inst.substs.has_param_types());
183 let fn_ty = inst.ty(tcx);
184 let sig = clif_sig_from_fn_ty(tcx, fn_ty);
185 (tcx.symbol_name(inst).as_str().to_string(), sig)
188 impl<'a, 'tcx: 'a, B: Backend + 'a> FunctionCx<'a, 'tcx, B> {
189 /// Instance must be monomorphized
190 pub fn get_function_id(&mut self, inst: Instance<'tcx>) -> FuncId {
191 let (name, sig) = get_function_name_and_sig(self.tcx, inst);
193 .declare_function(&name, Linkage::Import, &sig)
197 /// Instance must be monomorphized
198 pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
199 let func_id = self.get_function_id(inst);
201 .declare_func_in_func(func_id, &mut self.bcx.func)
207 input_tys: Vec<types::Type>,
208 output_ty: Option<types::Type>,
211 let sig = Signature {
212 params: input_tys.iter().cloned().map(AbiParam::new).collect(),
214 .map(|output_ty| vec![AbiParam::new(output_ty)])
215 .unwrap_or(Vec::new()),
216 call_conv: CallConv::SystemV,
220 .declare_function(&name, Linkage::Import, &sig)
224 .declare_func_in_func(func_id, &mut self.bcx.func);
225 let call_inst = self.bcx.ins().call(func_ref, args);
226 if output_ty.is_none() {
229 let results = self.bcx.inst_results(call_inst);
230 assert_eq!(results.len(), 1);
237 args: &[CValue<'tcx>],
240 let (input_tys, args): (Vec<_>, Vec<_>) = args
244 self.clif_type(arg.layout().ty).unwrap(),
245 arg.load_value(self),
249 let return_layout = self.layout_of(return_ty);
250 let return_ty = if let ty::Tuple(tup) = return_ty.sty {
252 bug!("easy_call( (...) -> <non empty tuple> ) is not allowed");
256 Some(self.clif_type(return_ty).unwrap())
258 if let Some(val) = self.lib_call(name, input_tys, return_ty, &args) {
259 CValue::ByVal(val, return_layout)
261 CValue::ByRef(self.bcx.ins().iconst(self.pointer_type, 0), return_layout)
265 fn self_sig(&self) -> FnSig<'tcx> {
266 ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
269 fn return_type(&self) -> Ty<'tcx> {
270 self.self_sig().output()
274 fn add_local_comment<'a, 'tcx: 'a>(
275 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
278 local_field: Option<usize>,
279 param: Option<Value>,
280 pass_mode: Option<PassMode>,
281 ssa: crate::analyze::Flags,
284 let local_field = if let Some(local_field) = local_field {
285 Cow::Owned(format!(".{}", local_field))
289 let param = if let Some(param) = param {
290 Cow::Owned(format!("= {:?}", param))
294 let pass_mode = if let Some(pass_mode) = pass_mode {
295 Cow::Owned(format!("{:?}", pass_mode))
299 fx.add_global_comment(format!(
300 "{msg:5} {local:>3}{local_field:<5} {param:10} {pass_mode:20} {ssa:10} {ty:?}",
301 msg=msg, local=format!("{:?}", local), local_field=local_field, param=param, pass_mode=pass_mode, ssa=format!("{:?}", ssa), ty=ty,
305 fn add_local_header_comment(fx: &mut FunctionCx<impl Backend>) {
306 fx.add_global_comment(format!("msg loc.idx param pass mode ssa flags ty"));
309 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(
310 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
313 let ssa_analyzed = crate::analyze::analyze(fx);
315 let ret_layout = fx.layout_of(fx.return_type());
316 let output_pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true);
317 let ret_param = match output_pass_mode {
318 PassMode::NoPass => None,
319 PassMode::ByVal(_) => None,
320 PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, fx.pointer_type)),
332 let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
334 // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
335 if Some(local) == fx.mir.spread_arg {
336 // This argument (e.g. the last argument in the "rust-call" ABI)
337 // is a tuple that was spread at the ABI level and now we have
338 // to reconstruct it into a tuple local variable, from multiple
339 // individual function arguments.
341 let tupled_arg_tys = match arg_ty.sty {
342 ty::Tuple(ref tys) => tys,
343 _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
346 let mut ebb_params = Vec::new();
347 for arg_ty in tupled_arg_tys.iter() {
349 get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
350 ebb_params.push(fx.bcx.append_ebb_param(start_ebb, clif_type));
353 (local, ArgKind::Spread(ebb_params), arg_ty)
356 get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
359 ArgKind::Normal(fx.bcx.append_ebb_param(start_ebb, clif_type)),
364 .collect::<Vec<(Local, ArgKind, Ty)>>();
366 fx.bcx.switch_to_block(start_ebb);
368 fx.add_global_comment(format!("ssa {:?}", ssa_analyzed));
370 match output_pass_mode {
371 PassMode::NoPass => {
372 let null = fx.bcx.ins().iconst(fx.pointer_type, 0);
373 //unimplemented!("pass mode nopass");
376 CPlace::Addr(null, None, fx.layout_of(fx.return_type())),
379 PassMode::ByVal(ret_ty) => {
380 fx.bcx.declare_var(mir_var(RETURN_PLACE), ret_ty);
382 .insert(RETURN_PLACE, CPlace::Var(RETURN_PLACE, ret_layout));
387 CPlace::Addr(ret_param.unwrap(), None, ret_layout),
392 add_local_header_comment(fx);
393 add_local_comment(fx, "ret", RETURN_PLACE, None, ret_param, Some(output_pass_mode), ssa_analyzed[&RETURN_PLACE], ret_layout.ty);
395 for (local, arg_kind, ty) in func_params {
396 let layout = fx.layout_of(ty);
399 ArgKind::Normal(ebb_param) => {
400 let pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false);
401 add_local_comment(fx, "arg", local, None, Some(ebb_param), Some(pass_mode), ssa_analyzed[&local], ty);
403 ArgKind::Spread(ref ebb_params) => {
404 for (i, &ebb_param) in ebb_params.iter().enumerate() {
405 let sub_layout = layout.field(fx, i);
406 let pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, sub_layout.ty, false);
407 add_local_comment(fx, "arg", local, Some(i), Some(ebb_param), Some(pass_mode), ssa_analyzed[&local], sub_layout.ty);
412 if let ArgKind::Normal(ebb_param) = arg_kind {
416 .contains(crate::analyze::Flags::NOT_SSA)
419 .declare_var(mir_var(local), fx.clif_type(ty).unwrap());
420 match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false) {
421 PassMode::NoPass => unimplemented!("pass mode nopass"),
422 PassMode::ByVal(_) => fx.bcx.def_var(mir_var(local), ebb_param),
424 let val = CValue::ByRef(ebb_param, fx.layout_of(ty)).load_value(fx);
425 fx.bcx.def_var(mir_var(local), val);
428 fx.local_map.insert(local, CPlace::Var(local, layout));
433 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
434 kind: StackSlotKind::ExplicitSlot,
435 size: layout.size.bytes() as u32,
439 let place = CPlace::from_stack_slot(fx, stack_slot, ty);
442 ArgKind::Normal(ebb_param) => match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false)
444 PassMode::NoPass => unimplemented!("pass mode nopass"),
445 PassMode::ByVal(_) => {
446 place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()))
448 PassMode::ByRef => place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout())),
450 ArgKind::Spread(ebb_params) => {
451 for (i, ebb_param) in ebb_params.into_iter().enumerate() {
452 let sub_place = place.place_field(fx, mir::Field::new(i));
453 match get_pass_mode(fx.tcx, fx.self_sig().abi, sub_place.layout().ty, false) {
454 PassMode::NoPass => unimplemented!("pass mode nopass"),
455 PassMode::ByVal(_) => {
456 sub_place.write_cvalue(fx, CValue::ByVal(ebb_param, sub_place.layout()))
459 sub_place.write_cvalue(fx, CValue::ByRef(ebb_param, sub_place.layout()))
465 fx.local_map.insert(local, place);
468 for local in fx.mir.vars_and_temps_iter() {
469 let ty = fx.mir.local_decls[local].ty;
470 let layout = fx.layout_of(ty);
472 add_local_comment(fx, "local", local, None, None, None, ssa_analyzed[&local], ty);
474 let place = if ssa_analyzed
477 .contains(crate::analyze::Flags::NOT_SSA)
479 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
480 kind: StackSlotKind::ExplicitSlot,
481 size: layout.size.bytes() as u32,
484 CPlace::from_stack_slot(fx, stack_slot, ty)
487 .declare_var(mir_var(local), fx.clif_type(ty).unwrap());
488 CPlace::Var(local, layout)
491 fx.local_map.insert(local, place);
496 .jump(*fx.ebb_map.get(&START_BLOCK).unwrap(), &[]);
499 pub fn codegen_terminator_call<'a, 'tcx: 'a>(
500 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
501 func: &Operand<'tcx>,
502 args: &[Operand<'tcx>],
503 destination: &Option<(Place<'tcx>, BasicBlock)>,
505 let fn_ty = fx.monomorphize(&func.ty(fx.mir, fx.tcx));
506 let sig = ty_fn_sig(fx.tcx, fn_ty);
508 // Unpack arguments tuple for closures
509 let args = if sig.abi == Abi::RustCall {
510 assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
511 let self_arg = trans_operand(fx, &args[0]);
512 let pack_arg = trans_operand(fx, &args[1]);
513 let mut args = Vec::new();
515 match pack_arg.layout().ty.sty {
516 ty::Tuple(ref tupled_arguments) => {
517 for (i, _) in tupled_arguments.iter().enumerate() {
518 args.push(pack_arg.value_field(fx, mir::Field::new(i)));
521 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
526 .map(|arg| trans_operand(fx, arg))
530 let destination = destination
532 .map(|&(ref place, bb)| (trans_place(fx, place), bb));
534 if let ty::FnDef(def_id, substs) = fn_ty.sty {
535 let instance = ty::Instance::resolve(
537 ty::ParamEnv::reveal_all(),
543 InstanceDef::Intrinsic(_) => {
544 crate::intrinsics::codegen_intrinsic_call(fx, def_id, substs, args, destination);
547 InstanceDef::DropGlue(_, None) => {
548 // empty drop glue - a nop.
549 let (_, dest) = destination.expect("Non terminating drop_in_place_real???");
550 let ret_ebb = fx.get_ebb(dest);
551 fx.bcx.ins().jump(ret_ebb, &[]);
563 destination.map(|(place, _)| place),
566 if let Some((_, dest)) = destination {
567 let ret_ebb = fx.get_ebb(dest);
568 fx.bcx.ins().jump(ret_ebb, &[]);
570 trap_unreachable(&mut fx.bcx);
574 pub fn codegen_call_inner<'a, 'tcx: 'a>(
575 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
576 func: Option<&Operand<'tcx>>,
578 args: Vec<CValue<'tcx>>,
579 ret_place: Option<CPlace<'tcx>>,
581 let sig = ty_fn_sig(fx.tcx, fn_ty);
583 let ret_layout = fx.layout_of(sig.output());
585 let output_pass_mode = get_pass_mode(fx.tcx, sig.abi, sig.output(), true);
586 let return_ptr = match output_pass_mode {
587 PassMode::NoPass => None,
588 PassMode::ByRef => match ret_place {
589 Some(ret_place) => Some(ret_place.expect_addr()),
590 None => Some(fx.bcx.ins().iconst(fx.pointer_type, 0)),
592 PassMode::ByVal(_) => None,
595 let instance = match fn_ty.sty {
596 ty::FnDef(def_id, substs) => {
597 Some(Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap())
602 let func_ref: Option<Value>; // Indirect call target
605 if let Some(Instance {
606 def: InstanceDef::Virtual(_, idx),
610 let (ptr, method) = crate::vtable::get_ptr_and_method_ref(fx, args[0], idx);
611 func_ref = Some(method);
614 func_ref = if instance.is_none() {
615 let func = trans_operand(fx, func.expect("indirect call without func Operand"));
616 Some(func.load_value(fx))
621 args.get(0).map(|arg| adjust_arg_for_abi(fx, sig, *arg))
626 let call_args: Vec<Value> = return_ptr
632 .map(|arg| adjust_arg_for_abi(fx, sig, arg)),
634 .collect::<Vec<_>>();
636 let sig = fx.bcx.import_signature(clif_sig_from_fn_ty(fx.tcx, fn_ty));
637 let call_inst = if let Some(func_ref) = func_ref {
638 fx.bcx.ins().call_indirect(sig, func_ref, &call_args)
640 let func_ref = fx.get_function_ref(instance.expect("non-indirect call on non-FnDef type"));
641 fx.bcx.ins().call(func_ref, &call_args)
644 match output_pass_mode {
645 PassMode::NoPass => {}
646 PassMode::ByVal(_) => {
647 if let Some(ret_place) = ret_place {
648 let results = fx.bcx.inst_results(call_inst);
649 ret_place.write_cvalue(fx, CValue::ByVal(results[0], ret_layout));
652 PassMode::ByRef => {}
656 pub fn codegen_return(fx: &mut FunctionCx<impl Backend>) {
657 match get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true) {
658 PassMode::NoPass | PassMode::ByRef => {
659 fx.bcx.ins().return_(&[]);
661 PassMode::ByVal(_) => {
662 let place = fx.get_local_place(RETURN_PLACE);
663 let ret_val = place.to_cvalue(fx).load_value(fx);
664 fx.bcx.ins().return_(&[ret_val]);