2 use rustc_hir::def_id::DefId;
3 use rustc_hir::lang_items::LangItem;
4 use rustc_middle::mir::*;
5 use rustc_middle::ty::query::Providers;
6 use rustc_middle::ty::subst::{InternalSubsts, Subst};
7 use rustc_middle::ty::{self, Ty, TyCtxt};
8 use rustc_target::abi::VariantIdx;
10 use rustc_index::vec::{Idx, IndexVec};
13 use rustc_target::spec::abi::Abi;
18 use crate::transform::{
19 add_call_guards, add_moves_for_packed_drops, no_landing_pads, remove_noop_landing_pads,
22 use crate::util::elaborate_drops::{self, DropElaborator, DropFlagMode, DropStyle};
23 use crate::util::expand_aggregate;
24 use crate::util::patch::MirPatch;
26 pub fn provide(providers: &mut Providers) {
27 providers.mir_shims = make_shim;
30 fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceDef<'tcx>) -> Body<'tcx> {
31 debug!("make_shim({:?})", instance);
33 let mut result = match instance {
34 ty::InstanceDef::Item(..) => bug!("item {:?} passed to make_shim", instance),
35 ty::InstanceDef::VtableShim(def_id) => {
36 build_call_shim(tcx, instance, Some(Adjustment::Deref), CallKind::Direct(def_id))
38 ty::InstanceDef::FnPtrShim(def_id, ty) => {
39 let trait_ = tcx.trait_of_item(def_id).unwrap();
40 let adjustment = match tcx.fn_trait_kind_from_lang_item(trait_) {
41 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
42 Some(ty::ClosureKind::FnMut | ty::ClosureKind::Fn) => Adjustment::Deref,
43 None => bug!("fn pointer {:?} is not an fn", ty),
46 build_call_shim(tcx, instance, Some(adjustment), CallKind::Indirect(ty))
48 // We are generating a call back to our def-id, which the
49 // codegen backend knows to turn to an actual call, be it
50 // a virtual call, or a direct call to a function for which
51 // indirect calls must be codegen'd differently than direct ones
52 // (such as `#[track_caller]`).
53 ty::InstanceDef::ReifyShim(def_id) => {
54 build_call_shim(tcx, instance, None, CallKind::Direct(def_id))
56 ty::InstanceDef::ClosureOnceShim { call_once: _ } => {
57 let fn_mut = tcx.require_lang_item(LangItem::FnMut, None);
59 .associated_items(fn_mut)
60 .in_definition_order()
61 .find(|it| it.kind == ty::AssocKind::Fn)
65 build_call_shim(tcx, instance, Some(Adjustment::RefMut), CallKind::Direct(call_mut))
67 ty::InstanceDef::DropGlue(def_id, ty) => build_drop_shim(tcx, def_id, ty),
68 ty::InstanceDef::CloneShim(def_id, ty) => build_clone_shim(tcx, def_id, ty),
69 ty::InstanceDef::Virtual(..) => {
70 bug!("InstanceDef::Virtual ({:?}) is for direct calls only", instance)
72 ty::InstanceDef::Intrinsic(_) => {
73 bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
76 debug!("make_shim({:?}) = untransformed {:?}", instance, result);
83 &add_moves_for_packed_drops::AddMovesForPackedDrops,
84 &no_landing_pads::NoLandingPads::new(tcx),
85 &remove_noop_landing_pads::RemoveNoopLandingPads,
86 &simplify::SimplifyCfg::new("make_shim"),
87 &add_call_guards::CriticalCallEdges,
91 debug!("make_shim({:?}) = {:?}", instance, result);
96 #[derive(Copy, Clone, Debug, PartialEq)]
98 /// Pass the receiver as-is.
101 /// We get passed `&[mut] self` and call the target with `*self`.
103 /// This either copies `self` (if `Self: Copy`, eg. for function items), or moves out of it
104 /// (for `VtableShim`, which effectively is passed `&own Self`).
107 /// We get passed `self: Self` and call the target with `&mut self`.
109 /// In this case we need to ensure that the `Self` is dropped after the call, as the callee
110 /// won't do it for us.
114 #[derive(Copy, Clone, Debug, PartialEq)]
115 enum CallKind<'tcx> {
116 /// Call the `FnPtr` that was passed as the receiver.
119 /// Call a known `FnDef`.
123 fn local_decls_for_sig<'tcx>(
124 sig: &ty::FnSig<'tcx>,
126 ) -> IndexVec<Local, LocalDecl<'tcx>> {
127 iter::once(LocalDecl::new(sig.output(), span))
128 .chain(sig.inputs().iter().map(|ity| LocalDecl::new(ity, span).immutable()))
132 fn build_drop_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, ty: Option<Ty<'tcx>>) -> Body<'tcx> {
133 debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
135 // Check if this is a generator, if so, return the drop glue for it
136 if let Some(&ty::Generator(gen_def_id, substs, _)) = ty.map(|ty| ty.kind()) {
137 let body = &**tcx.optimized_mir(gen_def_id).generator_drop.as_ref().unwrap();
138 return body.subst(tcx, substs);
141 let substs = if let Some(ty) = ty {
142 tcx.intern_substs(&[ty.into()])
144 InternalSubsts::identity_for_item(tcx, def_id)
146 let sig = tcx.fn_sig(def_id).subst(tcx, substs);
147 let sig = tcx.erase_late_bound_regions(&sig);
148 let span = tcx.def_span(def_id);
150 let source_info = SourceInfo::outermost(span);
152 let return_block = BasicBlock::new(1);
153 let mut blocks = IndexVec::with_capacity(2);
154 let block = |blocks: &mut IndexVec<_, _>, kind| {
155 blocks.push(BasicBlockData {
157 terminator: Some(Terminator { source_info, kind }),
161 block(&mut blocks, TerminatorKind::Goto { target: return_block });
162 block(&mut blocks, TerminatorKind::Return);
164 let source = MirSource::from_instance(ty::InstanceDef::DropGlue(def_id, ty));
166 new_body(source, blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span);
168 if let Some(..) = ty {
169 // The first argument (index 0), but add 1 for the return value.
170 let dropee_ptr = Place::from(Local::new(1 + 0));
171 if tcx.sess.opts.debugging_opts.mir_emit_retag {
172 // Function arguments should be retagged, and we make this one raw.
173 body.basic_blocks_mut()[START_BLOCK].statements.insert(
177 kind: StatementKind::Retag(RetagKind::Raw, box (dropee_ptr)),
182 let param_env = tcx.param_env_reveal_all_normalized(def_id);
184 DropShimElaborator { body: &body, patch: MirPatch::new(&body), tcx, param_env };
185 let dropee = tcx.mk_place_deref(dropee_ptr);
186 let resume_block = elaborator.patch.resume_block();
187 elaborate_drops::elaborate_drop(
193 elaborate_drops::Unwind::To(resume_block),
198 patch.apply(&mut body);
205 source: MirSource<'tcx>,
206 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
207 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
214 IndexVec::from_elem_n(
219 inlined_parent_scope: None,
220 local_data: ClearCrossCrate::Clear,
233 pub struct DropShimElaborator<'a, 'tcx> {
234 pub body: &'a Body<'tcx>,
235 pub patch: MirPatch<'tcx>,
236 pub tcx: TyCtxt<'tcx>,
237 pub param_env: ty::ParamEnv<'tcx>,
240 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
241 fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
246 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
249 fn patch(&mut self) -> &mut MirPatch<'tcx> {
252 fn body(&self) -> &'a Body<'tcx> {
255 fn tcx(&self) -> TyCtxt<'tcx> {
258 fn param_env(&self) -> ty::ParamEnv<'tcx> {
262 fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
264 DropFlagMode::Shallow => {
265 // Drops for the contained fields are "shallow" and "static" - they will simply call
266 // the field's own drop glue.
269 DropFlagMode::Deep => {
270 // The top-level drop is "deep" and "open" - it will be elaborated to a drop ladder
271 // dropping each field contained in the value.
277 fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
281 fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {}
283 fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
286 fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
289 fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> {
292 fn array_subpath(&self, _path: Self::Path, _index: u64, _size: u64) -> Option<Self::Path> {
297 /// Builds a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
298 fn build_clone_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Body<'tcx> {
299 debug!("build_clone_shim(def_id={:?})", def_id);
301 let param_env = tcx.param_env(def_id);
303 let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty);
304 let is_copy = self_ty.is_copy_modulo_regions(tcx.at(builder.span), param_env);
306 let dest = Place::return_place();
307 let src = tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
309 match self_ty.kind() {
310 _ if is_copy => builder.copy_shim(),
311 ty::Array(ty, len) => {
312 let len = len.eval_usize(tcx, param_env);
313 builder.array_shim(dest, src, ty, len)
315 ty::Closure(_, substs) => {
316 builder.tuple_like_shim(dest, src, substs.as_closure().upvar_tys())
318 ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()),
319 _ => bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty),
325 struct CloneShimBuilder<'tcx> {
328 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
329 blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
331 sig: ty::FnSig<'tcx>,
334 impl CloneShimBuilder<'tcx> {
335 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Self {
336 // we must subst the self_ty because it's
337 // otherwise going to be TySelf and we can't index
338 // or access fields of a Place of type TySelf.
339 let substs = tcx.mk_substs_trait(self_ty, &[]);
340 let sig = tcx.fn_sig(def_id).subst(tcx, substs);
341 let sig = tcx.erase_late_bound_regions(&sig);
342 let span = tcx.def_span(def_id);
347 local_decls: local_decls_for_sig(&sig, span),
348 blocks: IndexVec::new(),
354 fn into_mir(self) -> Body<'tcx> {
355 let source = MirSource::from_instance(ty::InstanceDef::CloneShim(
357 self.sig.inputs_and_output[0],
359 new_body(source, self.blocks, self.local_decls, self.sig.inputs().len(), self.span)
362 fn source_info(&self) -> SourceInfo {
363 SourceInfo::outermost(self.span)
368 statements: Vec<Statement<'tcx>>,
369 kind: TerminatorKind<'tcx>,
372 let source_info = self.source_info();
373 self.blocks.push(BasicBlockData {
375 terminator: Some(Terminator { source_info, kind }),
380 /// Gives the index of an upcoming BasicBlock, with an offset.
381 /// offset=0 will give you the index of the next BasicBlock,
382 /// offset=1 will give the index of the next-to-next block,
383 /// offset=-1 will give you the index of the last-created block
384 fn block_index_offset(&mut self, offset: usize) -> BasicBlock {
385 BasicBlock::new(self.blocks.len() + offset)
388 fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
389 Statement { source_info: self.source_info(), kind }
392 fn copy_shim(&mut self) {
393 let rcvr = self.tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
394 let ret_statement = self.make_statement(StatementKind::Assign(box (
395 Place::return_place(),
396 Rvalue::Use(Operand::Copy(rcvr)),
398 self.block(vec![ret_statement], TerminatorKind::Return, false);
401 fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
402 let span = self.span;
403 let mut local = LocalDecl::new(ty, span);
404 if mutability == Mutability::Not {
405 local = local.immutable();
407 Place::from(self.local_decls.push(local))
420 let substs = tcx.mk_substs_trait(ty, &[]);
422 // `func == Clone::clone(&ty) -> ty`
423 let func_ty = tcx.mk_fn_def(self.def_id, substs);
424 let func = Operand::Constant(box Constant {
427 literal: ty::Const::zero_sized(tcx, func_ty),
430 let ref_loc = self.make_place(
432 tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }),
435 // `let ref_loc: &ty = &src;`
436 let statement = self.make_statement(StatementKind::Assign(box (
438 Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src),
441 // `let loc = Clone::clone(ref_loc);`
444 TerminatorKind::Call {
446 args: vec![Operand::Move(ref_loc)],
447 destination: Some((dest, next)),
448 cleanup: Some(cleanup),
460 loop_body: BasicBlock,
461 loop_end: BasicBlock,
466 let cond = self.make_place(Mutability::Mut, tcx.types.bool);
467 let compute_cond = self.make_statement(StatementKind::Assign(box (
469 Rvalue::BinaryOp(BinOp::Ne, Operand::Copy(end), Operand::Copy(beg)),
472 // `if end != beg { goto loop_body; } else { goto loop_end; }`
475 TerminatorKind::if_(tcx, Operand::Move(cond), loop_body, loop_end),
480 fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
484 literal: ty::Const::from_usize(self.tcx, value),
488 fn array_shim(&mut self, dest: Place<'tcx>, src: Place<'tcx>, ty: Ty<'tcx>, len: u64) {
490 let span = self.span;
492 let beg = self.local_decls.push(LocalDecl::new(tcx.types.usize, span));
493 let end = self.make_place(Mutability::Not, tcx.types.usize);
496 // `let mut beg = 0;`
500 self.make_statement(StatementKind::Assign(box (
502 Rvalue::Use(Operand::Constant(self.make_usize(0))),
504 self.make_statement(StatementKind::Assign(box (
506 Rvalue::Use(Operand::Constant(self.make_usize(len))),
509 self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
516 self.loop_header(Place::from(beg), end, BasicBlock::new(2), BasicBlock::new(4), false);
519 // `dest[i] = Clone::clone(src[beg])`;
520 // Goto #3 if ok, #5 if unwinding happens.
521 let dest_field = self.tcx.mk_place_index(dest, beg);
522 let src_field = self.tcx.mk_place_index(src, beg);
523 self.make_clone_call(dest_field, src_field, ty, BasicBlock::new(3), BasicBlock::new(5));
528 let statements = vec![self.make_statement(StatementKind::Assign(box (
532 Operand::Copy(Place::from(beg)),
533 Operand::Constant(self.make_usize(1)),
536 self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
540 self.block(vec![], TerminatorKind::Return, false);
544 // `let mut beg = 0;`
547 let beg = self.local_decls.push(LocalDecl::new(tcx.types.usize, span));
548 let init = self.make_statement(StatementKind::Assign(box (
550 Rvalue::Use(Operand::Constant(self.make_usize(0))),
552 self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
554 // BB #6 (cleanup): loop {
568 // `drop(dest[beg])`;
571 TerminatorKind::Drop {
572 place: self.tcx.mk_place_index(dest, beg),
573 target: BasicBlock::new(8),
582 let statement = self.make_statement(StatementKind::Assign(box (
586 Operand::Copy(Place::from(beg)),
587 Operand::Constant(self.make_usize(1)),
590 self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
593 self.block(vec![], TerminatorKind::Resume, true);
596 fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>, src: Place<'tcx>, tys: I)
598 I: Iterator<Item = Ty<'tcx>>,
600 let mut previous_field = None;
601 for (i, ity) in tys.enumerate() {
602 let field = Field::new(i);
603 let src_field = self.tcx.mk_place_field(src, field, ity);
605 let dest_field = self.tcx.mk_place_field(dest, field, ity);
607 // #(2i + 1) is the cleanup block for the previous clone operation
608 let cleanup_block = self.block_index_offset(1);
609 // #(2i + 2) is the next cloning block
610 // (or the Return terminator if this is the last block)
611 let next_block = self.block_index_offset(2);
614 // `dest.i = Clone::clone(&src.i);`
615 // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
616 self.make_clone_call(dest_field, src_field, ity, next_block, cleanup_block);
618 // BB #(2i + 1) (cleanup)
619 if let Some((previous_field, previous_cleanup)) = previous_field.take() {
620 // Drop previous field and goto previous cleanup block.
623 TerminatorKind::Drop {
624 place: previous_field,
625 target: previous_cleanup,
631 // Nothing to drop, just resume.
632 self.block(vec![], TerminatorKind::Resume, true);
635 previous_field = Some((dest_field, cleanup_block));
638 self.block(vec![], TerminatorKind::Return, false);
642 /// Builds a "call" shim for `instance`. The shim calls the function specified by `call_kind`,
643 /// first adjusting its first argument according to `rcvr_adjustment`.
644 fn build_call_shim<'tcx>(
646 instance: ty::InstanceDef<'tcx>,
647 rcvr_adjustment: Option<Adjustment>,
648 call_kind: CallKind<'tcx>,
651 "build_call_shim(instance={:?}, rcvr_adjustment={:?}, call_kind={:?})",
652 instance, rcvr_adjustment, call_kind
655 // `FnPtrShim` contains the fn pointer type that a call shim is being built for - this is used
656 // to substitute into the signature of the shim. It is not necessary for users of this
657 // MIR body to perform further substitutions (see `InstanceDef::has_polymorphic_mir_body`).
658 let (sig_substs, untuple_args) = if let ty::InstanceDef::FnPtrShim(_, ty) = instance {
659 let sig = tcx.erase_late_bound_regions(&ty.fn_sig(tcx));
661 let untuple_args = sig.inputs();
663 // Create substitutions for the `Self` and `Args` generic parameters of the shim body.
664 let arg_tup = tcx.mk_tup(untuple_args.iter());
665 let sig_substs = tcx.mk_substs_trait(ty, &[ty::subst::GenericArg::from(arg_tup)]);
667 (Some(sig_substs), Some(untuple_args))
672 let def_id = instance.def_id();
673 let sig = tcx.fn_sig(def_id);
674 let mut sig = tcx.erase_late_bound_regions(&sig);
676 assert_eq!(sig_substs.is_some(), !instance.has_polymorphic_mir_body());
677 if let Some(sig_substs) = sig_substs {
678 sig = sig.subst(tcx, sig_substs);
681 if let CallKind::Indirect(fnty) = call_kind {
682 // `sig` determines our local decls, and thus the callee type in the `Call` terminator. This
683 // can only be an `FnDef` or `FnPtr`, but currently will be `Self` since the types come from
684 // the implemented `FnX` trait.
686 // Apply the opposite adjustment to the MIR input.
687 let mut inputs_and_output = sig.inputs_and_output.to_vec();
689 // Initial signature is `fn(&? Self, Args) -> Self::Output` where `Args` is a tuple of the
690 // fn arguments. `Self` may be passed via (im)mutable reference or by-value.
691 assert_eq!(inputs_and_output.len(), 3);
693 // `Self` is always the original fn type `ty`. The MIR call terminator is only defined for
694 // `FnDef` and `FnPtr` callees, not the `Self` type param.
695 let self_arg = &mut inputs_and_output[0];
696 *self_arg = match rcvr_adjustment.unwrap() {
697 Adjustment::Identity => fnty,
698 Adjustment::Deref => tcx.mk_imm_ptr(fnty),
699 Adjustment::RefMut => tcx.mk_mut_ptr(fnty),
701 sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
704 // FIXME(eddyb) avoid having this snippet both here and in
705 // `Instance::fn_sig` (introduce `InstanceDef::fn_sig`?).
706 if let ty::InstanceDef::VtableShim(..) = instance {
707 // Modify fn(self, ...) to fn(self: *mut Self, ...)
708 let mut inputs_and_output = sig.inputs_and_output.to_vec();
709 let self_arg = &mut inputs_and_output[0];
710 debug_assert!(tcx.generics_of(def_id).has_self && *self_arg == tcx.types.self_param);
711 *self_arg = tcx.mk_mut_ptr(*self_arg);
712 sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
715 let span = tcx.def_span(def_id);
717 debug!("build_call_shim: sig={:?}", sig);
719 let mut local_decls = local_decls_for_sig(&sig, span);
720 let source_info = SourceInfo::outermost(span);
722 let rcvr_place = || {
723 assert!(rcvr_adjustment.is_some());
724 Place::from(Local::new(1 + 0))
726 let mut statements = vec![];
728 let rcvr = rcvr_adjustment.map(|rcvr_adjustment| match rcvr_adjustment {
729 Adjustment::Identity => Operand::Move(rcvr_place()),
730 Adjustment::Deref => Operand::Move(tcx.mk_place_deref(rcvr_place())),
731 Adjustment::RefMut => {
732 // let rcvr = &mut rcvr;
733 let ref_rcvr = local_decls.push(
736 tcx.lifetimes.re_erased,
737 ty::TypeAndMut { ty: sig.inputs()[0], mutbl: hir::Mutability::Mut },
743 let borrow_kind = BorrowKind::Mut { allow_two_phase_borrow: false };
744 statements.push(Statement {
746 kind: StatementKind::Assign(box (
747 Place::from(ref_rcvr),
748 Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_place()),
751 Operand::Move(Place::from(ref_rcvr))
755 let (callee, mut args) = match call_kind {
756 // `FnPtr` call has no receiver. Args are untupled below.
757 CallKind::Indirect(_) => (rcvr.unwrap(), vec![]),
759 // `FnDef` call with optional receiver.
760 CallKind::Direct(def_id) => {
761 let ty = tcx.type_of(def_id);
763 Operand::Constant(box Constant {
766 literal: ty::Const::zero_sized(tcx, ty),
768 rcvr.into_iter().collect::<Vec<_>>(),
773 let mut arg_range = 0..sig.inputs().len();
775 // Take the `self` ("receiver") argument out of the range (it's adjusted above).
776 if rcvr_adjustment.is_some() {
777 arg_range.start += 1;
780 // Take the last argument, if we need to untuple it (handled below).
781 if untuple_args.is_some() {
785 // Pass all of the non-special arguments directly.
786 args.extend(arg_range.map(|i| Operand::Move(Place::from(Local::new(1 + i)))));
788 // Untuple the last argument, if we have to.
789 if let Some(untuple_args) = untuple_args {
790 let tuple_arg = Local::new(1 + (sig.inputs().len() - 1));
791 args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
792 Operand::Move(tcx.mk_place_field(Place::from(tuple_arg), Field::new(i), *ity))
796 let n_blocks = if let Some(Adjustment::RefMut) = rcvr_adjustment { 5 } else { 2 };
797 let mut blocks = IndexVec::with_capacity(n_blocks);
798 let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
799 blocks.push(BasicBlockData {
801 terminator: Some(Terminator { source_info, kind }),
810 TerminatorKind::Call {
813 destination: Some((Place::return_place(), BasicBlock::new(1))),
814 cleanup: if let Some(Adjustment::RefMut) = rcvr_adjustment {
815 Some(BasicBlock::new(3))
825 if let Some(Adjustment::RefMut) = rcvr_adjustment {
826 // BB #1 - drop for Self
830 TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(2), unwind: None },
835 block(&mut blocks, vec![], TerminatorKind::Return, false);
836 if let Some(Adjustment::RefMut) = rcvr_adjustment {
837 // BB #3 - drop if closure panics
841 TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(4), unwind: None },
846 block(&mut blocks, vec![], TerminatorKind::Resume, true);
850 new_body(MirSource::from_instance(instance), blocks, local_decls, sig.inputs().len(), span);
852 if let Abi::RustCall = sig.abi {
853 body.spread_arg = Some(Local::new(sig.inputs().len()));
859 pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> {
860 debug_assert!(tcx.is_constructor(ctor_id));
863 tcx.hir().span_if_local(ctor_id).unwrap_or_else(|| bug!("no span for ctor {:?}", ctor_id));
865 let param_env = tcx.param_env(ctor_id);
867 // Normalize the sig.
868 let sig = tcx.fn_sig(ctor_id).no_bound_vars().expect("LBR in ADT constructor signature");
869 let sig = tcx.normalize_erasing_regions(param_env, sig);
871 let (adt_def, substs) = match sig.output().kind() {
872 ty::Adt(adt_def, substs) => (adt_def, substs),
873 _ => bug!("unexpected type for ADT ctor {:?}", sig.output()),
876 debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig);
878 let local_decls = local_decls_for_sig(&sig, span);
880 let source_info = SourceInfo::outermost(span);
882 let variant_index = if adt_def.is_enum() {
883 adt_def.variant_index_with_ctor_id(ctor_id)
888 // Generate the following MIR:
890 // (return as Variant).field0 = arg0;
891 // (return as Variant).field1 = arg1;
894 debug!("build_ctor: variant_index={:?}", variant_index);
896 let statements = expand_aggregate(
897 Place::return_place(),
898 adt_def.variants[variant_index].fields.iter().enumerate().map(|(idx, field_def)| {
899 (Operand::Move(Place::from(Local::new(idx + 1))), field_def.ty(tcx, substs))
901 AggregateKind::Adt(adt_def, variant_index, substs, None, None),
907 let start_block = BasicBlockData {
909 terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }),
913 let source = MirSource::item(ctor_id);
916 IndexVec::from_elem_n(start_block, 1),
922 crate::util::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(()));