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