]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/shim.rs
nix rustc_target::abi::* reexport in ty::layout
[rust.git] / src / librustc_mir / shim.rs
1 use rustc_hir as hir;
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;
8
9 use rustc_index::vec::{Idx, IndexVec};
10
11 use rustc_span::Span;
12 use rustc_target::spec::abi::Abi;
13
14 use std::fmt;
15 use std::iter;
16
17 use crate::transform::{
18     add_call_guards, add_moves_for_packed_drops, no_landing_pads, remove_noop_landing_pads,
19     run_passes, simplify,
20 };
21 use crate::util::elaborate_drops::{self, DropElaborator, DropFlagMode, DropStyle};
22 use crate::util::expand_aggregate;
23 use crate::util::patch::MirPatch;
24
25 pub fn provide(providers: &mut Providers<'_>) {
26     providers.mir_shims = make_shim;
27 }
28
29 fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceDef<'tcx>) -> &'tcx BodyAndCache<'tcx> {
30     debug!("make_shim({:?})", instance);
31
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(
35             tcx,
36             instance,
37             Some(Adjustment::DerefMove),
38             CallKind::Direct(def_id),
39             None,
40         ),
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());
46
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),
52             };
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();
61
62             build_call_shim(tcx, instance, Some(adjustment), CallKind::Indirect, Some(arg_tys))
63         }
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)
71         }
72         ty::InstanceDef::ClosureOnceShim { call_once: _ } => {
73             let fn_mut = tcx.lang_items().fn_mut_trait().unwrap();
74             let call_mut = tcx
75                 .associated_items(fn_mut)
76                 .in_definition_order()
77                 .find(|it| it.kind == ty::AssocKind::Method)
78                 .unwrap()
79                 .def_id;
80
81             build_call_shim(
82                 tcx,
83                 instance,
84                 Some(Adjustment::RefMut),
85                 CallKind::Direct(call_mut),
86                 None,
87             )
88         }
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());
94
95             build_drop_shim(tcx, def_id, ty)
96         }
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());
102
103             build_clone_shim(tcx, def_id, ty)
104         }
105         ty::InstanceDef::Virtual(..) => {
106             bug!("InstanceDef::Virtual ({:?}) is for direct calls only", instance)
107         }
108         ty::InstanceDef::Intrinsic(_) => {
109             bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
110         }
111     };
112     debug!("make_shim({:?}) = untransformed {:?}", instance, result);
113
114     run_passes(
115         tcx,
116         &mut result,
117         instance,
118         None,
119         MirPhase::Const,
120         &[
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,
126         ],
127     );
128
129     debug!("make_shim({:?}) = {:?}", instance, result);
130
131     result.ensure_predecessors();
132     tcx.arena.alloc(result)
133 }
134
135 #[derive(Copy, Clone, Debug, PartialEq)]
136 enum Adjustment {
137     Identity,
138     Deref,
139     DerefMove,
140     RefMut,
141 }
142
143 #[derive(Copy, Clone, Debug, PartialEq)]
144 enum CallKind {
145     Indirect,
146     Direct(DefId),
147 }
148
149 fn temp_decl(mutability: Mutability, ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
150     let source_info = SourceInfo { scope: OUTERMOST_SOURCE_SCOPE, span };
151     LocalDecl {
152         mutability,
153         ty,
154         user_ty: UserTypeProjections::none(),
155         source_info,
156         internal: false,
157         local_info: LocalInfo::Other,
158         is_block_tail: None,
159     }
160 }
161
162 fn local_decls_for_sig<'tcx>(
163     sig: &ty::FnSig<'tcx>,
164     span: Span,
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)))
168         .collect()
169 }
170
171 fn build_drop_shim<'tcx>(
172     tcx: TyCtxt<'tcx>,
173     def_id: DefId,
174     ty: Option<Ty<'tcx>>,
175 ) -> BodyAndCache<'tcx> {
176     debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
177
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);
182     }
183
184     let substs = if let Some(ty) = ty {
185         tcx.intern_substs(&[ty.into()])
186     } else {
187         InternalSubsts::identity_for_item(tcx, def_id)
188     };
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);
192
193     let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
194
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 {
199             statements: vec![],
200             terminator: Some(Terminator { source_info, kind }),
201             is_cleanup: false,
202         })
203     };
204     block(&mut blocks, TerminatorKind::Goto { target: return_block });
205     block(&mut blocks, TerminatorKind::Return);
206
207     let body = new_body(blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span);
208
209     let mut body = BodyAndCache::new(body);
210
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(
217                 0,
218                 Statement {
219                     source_info,
220                     kind: StatementKind::Retag(RetagKind::Raw, box (dropee_ptr)),
221                 },
222             );
223         }
224         let patch = {
225             let param_env = tcx.param_env(def_id).with_reveal_all();
226             let mut elaborator =
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(
231                 &mut elaborator,
232                 source_info,
233                 dropee,
234                 (),
235                 return_block,
236                 elaborate_drops::Unwind::To(resume_block),
237                 START_BLOCK,
238             );
239             elaborator.patch
240         };
241         patch.apply(&mut body);
242     }
243
244     body
245 }
246
247 fn new_body<'tcx>(
248     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
249     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
250     arg_count: usize,
251     span: Span,
252 ) -> Body<'tcx> {
253     Body::new(
254         basic_blocks,
255         IndexVec::from_elem_n(
256             SourceScopeData { span, parent_scope: None, local_data: ClearCrossCrate::Clear },
257             1,
258         ),
259         local_decls,
260         IndexVec::new(),
261         arg_count,
262         vec![],
263         span,
264         vec![],
265         None,
266     )
267 }
268
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>,
274 }
275
276 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
277     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
278         Ok(())
279     }
280 }
281
282 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
283     type Path = ();
284
285     fn patch(&mut self) -> &mut MirPatch<'tcx> {
286         &mut self.patch
287     }
288     fn body(&self) -> &'a Body<'tcx> {
289         self.body
290     }
291     fn tcx(&self) -> TyCtxt<'tcx> {
292         self.tcx
293     }
294     fn param_env(&self) -> ty::ParamEnv<'tcx> {
295         self.param_env
296     }
297
298     fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
299         if let DropFlagMode::Shallow = mode { DropStyle::Static } else { DropStyle::Open }
300     }
301
302     fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
303         None
304     }
305
306     fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {}
307
308     fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
309         None
310     }
311     fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
312         None
313     }
314     fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> {
315         Some(())
316     }
317     fn array_subpath(&self, _path: Self::Path, _index: u32, _size: u32) -> Option<Self::Path> {
318         None
319     }
320 }
321
322 /// Builds a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
323 fn build_clone_shim<'tcx>(
324     tcx: TyCtxt<'tcx>,
325     def_id: DefId,
326     self_ty: Ty<'tcx>,
327 ) -> BodyAndCache<'tcx> {
328     debug!("build_clone_shim(def_id={:?})", def_id);
329
330     let param_env = tcx.param_env(def_id);
331
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);
334
335     let dest = Place::return_place();
336     let src = tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
337
338     match self_ty.kind {
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)
343         }
344         ty::Closure(_, substs) => {
345             builder.tuple_like_shim(dest, src, substs.as_closure().upvar_tys())
346         }
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),
349     };
350
351     BodyAndCache::new(builder.into_mir())
352 }
353
354 struct CloneShimBuilder<'tcx> {
355     tcx: TyCtxt<'tcx>,
356     def_id: DefId,
357     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
358     blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
359     span: Span,
360     sig: ty::FnSig<'tcx>,
361 }
362
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);
372
373         CloneShimBuilder {
374             tcx,
375             def_id,
376             local_decls: local_decls_for_sig(&sig, span),
377             blocks: IndexVec::new(),
378             span,
379             sig,
380         }
381     }
382
383     fn into_mir(self) -> Body<'tcx> {
384         new_body(self.blocks, self.local_decls, self.sig.inputs().len(), self.span)
385     }
386
387     fn source_info(&self) -> SourceInfo {
388         SourceInfo { span: self.span, scope: OUTERMOST_SOURCE_SCOPE }
389     }
390
391     fn block(
392         &mut self,
393         statements: Vec<Statement<'tcx>>,
394         kind: TerminatorKind<'tcx>,
395         is_cleanup: bool,
396     ) -> BasicBlock {
397         let source_info = self.source_info();
398         self.blocks.push(BasicBlockData {
399             statements,
400             terminator: Some(Terminator { source_info, kind }),
401             is_cleanup,
402         })
403     }
404
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)
411     }
412
413     fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
414         Statement { source_info: self.source_info(), kind }
415     }
416
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)),
422         )));
423         self.block(vec![ret_statement], TerminatorKind::Return, false);
424     }
425
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)))
429     }
430
431     fn make_clone_call(
432         &mut self,
433         dest: Place<'tcx>,
434         src: Place<'tcx>,
435         ty: Ty<'tcx>,
436         next: BasicBlock,
437         cleanup: BasicBlock,
438     ) {
439         let tcx = self.tcx;
440
441         let substs = tcx.mk_substs_trait(ty, &[]);
442
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 {
446             span: self.span,
447             user_ty: None,
448             literal: ty::Const::zero_sized(tcx, func_ty),
449         });
450
451         let ref_loc = self.make_place(
452             Mutability::Not,
453             tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }),
454         );
455
456         // `let ref_loc: &ty = &src;`
457         let statement = self.make_statement(StatementKind::Assign(box (
458             ref_loc,
459             Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src),
460         )));
461
462         // `let loc = Clone::clone(ref_loc);`
463         self.block(
464             vec![statement],
465             TerminatorKind::Call {
466                 func,
467                 args: vec![Operand::Move(ref_loc)],
468                 destination: Some((dest, next)),
469                 cleanup: Some(cleanup),
470                 from_hir_call: true,
471             },
472             false,
473         );
474     }
475
476     fn loop_header(
477         &mut self,
478         beg: Place<'tcx>,
479         end: Place<'tcx>,
480         loop_body: BasicBlock,
481         loop_end: BasicBlock,
482         is_cleanup: bool,
483     ) {
484         let tcx = self.tcx;
485
486         let cond = self.make_place(Mutability::Mut, tcx.types.bool);
487         let compute_cond = self.make_statement(StatementKind::Assign(box (
488             cond,
489             Rvalue::BinaryOp(BinOp::Ne, Operand::Copy(end), Operand::Copy(beg)),
490         )));
491
492         // `if end != beg { goto loop_body; } else { goto loop_end; }`
493         self.block(
494             vec![compute_cond],
495             TerminatorKind::if_(tcx, Operand::Move(cond), loop_body, loop_end),
496             is_cleanup,
497         );
498     }
499
500     fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
501         box Constant {
502             span: self.span,
503             user_ty: None,
504             literal: ty::Const::from_usize(self.tcx, value),
505         }
506     }
507
508     fn array_shim(&mut self, dest: Place<'tcx>, src: Place<'tcx>, ty: Ty<'tcx>, len: u64) {
509         let tcx = self.tcx;
510         let span = self.span;
511
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);
514
515         // BB #0
516         // `let mut beg = 0;`
517         // `let end = len;`
518         // `goto #1;`
519         let inits = vec![
520             self.make_statement(StatementKind::Assign(box (
521                 Place::from(beg),
522                 Rvalue::Use(Operand::Constant(self.make_usize(0))),
523             ))),
524             self.make_statement(StatementKind::Assign(box (
525                 end,
526                 Rvalue::Use(Operand::Constant(self.make_usize(len))),
527             ))),
528         ];
529         self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
530
531         // BB #1: loop {
532         //     BB #2;
533         //     BB #3;
534         // }
535         // BB #4;
536         self.loop_header(Place::from(beg), end, BasicBlock::new(2), BasicBlock::new(4), false);
537
538         // BB #2
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));
544
545         // BB #3
546         // `beg = beg + 1;`
547         // `goto #1`;
548         let statements = vec![self.make_statement(StatementKind::Assign(box (
549             Place::from(beg),
550             Rvalue::BinaryOp(
551                 BinOp::Add,
552                 Operand::Copy(Place::from(beg)),
553                 Operand::Constant(self.make_usize(1)),
554             ),
555         )))];
556         self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
557
558         // BB #4
559         // `return dest;`
560         self.block(vec![], TerminatorKind::Return, false);
561
562         // BB #5 (cleanup)
563         // `let end = beg;`
564         // `let mut beg = 0;`
565         // goto #6;
566         let end = beg;
567         let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
568         let init = self.make_statement(StatementKind::Assign(box (
569             Place::from(beg),
570             Rvalue::Use(Operand::Constant(self.make_usize(0))),
571         )));
572         self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
573
574         // BB #6 (cleanup): loop {
575         //     BB #7;
576         //     BB #8;
577         // }
578         // BB #9;
579         self.loop_header(
580             Place::from(beg),
581             Place::from(end),
582             BasicBlock::new(7),
583             BasicBlock::new(9),
584             true,
585         );
586
587         // BB #7 (cleanup)
588         // `drop(dest[beg])`;
589         self.block(
590             vec![],
591             TerminatorKind::Drop {
592                 location: self.tcx.mk_place_index(dest, beg),
593                 target: BasicBlock::new(8),
594                 unwind: None,
595             },
596             true,
597         );
598
599         // BB #8 (cleanup)
600         // `beg = beg + 1;`
601         // `goto #6;`
602         let statement = self.make_statement(StatementKind::Assign(box (
603             Place::from(beg),
604             Rvalue::BinaryOp(
605                 BinOp::Add,
606                 Operand::Copy(Place::from(beg)),
607                 Operand::Constant(self.make_usize(1)),
608             ),
609         )));
610         self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
611
612         // BB #9 (resume)
613         self.block(vec![], TerminatorKind::Resume, true);
614     }
615
616     fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>, src: Place<'tcx>, tys: I)
617     where
618         I: Iterator<Item = Ty<'tcx>>,
619     {
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);
624
625             let dest_field = self.tcx.mk_place_field(dest.clone(), field, ity);
626
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);
632
633             // BB #(2i)
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);
637
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.
641                 self.block(
642                     vec![],
643                     TerminatorKind::Drop {
644                         location: previous_field,
645                         target: previous_cleanup,
646                         unwind: None,
647                     },
648                     true,
649                 );
650             } else {
651                 // Nothing to drop, just resume.
652                 self.block(vec![], TerminatorKind::Resume, true);
653             }
654
655             previous_field = Some((dest_field, cleanup_block));
656         }
657
658         self.block(vec![], TerminatorKind::Return, false);
659     }
660 }
661
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`.
665 ///
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>(
669     tcx: TyCtxt<'tcx>,
670     instance: ty::InstanceDef<'tcx>,
671     rcvr_adjustment: Option<Adjustment>,
672     call_kind: CallKind,
673     untuple_args: Option<&[Ty<'tcx>]>,
674 ) -> BodyAndCache<'tcx> {
675     debug!(
676         "build_call_shim(instance={:?}, rcvr_adjustment={:?}, \
677             call_kind={:?}, untuple_args={:?})",
678         instance, rcvr_adjustment, call_kind, untuple_args
679     );
680
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);
684
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);
694     }
695
696     let span = tcx.def_span(def_id);
697
698     debug!("build_call_shim: sig={:?}", sig);
699
700     let mut local_decls = local_decls_for_sig(&sig, span);
701     let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
702
703     let rcvr_place = || {
704         assert!(rcvr_adjustment.is_some());
705         Place::from(Local::new(1 + 0))
706     };
707     let mut statements = vec![];
708
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(
716                 Mutability::Not,
717                 tcx.mk_ref(
718                     tcx.lifetimes.re_erased,
719                     ty::TypeAndMut { ty: sig.inputs()[0], mutbl: hir::Mutability::Mut },
720                 ),
721                 span,
722             ));
723             let borrow_kind = BorrowKind::Mut { allow_two_phase_borrow: false };
724             statements.push(Statement {
725                 source_info,
726                 kind: StatementKind::Assign(box (
727                     Place::from(ref_rcvr),
728                     Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_place()),
729                 )),
730             });
731             Operand::Move(Place::from(ref_rcvr))
732         }
733     });
734
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);
739             (
740                 Operand::Constant(box Constant {
741                     span,
742                     user_ty: None,
743                     literal: ty::Const::zero_sized(tcx, ty),
744                 }),
745                 rcvr.into_iter().collect::<Vec<_>>(),
746             )
747         }
748     };
749
750     let mut arg_range = 0..sig.inputs().len();
751
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;
755     }
756
757     // Take the last argument, if we need to untuple it (handled below).
758     if untuple_args.is_some() {
759         arg_range.end -= 1;
760     }
761
762     // Pass all of the non-special arguments directly.
763     args.extend(arg_range.map(|i| Operand::Move(Place::from(Local::new(1 + i)))));
764
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))
770         }));
771     }
772
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 {
777             statements,
778             terminator: Some(Terminator { source_info, kind }),
779             is_cleanup,
780         })
781     };
782
783     // BB #0
784     block(
785         &mut blocks,
786         statements,
787         TerminatorKind::Call {
788             func: callee,
789             args,
790             destination: Some((Place::return_place(), BasicBlock::new(1))),
791             cleanup: if let Some(Adjustment::RefMut) = rcvr_adjustment {
792                 Some(BasicBlock::new(3))
793             } else {
794                 None
795             },
796             from_hir_call: true,
797         },
798         false,
799     );
800
801     if let Some(Adjustment::RefMut) = rcvr_adjustment {
802         // BB #1 - drop for Self
803         block(
804             &mut blocks,
805             vec![],
806             TerminatorKind::Drop {
807                 location: rcvr_place(),
808                 target: BasicBlock::new(2),
809                 unwind: None,
810             },
811             false,
812         );
813     }
814     // BB #1/#2 - return
815     block(&mut blocks, vec![], TerminatorKind::Return, false);
816     if let Some(Adjustment::RefMut) = rcvr_adjustment {
817         // BB #3 - drop if closure panics
818         block(
819             &mut blocks,
820             vec![],
821             TerminatorKind::Drop {
822                 location: rcvr_place(),
823                 target: BasicBlock::new(4),
824                 unwind: None,
825             },
826             true,
827         );
828
829         // BB #4 - resume
830         block(&mut blocks, vec![], TerminatorKind::Resume, true);
831     }
832
833     let mut body = new_body(blocks, local_decls, sig.inputs().len(), span);
834
835     if let Abi::RustCall = sig.abi {
836         body.spread_arg = Some(Local::new(sig.inputs().len()));
837     }
838     BodyAndCache::new(body)
839 }
840
841 pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> &BodyAndCache<'_> {
842     debug_assert!(tcx.is_constructor(ctor_id));
843
844     let span =
845         tcx.hir().span_if_local(ctor_id).unwrap_or_else(|| bug!("no span for ctor {:?}", ctor_id));
846
847     let param_env = tcx.param_env(ctor_id);
848
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);
852
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()),
856     };
857
858     debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig);
859
860     let local_decls = local_decls_for_sig(&sig, span);
861
862     let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
863
864     let variant_index = if adt_def.is_enum() {
865         adt_def.variant_index_with_ctor_id(ctor_id)
866     } else {
867         VariantIdx::new(0)
868     };
869
870     // Generate the following MIR:
871     //
872     // (return as Variant).field0 = arg0;
873     // (return as Variant).field1 = arg1;
874     //
875     // return;
876     debug!("build_ctor: variant_index={:?}", variant_index);
877
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))
882         }),
883         AggregateKind::Adt(adt_def, variant_index, substs, None, None),
884         source_info,
885         tcx,
886     )
887     .collect();
888
889     let start_block = BasicBlockData {
890         statements,
891         terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }),
892         is_cleanup: false,
893     };
894
895     let body =
896         new_body(IndexVec::from_elem_n(start_block, 1), local_decls, sig.inputs().len(), span);
897
898     crate::util::dump_mir(
899         tcx,
900         None,
901         "mir_map",
902         &0,
903         crate::transform::MirSource::item(ctor_id),
904         &body,
905         |_, _| Ok(()),
906     );
907
908     let mut body = BodyAndCache::new(body);
909     body.ensure_predecessors();
910     tcx.arena.alloc(body)
911 }