4 use rustc_target::spec::abi::Abi;
16 fn get_param_ty(self, fx: &FunctionCx<impl Backend>) -> Type {
18 PassMode::NoPass => unimplemented!("pass mode nopass"),
19 PassMode::ByVal(cton_type) => cton_type,
20 PassMode::ByRef => fx.module.pointer_type(),
25 fn get_pass_mode<'a, 'tcx: 'a>(
26 tcx: TyCtxt<'a, 'tcx, 'tcx>,
32 !tcx.layout_of(ParamEnv::reveal_all().and(ty))
36 if ty.sty == tcx.mk_nil().sty {
43 } else if let Some(ret_ty) = crate::common::cton_type_from_ty(tcx, ty) {
44 PassMode::ByVal(ret_ty)
47 unimplemented!("Non scalars are not yet supported for \"C\" abi");
53 pub fn cton_sig_from_fn_ty<'a, 'tcx: 'a>(
54 tcx: TyCtxt<'a, 'tcx, 'tcx>,
57 let sig = ty_fn_sig(tcx, fn_ty);
58 assert!(!sig.variadic, "Variadic function are not yet supported");
59 let (call_conv, inputs, output): (CallConv, Vec<Ty>, Ty) = match sig.abi {
60 Abi::Rust => (CallConv::Fast, sig.inputs().to_vec(), sig.output()),
61 Abi::C => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
63 assert_eq!(sig.inputs().len(), 2);
64 let extra_args = match sig.inputs().last().unwrap().sty {
65 ty::Tuple(ref tupled_arguments) => tupled_arguments,
66 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
68 let mut inputs: Vec<Ty> = vec![sig.inputs()[0]];
69 inputs.extend(extra_args.into_iter());
70 (CallConv::Fast, inputs, sig.output())
72 Abi::System => bug!("system abi should be selected elsewhere"),
73 Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
74 _ => unimplemented!("unsupported abi {:?}", sig.abi),
79 .filter_map(|ty| match get_pass_mode(tcx, sig.abi, ty, false) {
80 PassMode::ByVal(cton_ty) => Some(cton_ty),
81 PassMode::NoPass => unimplemented!("pass mode nopass"),
82 PassMode::ByRef => Some(pointer_ty(tcx)),
85 let (params, returns) = match get_pass_mode(tcx, sig.abi, output, true) {
86 PassMode::NoPass => (inputs.map(AbiParam::new).collect(), vec![]),
87 PassMode::ByVal(ret_ty) => (
88 inputs.map(AbiParam::new).collect(),
89 vec![AbiParam::new(ret_ty)],
93 Some(pointer_ty(tcx)).into_iter() // First param is place to put return val
109 fn ty_fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> ty::FnSig<'tcx> {
110 let sig = match ty.sty {
112 // Shims currently have type TyFnPtr. Not sure this should remain.
113 ty::FnPtr(_) => ty.fn_sig(tcx),
114 ty::Closure(def_id, substs) => {
115 let sig = substs.closure_sig(def_id, tcx);
117 let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
118 sig.map_bound(|sig| tcx.mk_fn_sig(
119 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
126 ty::Generator(def_id, substs, _) => {
127 let sig = substs.poly_sig(def_id, tcx);
129 let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
130 let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
132 sig.map_bound(|sig| {
133 let state_did = tcx.lang_items().gen_state().unwrap();
134 let state_adt_ref = tcx.adt_def(state_did);
135 let state_substs = tcx.intern_substs(&[
137 sig.return_ty.into(),
139 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
141 tcx.mk_fn_sig(iter::once(env_ty),
144 hir::Unsafety::Normal,
149 _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
151 tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig)
154 pub fn get_function_name_and_sig<'a, 'tcx>(
155 tcx: TyCtxt<'a, 'tcx, 'tcx>,
156 inst: Instance<'tcx>,
157 ) -> (String, Signature) {
158 assert!(!inst.substs.needs_infer() && !inst.substs.has_param_types());
159 let fn_ty = inst.ty(tcx);
160 let sig = cton_sig_from_fn_ty(tcx, fn_ty);
161 (tcx.symbol_name(inst).as_str().to_string(), sig)
164 impl<'a, 'tcx: 'a, B: Backend + 'a> FunctionCx<'a, 'tcx, B> {
165 /// Instance must be monomorphized
166 pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
167 let (name, sig) = get_function_name_and_sig(self.tcx, inst);
170 .declare_function(&name, Linkage::Import, &sig)
173 .declare_func_in_func(func_id, &mut self.bcx.func)
179 input_tys: Vec<types::Type>,
180 output_ty: Option<types::Type>,
183 let sig = Signature {
184 params: input_tys.iter().cloned().map(AbiParam::new).collect(),
185 returns: output_ty.map(|output_ty| vec![AbiParam::new(output_ty)]).unwrap_or(Vec::new()),
186 call_conv: CallConv::SystemV,
190 .declare_function(&name, Linkage::Import, &sig)
194 .declare_func_in_func(func_id, &mut self.bcx.func);
195 let call_inst = self.bcx.ins().call(func_ref, args);
196 if output_ty.is_none() {
199 let results = self.bcx.inst_results(call_inst);
200 assert_eq!(results.len(), 1);
207 args: &[CValue<'tcx>],
210 let (input_tys, args): (Vec<_>, Vec<_>) = args
214 self.cton_type(arg.layout().ty).unwrap(),
215 arg.load_value(self),
218 let return_layout = self.layout_of(return_ty);
219 let return_ty = if let ty::Tuple(tup) = return_ty.sty {
221 bug!("easy_call( (...) -> <non empty tuple> ) is not allowed");
225 Some(self.cton_type(return_ty).unwrap())
227 if let Some(val) = self.lib_call(name, input_tys, return_ty, &args) {
228 CValue::ByVal(val, return_layout)
231 self.bcx.ins().iconst(self.module.pointer_type(), 0),
237 fn self_sig(&self) -> FnSig<'tcx> {
238 ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
241 fn return_type(&self) -> Ty<'tcx> {
242 self.self_sig().output()
246 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(
247 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
250 let ssa_analyzed = crate::analyze::analyze(fx);
252 match fx.self_sig().abi {
253 Abi::Rust | Abi::RustCall => {}
254 _ => unimplemented!("declared function with non \"rust\" or \"rust-call\" abi"),
257 let ret_layout = fx.layout_of(fx.return_type());
258 let output_pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true);
259 let ret_param = match output_pass_mode {
260 PassMode::NoPass => None,
261 PassMode::ByVal(_) => None,
262 PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, fx.module.pointer_type())),
274 let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
276 // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
277 if Some(local) == fx.mir.spread_arg {
278 // This argument (e.g. the last argument in the "rust-call" ABI)
279 // is a tuple that was spread at the ABI level and now we have
280 // to reconstruct it into a tuple local variable, from multiple
281 // individual function arguments.
283 let tupled_arg_tys = match arg_ty.sty {
284 ty::Tuple(ref tys) => tys,
285 _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
288 let mut ebb_params = Vec::new();
289 for arg_ty in tupled_arg_tys.iter() {
291 get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
292 ebb_params.push(fx.bcx.append_ebb_param(start_ebb, cton_type));
295 (local, ArgKind::Spread(ebb_params), arg_ty)
298 get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
301 ArgKind::Normal(fx.bcx.append_ebb_param(start_ebb, cton_type)),
305 }).collect::<Vec<(Local, ArgKind, Ty)>>();
307 fx.bcx.switch_to_block(start_ebb);
309 fx.top_nop = Some(fx.bcx.ins().nop());
310 fx.add_global_comment(format!("ssa {:?}", ssa_analyzed));
312 match output_pass_mode {
313 PassMode::NoPass => {
314 let null = fx.bcx.ins().iconst(fx.module.pointer_type(), 0);
315 //unimplemented!("pass mode nopass");
318 CPlace::Addr(null, None, fx.layout_of(fx.return_type())),
321 PassMode::ByVal(ret_ty) => {
322 fx.bcx.declare_var(mir_var(RETURN_PLACE), ret_ty);
324 .insert(RETURN_PLACE, CPlace::Var(RETURN_PLACE, ret_layout));
329 CPlace::Addr(ret_param.unwrap(), None, ret_layout),
334 for (local, arg_kind, ty) in func_params {
335 let layout = fx.layout_of(ty);
337 if let ArgKind::Normal(ebb_param) = arg_kind {
341 .contains(crate::analyze::Flags::NOT_SSA)
344 .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
345 match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false) {
346 PassMode::NoPass => unimplemented!("pass mode nopass"),
347 PassMode::ByVal(_) => fx.bcx.def_var(mir_var(local), ebb_param),
349 let val = CValue::ByRef(ebb_param, fx.layout_of(ty)).load_value(fx);
350 fx.bcx.def_var(mir_var(local), val);
353 fx.local_map.insert(local, CPlace::Var(local, layout));
358 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
359 kind: StackSlotKind::ExplicitSlot,
360 size: layout.size.bytes() as u32,
364 let place = CPlace::from_stack_slot(fx, stack_slot, ty);
367 ArgKind::Normal(ebb_param) => match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false)
369 PassMode::NoPass => unimplemented!("pass mode nopass"),
370 PassMode::ByVal(_) => {
371 place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()))
373 PassMode::ByRef => place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout())),
375 ArgKind::Spread(ebb_params) => {
376 for (i, ebb_param) in ebb_params.into_iter().enumerate() {
377 let sub_place = place.place_field(fx, mir::Field::new(i));
378 match get_pass_mode(fx.tcx, fx.self_sig().abi, sub_place.layout().ty, false) {
379 PassMode::NoPass => unimplemented!("pass mode nopass"),
380 PassMode::ByVal(_) => {
381 sub_place.write_cvalue(fx, CValue::ByVal(ebb_param, sub_place.layout()))
384 sub_place.write_cvalue(fx, CValue::ByRef(ebb_param, sub_place.layout()))
390 fx.local_map.insert(local, place);
393 for local in fx.mir.vars_and_temps_iter() {
394 let ty = fx.mir.local_decls[local].ty;
395 let layout = fx.layout_of(ty);
397 let place = if ssa_analyzed
400 .contains(crate::analyze::Flags::NOT_SSA)
402 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
403 kind: StackSlotKind::ExplicitSlot,
404 size: layout.size.bytes() as u32,
407 CPlace::from_stack_slot(fx, stack_slot, ty)
410 .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
411 CPlace::Var(local, layout)
414 fx.local_map.insert(local, place);
419 .jump(*fx.ebb_map.get(&START_BLOCK).unwrap(), &[]);
422 pub fn codegen_call<'a, 'tcx: 'a>(
423 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
424 func: &Operand<'tcx>,
425 args: &[Operand<'tcx>],
426 destination: &Option<(Place<'tcx>, BasicBlock)>,
428 let fn_ty = fx.monomorphize(&func.ty(&fx.mir.local_decls, fx.tcx));
429 let sig = ty_fn_sig(fx.tcx, fn_ty);
431 // Unpack arguments tuple for closures
432 let args = if sig.abi == Abi::RustCall {
433 assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
434 let self_arg = trans_operand(fx, &args[0]);
435 let pack_arg = trans_operand(fx, &args[1]);
436 let mut args = Vec::new();
438 match pack_arg.layout().ty.sty {
439 ty::Tuple(ref tupled_arguments) => {
440 for (i, _) in tupled_arguments.iter().enumerate() {
441 args.push(pack_arg.value_field(fx, mir::Field::new(i)));
444 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
449 .map(|arg| trans_operand(fx, arg))
453 let destination = destination
455 .map(|(place, bb)| (trans_place(fx, place), *bb));
457 if codegen_intrinsic_call(fx, fn_ty, sig, &args, destination) {
461 let ret_layout = fx.layout_of(sig.output());
463 let output_pass_mode = get_pass_mode(fx.tcx, sig.abi, sig.output(), true);
464 let return_ptr = match output_pass_mode {
465 PassMode::NoPass => None,
466 PassMode::ByRef => match destination {
467 Some((place, _)) => Some(place.expect_addr()),
468 None => Some(fx.bcx.ins().iconst(fx.module.pointer_type(), 0)),
470 PassMode::ByVal(_) => None,
473 let call_args: Vec<Value> = return_ptr
475 .chain(args.into_iter().map(|arg| {
476 match get_pass_mode(fx.tcx, sig.abi, arg.layout().ty, false) {
477 PassMode::NoPass => unimplemented!("pass mode nopass"),
478 PassMode::ByVal(_) => arg.load_value(fx),
479 PassMode::ByRef => arg.force_stack(fx),
481 })).collect::<Vec<_>>();
483 let call_inst = match fn_ty.sty {
484 ty::FnDef(def_id, substs) => {
485 let inst = Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap();
486 let func_ref = fx.get_function_ref(inst);
487 fx.bcx.ins().call(func_ref, &call_args)
490 let func = trans_operand(fx, func);
491 let func = func.load_value(fx);
492 let sig = fx.bcx.import_signature(cton_sig_from_fn_ty(fx.tcx, fn_ty));
493 fx.bcx.ins().call_indirect(sig, func, &call_args)
495 _ => bug!("{:?}", fn_ty),
498 match output_pass_mode {
499 PassMode::NoPass => {}
500 PassMode::ByVal(_) => {
501 if let Some((ret_place, _)) = destination {
502 let results = fx.bcx.inst_results(call_inst);
503 ret_place.write_cvalue(fx, CValue::ByVal(results[0], ret_layout));
506 PassMode::ByRef => {}
508 if let Some((_, dest)) = destination {
509 let ret_ebb = fx.get_ebb(dest);
510 fx.bcx.ins().jump(ret_ebb, &[]);
512 fx.bcx.ins().trap(TrapCode::User(!0));
516 pub fn codegen_return(fx: &mut FunctionCx<impl Backend>) {
517 match get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true) {
518 PassMode::NoPass | PassMode::ByRef => {
519 fx.bcx.ins().return_(&[]);
521 PassMode::ByVal(_) => {
522 let place = fx.get_local_place(RETURN_PLACE);
523 let ret_val = place.to_cvalue(fx).load_value(fx);
524 fx.bcx.ins().return_(&[ret_val]);
529 fn codegen_intrinsic_call<'a, 'tcx: 'a>(
530 fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
533 args: &[CValue<'tcx>],
534 destination: Option<(CPlace<'tcx>, BasicBlock)>,
536 if let ty::FnDef(def_id, substs) = fn_ty.sty {
537 if sig.abi == Abi::RustIntrinsic {
538 let intrinsic = fx.tcx.item_name(def_id).as_str();
539 let intrinsic = &intrinsic[..];
541 let ret = match destination {
542 Some((place, _)) => place,
544 // Insert non returning intrinsics here
547 fx.bcx.ins().trap(TrapCode::User(!0 - 1));
550 fx.bcx.ins().trap(TrapCode::User(!0 - 1));
552 _ => unimplemented!("unsupported instrinsic {}", intrinsic),
558 let nil_ty = fx.tcx.mk_nil();
559 let u64_layout = fx.layout_of(fx.tcx.types.u64);
560 let usize_layout = fx.layout_of(fx.tcx.types.usize);
564 assert_eq!(args.len(), 1);
567 assert_eq!(args.len(), 2);
568 let base = args[0].load_value(fx);
569 let offset = args[1].load_value(fx);
570 let res = fx.bcx.ins().iadd(base, offset);
571 let res = CValue::ByVal(res, ret.layout());
572 ret.write_cvalue(fx, res);
574 "likely" | "unlikely" => {
575 assert_eq!(args.len(), 1);
576 ret.write_cvalue(fx, args[0]);
578 "copy" | "copy_nonoverlapping" => {
579 let elem_ty = substs.type_at(0);
580 let elem_size: u64 = fx.layout_of(elem_ty).size.bytes();
584 .iconst(fx.module.pointer_type(), elem_size as i64);
585 assert_eq!(args.len(), 3);
588 let count = args[2].load_value(fx);
589 let byte_amount = fx.bcx.ins().imul(count, elem_size);
592 &[dst, src, CValue::ByVal(byte_amount, usize_layout)],
596 "discriminant_value" => {
597 assert_eq!(args.len(), 1);
598 let discr = crate::base::trans_get_discriminant(fx, args[0], ret.layout());
599 ret.write_cvalue(fx, discr);
602 assert_eq!(args.len(), 0);
603 let size_of = fx.layout_of(substs.type_at(0)).size.bytes();
604 let size_of = CValue::const_val(fx, usize_layout.ty, size_of as i64);
605 ret.write_cvalue(fx, size_of);
608 assert_eq!(args.len(), 1);
609 let size = match &substs.type_at(0).sty {
611 let len = args[0].load_value_pair(fx).1;
612 let elem_size = fx.layout_of(elem).size.bytes();
613 fx.bcx.ins().imul_imm(len, elem_size as i64)
615 ty => unimplemented!("size_of_val for {:?}", ty),
617 ret.write_cvalue(fx, CValue::ByVal(size, usize_layout));
620 assert_eq!(args.len(), 0);
621 let type_id = fx.tcx.type_id_hash(substs.type_at(0));
622 let type_id = CValue::const_val(fx, u64_layout.ty, type_id as i64);
623 ret.write_cvalue(fx, type_id);
626 assert_eq!(args.len(), 0);
627 let min_align = fx.layout_of(substs.type_at(0)).align.abi();
628 let min_align = CValue::const_val(fx, usize_layout.ty, min_align as i64);
629 ret.write_cvalue(fx, min_align);
631 _ if intrinsic.starts_with("unchecked_") => {
632 assert_eq!(args.len(), 2);
633 let bin_op = match intrinsic {
634 "unchecked_div" => BinOp::Div,
635 "unchecked_rem" => BinOp::Rem,
636 "unchecked_shl" => BinOp::Shl,
637 "unchecked_shr" => BinOp::Shr,
638 _ => unimplemented!("intrinsic {}", intrinsic),
640 let res = match ret.layout().ty.sty {
641 ty::Uint(_) => crate::base::trans_int_binop(
649 ty::Int(_) => crate::base::trans_int_binop(
659 ret.write_cvalue(fx, res);
661 _ if intrinsic.ends_with("_with_overflow") => {
662 assert_eq!(args.len(), 2);
663 assert_eq!(args[0].layout().ty, args[1].layout().ty);
664 let bin_op = match intrinsic {
665 "add_with_overflow" => BinOp::Add,
666 "sub_with_overflow" => BinOp::Sub,
667 "mul_with_overflow" => BinOp::Mul,
668 _ => unimplemented!("intrinsic {}", intrinsic),
670 let res = match args[0].layout().ty.sty {
671 ty::Uint(_) => crate::base::trans_checked_int_binop(
679 ty::Int(_) => crate::base::trans_checked_int_binop(
689 ret.write_cvalue(fx, res);
691 _ if intrinsic.starts_with("overflowing_") => {
692 assert_eq!(args.len(), 2);
693 assert_eq!(args[0].layout().ty, args[1].layout().ty);
694 let bin_op = match intrinsic {
695 "overflowing_add" => BinOp::Add,
696 "overflowing_sub" => BinOp::Sub,
697 "overflowing_mul" => BinOp::Mul,
698 _ => unimplemented!("intrinsic {}", intrinsic),
700 let res = match args[0].layout().ty.sty {
701 ty::Uint(_) => crate::base::trans_int_binop(
709 ty::Int(_) => crate::base::trans_int_binop(
719 ret.write_cvalue(fx, res);
722 assert_eq!(args.len(), 2);
723 let base = args[0].load_value(fx);
724 let offset = args[1].load_value(fx);
725 let res = fx.bcx.ins().iadd(base, offset);
726 ret.write_cvalue(fx, CValue::ByVal(res, args[0].layout()));
729 assert_eq!(args.len(), 1);
730 let src_ty = substs.type_at(0);
731 let dst_ty = substs.type_at(1);
732 assert_eq!(args[0].layout().ty, src_ty);
733 let addr = args[0].force_stack(fx);
734 let dst_layout = fx.layout_of(dst_ty);
735 ret.write_cvalue(fx, CValue::ByRef(addr, dst_layout))
738 assert_eq!(args.len(), 0);
739 let ty = substs.type_at(0);
740 let layout = fx.layout_of(ty);
741 let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
742 kind: StackSlotKind::ExplicitSlot,
743 size: layout.size.bytes() as u32,
747 let uninit_place = CPlace::from_stack_slot(fx, stack_slot, ty);
748 let uninit_val = uninit_place.to_cvalue(fx);
749 ret.write_cvalue(fx, uninit_val);
751 "ctlz" | "ctlz_nonzero" => {
752 assert_eq!(args.len(), 1);
753 let arg = args[0].load_value(fx);
754 let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
755 ret.write_cvalue(fx, res);
757 "cttz" | "cttz_nonzero" => {
758 assert_eq!(args.len(), 1);
759 let arg = args[0].load_value(fx);
760 let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
761 ret.write_cvalue(fx, res);
764 assert_eq!(args.len(), 1);
765 let arg = args[0].load_value(fx);
766 let res = CValue::ByVal(fx.bcx.ins().popcnt(arg), args[0].layout());
767 ret.write_cvalue(fx, res);
769 _ => unimpl!("unsupported intrinsic {}", intrinsic),
772 if let Some((_, dest)) = destination {
773 let ret_ebb = fx.get_ebb(dest);
774 fx.bcx.ins().jump(ret_ebb, &[]);
776 fx.bcx.ins().trap(TrapCode::User(!0));