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