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