2 use rustc_hir::def_id::DefId;
3 use rustc_middle::mir::*;
4 use rustc_middle::ty::query::Providers;
5 use rustc_middle::ty::subst::{InternalSubsts, Subst};
6 use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable};
7 use rustc_target::abi::VariantIdx;
9 use rustc_index::vec::{Idx, IndexVec};
12 use rustc_target::spec::abi::Abi;
17 use crate::transform::{
18 add_call_guards, add_moves_for_packed_drops, no_landing_pads, remove_noop_landing_pads,
21 use crate::util::elaborate_drops::{self, DropElaborator, DropFlagMode, DropStyle};
22 use crate::util::expand_aggregate;
23 use crate::util::patch::MirPatch;
25 pub fn provide(providers: &mut Providers<'_>) {
26 providers.mir_shims = make_shim;
29 fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceDef<'tcx>) -> &'tcx BodyAndCache<'tcx> {
30 debug!("make_shim({:?})", instance);
32 let mut result = match instance {
33 ty::InstanceDef::Item(..) => bug!("item {:?} passed to make_shim", instance),
34 ty::InstanceDef::VtableShim(def_id) => build_call_shim(
37 Some(Adjustment::DerefMove),
38 CallKind::Direct(def_id),
41 ty::InstanceDef::FnPtrShim(def_id, ty) => {
42 // FIXME(eddyb) support generating shims for a "shallow type",
43 // e.g. `Foo<_>` or `[_]` instead of requiring a fully monomorphic
44 // `Foo<Bar>` or `[String]` etc.
45 assert!(!ty.needs_subst());
47 let trait_ = tcx.trait_of_item(def_id).unwrap();
48 let adjustment = match tcx.fn_trait_kind_from_lang_item(trait_) {
49 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
50 Some(ty::ClosureKind::FnMut) | Some(ty::ClosureKind::Fn) => Adjustment::Deref,
51 None => bug!("fn pointer {:?} is not an fn", ty),
53 // HACK: we need the "real" argument types for the MIR,
54 // but because our substs are (Self, Args), where Args
55 // is a tuple, we must include the *concrete* argument
56 // types in the MIR. They will be substituted again with
57 // the param-substs, but because they are concrete, this
58 // will not do any harm.
59 let sig = tcx.erase_late_bound_regions(&ty.fn_sig(tcx));
60 let arg_tys = sig.inputs();
62 build_call_shim(tcx, instance, Some(adjustment), CallKind::Indirect, Some(arg_tys))
64 // We are generating a call back to our def-id, which the
65 // codegen backend knows to turn to an actual call, be it
66 // a virtual call, or a direct call to a function for which
67 // indirect calls must be codegen'd differently than direct ones
68 // (such as `#[track_caller]`).
69 ty::InstanceDef::ReifyShim(def_id) => {
70 build_call_shim(tcx, instance, None, CallKind::Direct(def_id), None)
72 ty::InstanceDef::ClosureOnceShim { call_once: _ } => {
73 let fn_mut = tcx.lang_items().fn_mut_trait().unwrap();
75 .associated_items(fn_mut)
76 .in_definition_order()
77 .find(|it| it.kind == ty::AssocKind::Method)
84 Some(Adjustment::RefMut),
85 CallKind::Direct(call_mut),
89 ty::InstanceDef::DropGlue(def_id, ty) => {
90 // FIXME(eddyb) support generating shims for a "shallow type",
91 // e.g. `Foo<_>` or `[_]` instead of requiring a fully monomorphic
92 // `Foo<Bar>` or `[String]` etc.
93 assert!(!ty.needs_subst());
95 build_drop_shim(tcx, def_id, ty)
97 ty::InstanceDef::CloneShim(def_id, ty) => {
98 // FIXME(eddyb) support generating shims for a "shallow type",
99 // e.g. `Foo<_>` or `[_]` instead of requiring a fully monomorphic
100 // `Foo<Bar>` or `[String]` etc.
101 assert!(!ty.needs_subst());
103 build_clone_shim(tcx, def_id, ty)
105 ty::InstanceDef::Virtual(..) => {
106 bug!("InstanceDef::Virtual ({:?}) is for direct calls only", instance)
108 ty::InstanceDef::Intrinsic(_) => {
109 bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
112 debug!("make_shim({:?}) = untransformed {:?}", instance, result);
121 &add_moves_for_packed_drops::AddMovesForPackedDrops,
122 &no_landing_pads::NoLandingPads::new(tcx),
123 &remove_noop_landing_pads::RemoveNoopLandingPads,
124 &simplify::SimplifyCfg::new("make_shim"),
125 &add_call_guards::CriticalCallEdges,
129 debug!("make_shim({:?}) = {:?}", instance, result);
131 result.ensure_predecessors();
132 tcx.arena.alloc(result)
135 #[derive(Copy, Clone, Debug, PartialEq)]
143 #[derive(Copy, Clone, Debug, PartialEq)]
149 fn temp_decl(mutability: Mutability, ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
150 let source_info = SourceInfo { scope: OUTERMOST_SOURCE_SCOPE, span };
154 user_ty: UserTypeProjections::none(),
157 local_info: LocalInfo::Other,
162 fn local_decls_for_sig<'tcx>(
163 sig: &ty::FnSig<'tcx>,
165 ) -> IndexVec<Local, LocalDecl<'tcx>> {
166 iter::once(temp_decl(Mutability::Mut, sig.output(), span))
167 .chain(sig.inputs().iter().map(|ity| temp_decl(Mutability::Not, ity, span)))
171 fn build_drop_shim<'tcx>(
174 ty: Option<Ty<'tcx>>,
175 ) -> BodyAndCache<'tcx> {
176 debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
178 // Check if this is a generator, if so, return the drop glue for it
179 if let Some(&ty::TyS { kind: ty::Generator(gen_def_id, substs, _), .. }) = ty {
180 let body = &**tcx.optimized_mir(gen_def_id).generator_drop.as_ref().unwrap();
181 return body.subst(tcx, substs);
184 let substs = if let Some(ty) = ty {
185 tcx.intern_substs(&[ty.into()])
187 InternalSubsts::identity_for_item(tcx, def_id)
189 let sig = tcx.fn_sig(def_id).subst(tcx, substs);
190 let sig = tcx.erase_late_bound_regions(&sig);
191 let span = tcx.def_span(def_id);
193 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
195 let return_block = BasicBlock::new(1);
196 let mut blocks = IndexVec::with_capacity(2);
197 let block = |blocks: &mut IndexVec<_, _>, kind| {
198 blocks.push(BasicBlockData {
200 terminator: Some(Terminator { source_info, kind }),
204 block(&mut blocks, TerminatorKind::Goto { target: return_block });
205 block(&mut blocks, TerminatorKind::Return);
207 let body = new_body(blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span);
209 let mut body = BodyAndCache::new(body);
211 if let Some(..) = ty {
212 // The first argument (index 0), but add 1 for the return value.
213 let dropee_ptr = Place::from(Local::new(1 + 0));
214 if tcx.sess.opts.debugging_opts.mir_emit_retag {
215 // Function arguments should be retagged, and we make this one raw.
216 body.basic_blocks_mut()[START_BLOCK].statements.insert(
220 kind: StatementKind::Retag(RetagKind::Raw, box (dropee_ptr)),
225 let param_env = tcx.param_env(def_id).with_reveal_all();
227 DropShimElaborator { body: &body, patch: MirPatch::new(&body), tcx, param_env };
228 let dropee = tcx.mk_place_deref(dropee_ptr);
229 let resume_block = elaborator.patch.resume_block();
230 elaborate_drops::elaborate_drop(
236 elaborate_drops::Unwind::To(resume_block),
241 patch.apply(&mut body);
248 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
249 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
255 IndexVec::from_elem_n(
256 SourceScopeData { span, parent_scope: None, local_data: ClearCrossCrate::Clear },
269 pub struct DropShimElaborator<'a, 'tcx> {
270 pub body: &'a Body<'tcx>,
271 pub patch: MirPatch<'tcx>,
272 pub tcx: TyCtxt<'tcx>,
273 pub param_env: ty::ParamEnv<'tcx>,
276 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
277 fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
282 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
285 fn patch(&mut self) -> &mut MirPatch<'tcx> {
288 fn body(&self) -> &'a Body<'tcx> {
291 fn tcx(&self) -> TyCtxt<'tcx> {
294 fn param_env(&self) -> ty::ParamEnv<'tcx> {
298 fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
299 if let DropFlagMode::Shallow = mode { DropStyle::Static } else { DropStyle::Open }
302 fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
306 fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {}
308 fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
311 fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
314 fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> {
317 fn array_subpath(&self, _path: Self::Path, _index: u32, _size: u32) -> Option<Self::Path> {
322 /// Builds a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
323 fn build_clone_shim<'tcx>(
327 ) -> BodyAndCache<'tcx> {
328 debug!("build_clone_shim(def_id={:?})", def_id);
330 let param_env = tcx.param_env(def_id);
332 let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty);
333 let is_copy = self_ty.is_copy_modulo_regions(tcx, param_env, builder.span);
335 let dest = Place::return_place();
336 let src = tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
339 _ if is_copy => builder.copy_shim(),
340 ty::Array(ty, len) => {
341 let len = len.eval_usize(tcx, param_env);
342 builder.array_shim(dest, src, ty, len)
344 ty::Closure(_, substs) => {
345 builder.tuple_like_shim(dest, src, substs.as_closure().upvar_tys())
347 ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()),
348 _ => bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty),
351 BodyAndCache::new(builder.into_mir())
354 struct CloneShimBuilder<'tcx> {
357 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
358 blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
360 sig: ty::FnSig<'tcx>,
363 impl CloneShimBuilder<'tcx> {
364 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Self {
365 // we must subst the self_ty because it's
366 // otherwise going to be TySelf and we can't index
367 // or access fields of a Place of type TySelf.
368 let substs = tcx.mk_substs_trait(self_ty, &[]);
369 let sig = tcx.fn_sig(def_id).subst(tcx, substs);
370 let sig = tcx.erase_late_bound_regions(&sig);
371 let span = tcx.def_span(def_id);
376 local_decls: local_decls_for_sig(&sig, span),
377 blocks: IndexVec::new(),
383 fn into_mir(self) -> Body<'tcx> {
384 new_body(self.blocks, self.local_decls, self.sig.inputs().len(), self.span)
387 fn source_info(&self) -> SourceInfo {
388 SourceInfo { span: self.span, scope: OUTERMOST_SOURCE_SCOPE }
393 statements: Vec<Statement<'tcx>>,
394 kind: TerminatorKind<'tcx>,
397 let source_info = self.source_info();
398 self.blocks.push(BasicBlockData {
400 terminator: Some(Terminator { source_info, kind }),
405 /// Gives the index of an upcoming BasicBlock, with an offset.
406 /// offset=0 will give you the index of the next BasicBlock,
407 /// offset=1 will give the index of the next-to-next block,
408 /// offset=-1 will give you the index of the last-created block
409 fn block_index_offset(&mut self, offset: usize) -> BasicBlock {
410 BasicBlock::new(self.blocks.len() + offset)
413 fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
414 Statement { source_info: self.source_info(), kind }
417 fn copy_shim(&mut self) {
418 let rcvr = self.tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
419 let ret_statement = self.make_statement(StatementKind::Assign(box (
420 Place::return_place(),
421 Rvalue::Use(Operand::Copy(rcvr)),
423 self.block(vec![ret_statement], TerminatorKind::Return, false);
426 fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
427 let span = self.span;
428 Place::from(self.local_decls.push(temp_decl(mutability, ty, span)))
441 let substs = tcx.mk_substs_trait(ty, &[]);
443 // `func == Clone::clone(&ty) -> ty`
444 let func_ty = tcx.mk_fn_def(self.def_id, substs);
445 let func = Operand::Constant(box Constant {
448 literal: ty::Const::zero_sized(tcx, func_ty),
451 let ref_loc = self.make_place(
453 tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }),
456 // `let ref_loc: &ty = &src;`
457 let statement = self.make_statement(StatementKind::Assign(box (
459 Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src),
462 // `let loc = Clone::clone(ref_loc);`
465 TerminatorKind::Call {
467 args: vec![Operand::Move(ref_loc)],
468 destination: Some((dest, next)),
469 cleanup: Some(cleanup),
480 loop_body: BasicBlock,
481 loop_end: BasicBlock,
486 let cond = self.make_place(Mutability::Mut, tcx.types.bool);
487 let compute_cond = self.make_statement(StatementKind::Assign(box (
489 Rvalue::BinaryOp(BinOp::Ne, Operand::Copy(end), Operand::Copy(beg)),
492 // `if end != beg { goto loop_body; } else { goto loop_end; }`
495 TerminatorKind::if_(tcx, Operand::Move(cond), loop_body, loop_end),
500 fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
504 literal: ty::Const::from_usize(self.tcx, value),
508 fn array_shim(&mut self, dest: Place<'tcx>, src: Place<'tcx>, ty: Ty<'tcx>, len: u64) {
510 let span = self.span;
512 let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
513 let end = self.make_place(Mutability::Not, tcx.types.usize);
516 // `let mut beg = 0;`
520 self.make_statement(StatementKind::Assign(box (
522 Rvalue::Use(Operand::Constant(self.make_usize(0))),
524 self.make_statement(StatementKind::Assign(box (
526 Rvalue::Use(Operand::Constant(self.make_usize(len))),
529 self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
536 self.loop_header(Place::from(beg), end, BasicBlock::new(2), BasicBlock::new(4), false);
539 // `dest[i] = Clone::clone(src[beg])`;
540 // Goto #3 if ok, #5 if unwinding happens.
541 let dest_field = self.tcx.mk_place_index(dest.clone(), beg);
542 let src_field = self.tcx.mk_place_index(src, beg);
543 self.make_clone_call(dest_field, src_field, ty, BasicBlock::new(3), BasicBlock::new(5));
548 let statements = vec![self.make_statement(StatementKind::Assign(box (
552 Operand::Copy(Place::from(beg)),
553 Operand::Constant(self.make_usize(1)),
556 self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
560 self.block(vec![], TerminatorKind::Return, false);
564 // `let mut beg = 0;`
567 let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
568 let init = self.make_statement(StatementKind::Assign(box (
570 Rvalue::Use(Operand::Constant(self.make_usize(0))),
572 self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
574 // BB #6 (cleanup): loop {
588 // `drop(dest[beg])`;
591 TerminatorKind::Drop {
592 location: self.tcx.mk_place_index(dest, beg),
593 target: BasicBlock::new(8),
602 let statement = self.make_statement(StatementKind::Assign(box (
606 Operand::Copy(Place::from(beg)),
607 Operand::Constant(self.make_usize(1)),
610 self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
613 self.block(vec![], TerminatorKind::Resume, true);
616 fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>, src: Place<'tcx>, tys: I)
618 I: Iterator<Item = Ty<'tcx>>,
620 let mut previous_field = None;
621 for (i, ity) in tys.enumerate() {
622 let field = Field::new(i);
623 let src_field = self.tcx.mk_place_field(src.clone(), field, ity);
625 let dest_field = self.tcx.mk_place_field(dest.clone(), field, ity);
627 // #(2i + 1) is the cleanup block for the previous clone operation
628 let cleanup_block = self.block_index_offset(1);
629 // #(2i + 2) is the next cloning block
630 // (or the Return terminator if this is the last block)
631 let next_block = self.block_index_offset(2);
634 // `dest.i = Clone::clone(&src.i);`
635 // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
636 self.make_clone_call(dest_field.clone(), src_field, ity, next_block, cleanup_block);
638 // BB #(2i + 1) (cleanup)
639 if let Some((previous_field, previous_cleanup)) = previous_field.take() {
640 // Drop previous field and goto previous cleanup block.
643 TerminatorKind::Drop {
644 location: previous_field,
645 target: previous_cleanup,
651 // Nothing to drop, just resume.
652 self.block(vec![], TerminatorKind::Resume, true);
655 previous_field = Some((dest_field, cleanup_block));
658 self.block(vec![], TerminatorKind::Return, false);
662 /// Builds a "call" shim for `instance`. The shim calls the
663 /// function specified by `call_kind`, first adjusting its first
664 /// argument according to `rcvr_adjustment`.
666 /// If `untuple_args` is a vec of types, the second argument of the
667 /// function will be untupled as these types.
668 fn build_call_shim<'tcx>(
670 instance: ty::InstanceDef<'tcx>,
671 rcvr_adjustment: Option<Adjustment>,
673 untuple_args: Option<&[Ty<'tcx>]>,
674 ) -> BodyAndCache<'tcx> {
676 "build_call_shim(instance={:?}, rcvr_adjustment={:?}, \
677 call_kind={:?}, untuple_args={:?})",
678 instance, rcvr_adjustment, call_kind, untuple_args
681 let def_id = instance.def_id();
682 let sig = tcx.fn_sig(def_id);
683 let mut sig = tcx.erase_late_bound_regions(&sig);
685 // FIXME(eddyb) avoid having this snippet both here and in
686 // `Instance::fn_sig` (introduce `InstanceDef::fn_sig`?).
687 if let ty::InstanceDef::VtableShim(..) = instance {
688 // Modify fn(self, ...) to fn(self: *mut Self, ...)
689 let mut inputs_and_output = sig.inputs_and_output.to_vec();
690 let self_arg = &mut inputs_and_output[0];
691 debug_assert!(tcx.generics_of(def_id).has_self && *self_arg == tcx.types.self_param);
692 *self_arg = tcx.mk_mut_ptr(*self_arg);
693 sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
696 let span = tcx.def_span(def_id);
698 debug!("build_call_shim: sig={:?}", sig);
700 let mut local_decls = local_decls_for_sig(&sig, span);
701 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
703 let rcvr_place = || {
704 assert!(rcvr_adjustment.is_some());
705 Place::from(Local::new(1 + 0))
707 let mut statements = vec![];
709 let rcvr = rcvr_adjustment.map(|rcvr_adjustment| match rcvr_adjustment {
710 Adjustment::Identity => Operand::Move(rcvr_place()),
711 Adjustment::Deref => Operand::Copy(tcx.mk_place_deref(rcvr_place())),
712 Adjustment::DerefMove => Operand::Move(tcx.mk_place_deref(rcvr_place())),
713 Adjustment::RefMut => {
714 // let rcvr = &mut rcvr;
715 let ref_rcvr = local_decls.push(temp_decl(
718 tcx.lifetimes.re_erased,
719 ty::TypeAndMut { ty: sig.inputs()[0], mutbl: hir::Mutability::Mut },
723 let borrow_kind = BorrowKind::Mut { allow_two_phase_borrow: false };
724 statements.push(Statement {
726 kind: StatementKind::Assign(box (
727 Place::from(ref_rcvr),
728 Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_place()),
731 Operand::Move(Place::from(ref_rcvr))
735 let (callee, mut args) = match call_kind {
736 CallKind::Indirect => (rcvr.unwrap(), vec![]),
737 CallKind::Direct(def_id) => {
738 let ty = tcx.type_of(def_id);
740 Operand::Constant(box Constant {
743 literal: ty::Const::zero_sized(tcx, ty),
745 rcvr.into_iter().collect::<Vec<_>>(),
750 let mut arg_range = 0..sig.inputs().len();
752 // Take the `self` ("receiver") argument out of the range (it's adjusted above).
753 if rcvr_adjustment.is_some() {
754 arg_range.start += 1;
757 // Take the last argument, if we need to untuple it (handled below).
758 if untuple_args.is_some() {
762 // Pass all of the non-special arguments directly.
763 args.extend(arg_range.map(|i| Operand::Move(Place::from(Local::new(1 + i)))));
765 // Untuple the last argument, if we have to.
766 if let Some(untuple_args) = untuple_args {
767 let tuple_arg = Local::new(1 + (sig.inputs().len() - 1));
768 args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
769 Operand::Move(tcx.mk_place_field(Place::from(tuple_arg), Field::new(i), *ity))
773 let n_blocks = if let Some(Adjustment::RefMut) = rcvr_adjustment { 5 } else { 2 };
774 let mut blocks = IndexVec::with_capacity(n_blocks);
775 let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
776 blocks.push(BasicBlockData {
778 terminator: Some(Terminator { source_info, kind }),
787 TerminatorKind::Call {
790 destination: Some((Place::return_place(), BasicBlock::new(1))),
791 cleanup: if let Some(Adjustment::RefMut) = rcvr_adjustment {
792 Some(BasicBlock::new(3))
801 if let Some(Adjustment::RefMut) = rcvr_adjustment {
802 // BB #1 - drop for Self
806 TerminatorKind::Drop {
807 location: rcvr_place(),
808 target: BasicBlock::new(2),
815 block(&mut blocks, vec![], TerminatorKind::Return, false);
816 if let Some(Adjustment::RefMut) = rcvr_adjustment {
817 // BB #3 - drop if closure panics
821 TerminatorKind::Drop {
822 location: rcvr_place(),
823 target: BasicBlock::new(4),
830 block(&mut blocks, vec![], TerminatorKind::Resume, true);
833 let mut body = new_body(blocks, local_decls, sig.inputs().len(), span);
835 if let Abi::RustCall = sig.abi {
836 body.spread_arg = Some(Local::new(sig.inputs().len()));
838 BodyAndCache::new(body)
841 pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> &BodyAndCache<'_> {
842 debug_assert!(tcx.is_constructor(ctor_id));
845 tcx.hir().span_if_local(ctor_id).unwrap_or_else(|| bug!("no span for ctor {:?}", ctor_id));
847 let param_env = tcx.param_env(ctor_id);
849 // Normalize the sig.
850 let sig = tcx.fn_sig(ctor_id).no_bound_vars().expect("LBR in ADT constructor signature");
851 let sig = tcx.normalize_erasing_regions(param_env, sig);
853 let (adt_def, substs) = match sig.output().kind {
854 ty::Adt(adt_def, substs) => (adt_def, substs),
855 _ => bug!("unexpected type for ADT ctor {:?}", sig.output()),
858 debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig);
860 let local_decls = local_decls_for_sig(&sig, span);
862 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
864 let variant_index = if adt_def.is_enum() {
865 adt_def.variant_index_with_ctor_id(ctor_id)
870 // Generate the following MIR:
872 // (return as Variant).field0 = arg0;
873 // (return as Variant).field1 = arg1;
876 debug!("build_ctor: variant_index={:?}", variant_index);
878 let statements = expand_aggregate(
879 Place::return_place(),
880 adt_def.variants[variant_index].fields.iter().enumerate().map(|(idx, field_def)| {
881 (Operand::Move(Place::from(Local::new(idx + 1))), field_def.ty(tcx, substs))
883 AggregateKind::Adt(adt_def, variant_index, substs, None, None),
889 let start_block = BasicBlockData {
891 terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }),
896 new_body(IndexVec::from_elem_n(start_block, 1), local_decls, sig.inputs().len(), span);
898 crate::util::dump_mir(
903 crate::transform::MirSource::item(ctor_id),
908 let mut body = BodyAndCache::new(body);
909 body.ensure_predecessors();
910 tcx.arena.alloc(body)