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