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