]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/shim.rs
Rollup merge of #63613 - petrochenkov:stdhyg, r=alexcrichton
[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>, 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>(tcx: TyCtxt<'tcx>, def_id: DefId, ty: Option<Ty<'tcx>>) -> Body<'tcx> {
167     debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
168
169     // Check if this is a generator, if so, return the drop glue for it
170     if let Some(&ty::TyS { sty: ty::Generator(gen_def_id, substs, _), .. }) = ty {
171         let body = &**tcx.optimized_mir(gen_def_id).generator_drop.as_ref().unwrap();
172         return body.subst(tcx, substs.substs);
173     }
174
175     let substs = if let Some(ty) = ty {
176         tcx.intern_substs(&[ty.into()])
177     } else {
178         InternalSubsts::identity_for_item(tcx, def_id)
179     };
180     let sig = tcx.fn_sig(def_id).subst(tcx, substs);
181     let sig = tcx.erase_late_bound_regions(&sig);
182     let span = tcx.def_span(def_id);
183
184     let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
185
186     let return_block = BasicBlock::new(1);
187     let mut blocks = IndexVec::with_capacity(2);
188     let block = |blocks: &mut IndexVec<_, _>, kind| {
189         blocks.push(BasicBlockData {
190             statements: vec![],
191             terminator: Some(Terminator { source_info, kind }),
192             is_cleanup: false
193         })
194     };
195     block(&mut blocks, TerminatorKind::Goto { target: return_block });
196     block(&mut blocks, TerminatorKind::Return);
197
198     let mut body = Body::new(
199         blocks,
200         IndexVec::from_elem_n(
201             SourceScopeData { span: span, parent_scope: None }, 1
202         ),
203         ClearCrossCrate::Clear,
204         IndexVec::new(),
205         None,
206         local_decls_for_sig(&sig, span),
207         IndexVec::new(),
208         sig.inputs().len(),
209         vec![],
210         span,
211         vec![],
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, 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 = dropee_ptr.deref();
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 = Place::from(Local::new(1+0)).deref();
314
315     match self_ty.sty {
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.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             IndexVec::new(),
373             None,
374             self.local_decls,
375             IndexVec::new(),
376             self.sig.inputs().len(),
377             vec![],
378             self.span,
379             vec![],
380         )
381     }
382
383     fn source_info(&self) -> SourceInfo {
384         SourceInfo { span: self.span, scope: OUTERMOST_SOURCE_SCOPE }
385     }
386
387     fn block(
388         &mut self,
389         statements: Vec<Statement<'tcx>>,
390         kind: TerminatorKind<'tcx>,
391         is_cleanup: bool
392     ) -> BasicBlock {
393         let source_info = self.source_info();
394         self.blocks.push(BasicBlockData {
395             statements,
396             terminator: Some(Terminator { source_info, kind }),
397             is_cleanup,
398         })
399     }
400
401     /// Gives the index of an upcoming BasicBlock, with an offset.
402     /// offset=0 will give you the index of the next BasicBlock,
403     /// offset=1 will give the index of the next-to-next block,
404     /// offset=-1 will give you the index of the last-created block
405     fn block_index_offset(&mut self, offset: usize) -> BasicBlock {
406         BasicBlock::new(self.blocks.len() + offset)
407     }
408
409     fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
410         Statement {
411             source_info: self.source_info(),
412             kind,
413         }
414     }
415
416     fn copy_shim(&mut self) {
417         let rcvr = Place::from(Local::new(1+0)).deref();
418         let ret_statement = self.make_statement(
419             StatementKind::Assign(
420                 Place::RETURN_PLACE,
421                 box Rvalue::Use(Operand::Copy(rcvr))
422             )
423         );
424         self.block(vec![ret_statement], TerminatorKind::Return, false);
425     }
426
427     fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
428         let span = self.span;
429         Place::from(self.local_decls.push(temp_decl(mutability, ty, span)))
430     }
431
432     fn make_clone_call(
433         &mut self,
434         dest: Place<'tcx>,
435         src: Place<'tcx>,
436         ty: Ty<'tcx>,
437         next: BasicBlock,
438         cleanup: BasicBlock
439     ) {
440         let tcx = self.tcx;
441
442         let substs = tcx.mk_substs_trait(ty, &[]);
443
444         // `func == Clone::clone(&ty) -> ty`
445         let func_ty = tcx.mk_fn_def(self.def_id, substs);
446         let func = Operand::Constant(box Constant {
447             span: self.span,
448             user_ty: None,
449             literal: ty::Const::zero_sized(tcx, func_ty),
450         });
451
452         let ref_loc = self.make_place(
453             Mutability::Not,
454             tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut {
455                 ty,
456                 mutbl: hir::Mutability::MutImmutable,
457             })
458         );
459
460         // `let ref_loc: &ty = &src;`
461         let statement = self.make_statement(
462             StatementKind::Assign(
463                 ref_loc.clone(),
464                 box Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src)
465             )
466         );
467
468         // `let loc = Clone::clone(ref_loc);`
469         self.block(vec![statement], TerminatorKind::Call {
470             func,
471             args: vec![Operand::Move(ref_loc)],
472             destination: Some((dest, next)),
473             cleanup: Some(cleanup),
474             from_hir_call: true,
475         }, false);
476     }
477
478     fn loop_header(
479         &mut self,
480         beg: Place<'tcx>,
481         end: Place<'tcx>,
482         loop_body: BasicBlock,
483         loop_end: BasicBlock,
484         is_cleanup: bool
485     ) {
486         let tcx = self.tcx;
487
488         let cond = self.make_place(Mutability::Mut, tcx.types.bool);
489         let compute_cond = self.make_statement(
490             StatementKind::Assign(
491                 cond.clone(),
492                 box Rvalue::BinaryOp(BinOp::Ne, Operand::Copy(end), Operand::Copy(beg))
493             )
494         );
495
496         // `if end != beg { goto loop_body; } else { goto loop_end; }`
497         self.block(
498             vec![compute_cond],
499             TerminatorKind::if_(tcx, Operand::Move(cond), loop_body, loop_end),
500             is_cleanup
501         );
502     }
503
504     fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
505         box Constant {
506             span: self.span,
507             user_ty: None,
508             literal: ty::Const::from_usize(self.tcx, value),
509         }
510     }
511
512     fn array_shim(&mut self, dest: Place<'tcx>, src: Place<'tcx>, ty: Ty<'tcx>, len: u64) {
513         let tcx = self.tcx;
514         let span = self.span;
515
516         let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
517         let end = self.make_place(Mutability::Not, tcx.types.usize);
518
519         // BB #0
520         // `let mut beg = 0;`
521         // `let end = len;`
522         // `goto #1;`
523         let inits = vec![
524             self.make_statement(
525                 StatementKind::Assign(
526                     Place::from(beg),
527                     box Rvalue::Use(Operand::Constant(self.make_usize(0)))
528                 )
529             ),
530             self.make_statement(
531                 StatementKind::Assign(
532                     end.clone(),
533                     box Rvalue::Use(Operand::Constant(self.make_usize(len)))
534                 )
535             )
536         ];
537         self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
538
539         // BB #1: loop {
540         //     BB #2;
541         //     BB #3;
542         // }
543         // BB #4;
544         self.loop_header(Place::from(beg),
545                          end,
546                          BasicBlock::new(2),
547                          BasicBlock::new(4),
548                          false);
549
550         // BB #2
551         // `dest[i] = Clone::clone(src[beg])`;
552         // Goto #3 if ok, #5 if unwinding happens.
553         let dest_field = dest.clone().index(beg);
554         let src_field = src.index(beg);
555         self.make_clone_call(dest_field, src_field, ty, BasicBlock::new(3),
556                              BasicBlock::new(5));
557
558         // BB #3
559         // `beg = beg + 1;`
560         // `goto #1`;
561         let statements = vec![
562             self.make_statement(
563                 StatementKind::Assign(
564                     Place::from(beg),
565                     box Rvalue::BinaryOp(
566                         BinOp::Add,
567                         Operand::Copy(Place::from(beg)),
568                         Operand::Constant(self.make_usize(1))
569                     )
570                 )
571             )
572         ];
573         self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
574
575         // BB #4
576         // `return dest;`
577         self.block(vec![], TerminatorKind::Return, false);
578
579         // BB #5 (cleanup)
580         // `let end = beg;`
581         // `let mut beg = 0;`
582         // goto #6;
583         let end = beg;
584         let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
585         let init = self.make_statement(
586             StatementKind::Assign(
587                 Place::from(beg),
588                 box Rvalue::Use(Operand::Constant(self.make_usize(0)))
589             )
590         );
591         self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
592
593         // BB #6 (cleanup): loop {
594         //     BB #7;
595         //     BB #8;
596         // }
597         // BB #9;
598         self.loop_header(Place::from(beg), Place::from(end),
599                          BasicBlock::new(7), BasicBlock::new(9), true);
600
601         // BB #7 (cleanup)
602         // `drop(dest[beg])`;
603         self.block(vec![], TerminatorKind::Drop {
604             location: dest.index(beg),
605             target: BasicBlock::new(8),
606             unwind: None,
607         }, true);
608
609         // BB #8 (cleanup)
610         // `beg = beg + 1;`
611         // `goto #6;`
612         let statement = self.make_statement(
613             StatementKind::Assign(
614                 Place::from(beg),
615                 box Rvalue::BinaryOp(
616                     BinOp::Add,
617                     Operand::Copy(Place::from(beg)),
618                     Operand::Constant(self.make_usize(1))
619                 )
620             )
621         );
622         self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
623
624         // BB #9 (resume)
625         self.block(vec![], TerminatorKind::Resume, true);
626     }
627
628     fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>,
629                           src: Place<'tcx>, tys: I)
630             where I: Iterator<Item = Ty<'tcx>> {
631         let mut previous_field = None;
632         for (i, ity) in tys.enumerate() {
633             let field = Field::new(i);
634             let src_field = src.clone().field(field, ity);
635
636             let dest_field = dest.clone().field(field, ity);
637
638             // #(2i + 1) is the cleanup block for the previous clone operation
639             let cleanup_block = self.block_index_offset(1);
640             // #(2i + 2) is the next cloning block
641             // (or the Return terminator if this is the last block)
642             let next_block = self.block_index_offset(2);
643
644             // BB #(2i)
645             // `dest.i = Clone::clone(&src.i);`
646             // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
647             self.make_clone_call(
648                 dest_field.clone(),
649                 src_field,
650                 ity,
651                 next_block,
652                 cleanup_block,
653             );
654
655             // BB #(2i + 1) (cleanup)
656             if let Some((previous_field, previous_cleanup)) = previous_field.take() {
657                 // Drop previous field and goto previous cleanup block.
658                 self.block(vec![], TerminatorKind::Drop {
659                     location: previous_field,
660                     target: previous_cleanup,
661                     unwind: None,
662                 }, true);
663             } else {
664                 // Nothing to drop, just resume.
665                 self.block(vec![], TerminatorKind::Resume, true);
666             }
667
668             previous_field = Some((dest_field, cleanup_block));
669         }
670
671         self.block(vec![], TerminatorKind::Return, false);
672     }
673 }
674
675 /// Builds a "call" shim for `def_id`. The shim calls the
676 /// function specified by `call_kind`, first adjusting its first
677 /// argument according to `rcvr_adjustment`.
678 ///
679 /// If `untuple_args` is a vec of types, the second argument of the
680 /// function will be untupled as these types.
681 fn build_call_shim<'tcx>(
682     tcx: TyCtxt<'tcx>,
683     def_id: DefId,
684     rcvr_adjustment: Adjustment,
685     call_kind: CallKind,
686     untuple_args: Option<&[Ty<'tcx>]>,
687 ) -> Body<'tcx> {
688     debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
689             call_kind={:?}, untuple_args={:?})",
690            def_id, rcvr_adjustment, call_kind, untuple_args);
691
692     let sig = tcx.fn_sig(def_id);
693     let sig = tcx.erase_late_bound_regions(&sig);
694     let span = tcx.def_span(def_id);
695
696     debug!("build_call_shim: sig={:?}", sig);
697
698     let mut local_decls = local_decls_for_sig(&sig, span);
699     let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
700
701     let rcvr_arg = Local::new(1+0);
702     let rcvr_l = Place::from(rcvr_arg);
703     let mut statements = vec![];
704
705     let rcvr = match rcvr_adjustment {
706         Adjustment::Identity => Operand::Move(rcvr_l),
707         Adjustment::Deref => Operand::Copy(rcvr_l.deref()),
708         Adjustment::DerefMove => {
709             // fn(Self, ...) -> fn(*mut Self, ...)
710             let arg_ty = local_decls[rcvr_arg].ty;
711             assert!(arg_ty.is_self());
712             local_decls[rcvr_arg].ty = tcx.mk_mut_ptr(arg_ty);
713
714             Operand::Move(rcvr_l.deref())
715         }
716         Adjustment::RefMut => {
717             // let rcvr = &mut rcvr;
718             let ref_rcvr = local_decls.push(temp_decl(
719                 Mutability::Not,
720                 tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut {
721                     ty: sig.inputs()[0],
722                     mutbl: hir::Mutability::MutMutable
723                 }),
724                 span
725             ));
726             let borrow_kind = BorrowKind::Mut {
727                 allow_two_phase_borrow: false,
728             };
729             statements.push(Statement {
730                 source_info,
731                 kind: StatementKind::Assign(
732                     Place::from(ref_rcvr),
733                     box Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_l)
734                 )
735             });
736             Operand::Move(Place::from(ref_rcvr))
737         }
738     };
739
740     let (callee, mut args) = match call_kind {
741         CallKind::Indirect => (rcvr, vec![]),
742         CallKind::Direct(def_id) => {
743             let ty = tcx.type_of(def_id);
744             (Operand::Constant(box Constant {
745                 span,
746                 user_ty: None,
747                 literal: ty::Const::zero_sized(tcx, ty),
748              }),
749              vec![rcvr])
750         }
751     };
752
753     if let Some(untuple_args) = untuple_args {
754         args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
755             let arg_place = Place::from(Local::new(1+1));
756             Operand::Move(arg_place.field(Field::new(i), *ity))
757         }));
758     } else {
759         args.extend((1..sig.inputs().len()).map(|i| {
760             Operand::Move(Place::from(Local::new(1+i)))
761         }));
762     }
763
764     let n_blocks = if let Adjustment::RefMut = rcvr_adjustment { 5 } else { 2 };
765     let mut blocks = IndexVec::with_capacity(n_blocks);
766     let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
767         blocks.push(BasicBlockData {
768             statements,
769             terminator: Some(Terminator { source_info, kind }),
770             is_cleanup
771         })
772     };
773
774     // BB #0
775     block(&mut blocks, statements, TerminatorKind::Call {
776         func: callee,
777         args,
778         destination: Some((Place::RETURN_PLACE,
779                            BasicBlock::new(1))),
780         cleanup: if let Adjustment::RefMut = rcvr_adjustment {
781             Some(BasicBlock::new(3))
782         } else {
783             None
784         },
785         from_hir_call: true,
786     }, false);
787
788     if let Adjustment::RefMut = rcvr_adjustment {
789         // BB #1 - drop for Self
790         block(&mut blocks, vec![], TerminatorKind::Drop {
791             location: Place::from(rcvr_arg),
792             target: BasicBlock::new(2),
793             unwind: None
794         }, false);
795     }
796     // BB #1/#2 - return
797     block(&mut blocks, vec![], TerminatorKind::Return, false);
798     if let Adjustment::RefMut = rcvr_adjustment {
799         // BB #3 - drop if closure panics
800         block(&mut blocks, vec![], TerminatorKind::Drop {
801             location: Place::from(rcvr_arg),
802             target: BasicBlock::new(4),
803             unwind: None
804         }, true);
805
806         // BB #4 - resume
807         block(&mut blocks, vec![], TerminatorKind::Resume, true);
808     }
809
810     let mut body = Body::new(
811         blocks,
812         IndexVec::from_elem_n(
813             SourceScopeData { span: span, parent_scope: None }, 1
814         ),
815         ClearCrossCrate::Clear,
816         IndexVec::new(),
817         None,
818         local_decls,
819         IndexVec::new(),
820         sig.inputs().len(),
821         vec![],
822         span,
823         vec![],
824     );
825     if let Abi::RustCall = sig.abi {
826         body.spread_arg = Some(Local::new(sig.inputs().len()));
827     }
828     body
829 }
830
831 pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> &Body<'_> {
832     debug_assert!(tcx.is_constructor(ctor_id));
833
834     let span = tcx.hir().span_if_local(ctor_id)
835         .unwrap_or_else(|| bug!("no span for ctor {:?}", ctor_id));
836
837     let param_env = tcx.param_env(ctor_id);
838
839     // Normalize the sig.
840     let sig = tcx.fn_sig(ctor_id)
841         .no_bound_vars()
842         .expect("LBR in ADT constructor signature");
843     let sig = tcx.normalize_erasing_regions(param_env, sig);
844
845     let (adt_def, substs) = match sig.output().sty {
846         ty::Adt(adt_def, substs) => (adt_def, substs),
847         _ => bug!("unexpected type for ADT ctor {:?}", sig.output())
848     };
849
850     debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig);
851
852     let local_decls = local_decls_for_sig(&sig, span);
853
854     let source_info = SourceInfo {
855         span,
856         scope: OUTERMOST_SOURCE_SCOPE
857     };
858
859     let variant_index = if adt_def.is_enum() {
860         adt_def.variant_index_with_ctor_id(ctor_id)
861     } else {
862         VariantIdx::new(0)
863     };
864
865     // Generate the following MIR:
866     //
867     // (return as Variant).field0 = arg0;
868     // (return as Variant).field1 = arg1;
869     //
870     // return;
871     debug!("build_ctor: variant_index={:?}", variant_index);
872
873     let statements = expand_aggregate(
874         Place::RETURN_PLACE,
875         adt_def
876             .variants[variant_index]
877             .fields
878             .iter()
879             .enumerate()
880             .map(|(idx, field_def)| (
881                 Operand::Move(Place::from(Local::new(idx + 1))),
882                 field_def.ty(tcx, substs),
883             )),
884         AggregateKind::Adt(adt_def, variant_index, substs, None, None),
885         source_info,
886     ).collect();
887
888     let start_block = BasicBlockData {
889         statements,
890         terminator: Some(Terminator {
891             source_info,
892             kind: TerminatorKind::Return,
893         }),
894         is_cleanup: false
895     };
896
897     let body = Body::new(
898         IndexVec::from_elem_n(start_block, 1),
899         IndexVec::from_elem_n(
900             SourceScopeData { span: span, parent_scope: None }, 1
901         ),
902         ClearCrossCrate::Clear,
903         IndexVec::new(),
904         None,
905         local_decls,
906         IndexVec::new(),
907         sig.inputs().len(),
908         vec![],
909         span,
910         vec![],
911     );
912
913     crate::util::dump_mir(
914         tcx,
915         None,
916         "mir_map",
917         &0,
918         crate::transform::MirSource::item(ctor_id),
919         &body,
920         |_, _| Ok(()),
921     );
922
923     tcx.arena.alloc(body)
924 }