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