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