5 use rustc_target::spec::abi::Abi;
9 #[derive(Copy, Clone, Debug)]
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_sig<'a, 'tcx: 'a>(
75 tcx: TyCtxt<'a, 'tcx, 'tcx>,
78 let (call_conv, inputs, output): (CallConv, Vec<Ty>, Ty) = match sig.abi {
79 Abi::Rust => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
80 Abi::C => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
82 assert_eq!(sig.inputs().len(), 2);
83 let extra_args = match sig.inputs().last().unwrap().sty {
84 ty::Tuple(ref tupled_arguments) => tupled_arguments,
85 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
87 let mut inputs: Vec<Ty> = vec![sig.inputs()[0]];
88 inputs.extend(extra_args.into_iter());
89 (CallConv::SystemV, inputs, sig.output())
91 Abi::System => bug!("system abi should be selected elsewhere"),
92 Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
93 _ => unimplemented!("unsupported abi {:?}", sig.abi),
98 .filter_map(|ty| match get_pass_mode(tcx, sig.abi, ty, false) {
99 PassMode::ByVal(clif_ty) => Some(clif_ty),
100 PassMode::NoPass => unimplemented!("pass mode nopass"),
101 PassMode::ByRef => Some(pointer_ty(tcx)),
104 let (params, returns) = match get_pass_mode(tcx, sig.abi, output, true) {
105 PassMode::NoPass => (inputs.map(AbiParam::new).collect(), vec![]),
106 PassMode::ByVal(ret_ty) => (
107 inputs.map(AbiParam::new).collect(),
108 vec![AbiParam::new(ret_ty)],
112 Some(pointer_ty(tcx)) // First param is place to put return val
129 pub fn ty_fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> ty::FnSig<'tcx> {
130 let sig = match ty.sty {
132 // Shims currently have type TyFnPtr. Not sure this should remain.
133 ty::FnPtr(_) => ty.fn_sig(tcx),
134 ty::Closure(def_id, substs) => {
135 let sig = substs.closure_sig(def_id, tcx);
137 let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
138 sig.map_bound(|sig| tcx.mk_fn_sig(
139 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
146 ty::Generator(def_id, substs, _) => {
147 let sig = substs.poly_sig(def_id, tcx);
149 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
150 let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
152 sig.map_bound(|sig| {
153 let state_did = tcx.lang_items().gen_state().unwrap();
154 let state_adt_ref = tcx.adt_def(state_did);
155 let state_substs = tcx.intern_substs(&[
157 sig.return_ty.into(),
159 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
161 tcx.mk_fn_sig(iter::once(env_ty),
164 hir::Unsafety::Normal,
169 _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
171 tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig)
174 pub fn get_function_name_and_sig<'a, 'tcx>(
175 tcx: TyCtxt<'a, 'tcx, 'tcx>,
176 inst: Instance<'tcx>,
177 ) -> (String, Signature) {
178 assert!(!inst.substs.needs_infer() && !inst.substs.has_param_types());
179 let fn_ty = inst.ty(tcx);
180 let fn_sig = ty_fn_sig(tcx, fn_ty);
182 unimpl!("Variadic functions are not yet supported");
184 let sig = clif_sig_from_fn_sig(tcx, fn_sig);
185 (tcx.symbol_name(inst).as_str().to_string(), sig)
188 /// Instance must be monomorphized
189 pub fn import_function<'a, 'tcx: 'a>(
190 tcx: TyCtxt<'a, 'tcx, 'tcx>,
191 module: &mut Module<impl Backend>,
192 inst: Instance<'tcx>,
194 let (name, sig) = get_function_name_and_sig(tcx, inst);
196 .declare_function(&name, Linkage::Import, &sig)
200 impl<'a, 'tcx: 'a, B: Backend + 'a> FunctionCx<'a, 'tcx, B> {
201 /// Instance must be monomorphized
202 pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
203 let func_id = import_function(self.tcx, self.module, inst);
204 let func_ref = self.module
205 .declare_func_in_func(func_id, &mut self.bcx.func);
207 #[cfg(debug_assertions)]
208 self.add_entity_comment(func_ref, format!("{:?}", inst));
216 input_tys: Vec<types::Type>,
217 output_ty: Option<types::Type>,
220 let sig = Signature {
221 params: input_tys.iter().cloned().map(AbiParam::new).collect(),
223 .map(|output_ty| vec![AbiParam::new(output_ty)])
224 .unwrap_or(Vec::new()),
225 call_conv: CallConv::SystemV,
229 .declare_function(&name, Linkage::Import, &sig)
233 .declare_func_in_func(func_id, &mut self.bcx.func);
234 let call_inst = self.bcx.ins().call(func_ref, args);
235 if output_ty.is_none() {
238 let results = self.bcx.inst_results(call_inst);
239 assert_eq!(results.len(), 1);
246 args: &[CValue<'tcx>],
249 let (input_tys, args): (Vec<_>, Vec<_>) = args
253 self.clif_type(arg.layout().ty).unwrap(),
254 arg.load_value(self),
258 let return_layout = self.layout_of(return_ty);
259 let return_ty = if let ty::Tuple(tup) = return_ty.sty {
261 bug!("easy_call( (...) -> <non empty tuple> ) is not allowed");
265 Some(self.clif_type(return_ty).unwrap())
267 if let Some(val) = self.lib_call(name, input_tys, return_ty, &args) {
268 CValue::ByVal(val, return_layout)
270 CValue::ByRef(self.bcx.ins().iconst(self.pointer_type, 0), return_layout)
274 fn self_sig(&self) -> FnSig<'tcx> {
275 ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
278 fn return_type(&self) -> Ty<'tcx> {
279 self.self_sig().output()
283 #[cfg(debug_assertions)]
284 fn add_arg_comment<'a, 'tcx: 'a>(
285 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
288 local_field: Option<usize>,
289 param: Option<Value>,
291 ssa: crate::analyze::Flags,
294 let local_field = if let Some(local_field) = local_field {
295 Cow::Owned(format!(".{}", local_field))
299 let param = if let Some(param) = param {
300 Cow::Owned(format!("= {:?}", param))
304 let pass_mode = format!("{:?}", pass_mode);
305 fx.add_global_comment(format!(
306 "{msg:5} {local:>3}{local_field:<5} {param:10} {pass_mode:20} {ssa:10} {ty:?}",
307 msg=msg, local=format!("{:?}", local), local_field=local_field, param=param, pass_mode=pass_mode, ssa=format!("{:?}", ssa), ty=ty,
311 #[cfg(debug_assertions)]
312 fn add_local_header_comment(fx: &mut FunctionCx<impl Backend>) {
313 fx.add_global_comment(format!("msg loc.idx param pass mode ssa flags ty"));
316 fn local_place<'a, 'tcx: 'a>(
317 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
319 layout: TyLayout<'tcx>,
322 let place = if is_ssa {
323 fx.bcx.declare_var(mir_var(local), fx.clif_type(layout.ty).unwrap());
324 CPlace::Var(local, layout)
326 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
327 kind: StackSlotKind::ExplicitSlot,
328 size: layout.size.bytes() as u32,
332 #[cfg(debug_assertions)]
334 let TyLayout { ty, details } = layout;
335 let ty::layout::LayoutDetails { size, align, abi: _, variants: _, fields: _ } = details;
336 fx.add_entity_comment(stack_slot, format!(
337 "{:?}: {:?} size={} align={},{}",
338 local, ty, size.bytes(), align.abi.bytes(), align.pref.bytes(),
342 CPlace::from_stack_slot(fx, stack_slot, layout.ty)
345 let prev_place = fx.local_map.insert(local, place);
346 debug_assert!(prev_place.is_none());
350 fn cvalue_for_param<'a, 'tcx: 'a>(
351 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
354 local_field: Option<usize>,
356 ssa_flags: crate::analyze::Flags,
358 let layout = fx.layout_of(arg_ty);
359 let pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false);
360 let clif_type = pass_mode.get_param_ty(fx);
361 let ebb_param = fx.bcx.append_ebb_param(start_ebb, clif_type);
363 #[cfg(debug_assertions)]
364 add_arg_comment(fx, "arg", local, local_field, Some(ebb_param), pass_mode, ssa_flags, arg_ty);
367 PassMode::NoPass => unimplemented!("pass mode nopass"),
368 PassMode::ByVal(_) => CValue::ByVal(ebb_param, layout),
369 PassMode::ByRef => CValue::ByRef(ebb_param, layout),
373 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(
374 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
377 let ssa_analyzed = crate::analyze::analyze(fx);
379 #[cfg(debug_assertions)]
380 fx.add_global_comment(format!("ssa {:?}", ssa_analyzed));
382 let ret_layout = fx.layout_of(fx.return_type());
383 let output_pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true);
384 let ret_param = match output_pass_mode {
385 PassMode::NoPass => None,
386 PassMode::ByVal(_) => None,
387 PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, fx.pointer_type)),
390 #[cfg(debug_assertions)]
392 add_local_header_comment(fx);
393 add_arg_comment(fx, "ret", RETURN_PLACE, None, ret_param, output_pass_mode, ssa_analyzed[&RETURN_PLACE], ret_layout.ty);
397 Normal(CValue<'tcx>),
398 Spread(Vec<CValue<'tcx>>),
405 let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
407 // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
408 if Some(local) == fx.mir.spread_arg {
409 // This argument (e.g. the last argument in the "rust-call" ABI)
410 // is a tuple that was spread at the ABI level and now we have
411 // to reconstruct it into a tuple local variable, from multiple
412 // individual function arguments.
414 let tupled_arg_tys = match arg_ty.sty {
415 ty::Tuple(ref tys) => tys,
416 _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
419 let mut params = Vec::new();
420 for (i, arg_ty) in tupled_arg_tys.iter().enumerate() {
421 let param = cvalue_for_param(fx, start_ebb, local, Some(i), arg_ty, ssa_analyzed[&local]);
425 (local, ArgKind::Spread(params), arg_ty)
427 let param = cvalue_for_param(fx, start_ebb, local, None, arg_ty, ssa_analyzed[&local]);
430 ArgKind::Normal(param),
435 .collect::<Vec<(Local, ArgKind, Ty)>>();
437 fx.bcx.switch_to_block(start_ebb);
439 match output_pass_mode {
440 PassMode::NoPass => {
441 let null = fx.bcx.ins().iconst(fx.pointer_type, 0);
444 CPlace::Addr(null, None, fx.layout_of(fx.return_type())),
447 PassMode::ByVal(ret_ty) => {
448 fx.bcx.declare_var(mir_var(RETURN_PLACE), ret_ty);
450 .insert(RETURN_PLACE, CPlace::Var(RETURN_PLACE, ret_layout));
455 CPlace::Addr(ret_param.unwrap(), None, ret_layout),
460 for (local, arg_kind, ty) in func_params {
461 let layout = fx.layout_of(ty);
463 let is_ssa = !ssa_analyzed
466 .contains(crate::analyze::Flags::NOT_SSA);
468 let place = local_place(fx, local, layout, is_ssa);
471 ArgKind::Normal(param) => {
472 place.write_cvalue(fx, param);
474 ArgKind::Spread(params) => {
475 for (i, param) in params.into_iter().enumerate() {
476 place.place_field(fx, mir::Field::new(i)).write_cvalue(fx, param);
482 for local in fx.mir.vars_and_temps_iter() {
483 let ty = fx.mir.local_decls[local].ty;
484 let layout = fx.layout_of(ty);
486 let is_ssa = !ssa_analyzed
489 .contains(crate::analyze::Flags::NOT_SSA);
491 local_place(fx, local, layout, is_ssa);
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 fn_sig = ty_fn_sig(fx.tcx, fn_ty);
583 let ret_layout = fx.layout_of(fn_sig.output());
585 let output_pass_mode = get_pass_mode(fx.tcx, fn_sig.abi, fn_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, fn_sig, *arg))
626 let call_args: Vec<Value> = return_ptr
632 .map(|arg| adjust_arg_for_abi(fx, fn_sig, arg)),
634 .collect::<Vec<_>>();
636 let call_inst = if let Some(func_ref) = func_ref {
637 let sig = fx.bcx.import_signature(clif_sig_from_fn_sig(fx.tcx, fn_sig));
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]);