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