]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/shim.rs
Let `mk_fn_def` take an iterator instead to simplify some call sites
[rust.git] / compiler / rustc_mir_transform / src / shim.rs
1 use rustc_hir as hir;
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::InternalSubsts;
7 use rustc_middle::ty::{self, EarlyBinder, GeneratorSubsts, Ty, TyCtxt};
8 use rustc_target::abi::VariantIdx;
9
10 use rustc_index::vec::{Idx, IndexVec};
11
12 use rustc_span::Span;
13 use rustc_target::spec::abi::Abi;
14
15 use std::fmt;
16 use std::iter;
17
18 use crate::util::expand_aggregate;
19 use crate::{
20     abort_unwinding_calls, add_call_guards, add_moves_for_packed_drops, deref_separator,
21     pass_manager as pm, remove_noop_landing_pads, simplify,
22 };
23 use rustc_middle::mir::patch::MirPatch;
24 use rustc_mir_dataflow::elaborate_drops::{self, DropElaborator, DropFlagMode, DropStyle};
25
26 pub fn provide(providers: &mut Providers) {
27     providers.mir_shims = make_shim;
28 }
29
30 fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceDef<'tcx>) -> Body<'tcx> {
31     debug!("make_shim({:?})", instance);
32
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))
37         }
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_def_id(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),
44             };
45
46             build_call_shim(tcx, instance, Some(adjustment), CallKind::Indirect(ty))
47         }
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))
55         }
56         ty::InstanceDef::ClosureOnceShim { call_once: _, track_caller: _ } => {
57             let fn_mut = tcx.require_lang_item(LangItem::FnMut, None);
58             let call_mut = tcx
59                 .associated_items(fn_mut)
60                 .in_definition_order()
61                 .find(|it| it.kind == ty::AssocKind::Fn)
62                 .unwrap()
63                 .def_id;
64
65             build_call_shim(tcx, instance, Some(Adjustment::RefMut), CallKind::Direct(call_mut))
66         }
67
68         ty::InstanceDef::DropGlue(def_id, ty) => {
69             // FIXME(#91576): Drop shims for generators aren't subject to the MIR passes at the end
70             // of this function. Is this intentional?
71             if let Some(ty::Generator(gen_def_id, substs, _)) = ty.map(Ty::kind) {
72                 let body = tcx.optimized_mir(*gen_def_id).generator_drop().unwrap();
73                 let body = EarlyBinder(body.clone()).subst(tcx, substs);
74                 debug!("make_shim({:?}) = {:?}", instance, body);
75                 return body;
76             }
77
78             build_drop_shim(tcx, def_id, ty)
79         }
80         ty::InstanceDef::CloneShim(def_id, ty) => build_clone_shim(tcx, def_id, ty),
81         ty::InstanceDef::Virtual(..) => {
82             bug!("InstanceDef::Virtual ({:?}) is for direct calls only", instance)
83         }
84         ty::InstanceDef::Intrinsic(_) => {
85             bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
86         }
87     };
88     debug!("make_shim({:?}) = untransformed {:?}", instance, result);
89
90     pm::run_passes(
91         tcx,
92         &mut result,
93         &[
94             &add_moves_for_packed_drops::AddMovesForPackedDrops,
95             &deref_separator::Derefer,
96             &remove_noop_landing_pads::RemoveNoopLandingPads,
97             &simplify::SimplifyCfg::new("make_shim"),
98             &add_call_guards::CriticalCallEdges,
99             &abort_unwinding_calls::AbortUnwindingCalls,
100         ],
101         Some(MirPhase::Runtime(RuntimePhase::Optimized)),
102     );
103
104     debug!("make_shim({:?}) = {:?}", instance, result);
105
106     result
107 }
108
109 #[derive(Copy, Clone, Debug, PartialEq)]
110 enum Adjustment {
111     /// Pass the receiver as-is.
112     Identity,
113
114     /// We get passed `&[mut] self` and call the target with `*self`.
115     ///
116     /// This either copies `self` (if `Self: Copy`, eg. for function items), or moves out of it
117     /// (for `VTableShim`, which effectively is passed `&own Self`).
118     Deref,
119
120     /// We get passed `self: Self` and call the target with `&mut self`.
121     ///
122     /// In this case we need to ensure that the `Self` is dropped after the call, as the callee
123     /// won't do it for us.
124     RefMut,
125 }
126
127 #[derive(Copy, Clone, Debug, PartialEq)]
128 enum CallKind<'tcx> {
129     /// Call the `FnPtr` that was passed as the receiver.
130     Indirect(Ty<'tcx>),
131
132     /// Call a known `FnDef`.
133     Direct(DefId),
134 }
135
136 fn local_decls_for_sig<'tcx>(
137     sig: &ty::FnSig<'tcx>,
138     span: Span,
139 ) -> IndexVec<Local, LocalDecl<'tcx>> {
140     iter::once(LocalDecl::new(sig.output(), span))
141         .chain(sig.inputs().iter().map(|ity| LocalDecl::new(*ity, span).immutable()))
142         .collect()
143 }
144
145 fn build_drop_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, ty: Option<Ty<'tcx>>) -> Body<'tcx> {
146     debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
147
148     assert!(!matches!(ty, Some(ty) if ty.is_generator()));
149
150     let substs = if let Some(ty) = ty {
151         tcx.intern_substs(&[ty.into()])
152     } else {
153         InternalSubsts::identity_for_item(tcx, def_id)
154     };
155     let sig = tcx.bound_fn_sig(def_id).subst(tcx, substs);
156     let sig = tcx.erase_late_bound_regions(sig);
157     let span = tcx.def_span(def_id);
158
159     let source_info = SourceInfo::outermost(span);
160
161     let return_block = BasicBlock::new(1);
162     let mut blocks = IndexVec::with_capacity(2);
163     let block = |blocks: &mut IndexVec<_, _>, kind| {
164         blocks.push(BasicBlockData {
165             statements: vec![],
166             terminator: Some(Terminator { source_info, kind }),
167             is_cleanup: false,
168         })
169     };
170     block(&mut blocks, TerminatorKind::Goto { target: return_block });
171     block(&mut blocks, TerminatorKind::Return);
172
173     let source = MirSource::from_instance(ty::InstanceDef::DropGlue(def_id, ty));
174     let mut body =
175         new_body(source, blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span);
176
177     if ty.is_some() {
178         // The first argument (index 0), but add 1 for the return value.
179         let dropee_ptr = Place::from(Local::new(1 + 0));
180         let patch = {
181             let param_env = tcx.param_env_reveal_all_normalized(def_id);
182             let mut elaborator =
183                 DropShimElaborator { body: &body, patch: MirPatch::new(&body), tcx, param_env };
184             let dropee = tcx.mk_place_deref(dropee_ptr);
185             let resume_block = elaborator.patch.resume_block();
186             elaborate_drops::elaborate_drop(
187                 &mut elaborator,
188                 source_info,
189                 dropee,
190                 (),
191                 return_block,
192                 elaborate_drops::Unwind::To(resume_block),
193                 START_BLOCK,
194             );
195             elaborator.patch
196         };
197         patch.apply(&mut body);
198     }
199
200     body
201 }
202
203 fn new_body<'tcx>(
204     source: MirSource<'tcx>,
205     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
206     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
207     arg_count: usize,
208     span: Span,
209 ) -> Body<'tcx> {
210     Body::new(
211         source,
212         basic_blocks,
213         IndexVec::from_elem_n(
214             SourceScopeData {
215                 span,
216                 parent_scope: None,
217                 inlined: None,
218                 inlined_parent_scope: None,
219                 local_data: ClearCrossCrate::Clear,
220             },
221             1,
222         ),
223         local_decls,
224         IndexVec::new(),
225         arg_count,
226         vec![],
227         span,
228         None,
229         // FIXME(compiler-errors): is this correct?
230         None,
231     )
232 }
233
234 pub struct DropShimElaborator<'a, 'tcx> {
235     pub body: &'a Body<'tcx>,
236     pub patch: MirPatch<'tcx>,
237     pub tcx: TyCtxt<'tcx>,
238     pub param_env: ty::ParamEnv<'tcx>,
239 }
240
241 impl fmt::Debug for DropShimElaborator<'_, '_> {
242     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
243         Ok(())
244     }
245 }
246
247 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
248     type Path = ();
249
250     fn patch(&mut self) -> &mut MirPatch<'tcx> {
251         &mut self.patch
252     }
253     fn body(&self) -> &'a Body<'tcx> {
254         self.body
255     }
256     fn tcx(&self) -> TyCtxt<'tcx> {
257         self.tcx
258     }
259     fn param_env(&self) -> ty::ParamEnv<'tcx> {
260         self.param_env
261     }
262
263     fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
264         match mode {
265             DropFlagMode::Shallow => {
266                 // Drops for the contained fields are "shallow" and "static" - they will simply call
267                 // the field's own drop glue.
268                 DropStyle::Static
269             }
270             DropFlagMode::Deep => {
271                 // The top-level drop is "deep" and "open" - it will be elaborated to a drop ladder
272                 // dropping each field contained in the value.
273                 DropStyle::Open
274             }
275         }
276     }
277
278     fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
279         None
280     }
281
282     fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {}
283
284     fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
285         None
286     }
287     fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
288         None
289     }
290     fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> {
291         Some(())
292     }
293     fn array_subpath(&self, _path: Self::Path, _index: u64, _size: u64) -> Option<Self::Path> {
294         None
295     }
296 }
297
298 /// Builds a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
299 fn build_clone_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Body<'tcx> {
300     debug!("build_clone_shim(def_id={:?})", def_id);
301
302     let param_env = tcx.param_env(def_id);
303
304     let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty);
305     let is_copy = self_ty.is_copy_modulo_regions(tcx, param_env);
306
307     let dest = Place::return_place();
308     let src = tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
309
310     match self_ty.kind() {
311         _ if is_copy => builder.copy_shim(),
312         ty::Closure(_, substs) => {
313             builder.tuple_like_shim(dest, src, substs.as_closure().upvar_tys())
314         }
315         ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()),
316         ty::Generator(gen_def_id, substs, hir::Movability::Movable) => {
317             builder.generator_shim(dest, src, *gen_def_id, substs.as_generator())
318         }
319         _ => bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty),
320     };
321
322     builder.into_mir()
323 }
324
325 struct CloneShimBuilder<'tcx> {
326     tcx: TyCtxt<'tcx>,
327     def_id: DefId,
328     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
329     blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
330     span: Span,
331     sig: ty::FnSig<'tcx>,
332 }
333
334 impl<'tcx> 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.bound_fn_sig(def_id).subst(tcx, substs);
341         let sig = tcx.erase_late_bound_regions(sig);
342         let span = tcx.def_span(def_id);
343
344         CloneShimBuilder {
345             tcx,
346             def_id,
347             local_decls: local_decls_for_sig(&sig, span),
348             blocks: IndexVec::new(),
349             span,
350             sig,
351         }
352     }
353
354     fn into_mir(self) -> Body<'tcx> {
355         let source = MirSource::from_instance(ty::InstanceDef::CloneShim(
356             self.def_id,
357             self.sig.inputs_and_output[0],
358         ));
359         new_body(source, self.blocks, self.local_decls, self.sig.inputs().len(), self.span)
360     }
361
362     fn source_info(&self) -> SourceInfo {
363         SourceInfo::outermost(self.span)
364     }
365
366     fn block(
367         &mut self,
368         statements: Vec<Statement<'tcx>>,
369         kind: TerminatorKind<'tcx>,
370         is_cleanup: bool,
371     ) -> BasicBlock {
372         let source_info = self.source_info();
373         self.blocks.push(BasicBlockData {
374             statements,
375             terminator: Some(Terminator { source_info, kind }),
376             is_cleanup,
377         })
378     }
379
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(&self, offset: usize) -> BasicBlock {
385         BasicBlock::new(self.blocks.len() + offset)
386     }
387
388     fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
389         Statement { source_info: self.source_info(), kind }
390     }
391
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::new((
395             Place::return_place(),
396             Rvalue::Use(Operand::Copy(rcvr)),
397         ))));
398         self.block(vec![ret_statement], TerminatorKind::Return, false);
399     }
400
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();
406         }
407         Place::from(self.local_decls.push(local))
408     }
409
410     fn make_clone_call(
411         &mut self,
412         dest: Place<'tcx>,
413         src: Place<'tcx>,
414         ty: Ty<'tcx>,
415         next: BasicBlock,
416         cleanup: BasicBlock,
417     ) {
418         let tcx = self.tcx;
419
420         // `func == Clone::clone(&ty) -> ty`
421         let func_ty = tcx.mk_fn_def(self.def_id, [ty]);
422         let func = Operand::Constant(Box::new(Constant {
423             span: self.span,
424             user_ty: None,
425             literal: ConstantKind::zero_sized(func_ty),
426         }));
427
428         let ref_loc = self.make_place(
429             Mutability::Not,
430             tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }),
431         );
432
433         // `let ref_loc: &ty = &src;`
434         let statement = self.make_statement(StatementKind::Assign(Box::new((
435             ref_loc,
436             Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src),
437         ))));
438
439         // `let loc = Clone::clone(ref_loc);`
440         self.block(
441             vec![statement],
442             TerminatorKind::Call {
443                 func,
444                 args: vec![Operand::Move(ref_loc)],
445                 destination: dest,
446                 target: Some(next),
447                 cleanup: Some(cleanup),
448                 from_hir_call: true,
449                 fn_span: self.span,
450             },
451             false,
452         );
453     }
454
455     fn clone_fields<I>(
456         &mut self,
457         dest: Place<'tcx>,
458         src: Place<'tcx>,
459         target: BasicBlock,
460         mut unwind: BasicBlock,
461         tys: I,
462     ) -> BasicBlock
463     where
464         I: IntoIterator<Item = Ty<'tcx>>,
465     {
466         // For an iterator of length n, create 2*n + 1 blocks.
467         for (i, ity) in tys.into_iter().enumerate() {
468             // Each iteration creates two blocks, referred to here as block 2*i and block 2*i + 1.
469             //
470             // Block 2*i attempts to clone the field. If successful it branches to 2*i + 2 (the
471             // next clone block). If unsuccessful it branches to the previous unwind block, which
472             // is initially the `unwind` argument passed to this function.
473             //
474             // Block 2*i + 1 is the unwind block for this iteration. It drops the cloned value
475             // created by block 2*i. We store this block in `unwind` so that the next clone block
476             // will unwind to it if cloning fails.
477
478             let field = Field::new(i);
479             let src_field = self.tcx.mk_place_field(src, field, ity);
480
481             let dest_field = self.tcx.mk_place_field(dest, field, ity);
482
483             let next_unwind = self.block_index_offset(1);
484             let next_block = self.block_index_offset(2);
485             self.make_clone_call(dest_field, src_field, ity, next_block, unwind);
486             self.block(
487                 vec![],
488                 TerminatorKind::Drop { place: dest_field, target: unwind, unwind: None },
489                 true,
490             );
491             unwind = next_unwind;
492         }
493         // If all clones succeed then we end up here.
494         self.block(vec![], TerminatorKind::Goto { target }, false);
495         unwind
496     }
497
498     fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>, src: Place<'tcx>, tys: I)
499     where
500         I: IntoIterator<Item = Ty<'tcx>>,
501     {
502         self.block(vec![], TerminatorKind::Goto { target: self.block_index_offset(3) }, false);
503         let unwind = self.block(vec![], TerminatorKind::Resume, true);
504         let target = self.block(vec![], TerminatorKind::Return, false);
505
506         let _final_cleanup_block = self.clone_fields(dest, src, target, unwind, tys);
507     }
508
509     fn generator_shim(
510         &mut self,
511         dest: Place<'tcx>,
512         src: Place<'tcx>,
513         gen_def_id: DefId,
514         substs: GeneratorSubsts<'tcx>,
515     ) {
516         self.block(vec![], TerminatorKind::Goto { target: self.block_index_offset(3) }, false);
517         let unwind = self.block(vec![], TerminatorKind::Resume, true);
518         // This will get overwritten with a switch once we know the target blocks
519         let switch = self.block(vec![], TerminatorKind::Unreachable, false);
520         let unwind = self.clone_fields(dest, src, switch, unwind, substs.upvar_tys());
521         let target = self.block(vec![], TerminatorKind::Return, false);
522         let unreachable = self.block(vec![], TerminatorKind::Unreachable, false);
523         let mut cases = Vec::with_capacity(substs.state_tys(gen_def_id, self.tcx).count());
524         for (index, state_tys) in substs.state_tys(gen_def_id, self.tcx).enumerate() {
525             let variant_index = VariantIdx::new(index);
526             let dest = self.tcx.mk_place_downcast_unnamed(dest, variant_index);
527             let src = self.tcx.mk_place_downcast_unnamed(src, variant_index);
528             let clone_block = self.block_index_offset(1);
529             let start_block = self.block(
530                 vec![self.make_statement(StatementKind::SetDiscriminant {
531                     place: Box::new(Place::return_place()),
532                     variant_index,
533                 })],
534                 TerminatorKind::Goto { target: clone_block },
535                 false,
536             );
537             cases.push((index as u128, start_block));
538             let _final_cleanup_block = self.clone_fields(dest, src, target, unwind, state_tys);
539         }
540         let discr_ty = substs.discr_ty(self.tcx);
541         let temp = self.make_place(Mutability::Mut, discr_ty);
542         let rvalue = Rvalue::Discriminant(src);
543         let statement = self.make_statement(StatementKind::Assign(Box::new((temp, rvalue))));
544         match &mut self.blocks[switch] {
545             BasicBlockData { statements, terminator: Some(Terminator { kind, .. }), .. } => {
546                 statements.push(statement);
547                 *kind = TerminatorKind::SwitchInt {
548                     discr: Operand::Move(temp),
549                     targets: SwitchTargets::new(cases.into_iter(), unreachable),
550                 };
551             }
552             BasicBlockData { terminator: None, .. } => unreachable!(),
553         }
554     }
555 }
556
557 /// Builds a "call" shim for `instance`. The shim calls the function specified by `call_kind`,
558 /// first adjusting its first argument according to `rcvr_adjustment`.
559 #[instrument(level = "debug", skip(tcx), ret)]
560 fn build_call_shim<'tcx>(
561     tcx: TyCtxt<'tcx>,
562     instance: ty::InstanceDef<'tcx>,
563     rcvr_adjustment: Option<Adjustment>,
564     call_kind: CallKind<'tcx>,
565 ) -> Body<'tcx> {
566     // `FnPtrShim` contains the fn pointer type that a call shim is being built for - this is used
567     // to substitute into the signature of the shim. It is not necessary for users of this
568     // MIR body to perform further substitutions (see `InstanceDef::has_polymorphic_mir_body`).
569     let (sig_substs, untuple_args) = if let ty::InstanceDef::FnPtrShim(_, ty) = instance {
570         let sig = tcx.erase_late_bound_regions(ty.fn_sig(tcx));
571
572         let untuple_args = sig.inputs();
573
574         // Create substitutions for the `Self` and `Args` generic parameters of the shim body.
575         let arg_tup = tcx.mk_tup(untuple_args.iter());
576         let sig_substs = tcx.mk_substs_trait(ty, [ty::subst::GenericArg::from(arg_tup)]);
577
578         (Some(sig_substs), Some(untuple_args))
579     } else {
580         (None, None)
581     };
582
583     let def_id = instance.def_id();
584     let sig = tcx.bound_fn_sig(def_id);
585     let sig = sig.map_bound(|sig| tcx.erase_late_bound_regions(sig));
586
587     assert_eq!(sig_substs.is_some(), !instance.has_polymorphic_mir_body());
588     let mut sig =
589         if let Some(sig_substs) = sig_substs { sig.subst(tcx, sig_substs) } else { sig.0 };
590
591     if let CallKind::Indirect(fnty) = call_kind {
592         // `sig` determines our local decls, and thus the callee type in the `Call` terminator. This
593         // can only be an `FnDef` or `FnPtr`, but currently will be `Self` since the types come from
594         // the implemented `FnX` trait.
595
596         // Apply the opposite adjustment to the MIR input.
597         let mut inputs_and_output = sig.inputs_and_output.to_vec();
598
599         // Initial signature is `fn(&? Self, Args) -> Self::Output` where `Args` is a tuple of the
600         // fn arguments. `Self` may be passed via (im)mutable reference or by-value.
601         assert_eq!(inputs_and_output.len(), 3);
602
603         // `Self` is always the original fn type `ty`. The MIR call terminator is only defined for
604         // `FnDef` and `FnPtr` callees, not the `Self` type param.
605         let self_arg = &mut inputs_and_output[0];
606         *self_arg = match rcvr_adjustment.unwrap() {
607             Adjustment::Identity => fnty,
608             Adjustment::Deref => tcx.mk_imm_ptr(fnty),
609             Adjustment::RefMut => tcx.mk_mut_ptr(fnty),
610         };
611         sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
612     }
613
614     // FIXME(eddyb) avoid having this snippet both here and in
615     // `Instance::fn_sig` (introduce `InstanceDef::fn_sig`?).
616     if let ty::InstanceDef::VTableShim(..) = instance {
617         // Modify fn(self, ...) to fn(self: *mut Self, ...)
618         let mut inputs_and_output = sig.inputs_and_output.to_vec();
619         let self_arg = &mut inputs_and_output[0];
620         debug_assert!(tcx.generics_of(def_id).has_self && *self_arg == tcx.types.self_param);
621         *self_arg = tcx.mk_mut_ptr(*self_arg);
622         sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
623     }
624
625     let span = tcx.def_span(def_id);
626
627     debug!(?sig);
628
629     let mut local_decls = local_decls_for_sig(&sig, span);
630     let source_info = SourceInfo::outermost(span);
631
632     let rcvr_place = || {
633         assert!(rcvr_adjustment.is_some());
634         Place::from(Local::new(1 + 0))
635     };
636     let mut statements = vec![];
637
638     let rcvr = rcvr_adjustment.map(|rcvr_adjustment| match rcvr_adjustment {
639         Adjustment::Identity => Operand::Move(rcvr_place()),
640         Adjustment::Deref => Operand::Move(tcx.mk_place_deref(rcvr_place())),
641         Adjustment::RefMut => {
642             // let rcvr = &mut rcvr;
643             let ref_rcvr = local_decls.push(
644                 LocalDecl::new(
645                     tcx.mk_ref(
646                         tcx.lifetimes.re_erased,
647                         ty::TypeAndMut { ty: sig.inputs()[0], mutbl: hir::Mutability::Mut },
648                     ),
649                     span,
650                 )
651                 .immutable(),
652             );
653             let borrow_kind = BorrowKind::Mut { allow_two_phase_borrow: false };
654             statements.push(Statement {
655                 source_info,
656                 kind: StatementKind::Assign(Box::new((
657                     Place::from(ref_rcvr),
658                     Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_place()),
659                 ))),
660             });
661             Operand::Move(Place::from(ref_rcvr))
662         }
663     });
664
665     let (callee, mut args) = match call_kind {
666         // `FnPtr` call has no receiver. Args are untupled below.
667         CallKind::Indirect(_) => (rcvr.unwrap(), vec![]),
668
669         // `FnDef` call with optional receiver.
670         CallKind::Direct(def_id) => {
671             let ty = tcx.type_of(def_id);
672             (
673                 Operand::Constant(Box::new(Constant {
674                     span,
675                     user_ty: None,
676                     literal: ConstantKind::zero_sized(ty),
677                 })),
678                 rcvr.into_iter().collect::<Vec<_>>(),
679             )
680         }
681     };
682
683     let mut arg_range = 0..sig.inputs().len();
684
685     // Take the `self` ("receiver") argument out of the range (it's adjusted above).
686     if rcvr_adjustment.is_some() {
687         arg_range.start += 1;
688     }
689
690     // Take the last argument, if we need to untuple it (handled below).
691     if untuple_args.is_some() {
692         arg_range.end -= 1;
693     }
694
695     // Pass all of the non-special arguments directly.
696     args.extend(arg_range.map(|i| Operand::Move(Place::from(Local::new(1 + i)))));
697
698     // Untuple the last argument, if we have to.
699     if let Some(untuple_args) = untuple_args {
700         let tuple_arg = Local::new(1 + (sig.inputs().len() - 1));
701         args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
702             Operand::Move(tcx.mk_place_field(Place::from(tuple_arg), Field::new(i), *ity))
703         }));
704     }
705
706     let n_blocks = if let Some(Adjustment::RefMut) = rcvr_adjustment { 5 } else { 2 };
707     let mut blocks = IndexVec::with_capacity(n_blocks);
708     let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
709         blocks.push(BasicBlockData {
710             statements,
711             terminator: Some(Terminator { source_info, kind }),
712             is_cleanup,
713         })
714     };
715
716     // BB #0
717     block(
718         &mut blocks,
719         statements,
720         TerminatorKind::Call {
721             func: callee,
722             args,
723             destination: Place::return_place(),
724             target: Some(BasicBlock::new(1)),
725             cleanup: if let Some(Adjustment::RefMut) = rcvr_adjustment {
726                 Some(BasicBlock::new(3))
727             } else {
728                 None
729             },
730             from_hir_call: true,
731             fn_span: span,
732         },
733         false,
734     );
735
736     if let Some(Adjustment::RefMut) = rcvr_adjustment {
737         // BB #1 - drop for Self
738         block(
739             &mut blocks,
740             vec![],
741             TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(2), unwind: None },
742             false,
743         );
744     }
745     // BB #1/#2 - return
746     block(&mut blocks, vec![], TerminatorKind::Return, false);
747     if let Some(Adjustment::RefMut) = rcvr_adjustment {
748         // BB #3 - drop if closure panics
749         block(
750             &mut blocks,
751             vec![],
752             TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(4), unwind: None },
753             true,
754         );
755
756         // BB #4 - resume
757         block(&mut blocks, vec![], TerminatorKind::Resume, true);
758     }
759
760     let mut body =
761         new_body(MirSource::from_instance(instance), blocks, local_decls, sig.inputs().len(), span);
762
763     if let Abi::RustCall = sig.abi {
764         body.spread_arg = Some(Local::new(sig.inputs().len()));
765     }
766
767     body
768 }
769
770 pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> {
771     debug_assert!(tcx.is_constructor(ctor_id));
772
773     let param_env = tcx.param_env(ctor_id);
774
775     // Normalize the sig.
776     let sig = tcx.fn_sig(ctor_id).no_bound_vars().expect("LBR in ADT constructor signature");
777     let sig = tcx.normalize_erasing_regions(param_env, sig);
778
779     let ty::Adt(adt_def, substs) = sig.output().kind() else {
780         bug!("unexpected type for ADT ctor {:?}", sig.output());
781     };
782
783     debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig);
784
785     let span = tcx.def_span(ctor_id);
786
787     let local_decls = local_decls_for_sig(&sig, span);
788
789     let source_info = SourceInfo::outermost(span);
790
791     let variant_index = if adt_def.is_enum() {
792         adt_def.variant_index_with_ctor_id(ctor_id)
793     } else {
794         VariantIdx::new(0)
795     };
796
797     // Generate the following MIR:
798     //
799     // (return as Variant).field0 = arg0;
800     // (return as Variant).field1 = arg1;
801     //
802     // return;
803     debug!("build_ctor: variant_index={:?}", variant_index);
804
805     let statements = expand_aggregate(
806         Place::return_place(),
807         adt_def.variant(variant_index).fields.iter().enumerate().map(|(idx, field_def)| {
808             (Operand::Move(Place::from(Local::new(idx + 1))), field_def.ty(tcx, substs))
809         }),
810         AggregateKind::Adt(adt_def.did(), variant_index, substs, None, None),
811         source_info,
812         tcx,
813     )
814     .collect();
815
816     let start_block = BasicBlockData {
817         statements,
818         terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }),
819         is_cleanup: false,
820     };
821
822     let source = MirSource::item(ctor_id);
823     let body = new_body(
824         source,
825         IndexVec::from_elem_n(start_block, 1),
826         local_decls,
827         sig.inputs().len(),
828         span,
829     );
830
831     crate::pass_manager::dump_mir_for_phase_change(tcx, &body);
832
833     body
834 }