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