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