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