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