]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/shim.rs
Block indent formatting
[rust.git] / src / librustc_mir / shim.rs
1 use rustc::hir;
2 use rustc::hir::def_id::DefId;
3 use rustc::mir::*;
4 use rustc::ty::{self, Ty, TyCtxt};
5 use rustc::ty::layout::VariantIdx;
6 use rustc::ty::subst::{Subst, InternalSubsts};
7 use rustc::ty::query::Providers;
8
9 use rustc_index::vec::{IndexVec, Idx};
10
11 use rustc_target::spec::abi::Abi;
12 use syntax_pos::{Span, sym};
13
14 use std::fmt;
15 use std::iter;
16
17 use crate::transform::{
18     add_moves_for_packed_drops, add_call_guards,
19     remove_noop_landing_pads, no_landing_pads, simplify, run_passes
20 };
21 use crate::util::elaborate_drops::{self, DropElaborator, DropStyle, DropFlagMode};
22 use crate::util::patch::MirPatch;
23 use crate::util::expand_aggregate;
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 Body<'tcx> {
30     debug!("make_shim({:?})", instance);
31
32     let mut result = match instance {
33         ty::InstanceDef::Item(..) =>
34             bug!("item {:?} passed to make_shim", instance),
35         ty::InstanceDef::VtableShim(def_id) => {
36             build_call_shim(
37                 tcx,
38                 def_id,
39                 Adjustment::DerefMove,
40                 CallKind::Direct(def_id),
41                 None,
42             )
43         }
44         ty::InstanceDef::FnPtrShim(def_id, ty) => {
45             let trait_ = tcx.trait_of_item(def_id).unwrap();
46             let adjustment = match tcx.lang_items().fn_trait_kind(trait_) {
47                 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
48                 Some(ty::ClosureKind::FnMut) |
49                 Some(ty::ClosureKind::Fn) => Adjustment::Deref,
50                 None => bug!("fn pointer {:?} is not an fn", ty)
51             };
52             // HACK: we need the "real" argument types for the MIR,
53             // but because our substs are (Self, Args), where Args
54             // is a tuple, we must include the *concrete* argument
55             // types in the MIR. They will be substituted again with
56             // the param-substs, but because they are concrete, this
57             // will not do any harm.
58             let sig = tcx.erase_late_bound_regions(&ty.fn_sig(tcx));
59             let arg_tys = sig.inputs();
60
61             build_call_shim(
62                 tcx,
63                 def_id,
64                 adjustment,
65                 CallKind::Indirect,
66                 Some(arg_tys)
67             )
68         }
69         // We are generating a call back to our def-id, which the
70         // codegen backend knows to turn to an actual virtual call.
71         ty::InstanceDef::Virtual(def_id, _) |
72         // ...or we are generating a direct call to a function for which indirect calls must be
73         // codegen'd differently than direct ones (example: #[track_caller])
74         ty::InstanceDef::ReifyShim(def_id) => {
75             build_call_shim(
76                 tcx,
77                 def_id,
78                 Adjustment::Identity,
79                 CallKind::Direct(def_id),
80                 None
81             )
82         }
83         ty::InstanceDef::ClosureOnceShim { call_once } => {
84             let fn_mut = tcx.lang_items().fn_mut_trait().unwrap();
85             let call_mut = tcx
86                 .associated_items(fn_mut)
87                 .find(|it| it.kind == ty::AssocKind::Method)
88                 .unwrap().def_id;
89
90             build_call_shim(
91                 tcx,
92                 call_once,
93                 Adjustment::RefMut,
94                 CallKind::Direct(call_mut),
95                 None
96             )
97         }
98         ty::InstanceDef::DropGlue(def_id, ty) => {
99             build_drop_shim(tcx, def_id, ty)
100         }
101         ty::InstanceDef::CloneShim(def_id, ty) => {
102             let name = tcx.item_name(def_id);
103             if name == sym::clone {
104                 build_clone_shim(tcx, def_id, ty)
105             } else if name == sym::clone_from {
106                 debug!("make_shim({:?}: using default trait implementation", instance);
107                 return tcx.optimized_mir(def_id);
108             } else {
109                 bug!("builtin clone shim {:?} not supported", instance)
110             }
111         }
112         ty::InstanceDef::Intrinsic(_) => {
113             bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
114         }
115     };
116     debug!("make_shim({:?}) = untransformed {:?}", instance, result);
117
118     run_passes(tcx, &mut result, instance, None, MirPhase::Const, &[
119         &add_moves_for_packed_drops::AddMovesForPackedDrops,
120         &no_landing_pads::NoLandingPads::new(tcx),
121         &remove_noop_landing_pads::RemoveNoopLandingPads,
122         &simplify::SimplifyCfg::new("make_shim"),
123         &add_call_guards::CriticalCallEdges,
124     ]);
125
126     debug!("make_shim({:?}) = {:?}", instance, result);
127
128     tcx.arena.alloc(result)
129 }
130
131 #[derive(Copy, Clone, Debug, PartialEq)]
132 enum Adjustment {
133     Identity,
134     Deref,
135     DerefMove,
136     RefMut,
137 }
138
139 #[derive(Copy, Clone, Debug, PartialEq)]
140 enum CallKind {
141     Indirect,
142     Direct(DefId),
143 }
144
145 fn temp_decl(mutability: Mutability, ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
146     let source_info = SourceInfo { scope: OUTERMOST_SOURCE_SCOPE, span };
147     LocalDecl {
148         mutability,
149         ty,
150         user_ty: UserTypeProjections::none(),
151         source_info,
152         internal: false,
153         local_info: LocalInfo::Other,
154         is_block_tail: None,
155     }
156 }
157
158 fn local_decls_for_sig<'tcx>(sig: &ty::FnSig<'tcx>, span: Span)
159     -> IndexVec<Local, LocalDecl<'tcx>>
160 {
161     iter::once(temp_decl(Mutability::Mut, sig.output(), span))
162         .chain(sig.inputs().iter().map(
163             |ity| temp_decl(Mutability::Not, ity, span)))
164         .collect()
165 }
166
167 fn build_drop_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, ty: Option<Ty<'tcx>>) -> Body<'tcx> {
168     debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
169
170     // Check if this is a generator, if so, return the drop glue for it
171     if let Some(&ty::TyS { kind: ty::Generator(gen_def_id, substs, _), .. }) = ty {
172         let body = &**tcx.optimized_mir(gen_def_id).generator_drop.as_ref().unwrap();
173         return body.subst(tcx, substs);
174     }
175
176     let substs = if let Some(ty) = ty {
177         tcx.intern_substs(&[ty.into()])
178     } else {
179         InternalSubsts::identity_for_item(tcx, def_id)
180     };
181     let sig = tcx.fn_sig(def_id).subst(tcx, substs);
182     let sig = tcx.erase_late_bound_regions(&sig);
183     let span = tcx.def_span(def_id);
184
185     let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
186
187     let return_block = BasicBlock::new(1);
188     let mut blocks = IndexVec::with_capacity(2);
189     let block = |blocks: &mut IndexVec<_, _>, kind| {
190         blocks.push(BasicBlockData {
191             statements: vec![],
192             terminator: Some(Terminator { source_info, kind }),
193             is_cleanup: false
194         })
195     };
196     block(&mut blocks, TerminatorKind::Goto { target: return_block });
197     block(&mut blocks, TerminatorKind::Return);
198
199     let mut body = new_body(
200         blocks,
201         IndexVec::from_elem_n(
202             SourceScopeData { span, parent_scope: None }, 1
203         ),
204         local_decls_for_sig(&sig, span),
205         sig.inputs().len(),
206         span);
207
208     if let Some(..) = ty {
209         // The first argument (index 0), but add 1 for the return value.
210         let dropee_ptr = Place::from(Local::new(1+0));
211         if tcx.sess.opts.debugging_opts.mir_emit_retag {
212             // Function arguments should be retagged, and we make this one raw.
213             body.basic_blocks_mut()[START_BLOCK].statements.insert(0, Statement {
214                 source_info,
215                 kind: StatementKind::Retag(RetagKind::Raw, box(dropee_ptr.clone())),
216             });
217         }
218         let patch = {
219             let param_env = tcx.param_env(def_id).with_reveal_all();
220             let mut elaborator = DropShimElaborator {
221                 body: &body,
222                 patch: MirPatch::new(&body),
223                 tcx,
224                 param_env
225             };
226             let dropee = tcx.mk_place_deref(dropee_ptr);
227             let resume_block = elaborator.patch.resume_block();
228             elaborate_drops::elaborate_drop(
229                 &mut elaborator,
230                 source_info,
231                 &dropee,
232                 (),
233                 return_block,
234                 elaborate_drops::Unwind::To(resume_block),
235                 START_BLOCK
236             );
237             elaborator.patch
238         };
239         patch.apply(&mut body);
240     }
241
242     body
243 }
244
245 fn new_body<'tcx>(
246     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
247     source_scopes: IndexVec<SourceScope, SourceScopeData>,
248     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
249     arg_count: usize,
250     span: Span,
251 ) -> Body<'tcx> {
252     Body::new(
253         basic_blocks,
254         source_scopes,
255         ClearCrossCrate::Clear,
256         None,
257         local_decls,
258         IndexVec::new(),
259         arg_count,
260         vec![],
261         span,
262         vec![],
263         None,
264     )
265 }
266
267 pub struct DropShimElaborator<'a, 'tcx> {
268     pub body: &'a Body<'tcx>,
269     pub patch: MirPatch<'tcx>,
270     pub tcx: TyCtxt<'tcx>,
271     pub param_env: ty::ParamEnv<'tcx>,
272 }
273
274 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
275     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
276         Ok(())
277     }
278 }
279
280 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
281     type Path = ();
282
283     fn patch(&mut self) -> &mut MirPatch<'tcx> { &mut self.patch }
284     fn body(&self) -> &'a Body<'tcx> { self.body }
285     fn tcx(&self) -> TyCtxt<'tcx> {
286         self.tcx
287         }
288     fn param_env(&self) -> ty::ParamEnv<'tcx> { self.param_env }
289
290     fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
291         if let DropFlagMode::Shallow = mode {
292             DropStyle::Static
293         } else {
294             DropStyle::Open
295         }
296     }
297
298     fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
299         None
300     }
301
302     fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {
303     }
304
305     fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
306         None
307     }
308     fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
309         None
310     }
311     fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> {
312         Some(())
313     }
314     fn array_subpath(&self, _path: Self::Path, _index: u32, _size: u32) -> Option<Self::Path> {
315         None
316     }
317 }
318
319 /// Builds a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
320 fn build_clone_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Body<'tcx> {
321     debug!("build_clone_shim(def_id={:?})", def_id);
322
323     let param_env = tcx.param_env(def_id);
324
325     let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty);
326     let is_copy = self_ty.is_copy_modulo_regions(tcx, param_env, builder.span);
327
328     let dest = Place::return_place();
329     let src = tcx.mk_place_deref(Place::from(Local::new(1+0)));
330
331     match self_ty.kind {
332         _ if is_copy => builder.copy_shim(),
333         ty::Array(ty, len) => {
334             let len = len.eval_usize(tcx, param_env);
335             builder.array_shim(dest, src, ty, len)
336         }
337         ty::Closure(def_id, substs) => {
338             builder.tuple_like_shim(
339                 dest, src,
340                 substs.as_closure().upvar_tys(def_id, tcx)
341             )
342         }
343         ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()),
344         _ => {
345             bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty)
346         }
347     };
348
349     builder.into_mir()
350 }
351
352 struct CloneShimBuilder<'tcx> {
353     tcx: TyCtxt<'tcx>,
354     def_id: DefId,
355     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
356     blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
357     span: Span,
358     sig: ty::FnSig<'tcx>,
359 }
360
361 impl CloneShimBuilder<'tcx> {
362     fn new(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Self {
363         // we must subst the self_ty because it's
364         // otherwise going to be TySelf and we can't index
365         // or access fields of a Place of type TySelf.
366         let substs = tcx.mk_substs_trait(self_ty, &[]);
367         let sig = tcx.fn_sig(def_id).subst(tcx, substs);
368         let sig = tcx.erase_late_bound_regions(&sig);
369         let span = tcx.def_span(def_id);
370
371         CloneShimBuilder {
372             tcx,
373             def_id,
374             local_decls: local_decls_for_sig(&sig, span),
375             blocks: IndexVec::new(),
376             span,
377             sig,
378         }
379     }
380
381     fn into_mir(self) -> Body<'tcx> {
382         new_body(
383             self.blocks,
384             IndexVec::from_elem_n(
385                 SourceScopeData { span: self.span, parent_scope: None }, 1
386             ),
387             self.local_decls,
388             self.sig.inputs().len(),
389             self.span,
390         )
391     }
392
393     fn source_info(&self) -> SourceInfo {
394         SourceInfo { span: self.span, scope: OUTERMOST_SOURCE_SCOPE }
395     }
396
397     fn block(
398         &mut self,
399         statements: Vec<Statement<'tcx>>,
400         kind: TerminatorKind<'tcx>,
401         is_cleanup: bool
402     ) -> BasicBlock {
403         let source_info = self.source_info();
404         self.blocks.push(BasicBlockData {
405             statements,
406             terminator: Some(Terminator { source_info, kind }),
407             is_cleanup,
408         })
409     }
410
411     /// Gives the index of an upcoming BasicBlock, with an offset.
412     /// offset=0 will give you the index of the next BasicBlock,
413     /// offset=1 will give the index of the next-to-next block,
414     /// offset=-1 will give you the index of the last-created block
415     fn block_index_offset(&mut self, offset: usize) -> BasicBlock {
416         BasicBlock::new(self.blocks.len() + offset)
417     }
418
419     fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
420         Statement {
421             source_info: self.source_info(),
422             kind,
423         }
424     }
425
426     fn copy_shim(&mut self) {
427         let rcvr = self.tcx.mk_place_deref(Place::from(Local::new(1+0)));
428         let ret_statement = self.make_statement(
429             StatementKind::Assign(
430                 box(
431                     Place::return_place(),
432                     Rvalue::Use(Operand::Copy(rcvr))
433                 )
434             )
435         );
436         self.block(vec![ret_statement], TerminatorKind::Return, false);
437     }
438
439     fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
440         let span = self.span;
441         Place::from(self.local_decls.push(temp_decl(mutability, ty, span)))
442     }
443
444     fn make_clone_call(
445         &mut self,
446         dest: Place<'tcx>,
447         src: Place<'tcx>,
448         ty: Ty<'tcx>,
449         next: BasicBlock,
450         cleanup: BasicBlock
451     ) {
452         let tcx = self.tcx;
453
454         let substs = tcx.mk_substs_trait(ty, &[]);
455
456         // `func == Clone::clone(&ty) -> ty`
457         let func_ty = tcx.mk_fn_def(self.def_id, substs);
458         let func = Operand::Constant(box Constant {
459             span: self.span,
460             user_ty: None,
461             literal: ty::Const::zero_sized(tcx, func_ty),
462         });
463
464         let ref_loc = self.make_place(
465             Mutability::Not,
466             tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut {
467                 ty,
468                 mutbl: hir::Mutability::Immutable,
469             })
470         );
471
472         // `let ref_loc: &ty = &src;`
473         let statement = self.make_statement(
474             StatementKind::Assign(
475                 box(
476                     ref_loc.clone(),
477                     Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src)
478                 )
479             )
480         );
481
482         // `let loc = Clone::clone(ref_loc);`
483         self.block(vec![statement], TerminatorKind::Call {
484             func,
485             args: vec![Operand::Move(ref_loc)],
486             destination: Some((dest, next)),
487             cleanup: Some(cleanup),
488             from_hir_call: true,
489         }, false);
490     }
491
492     fn loop_header(
493         &mut self,
494         beg: Place<'tcx>,
495         end: Place<'tcx>,
496         loop_body: BasicBlock,
497         loop_end: BasicBlock,
498         is_cleanup: bool
499     ) {
500         let tcx = self.tcx;
501
502         let cond = self.make_place(Mutability::Mut, tcx.types.bool);
503         let compute_cond = self.make_statement(
504             StatementKind::Assign(
505                 box(
506                     cond.clone(),
507                     Rvalue::BinaryOp(BinOp::Ne, Operand::Copy(end), Operand::Copy(beg))
508                 )
509             )
510         );
511
512         // `if end != beg { goto loop_body; } else { goto loop_end; }`
513         self.block(
514             vec![compute_cond],
515             TerminatorKind::if_(tcx, Operand::Move(cond), loop_body, loop_end),
516             is_cleanup
517         );
518     }
519
520     fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
521         box Constant {
522             span: self.span,
523             user_ty: None,
524             literal: ty::Const::from_usize(self.tcx, value),
525         }
526     }
527
528     fn array_shim(&mut self, dest: Place<'tcx>, src: Place<'tcx>, ty: Ty<'tcx>, len: u64) {
529         let tcx = self.tcx;
530         let span = self.span;
531
532         let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
533         let end = self.make_place(Mutability::Not, tcx.types.usize);
534
535         // BB #0
536         // `let mut beg = 0;`
537         // `let end = len;`
538         // `goto #1;`
539         let inits = vec![
540             self.make_statement(
541                 StatementKind::Assign(
542                     box(
543                         Place::from(beg),
544                         Rvalue::Use(Operand::Constant(self.make_usize(0)))
545                     )
546                 )
547             ),
548             self.make_statement(
549                 StatementKind::Assign(
550                     box(
551                         end.clone(),
552                         Rvalue::Use(Operand::Constant(self.make_usize(len)))
553                     )
554                 )
555             )
556         ];
557         self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
558
559         // BB #1: loop {
560         //     BB #2;
561         //     BB #3;
562         // }
563         // BB #4;
564         self.loop_header(Place::from(beg),
565                          end,
566                          BasicBlock::new(2),
567                          BasicBlock::new(4),
568                          false);
569
570         // BB #2
571         // `dest[i] = Clone::clone(src[beg])`;
572         // Goto #3 if ok, #5 if unwinding happens.
573         let dest_field = self.tcx.mk_place_index(dest.clone(), beg);
574         let src_field = self.tcx.mk_place_index(src, beg);
575         self.make_clone_call(dest_field, src_field, ty, BasicBlock::new(3),
576                              BasicBlock::new(5));
577
578         // BB #3
579         // `beg = beg + 1;`
580         // `goto #1`;
581         let statements = vec![
582             self.make_statement(
583                 StatementKind::Assign(
584                     box(
585                         Place::from(beg),
586                         Rvalue::BinaryOp(
587                             BinOp::Add,
588                             Operand::Copy(Place::from(beg)),
589                             Operand::Constant(self.make_usize(1))
590                         )
591                     )
592                 )
593             )
594         ];
595         self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
596
597         // BB #4
598         // `return dest;`
599         self.block(vec![], TerminatorKind::Return, false);
600
601         // BB #5 (cleanup)
602         // `let end = beg;`
603         // `let mut beg = 0;`
604         // goto #6;
605         let end = beg;
606         let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
607         let init = self.make_statement(
608             StatementKind::Assign(
609                 box(
610                     Place::from(beg),
611                     Rvalue::Use(Operand::Constant(self.make_usize(0)))
612                 )
613             )
614         );
615         self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
616
617         // BB #6 (cleanup): loop {
618         //     BB #7;
619         //     BB #8;
620         // }
621         // BB #9;
622         self.loop_header(Place::from(beg), Place::from(end),
623                          BasicBlock::new(7), BasicBlock::new(9), true);
624
625         // BB #7 (cleanup)
626         // `drop(dest[beg])`;
627         self.block(vec![], TerminatorKind::Drop {
628             location: self.tcx.mk_place_index(dest, beg),
629             target: BasicBlock::new(8),
630             unwind: None,
631         }, true);
632
633         // BB #8 (cleanup)
634         // `beg = beg + 1;`
635         // `goto #6;`
636         let statement = self.make_statement(
637             StatementKind::Assign(
638                 box(
639                     Place::from(beg),
640                     Rvalue::BinaryOp(
641                         BinOp::Add,
642                         Operand::Copy(Place::from(beg)),
643                         Operand::Constant(self.make_usize(1))
644                     )
645                 )
646             )
647         );
648         self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
649
650         // BB #9 (resume)
651         self.block(vec![], TerminatorKind::Resume, true);
652     }
653
654     fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>,
655                           src: Place<'tcx>, tys: I)
656             where I: Iterator<Item = Ty<'tcx>> {
657         let mut previous_field = None;
658         for (i, ity) in tys.enumerate() {
659             let field = Field::new(i);
660             let src_field = self.tcx.mk_place_field(src.clone(), field, ity);
661
662             let dest_field = self.tcx.mk_place_field(dest.clone(), field, ity);
663
664             // #(2i + 1) is the cleanup block for the previous clone operation
665             let cleanup_block = self.block_index_offset(1);
666             // #(2i + 2) is the next cloning block
667             // (or the Return terminator if this is the last block)
668             let next_block = self.block_index_offset(2);
669
670             // BB #(2i)
671             // `dest.i = Clone::clone(&src.i);`
672             // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
673             self.make_clone_call(
674                 dest_field.clone(),
675                 src_field,
676                 ity,
677                 next_block,
678                 cleanup_block,
679             );
680
681             // BB #(2i + 1) (cleanup)
682             if let Some((previous_field, previous_cleanup)) = previous_field.take() {
683                 // Drop previous field and goto previous cleanup block.
684                 self.block(vec![], TerminatorKind::Drop {
685                     location: previous_field,
686                     target: previous_cleanup,
687                     unwind: None,
688                 }, true);
689             } else {
690                 // Nothing to drop, just resume.
691                 self.block(vec![], TerminatorKind::Resume, true);
692             }
693
694             previous_field = Some((dest_field, cleanup_block));
695         }
696
697         self.block(vec![], TerminatorKind::Return, false);
698     }
699 }
700
701 /// Builds a "call" shim for `def_id`. The shim calls the
702 /// function specified by `call_kind`, first adjusting its first
703 /// argument according to `rcvr_adjustment`.
704 ///
705 /// If `untuple_args` is a vec of types, the second argument of the
706 /// function will be untupled as these types.
707 fn build_call_shim<'tcx>(
708     tcx: TyCtxt<'tcx>,
709     def_id: DefId,
710     rcvr_adjustment: Adjustment,
711     call_kind: CallKind,
712     untuple_args: Option<&[Ty<'tcx>]>,
713 ) -> Body<'tcx> {
714     debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
715             call_kind={:?}, untuple_args={:?})",
716            def_id, rcvr_adjustment, call_kind, untuple_args);
717
718     let sig = tcx.fn_sig(def_id);
719     let sig = tcx.erase_late_bound_regions(&sig);
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 { span, scope: OUTERMOST_SOURCE_SCOPE };
726
727     let rcvr_arg = Local::new(1+0);
728     let rcvr_l = Place::from(rcvr_arg);
729     let mut statements = vec![];
730
731     let rcvr = match rcvr_adjustment {
732         Adjustment::Identity => Operand::Move(rcvr_l),
733         Adjustment::Deref => Operand::Copy(tcx.mk_place_deref(rcvr_l)),
734         Adjustment::DerefMove => {
735             // fn(Self, ...) -> fn(*mut Self, ...)
736             let arg_ty = local_decls[rcvr_arg].ty;
737             debug_assert!(tcx.generics_of(def_id).has_self && arg_ty == tcx.types.self_param);
738             local_decls[rcvr_arg].ty = tcx.mk_mut_ptr(arg_ty);
739
740             Operand::Move(tcx.mk_place_deref(rcvr_l))
741         }
742         Adjustment::RefMut => {
743             // let rcvr = &mut rcvr;
744             let ref_rcvr = local_decls.push(temp_decl(
745                 Mutability::Not,
746                 tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut {
747                     ty: sig.inputs()[0],
748                     mutbl: hir::Mutability::Mutable
749                 }),
750                 span
751             ));
752             let borrow_kind = BorrowKind::Mut {
753                 allow_two_phase_borrow: false,
754             };
755             statements.push(Statement {
756                 source_info,
757                 kind: StatementKind::Assign(
758                     box(
759                         Place::from(ref_rcvr),
760                         Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_l)
761                     )
762                 )
763             });
764             Operand::Move(Place::from(ref_rcvr))
765         }
766     };
767
768     let (callee, mut args) = match call_kind {
769         CallKind::Indirect => (rcvr, vec![]),
770         CallKind::Direct(def_id) => {
771             let ty = tcx.type_of(def_id);
772             (Operand::Constant(box Constant {
773                 span,
774                 user_ty: None,
775                 literal: ty::Const::zero_sized(tcx, ty),
776              }),
777              vec![rcvr])
778         }
779     };
780
781     if let Some(untuple_args) = untuple_args {
782         args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
783             let arg_place = Place::from(Local::new(1+1));
784             Operand::Move(tcx.mk_place_field(arg_place, Field::new(i), *ity))
785         }));
786     } else {
787         args.extend((1..sig.inputs().len()).map(|i| {
788             Operand::Move(Place::from(Local::new(1+i)))
789         }));
790     }
791
792     let n_blocks = if let Adjustment::RefMut = rcvr_adjustment { 5 } else { 2 };
793     let mut blocks = IndexVec::with_capacity(n_blocks);
794     let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
795         blocks.push(BasicBlockData {
796             statements,
797             terminator: Some(Terminator { source_info, kind }),
798             is_cleanup
799         })
800     };
801
802     // BB #0
803     block(&mut blocks, statements, TerminatorKind::Call {
804         func: callee,
805         args,
806         destination: Some((Place::return_place(),
807                            BasicBlock::new(1))),
808         cleanup: if let Adjustment::RefMut = rcvr_adjustment {
809             Some(BasicBlock::new(3))
810         } else {
811             None
812         },
813         from_hir_call: true,
814     }, false);
815
816     if let Adjustment::RefMut = rcvr_adjustment {
817         // BB #1 - drop for Self
818         block(&mut blocks, vec![], TerminatorKind::Drop {
819             location: Place::from(rcvr_arg),
820             target: BasicBlock::new(2),
821             unwind: None
822         }, false);
823     }
824     // BB #1/#2 - return
825     block(&mut blocks, vec![], TerminatorKind::Return, false);
826     if let Adjustment::RefMut = rcvr_adjustment {
827         // BB #3 - drop if closure panics
828         block(&mut blocks, vec![], TerminatorKind::Drop {
829             location: Place::from(rcvr_arg),
830             target: BasicBlock::new(4),
831             unwind: None
832         }, true);
833
834         // BB #4 - resume
835         block(&mut blocks, vec![], TerminatorKind::Resume, true);
836     }
837
838     let mut body = new_body(
839         blocks,
840         IndexVec::from_elem_n(
841             SourceScopeData { span, parent_scope: None }, 1
842         ),
843         local_decls,
844         sig.inputs().len(),
845         span,
846     );
847
848     if let Abi::RustCall = sig.abi {
849         body.spread_arg = Some(Local::new(sig.inputs().len()));
850     }
851     body
852 }
853
854 pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> &Body<'_> {
855     debug_assert!(tcx.is_constructor(ctor_id));
856
857     let span = tcx.hir().span_if_local(ctor_id)
858         .unwrap_or_else(|| bug!("no span for ctor {:?}", ctor_id));
859
860     let param_env = tcx.param_env(ctor_id);
861
862     // Normalize the sig.
863     let sig = tcx.fn_sig(ctor_id)
864         .no_bound_vars()
865         .expect("LBR in ADT constructor signature");
866     let sig = tcx.normalize_erasing_regions(param_env, sig);
867
868     let (adt_def, substs) = match sig.output().kind {
869         ty::Adt(adt_def, substs) => (adt_def, substs),
870         _ => bug!("unexpected type for ADT ctor {:?}", sig.output())
871     };
872
873     debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig);
874
875     let local_decls = local_decls_for_sig(&sig, span);
876
877     let source_info = SourceInfo {
878         span,
879         scope: OUTERMOST_SOURCE_SCOPE
880     };
881
882     let variant_index = if adt_def.is_enum() {
883         adt_def.variant_index_with_ctor_id(ctor_id)
884     } else {
885         VariantIdx::new(0)
886     };
887
888     // Generate the following MIR:
889     //
890     // (return as Variant).field0 = arg0;
891     // (return as Variant).field1 = arg1;
892     //
893     // return;
894     debug!("build_ctor: variant_index={:?}", variant_index);
895
896     let statements = expand_aggregate(
897         Place::return_place(),
898         adt_def
899             .variants[variant_index]
900             .fields
901             .iter()
902             .enumerate()
903             .map(|(idx, field_def)| (
904                 Operand::Move(Place::from(Local::new(idx + 1))),
905                 field_def.ty(tcx, substs),
906             )),
907         AggregateKind::Adt(adt_def, variant_index, substs, None, None),
908         source_info,
909         tcx,
910     ).collect();
911
912     let start_block = BasicBlockData {
913         statements,
914         terminator: Some(Terminator {
915             source_info,
916             kind: TerminatorKind::Return,
917         }),
918         is_cleanup: false
919     };
920
921     let body = new_body(
922         IndexVec::from_elem_n(start_block, 1),
923         IndexVec::from_elem_n(
924             SourceScopeData { span, parent_scope: None }, 1
925         ),
926         local_decls,
927         sig.inputs().len(),
928         span,
929     );
930
931     crate::util::dump_mir(
932         tcx,
933         None,
934         "mir_map",
935         &0,
936         crate::transform::MirSource::item(ctor_id),
937         &body,
938         |_, _| Ok(()),
939     );
940
941     tcx.arena.alloc(body)
942 }