]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/shim.rs
Shrink the size of Rvalue by 16 bytes
[rust.git] / compiler / rustc_mir / 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::subst::{InternalSubsts, Subst};
7 use rustc_middle::ty::{self, 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::transform::{
19     add_call_guards, add_moves_for_packed_drops, no_landing_pads, remove_noop_landing_pads,
20     run_passes, simplify,
21 };
22 use crate::util::elaborate_drops::{self, DropElaborator, DropFlagMode, DropStyle};
23 use crate::util::expand_aggregate;
24 use crate::util::patch::MirPatch;
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_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),
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: _ } => {
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         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)
71         }
72         ty::InstanceDef::Intrinsic(_) => {
73             bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
74         }
75     };
76     debug!("make_shim({:?}) = untransformed {:?}", instance, result);
77
78     run_passes(
79         tcx,
80         &mut result,
81         MirPhase::Const,
82         &[&[
83             &add_moves_for_packed_drops::AddMovesForPackedDrops,
84             &no_landing_pads::NoLandingPads,
85             &remove_noop_landing_pads::RemoveNoopLandingPads,
86             &simplify::SimplifyCfg::new("make_shim"),
87             &add_call_guards::CriticalCallEdges,
88         ]],
89     );
90
91     debug!("make_shim({:?}) = {:?}", instance, result);
92
93     result
94 }
95
96 #[derive(Copy, Clone, Debug, PartialEq)]
97 enum Adjustment {
98     /// Pass the receiver as-is.
99     Identity,
100
101     /// We get passed `&[mut] self` and call the target with `*self`.
102     ///
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`).
105     Deref,
106
107     /// We get passed `self: Self` and call the target with `&mut self`.
108     ///
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.
111     RefMut,
112 }
113
114 #[derive(Copy, Clone, Debug, PartialEq)]
115 enum CallKind<'tcx> {
116     /// Call the `FnPtr` that was passed as the receiver.
117     Indirect(Ty<'tcx>),
118
119     /// Call a known `FnDef`.
120     Direct(DefId),
121 }
122
123 fn local_decls_for_sig<'tcx>(
124     sig: &ty::FnSig<'tcx>,
125     span: Span,
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()))
129         .collect()
130 }
131
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);
134
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.clone().subst(tcx, substs);
139     }
140
141     let substs = if let Some(ty) = ty {
142         tcx.intern_substs(&[ty.into()])
143     } else {
144         InternalSubsts::identity_for_item(tcx, def_id)
145     };
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);
149
150     let source_info = SourceInfo::outermost(span);
151
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 {
156             statements: vec![],
157             terminator: Some(Terminator { source_info, kind }),
158             is_cleanup: false,
159         })
160     };
161     block(&mut blocks, TerminatorKind::Goto { target: return_block });
162     block(&mut blocks, TerminatorKind::Return);
163
164     let source = MirSource::from_instance(ty::InstanceDef::DropGlue(def_id, ty));
165     let mut body =
166         new_body(source, blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span);
167
168     if ty.is_some() {
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(
174                 0,
175                 Statement {
176                     source_info,
177                     kind: StatementKind::Retag(RetagKind::Raw, box (dropee_ptr)),
178                 },
179             );
180         }
181         let patch = {
182             let param_env = tcx.param_env_reveal_all_normalized(def_id);
183             let mut elaborator =
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(
188                 &mut elaborator,
189                 source_info,
190                 dropee,
191                 (),
192                 return_block,
193                 elaborate_drops::Unwind::To(resume_block),
194                 START_BLOCK,
195             );
196             elaborator.patch
197         };
198         patch.apply(&mut body);
199     }
200
201     body
202 }
203
204 fn new_body<'tcx>(
205     source: MirSource<'tcx>,
206     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
207     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
208     arg_count: usize,
209     span: Span,
210 ) -> Body<'tcx> {
211     Body::new(
212         source,
213         basic_blocks,
214         IndexVec::from_elem_n(
215             SourceScopeData {
216                 span,
217                 parent_scope: None,
218                 inlined: None,
219                 inlined_parent_scope: None,
220                 local_data: ClearCrossCrate::Clear,
221             },
222             1,
223         ),
224         local_decls,
225         IndexVec::new(),
226         arg_count,
227         vec![],
228         span,
229         None,
230     )
231 }
232
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>,
238 }
239
240 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
241     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
242         Ok(())
243     }
244 }
245
246 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
247     type Path = ();
248
249     fn patch(&mut self) -> &mut MirPatch<'tcx> {
250         &mut self.patch
251     }
252     fn body(&self) -> &'a Body<'tcx> {
253         self.body
254     }
255     fn tcx(&self) -> TyCtxt<'tcx> {
256         self.tcx
257     }
258     fn param_env(&self) -> ty::ParamEnv<'tcx> {
259         self.param_env
260     }
261
262     fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
263         match mode {
264             DropFlagMode::Shallow => {
265                 // Drops for the contained fields are "shallow" and "static" - they will simply call
266                 // the field's own drop glue.
267                 DropStyle::Static
268             }
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.
272                 DropStyle::Open
273             }
274         }
275     }
276
277     fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
278         None
279     }
280
281     fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {}
282
283     fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
284         None
285     }
286     fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
287         None
288     }
289     fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> {
290         Some(())
291     }
292     fn array_subpath(&self, _path: Self::Path, _index: u64, _size: u64) -> Option<Self::Path> {
293         None
294     }
295 }
296
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);
300
301     let param_env = tcx.param_env(def_id);
302
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);
305
306     let dest = Place::return_place();
307     let src = tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
308
309     match self_ty.kind() {
310         _ if is_copy => builder.copy_shim(),
311         ty::Array(ty, len) => builder.array_shim(dest, src, ty, len),
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         _ => bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty),
317     };
318
319     builder.into_mir()
320 }
321
322 struct CloneShimBuilder<'tcx> {
323     tcx: TyCtxt<'tcx>,
324     def_id: DefId,
325     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
326     blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
327     span: Span,
328     sig: ty::FnSig<'tcx>,
329 }
330
331 impl CloneShimBuilder<'tcx> {
332     fn new(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Self {
333         // we must subst the self_ty because it's
334         // otherwise going to be TySelf and we can't index
335         // or access fields of a Place of type TySelf.
336         let substs = tcx.mk_substs_trait(self_ty, &[]);
337         let sig = tcx.fn_sig(def_id).subst(tcx, substs);
338         let sig = tcx.erase_late_bound_regions(sig);
339         let span = tcx.def_span(def_id);
340
341         CloneShimBuilder {
342             tcx,
343             def_id,
344             local_decls: local_decls_for_sig(&sig, span),
345             blocks: IndexVec::new(),
346             span,
347             sig,
348         }
349     }
350
351     fn into_mir(self) -> Body<'tcx> {
352         let source = MirSource::from_instance(ty::InstanceDef::CloneShim(
353             self.def_id,
354             self.sig.inputs_and_output[0],
355         ));
356         new_body(source, self.blocks, self.local_decls, self.sig.inputs().len(), self.span)
357     }
358
359     fn source_info(&self) -> SourceInfo {
360         SourceInfo::outermost(self.span)
361     }
362
363     fn block(
364         &mut self,
365         statements: Vec<Statement<'tcx>>,
366         kind: TerminatorKind<'tcx>,
367         is_cleanup: bool,
368     ) -> BasicBlock {
369         let source_info = self.source_info();
370         self.blocks.push(BasicBlockData {
371             statements,
372             terminator: Some(Terminator { source_info, kind }),
373             is_cleanup,
374         })
375     }
376
377     /// Gives the index of an upcoming BasicBlock, with an offset.
378     /// offset=0 will give you the index of the next BasicBlock,
379     /// offset=1 will give the index of the next-to-next block,
380     /// offset=-1 will give you the index of the last-created block
381     fn block_index_offset(&mut self, offset: usize) -> BasicBlock {
382         BasicBlock::new(self.blocks.len() + offset)
383     }
384
385     fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
386         Statement { source_info: self.source_info(), kind }
387     }
388
389     fn copy_shim(&mut self) {
390         let rcvr = self.tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
391         let ret_statement = self.make_statement(StatementKind::Assign(box (
392             Place::return_place(),
393             Rvalue::Use(Operand::Copy(rcvr)),
394         )));
395         self.block(vec![ret_statement], TerminatorKind::Return, false);
396     }
397
398     fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
399         let span = self.span;
400         let mut local = LocalDecl::new(ty, span);
401         if mutability == Mutability::Not {
402             local = local.immutable();
403         }
404         Place::from(self.local_decls.push(local))
405     }
406
407     fn make_clone_call(
408         &mut self,
409         dest: Place<'tcx>,
410         src: Place<'tcx>,
411         ty: Ty<'tcx>,
412         next: BasicBlock,
413         cleanup: BasicBlock,
414     ) {
415         let tcx = self.tcx;
416
417         let substs = tcx.mk_substs_trait(ty, &[]);
418
419         // `func == Clone::clone(&ty) -> ty`
420         let func_ty = tcx.mk_fn_def(self.def_id, substs);
421         let func = Operand::Constant(box Constant {
422             span: self.span,
423             user_ty: None,
424             literal: ty::Const::zero_sized(tcx, func_ty),
425         });
426
427         let ref_loc = self.make_place(
428             Mutability::Not,
429             tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }),
430         );
431
432         // `let ref_loc: &ty = &src;`
433         let statement = self.make_statement(StatementKind::Assign(box (
434             ref_loc,
435             Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src),
436         )));
437
438         // `let loc = Clone::clone(ref_loc);`
439         self.block(
440             vec![statement],
441             TerminatorKind::Call {
442                 func,
443                 args: vec![Operand::Move(ref_loc)],
444                 destination: Some((dest, next)),
445                 cleanup: Some(cleanup),
446                 from_hir_call: true,
447                 fn_span: self.span,
448             },
449             false,
450         );
451     }
452
453     fn loop_header(
454         &mut self,
455         beg: Place<'tcx>,
456         end: Place<'tcx>,
457         loop_body: BasicBlock,
458         loop_end: BasicBlock,
459         is_cleanup: bool,
460     ) {
461         let tcx = self.tcx;
462
463         let cond = self.make_place(Mutability::Mut, tcx.types.bool);
464         let compute_cond = self.make_statement(StatementKind::Assign(box (
465             cond,
466             Rvalue::BinaryOp(BinOp::Ne, box (Operand::Copy(end), Operand::Copy(beg))),
467         )));
468
469         // `if end != beg { goto loop_body; } else { goto loop_end; }`
470         self.block(
471             vec![compute_cond],
472             TerminatorKind::if_(tcx, Operand::Move(cond), loop_body, loop_end),
473             is_cleanup,
474         );
475     }
476
477     fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
478         box Constant {
479             span: self.span,
480             user_ty: None,
481             literal: ty::Const::from_usize(self.tcx, value),
482         }
483     }
484
485     fn array_shim(
486         &mut self,
487         dest: Place<'tcx>,
488         src: Place<'tcx>,
489         ty: Ty<'tcx>,
490         len: &'tcx ty::Const<'tcx>,
491     ) {
492         let tcx = self.tcx;
493         let span = self.span;
494
495         let beg = self.local_decls.push(LocalDecl::new(tcx.types.usize, span));
496         let end = self.make_place(Mutability::Not, tcx.types.usize);
497
498         // BB #0
499         // `let mut beg = 0;`
500         // `let end = len;`
501         // `goto #1;`
502         let inits = vec![
503             self.make_statement(StatementKind::Assign(box (
504                 Place::from(beg),
505                 Rvalue::Use(Operand::Constant(self.make_usize(0))),
506             ))),
507             self.make_statement(StatementKind::Assign(box (
508                 end,
509                 Rvalue::Use(Operand::Constant(box Constant {
510                     span: self.span,
511                     user_ty: None,
512                     literal: len,
513                 })),
514             ))),
515         ];
516         self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
517
518         // BB #1: loop {
519         //     BB #2;
520         //     BB #3;
521         // }
522         // BB #4;
523         self.loop_header(Place::from(beg), end, BasicBlock::new(2), BasicBlock::new(4), false);
524
525         // BB #2
526         // `dest[i] = Clone::clone(src[beg])`;
527         // Goto #3 if ok, #5 if unwinding happens.
528         let dest_field = self.tcx.mk_place_index(dest, beg);
529         let src_field = self.tcx.mk_place_index(src, beg);
530         self.make_clone_call(dest_field, src_field, ty, BasicBlock::new(3), BasicBlock::new(5));
531
532         // BB #3
533         // `beg = beg + 1;`
534         // `goto #1`;
535         let statements = vec![self.make_statement(StatementKind::Assign(box (
536             Place::from(beg),
537             Rvalue::BinaryOp(
538                 BinOp::Add,
539                 box (Operand::Copy(Place::from(beg)), Operand::Constant(self.make_usize(1))),
540             ),
541         )))];
542         self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
543
544         // BB #4
545         // `return dest;`
546         self.block(vec![], TerminatorKind::Return, false);
547
548         // BB #5 (cleanup)
549         // `let end = beg;`
550         // `let mut beg = 0;`
551         // goto #6;
552         let end = beg;
553         let beg = self.local_decls.push(LocalDecl::new(tcx.types.usize, span));
554         let init = self.make_statement(StatementKind::Assign(box (
555             Place::from(beg),
556             Rvalue::Use(Operand::Constant(self.make_usize(0))),
557         )));
558         self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
559
560         // BB #6 (cleanup): loop {
561         //     BB #7;
562         //     BB #8;
563         // }
564         // BB #9;
565         self.loop_header(
566             Place::from(beg),
567             Place::from(end),
568             BasicBlock::new(7),
569             BasicBlock::new(9),
570             true,
571         );
572
573         // BB #7 (cleanup)
574         // `drop(dest[beg])`;
575         self.block(
576             vec![],
577             TerminatorKind::Drop {
578                 place: self.tcx.mk_place_index(dest, beg),
579                 target: BasicBlock::new(8),
580                 unwind: None,
581             },
582             true,
583         );
584
585         // BB #8 (cleanup)
586         // `beg = beg + 1;`
587         // `goto #6;`
588         let statement = self.make_statement(StatementKind::Assign(box (
589             Place::from(beg),
590             Rvalue::BinaryOp(
591                 BinOp::Add,
592                 box (Operand::Copy(Place::from(beg)), Operand::Constant(self.make_usize(1))),
593             ),
594         )));
595         self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
596
597         // BB #9 (resume)
598         self.block(vec![], TerminatorKind::Resume, true);
599     }
600
601     fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>, src: Place<'tcx>, tys: I)
602     where
603         I: Iterator<Item = Ty<'tcx>>,
604     {
605         let mut previous_field = None;
606         for (i, ity) in tys.enumerate() {
607             let field = Field::new(i);
608             let src_field = self.tcx.mk_place_field(src, field, ity);
609
610             let dest_field = self.tcx.mk_place_field(dest, field, ity);
611
612             // #(2i + 1) is the cleanup block for the previous clone operation
613             let cleanup_block = self.block_index_offset(1);
614             // #(2i + 2) is the next cloning block
615             // (or the Return terminator if this is the last block)
616             let next_block = self.block_index_offset(2);
617
618             // BB #(2i)
619             // `dest.i = Clone::clone(&src.i);`
620             // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
621             self.make_clone_call(dest_field, src_field, ity, next_block, cleanup_block);
622
623             // BB #(2i + 1) (cleanup)
624             if let Some((previous_field, previous_cleanup)) = previous_field.take() {
625                 // Drop previous field and goto previous cleanup block.
626                 self.block(
627                     vec![],
628                     TerminatorKind::Drop {
629                         place: previous_field,
630                         target: previous_cleanup,
631                         unwind: None,
632                     },
633                     true,
634                 );
635             } else {
636                 // Nothing to drop, just resume.
637                 self.block(vec![], TerminatorKind::Resume, true);
638             }
639
640             previous_field = Some((dest_field, cleanup_block));
641         }
642
643         self.block(vec![], TerminatorKind::Return, false);
644     }
645 }
646
647 /// Builds a "call" shim for `instance`. The shim calls the function specified by `call_kind`,
648 /// first adjusting its first argument according to `rcvr_adjustment`.
649 fn build_call_shim<'tcx>(
650     tcx: TyCtxt<'tcx>,
651     instance: ty::InstanceDef<'tcx>,
652     rcvr_adjustment: Option<Adjustment>,
653     call_kind: CallKind<'tcx>,
654 ) -> Body<'tcx> {
655     debug!(
656         "build_call_shim(instance={:?}, rcvr_adjustment={:?}, call_kind={:?})",
657         instance, rcvr_adjustment, call_kind
658     );
659
660     // `FnPtrShim` contains the fn pointer type that a call shim is being built for - this is used
661     // to substitute into the signature of the shim. It is not necessary for users of this
662     // MIR body to perform further substitutions (see `InstanceDef::has_polymorphic_mir_body`).
663     let (sig_substs, untuple_args) = if let ty::InstanceDef::FnPtrShim(_, ty) = instance {
664         let sig = tcx.erase_late_bound_regions(ty.fn_sig(tcx));
665
666         let untuple_args = sig.inputs();
667
668         // Create substitutions for the `Self` and `Args` generic parameters of the shim body.
669         let arg_tup = tcx.mk_tup(untuple_args.iter());
670         let sig_substs = tcx.mk_substs_trait(ty, &[ty::subst::GenericArg::from(arg_tup)]);
671
672         (Some(sig_substs), Some(untuple_args))
673     } else {
674         (None, None)
675     };
676
677     let def_id = instance.def_id();
678     let sig = tcx.fn_sig(def_id);
679     let mut sig = tcx.erase_late_bound_regions(sig);
680
681     assert_eq!(sig_substs.is_some(), !instance.has_polymorphic_mir_body());
682     if let Some(sig_substs) = sig_substs {
683         sig = sig.subst(tcx, sig_substs);
684     }
685
686     if let CallKind::Indirect(fnty) = call_kind {
687         // `sig` determines our local decls, and thus the callee type in the `Call` terminator. This
688         // can only be an `FnDef` or `FnPtr`, but currently will be `Self` since the types come from
689         // the implemented `FnX` trait.
690
691         // Apply the opposite adjustment to the MIR input.
692         let mut inputs_and_output = sig.inputs_and_output.to_vec();
693
694         // Initial signature is `fn(&? Self, Args) -> Self::Output` where `Args` is a tuple of the
695         // fn arguments. `Self` may be passed via (im)mutable reference or by-value.
696         assert_eq!(inputs_and_output.len(), 3);
697
698         // `Self` is always the original fn type `ty`. The MIR call terminator is only defined for
699         // `FnDef` and `FnPtr` callees, not the `Self` type param.
700         let self_arg = &mut inputs_and_output[0];
701         *self_arg = match rcvr_adjustment.unwrap() {
702             Adjustment::Identity => fnty,
703             Adjustment::Deref => tcx.mk_imm_ptr(fnty),
704             Adjustment::RefMut => tcx.mk_mut_ptr(fnty),
705         };
706         sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
707     }
708
709     // FIXME(eddyb) avoid having this snippet both here and in
710     // `Instance::fn_sig` (introduce `InstanceDef::fn_sig`?).
711     if let ty::InstanceDef::VtableShim(..) = instance {
712         // Modify fn(self, ...) to fn(self: *mut Self, ...)
713         let mut inputs_and_output = sig.inputs_and_output.to_vec();
714         let self_arg = &mut inputs_and_output[0];
715         debug_assert!(tcx.generics_of(def_id).has_self && *self_arg == tcx.types.self_param);
716         *self_arg = tcx.mk_mut_ptr(*self_arg);
717         sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
718     }
719
720     let span = tcx.def_span(def_id);
721
722     debug!("build_call_shim: sig={:?}", sig);
723
724     let mut local_decls = local_decls_for_sig(&sig, span);
725     let source_info = SourceInfo::outermost(span);
726
727     let rcvr_place = || {
728         assert!(rcvr_adjustment.is_some());
729         Place::from(Local::new(1 + 0))
730     };
731     let mut statements = vec![];
732
733     let rcvr = rcvr_adjustment.map(|rcvr_adjustment| match rcvr_adjustment {
734         Adjustment::Identity => Operand::Move(rcvr_place()),
735         Adjustment::Deref => Operand::Move(tcx.mk_place_deref(rcvr_place())),
736         Adjustment::RefMut => {
737             // let rcvr = &mut rcvr;
738             let ref_rcvr = local_decls.push(
739                 LocalDecl::new(
740                     tcx.mk_ref(
741                         tcx.lifetimes.re_erased,
742                         ty::TypeAndMut { ty: sig.inputs()[0], mutbl: hir::Mutability::Mut },
743                     ),
744                     span,
745                 )
746                 .immutable(),
747             );
748             let borrow_kind = BorrowKind::Mut { allow_two_phase_borrow: false };
749             statements.push(Statement {
750                 source_info,
751                 kind: StatementKind::Assign(box (
752                     Place::from(ref_rcvr),
753                     Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_place()),
754                 )),
755             });
756             Operand::Move(Place::from(ref_rcvr))
757         }
758     });
759
760     let (callee, mut args) = match call_kind {
761         // `FnPtr` call has no receiver. Args are untupled below.
762         CallKind::Indirect(_) => (rcvr.unwrap(), vec![]),
763
764         // `FnDef` call with optional receiver.
765         CallKind::Direct(def_id) => {
766             let ty = tcx.type_of(def_id);
767             (
768                 Operand::Constant(box Constant {
769                     span,
770                     user_ty: None,
771                     literal: ty::Const::zero_sized(tcx, ty),
772                 }),
773                 rcvr.into_iter().collect::<Vec<_>>(),
774             )
775         }
776     };
777
778     let mut arg_range = 0..sig.inputs().len();
779
780     // Take the `self` ("receiver") argument out of the range (it's adjusted above).
781     if rcvr_adjustment.is_some() {
782         arg_range.start += 1;
783     }
784
785     // Take the last argument, if we need to untuple it (handled below).
786     if untuple_args.is_some() {
787         arg_range.end -= 1;
788     }
789
790     // Pass all of the non-special arguments directly.
791     args.extend(arg_range.map(|i| Operand::Move(Place::from(Local::new(1 + i)))));
792
793     // Untuple the last argument, if we have to.
794     if let Some(untuple_args) = untuple_args {
795         let tuple_arg = Local::new(1 + (sig.inputs().len() - 1));
796         args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
797             Operand::Move(tcx.mk_place_field(Place::from(tuple_arg), Field::new(i), *ity))
798         }));
799     }
800
801     let n_blocks = if let Some(Adjustment::RefMut) = rcvr_adjustment { 5 } else { 2 };
802     let mut blocks = IndexVec::with_capacity(n_blocks);
803     let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
804         blocks.push(BasicBlockData {
805             statements,
806             terminator: Some(Terminator { source_info, kind }),
807             is_cleanup,
808         })
809     };
810
811     // BB #0
812     block(
813         &mut blocks,
814         statements,
815         TerminatorKind::Call {
816             func: callee,
817             args,
818             destination: Some((Place::return_place(), BasicBlock::new(1))),
819             cleanup: if let Some(Adjustment::RefMut) = rcvr_adjustment {
820                 Some(BasicBlock::new(3))
821             } else {
822                 None
823             },
824             from_hir_call: true,
825             fn_span: span,
826         },
827         false,
828     );
829
830     if let Some(Adjustment::RefMut) = rcvr_adjustment {
831         // BB #1 - drop for Self
832         block(
833             &mut blocks,
834             vec![],
835             TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(2), unwind: None },
836             false,
837         );
838     }
839     // BB #1/#2 - return
840     block(&mut blocks, vec![], TerminatorKind::Return, false);
841     if let Some(Adjustment::RefMut) = rcvr_adjustment {
842         // BB #3 - drop if closure panics
843         block(
844             &mut blocks,
845             vec![],
846             TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(4), unwind: None },
847             true,
848         );
849
850         // BB #4 - resume
851         block(&mut blocks, vec![], TerminatorKind::Resume, true);
852     }
853
854     let mut body =
855         new_body(MirSource::from_instance(instance), blocks, local_decls, sig.inputs().len(), span);
856
857     if let Abi::RustCall = sig.abi {
858         body.spread_arg = Some(Local::new(sig.inputs().len()));
859     }
860
861     body
862 }
863
864 pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> {
865     debug_assert!(tcx.is_constructor(ctor_id));
866
867     let span =
868         tcx.hir().span_if_local(ctor_id).unwrap_or_else(|| bug!("no span for ctor {:?}", ctor_id));
869
870     let param_env = tcx.param_env(ctor_id);
871
872     // Normalize the sig.
873     let sig = tcx.fn_sig(ctor_id).no_bound_vars().expect("LBR in ADT constructor signature");
874     let sig = tcx.normalize_erasing_regions(param_env, sig);
875
876     let (adt_def, substs) = match sig.output().kind() {
877         ty::Adt(adt_def, substs) => (adt_def, substs),
878         _ => bug!("unexpected type for ADT ctor {:?}", sig.output()),
879     };
880
881     debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig);
882
883     let local_decls = local_decls_for_sig(&sig, span);
884
885     let source_info = SourceInfo::outermost(span);
886
887     let variant_index = if adt_def.is_enum() {
888         adt_def.variant_index_with_ctor_id(ctor_id)
889     } else {
890         VariantIdx::new(0)
891     };
892
893     // Generate the following MIR:
894     //
895     // (return as Variant).field0 = arg0;
896     // (return as Variant).field1 = arg1;
897     //
898     // return;
899     debug!("build_ctor: variant_index={:?}", variant_index);
900
901     let statements = expand_aggregate(
902         Place::return_place(),
903         adt_def.variants[variant_index].fields.iter().enumerate().map(|(idx, field_def)| {
904             (Operand::Move(Place::from(Local::new(idx + 1))), field_def.ty(tcx, substs))
905         }),
906         AggregateKind::Adt(adt_def, variant_index, substs, None, None),
907         source_info,
908         tcx,
909     )
910     .collect();
911
912     let start_block = BasicBlockData {
913         statements,
914         terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }),
915         is_cleanup: false,
916     };
917
918     let source = MirSource::item(ctor_id);
919     let body = new_body(
920         source,
921         IndexVec::from_elem_n(start_block, 1),
922         local_decls,
923         sig.inputs().len(),
924         span,
925     );
926
927     crate::util::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(()));
928
929     body
930 }