]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/shim.rs
Remove Ty prefix from Ty{Adt|Array|Slice|RawPtr|Ref|FnDef|FnPtr|Dynamic|Closure|Gener...
[rust.git] / src / librustc_mir / shim.rs
1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use rustc::hir;
12 use rustc::hir::def_id::DefId;
13 use rustc::infer;
14 use rustc::mir::*;
15 use rustc::ty::{self, Ty, TyCtxt, GenericParamDefKind};
16 use rustc::ty::subst::{Subst, Substs};
17 use rustc::ty::query::Providers;
18
19 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
20
21 use rustc_target::spec::abi::Abi;
22 use syntax::ast;
23 use syntax_pos::Span;
24
25 use std::fmt;
26 use std::iter;
27
28 use transform::{add_moves_for_packed_drops, add_call_guards};
29 use transform::{remove_noop_landing_pads, no_landing_pads, simplify};
30 use util::elaborate_drops::{self, DropElaborator, DropStyle, DropFlagMode};
31 use util::patch::MirPatch;
32
33 pub fn provide(providers: &mut Providers) {
34     providers.mir_shims = make_shim;
35 }
36
37 fn make_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
38                        instance: ty::InstanceDef<'tcx>)
39                        -> &'tcx Mir<'tcx>
40 {
41     debug!("make_shim({:?})", instance);
42
43     let mut result = match instance {
44         ty::InstanceDef::Item(..) =>
45             bug!("item {:?} passed to make_shim", instance),
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     RefMut,
132 }
133
134 #[derive(Copy, Clone, Debug, PartialEq)]
135 enum CallKind {
136     Indirect,
137     Direct(DefId),
138 }
139
140 fn temp_decl(mutability: Mutability, ty: Ty, span: Span) -> LocalDecl {
141     let source_info = SourceInfo { scope: OUTERMOST_SOURCE_SCOPE, span };
142     LocalDecl {
143         mutability, ty, name: None,
144         source_info,
145         visibility_scope: source_info.scope,
146         internal: false,
147         is_user_variable: None,
148     }
149 }
150
151 fn local_decls_for_sig<'tcx>(sig: &ty::FnSig<'tcx>, span: Span)
152     -> IndexVec<Local, LocalDecl<'tcx>>
153 {
154     iter::once(temp_decl(Mutability::Mut, sig.output(), span))
155         .chain(sig.inputs().iter().map(
156             |ity| temp_decl(Mutability::Not, ity, span)))
157         .collect()
158 }
159
160 fn build_drop_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
161                              def_id: DefId,
162                              ty: Option<Ty<'tcx>>)
163                              -> Mir<'tcx>
164 {
165     debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
166
167     // Check if this is a generator, if so, return the drop glue for it
168     if let Some(&ty::TyS { sty: ty::Generator(gen_def_id, substs, _), .. }) = ty {
169         let mir = &**tcx.optimized_mir(gen_def_id).generator_drop.as_ref().unwrap();
170         return mir.subst(tcx, substs.substs);
171     }
172
173     let substs = if let Some(ty) = ty {
174         tcx.intern_substs(&[ty.into()])
175     } else {
176         Substs::identity_for_item(tcx, def_id)
177     };
178     let sig = tcx.fn_sig(def_id).subst(tcx, substs);
179     let sig = tcx.erase_late_bound_regions(&sig);
180     let span = tcx.def_span(def_id);
181
182     let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
183
184     let return_block = BasicBlock::new(1);
185     let mut blocks = IndexVec::new();
186     let block = |blocks: &mut IndexVec<_, _>, kind| {
187         blocks.push(BasicBlockData {
188             statements: vec![],
189             terminator: Some(Terminator { source_info, kind }),
190             is_cleanup: false
191         })
192     };
193     block(&mut blocks, TerminatorKind::Goto { target: return_block });
194     block(&mut blocks, TerminatorKind::Return);
195
196     let mut mir = Mir::new(
197         blocks,
198         IndexVec::from_elem_n(
199             SourceScopeData { span: span, parent_scope: None }, 1
200         ),
201         ClearCrossCrate::Clear,
202         IndexVec::new(),
203         None,
204         local_decls_for_sig(&sig, span),
205         sig.inputs().len(),
206         vec![],
207         span
208     );
209
210     if let Some(..) = ty {
211         let patch = {
212             let param_env = tcx.param_env(def_id).with_reveal_all();
213             let mut elaborator = DropShimElaborator {
214                 mir: &mir,
215                 patch: MirPatch::new(&mir),
216                 tcx,
217                 param_env
218             };
219             let dropee = Place::Local(Local::new(1+0)).deref();
220             let resume_block = elaborator.patch.resume_block();
221             elaborate_drops::elaborate_drop(
222                 &mut elaborator,
223                 source_info,
224                 &dropee,
225                 (),
226                 return_block,
227                 elaborate_drops::Unwind::To(resume_block),
228                 START_BLOCK
229             );
230             elaborator.patch
231         };
232         patch.apply(&mut mir);
233     }
234
235     mir
236 }
237
238 pub struct DropShimElaborator<'a, 'tcx: 'a> {
239     pub mir: &'a Mir<'tcx>,
240     pub patch: MirPatch<'tcx>,
241     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
242     pub param_env: ty::ParamEnv<'tcx>,
243 }
244
245 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
246     fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
247         Ok(())
248     }
249 }
250
251 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
252     type Path = ();
253
254     fn patch(&mut self) -> &mut MirPatch<'tcx> { &mut self.patch }
255     fn mir(&self) -> &'a Mir<'tcx> { self.mir }
256     fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
257     fn param_env(&self) -> ty::ParamEnv<'tcx> { self.param_env }
258
259     fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
260         if let DropFlagMode::Shallow = mode {
261             DropStyle::Static
262         } else {
263             DropStyle::Open
264         }
265     }
266
267     fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
268         None
269     }
270
271     fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {
272     }
273
274     fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
275         None
276     }
277     fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
278         None
279     }
280     fn downcast_subpath(&self, _path: Self::Path, _variant: usize) -> Option<Self::Path> {
281         Some(())
282     }
283     fn array_subpath(&self, _path: Self::Path, _index: u32, _size: u32) -> Option<Self::Path> {
284         None
285     }
286 }
287
288 /// Build a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
289 fn build_clone_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
290                               def_id: DefId,
291                               self_ty: Ty<'tcx>)
292                               -> Mir<'tcx>
293 {
294     debug!("build_clone_shim(def_id={:?})", def_id);
295
296     let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty);
297     let is_copy = !self_ty.moves_by_default(tcx, tcx.param_env(def_id), builder.span);
298
299     let dest = Place::Local(RETURN_PLACE);
300     let src = Place::Local(Local::new(1+0)).deref();
301
302     match self_ty.sty {
303         _ if is_copy => builder.copy_shim(),
304         ty::Array(ty, len) => {
305             let len = len.unwrap_usize(tcx);
306             builder.array_shim(dest, src, ty, len)
307         }
308         ty::Closure(def_id, substs) => {
309             builder.tuple_like_shim(
310                 dest, src,
311                 substs.upvar_tys(def_id, tcx)
312             )
313         }
314         ty::Tuple(tys) => builder.tuple_like_shim(dest, src, tys.iter().cloned()),
315         _ => {
316             bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty)
317         }
318     };
319
320     builder.into_mir()
321 }
322
323 struct CloneShimBuilder<'a, 'tcx: 'a> {
324     tcx: TyCtxt<'a, 'tcx, 'tcx>,
325     def_id: DefId,
326     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
327     blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
328     span: Span,
329     sig: ty::FnSig<'tcx>,
330 }
331
332 impl<'a, 'tcx> CloneShimBuilder<'a, 'tcx> {
333     fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
334            def_id: DefId,
335            self_ty: Ty<'tcx>) -> Self {
336         // we must subst the self_ty because it's
337         // otherwise going to be TySelf and we can't index
338         // or access fields of a Place of type TySelf.
339         let substs = tcx.mk_substs_trait(self_ty, &[]);
340         let sig = tcx.fn_sig(def_id).subst(tcx, substs);
341         let sig = tcx.erase_late_bound_regions(&sig);
342         let span = tcx.def_span(def_id);
343
344         CloneShimBuilder {
345             tcx,
346             def_id,
347             local_decls: local_decls_for_sig(&sig, span),
348             blocks: IndexVec::new(),
349             span,
350             sig,
351         }
352     }
353
354     fn into_mir(self) -> Mir<'tcx> {
355         Mir::new(
356             self.blocks,
357             IndexVec::from_elem_n(
358                 SourceScopeData { span: self.span, parent_scope: None }, 1
359             ),
360             ClearCrossCrate::Clear,
361             IndexVec::new(),
362             None,
363             self.local_decls,
364             self.sig.inputs().len(),
365             vec![],
366             self.span
367         )
368     }
369
370     fn source_info(&self) -> SourceInfo {
371         SourceInfo { span: self.span, scope: OUTERMOST_SOURCE_SCOPE }
372     }
373
374     fn block(
375         &mut self,
376         statements: Vec<Statement<'tcx>>,
377         kind: TerminatorKind<'tcx>,
378         is_cleanup: bool
379     ) -> BasicBlock {
380         let source_info = self.source_info();
381         self.blocks.push(BasicBlockData {
382             statements,
383             terminator: Some(Terminator { source_info, kind }),
384             is_cleanup,
385         })
386     }
387
388     /// Gives the index of an upcoming BasicBlock, with an offset.
389     /// offset=0 will give you the index of the next BasicBlock,
390     /// offset=1 will give the index of the next-to-next block,
391     /// offset=-1 will give you the index of the last-created block
392     fn block_index_offset(&mut self, offset: usize) -> BasicBlock {
393         BasicBlock::new(self.blocks.len() + offset)
394     }
395
396     fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
397         Statement {
398             source_info: self.source_info(),
399             kind,
400         }
401     }
402
403     fn copy_shim(&mut self) {
404         let rcvr = Place::Local(Local::new(1+0)).deref();
405         let ret_statement = self.make_statement(
406             StatementKind::Assign(
407                 Place::Local(RETURN_PLACE),
408                 Rvalue::Use(Operand::Copy(rcvr))
409             )
410         );
411         self.block(vec![ret_statement], TerminatorKind::Return, false);
412     }
413
414     fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
415         let span = self.span;
416         Place::Local(
417             self.local_decls.push(temp_decl(mutability, ty, span))
418         )
419     }
420
421     fn make_clone_call(
422         &mut self,
423         dest: Place<'tcx>,
424         src: Place<'tcx>,
425         ty: Ty<'tcx>,
426         next: BasicBlock,
427         cleanup: BasicBlock
428     ) {
429         let tcx = self.tcx;
430
431         let substs = Substs::for_item(tcx, self.def_id, |param, _| {
432             match param.kind {
433                 GenericParamDefKind::Lifetime => tcx.types.re_erased.into(),
434                 GenericParamDefKind::Type {..} => ty.into(),
435             }
436         });
437
438         // `func == Clone::clone(&ty) -> ty`
439         let func_ty = tcx.mk_fn_def(self.def_id, substs);
440         let func = Operand::Constant(box Constant {
441             span: self.span,
442             ty: func_ty,
443             literal: ty::Const::zero_sized(self.tcx, func_ty),
444         });
445
446         let ref_loc = self.make_place(
447             Mutability::Not,
448             tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
449                 ty,
450                 mutbl: hir::Mutability::MutImmutable,
451             })
452         );
453
454         // `let ref_loc: &ty = &src;`
455         let statement = self.make_statement(
456             StatementKind::Assign(
457                 ref_loc.clone(),
458                 Rvalue::Ref(tcx.types.re_erased, BorrowKind::Shared, src)
459             )
460         );
461
462         // `let loc = Clone::clone(ref_loc);`
463         self.block(vec![statement], TerminatorKind::Call {
464             func,
465             args: vec![Operand::Move(ref_loc)],
466             destination: Some((dest, next)),
467             cleanup: Some(cleanup),
468         }, false);
469     }
470
471     fn loop_header(
472         &mut self,
473         beg: Place<'tcx>,
474         end: Place<'tcx>,
475         loop_body: BasicBlock,
476         loop_end: BasicBlock,
477         is_cleanup: bool
478     ) {
479         let tcx = self.tcx;
480
481         let cond = self.make_place(Mutability::Mut, tcx.types.bool);
482         let compute_cond = self.make_statement(
483             StatementKind::Assign(
484                 cond.clone(),
485                 Rvalue::BinaryOp(BinOp::Ne, Operand::Copy(end), Operand::Copy(beg))
486             )
487         );
488
489         // `if end != beg { goto loop_body; } else { goto loop_end; }`
490         self.block(
491             vec![compute_cond],
492             TerminatorKind::if_(tcx, Operand::Move(cond), loop_body, loop_end),
493             is_cleanup
494         );
495     }
496
497     fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
498         box Constant {
499             span: self.span,
500             ty: self.tcx.types.usize,
501             literal: ty::Const::from_usize(self.tcx, value),
502         }
503     }
504
505     fn array_shim(&mut self, dest: Place<'tcx>, src: Place<'tcx>, ty: Ty<'tcx>, len: u64) {
506         let tcx = self.tcx;
507         let span = self.span;
508
509         let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
510         let end = self.make_place(Mutability::Not, tcx.types.usize);
511
512         // BB #0
513         // `let mut beg = 0;`
514         // `let end = len;`
515         // `goto #1;`
516         let inits = vec![
517             self.make_statement(
518                 StatementKind::Assign(
519                     Place::Local(beg),
520                     Rvalue::Use(Operand::Constant(self.make_usize(0)))
521                 )
522             ),
523             self.make_statement(
524                 StatementKind::Assign(
525                     end.clone(),
526                     Rvalue::Use(Operand::Constant(self.make_usize(len)))
527                 )
528             )
529         ];
530         self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
531
532         // BB #1: loop {
533         //     BB #2;
534         //     BB #3;
535         // }
536         // BB #4;
537         self.loop_header(Place::Local(beg), end, BasicBlock::new(2), BasicBlock::new(4), false);
538
539         // BB #2
540         // `dest[i] = Clone::clone(src[beg])`;
541         // Goto #3 if ok, #5 if unwinding happens.
542         let dest_field = dest.clone().index(beg);
543         let src_field = src.clone().index(beg);
544         self.make_clone_call(dest_field, src_field, ty, BasicBlock::new(3),
545                              BasicBlock::new(5));
546
547         // BB #3
548         // `beg = beg + 1;`
549         // `goto #1`;
550         let statements = vec![
551             self.make_statement(
552                 StatementKind::Assign(
553                     Place::Local(beg),
554                     Rvalue::BinaryOp(
555                         BinOp::Add,
556                         Operand::Copy(Place::Local(beg)),
557                         Operand::Constant(self.make_usize(1))
558                     )
559                 )
560             )
561         ];
562         self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
563
564         // BB #4
565         // `return dest;`
566         self.block(vec![], TerminatorKind::Return, false);
567
568         // BB #5 (cleanup)
569         // `let end = beg;`
570         // `let mut beg = 0;`
571         // goto #6;
572         let end = beg;
573         let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
574         let init = self.make_statement(
575             StatementKind::Assign(
576                 Place::Local(beg),
577                 Rvalue::Use(Operand::Constant(self.make_usize(0)))
578             )
579         );
580         self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
581
582         // BB #6 (cleanup): loop {
583         //     BB #7;
584         //     BB #8;
585         // }
586         // BB #9;
587         self.loop_header(Place::Local(beg), Place::Local(end),
588                          BasicBlock::new(7), BasicBlock::new(9), true);
589
590         // BB #7 (cleanup)
591         // `drop(dest[beg])`;
592         self.block(vec![], TerminatorKind::Drop {
593             location: dest.index(beg),
594             target: BasicBlock::new(8),
595             unwind: None,
596         }, true);
597
598         // BB #8 (cleanup)
599         // `beg = beg + 1;`
600         // `goto #6;`
601         let statement = self.make_statement(
602             StatementKind::Assign(
603                 Place::Local(beg),
604                 Rvalue::BinaryOp(
605                     BinOp::Add,
606                     Operand::Copy(Place::Local(beg)),
607                     Operand::Constant(self.make_usize(1))
608                 )
609             )
610         );
611         self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
612
613         // BB #9 (resume)
614         self.block(vec![], TerminatorKind::Resume, true);
615     }
616
617     fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>,
618                           src: Place<'tcx>, tys: I)
619             where I: Iterator<Item = ty::Ty<'tcx>> {
620         let mut previous_field = None;
621         for (i, ity) in tys.enumerate() {
622             let field = Field::new(i);
623             let src_field = src.clone().field(field, ity);
624
625             let dest_field = dest.clone().field(field, ity);
626
627             // #(2i + 1) is the cleanup block for the previous clone operation
628             let cleanup_block = self.block_index_offset(1);
629             // #(2i + 2) is the next cloning block
630             // (or the Return terminator if this is the last block)
631             let next_block = self.block_index_offset(2);
632
633             // BB #(2i)
634             // `dest.i = Clone::clone(&src.i);`
635             // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
636             self.make_clone_call(
637                 dest_field.clone(),
638                 src_field,
639                 ity,
640                 next_block,
641                 cleanup_block,
642             );
643
644             // BB #(2i + 1) (cleanup)
645             if let Some((previous_field, previous_cleanup)) = previous_field.take() {
646                 // Drop previous field and goto previous cleanup block.
647                 self.block(vec![], TerminatorKind::Drop {
648                     location: previous_field,
649                     target: previous_cleanup,
650                     unwind: None,
651                 }, true);
652             } else {
653                 // Nothing to drop, just resume.
654                 self.block(vec![], TerminatorKind::Resume, true);
655             }
656
657             previous_field = Some((dest_field, cleanup_block));
658         }
659
660         self.block(vec![], TerminatorKind::Return, false);
661     }
662 }
663
664 /// Build a "call" shim for `def_id`. The shim calls the
665 /// function specified by `call_kind`, first adjusting its first
666 /// argument according to `rcvr_adjustment`.
667 ///
668 /// If `untuple_args` is a vec of types, the second argument of the
669 /// function will be untupled as these types.
670 fn build_call_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
671                              def_id: DefId,
672                              rcvr_adjustment: Adjustment,
673                              call_kind: CallKind,
674                              untuple_args: Option<&[Ty<'tcx>]>)
675                              -> Mir<'tcx>
676 {
677     debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
678             call_kind={:?}, untuple_args={:?})",
679            def_id, rcvr_adjustment, call_kind, untuple_args);
680
681     let sig = tcx.fn_sig(def_id);
682     let sig = tcx.erase_late_bound_regions(&sig);
683     let span = tcx.def_span(def_id);
684
685     debug!("build_call_shim: sig={:?}", sig);
686
687     let mut local_decls = local_decls_for_sig(&sig, span);
688     let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
689
690     let rcvr_arg = Local::new(1+0);
691     let rcvr_l = Place::Local(rcvr_arg);
692     let mut statements = vec![];
693
694     let rcvr = match rcvr_adjustment {
695         Adjustment::Identity => Operand::Move(rcvr_l),
696         Adjustment::Deref => Operand::Copy(rcvr_l.deref()),
697         Adjustment::RefMut => {
698             // let rcvr = &mut rcvr;
699             let ref_rcvr = local_decls.push(temp_decl(
700                 Mutability::Not,
701                 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
702                     ty: sig.inputs()[0],
703                     mutbl: hir::Mutability::MutMutable
704                 }),
705                 span
706             ));
707             let borrow_kind = BorrowKind::Mut {
708                 allow_two_phase_borrow: false,
709             };
710             statements.push(Statement {
711                 source_info,
712                 kind: StatementKind::Assign(
713                     Place::Local(ref_rcvr),
714                     Rvalue::Ref(tcx.types.re_erased, borrow_kind, rcvr_l)
715                 )
716             });
717             Operand::Move(Place::Local(ref_rcvr))
718         }
719     };
720
721     let (callee, mut args) = match call_kind {
722         CallKind::Indirect => (rcvr, vec![]),
723         CallKind::Direct(def_id) => {
724             let ty = tcx.type_of(def_id);
725             (Operand::Constant(box Constant {
726                 span,
727                 ty,
728                 literal: ty::Const::zero_sized(tcx, ty),
729              }),
730              vec![rcvr])
731         }
732     };
733
734     if let Some(untuple_args) = untuple_args {
735         args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
736             let arg_place = Place::Local(Local::new(1+1));
737             Operand::Move(arg_place.field(Field::new(i), *ity))
738         }));
739     } else {
740         args.extend((1..sig.inputs().len()).map(|i| {
741             Operand::Move(Place::Local(Local::new(1+i)))
742         }));
743     }
744
745     let mut blocks = IndexVec::new();
746     let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
747         blocks.push(BasicBlockData {
748             statements,
749             terminator: Some(Terminator { source_info, kind }),
750             is_cleanup
751         })
752     };
753
754     // BB #0
755     block(&mut blocks, statements, TerminatorKind::Call {
756         func: callee,
757         args,
758         destination: Some((Place::Local(RETURN_PLACE),
759                            BasicBlock::new(1))),
760         cleanup: if let Adjustment::RefMut = rcvr_adjustment {
761             Some(BasicBlock::new(3))
762         } else {
763             None
764         }
765     }, false);
766
767     if let Adjustment::RefMut = rcvr_adjustment {
768         // BB #1 - drop for Self
769         block(&mut blocks, vec![], TerminatorKind::Drop {
770             location: Place::Local(rcvr_arg),
771             target: BasicBlock::new(2),
772             unwind: None
773         }, false);
774     }
775     // BB #1/#2 - return
776     block(&mut blocks, vec![], TerminatorKind::Return, false);
777     if let Adjustment::RefMut = rcvr_adjustment {
778         // BB #3 - drop if closure panics
779         block(&mut blocks, vec![], TerminatorKind::Drop {
780             location: Place::Local(rcvr_arg),
781             target: BasicBlock::new(4),
782             unwind: None
783         }, true);
784
785         // BB #4 - resume
786         block(&mut blocks, vec![], TerminatorKind::Resume, true);
787     }
788
789     let mut mir = Mir::new(
790         blocks,
791         IndexVec::from_elem_n(
792             SourceScopeData { span: span, parent_scope: None }, 1
793         ),
794         ClearCrossCrate::Clear,
795         IndexVec::new(),
796         None,
797         local_decls,
798         sig.inputs().len(),
799         vec![],
800         span
801     );
802     if let Abi::RustCall = sig.abi {
803         mir.spread_arg = Some(Local::new(sig.inputs().len()));
804     }
805     mir
806 }
807
808 pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
809                                       ctor_id: ast::NodeId,
810                                       fields: &[hir::StructField],
811                                       span: Span)
812                                       -> Mir<'tcx>
813 {
814     let tcx = infcx.tcx;
815     let gcx = tcx.global_tcx();
816     let def_id = tcx.hir.local_def_id(ctor_id);
817     let param_env = gcx.param_env(def_id);
818
819     // Normalize the sig.
820     let sig = gcx.fn_sig(def_id).no_late_bound_regions().expect("LBR in ADT constructor signature");
821     let sig = gcx.normalize_erasing_regions(param_env, sig);
822
823     let (adt_def, substs) = match sig.output().sty {
824         ty::Adt(adt_def, substs) => (adt_def, substs),
825         _ => bug!("unexpected type for ADT ctor {:?}", sig.output())
826     };
827
828     debug!("build_ctor: def_id={:?} sig={:?} fields={:?}", def_id, sig, fields);
829
830     let local_decls = local_decls_for_sig(&sig, span);
831
832     let source_info = SourceInfo {
833         span,
834         scope: OUTERMOST_SOURCE_SCOPE
835     };
836
837     let variant_no = if adt_def.is_enum() {
838         adt_def.variant_index_with_id(def_id)
839     } else {
840         0
841     };
842
843     // return = ADT(arg0, arg1, ...); return
844     let start_block = BasicBlockData {
845         statements: vec![Statement {
846             source_info,
847             kind: StatementKind::Assign(
848                 Place::Local(RETURN_PLACE),
849                 Rvalue::Aggregate(
850                     box AggregateKind::Adt(adt_def, variant_no, substs, None),
851                     (1..sig.inputs().len()+1).map(|i| {
852                         Operand::Move(Place::Local(Local::new(i)))
853                     }).collect()
854                 )
855             )
856         }],
857         terminator: Some(Terminator {
858             source_info,
859             kind: TerminatorKind::Return,
860         }),
861         is_cleanup: false
862     };
863
864     Mir::new(
865         IndexVec::from_elem_n(start_block, 1),
866         IndexVec::from_elem_n(
867             SourceScopeData { span: span, parent_scope: None }, 1
868         ),
869         ClearCrossCrate::Clear,
870         IndexVec::new(),
871         None,
872         local_decls,
873         sig.inputs().len(),
874         vec![],
875         span
876     )
877 }