1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! This is the implementation of the pass which transforms generators into state machines.
13 //! MIR generation for generators creates a function which has a self argument which
14 //! passes by value. This argument is effectively a generator type which only contains upvars and
15 //! is only used for this argument inside the MIR for the generator.
16 //! It is passed by value to enable upvars to be moved out of it. Drop elaboration runs on that
17 //! MIR before this pass and creates drop flags for MIR locals.
18 //! It will also drop the generator argument (which only consists of upvars) if any of the upvars
19 //! are moved out of. This pass elaborates the drops of upvars / generator argument in the case
20 //! that none of the upvars were moved out of. This is because we cannot have any drops of this
21 //! generator in the MIR, since it is used to create the drop glue for the generator. We'd get
22 //! infinite recursion otherwise.
24 //! This pass creates the implementation for the Generator::resume function and the drop shim
25 //! for the generator based on the MIR input. It converts the generator argument from Self to
26 //! &mut Self adding derefs in the MIR as needed. It computes the final layout of the generator
27 //! struct which looks like this:
28 //! First upvars are stored
29 //! It is followed by the generator state field.
30 //! Then finally the MIR locals which are live across a suspension point are stored.
32 //! struct Generator {
38 //! This pass computes the meaning of the state field and the MIR locals which are live
39 //! across a suspension point. There are however two hardcoded generator states:
40 //! 0 - Generator have not been resumed yet
41 //! 1 - Generator has returned / is completed
42 //! 2 - Generator has been poisoned
44 //! It also rewrites `return x` and `yield y` as setting a new generator state and returning
45 //! GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
46 //! MIR locals which are live across a suspension point are moved to the generator struct
47 //! with references to them being updated with references to the generator struct.
49 //! The pass creates two functions which have a switch on the generator state giving
50 //! the action to take.
52 //! One of them is the implementation of Generator::resume.
53 //! For generators with state 0 (unresumed) it starts the execution of the generator.
54 //! For generators with state 1 (returned) and state 2 (poisoned) it panics.
55 //! Otherwise it continues the execution from the last suspension point.
57 //! The other function is the drop glue for the generator.
58 //! For generators with state 0 (unresumed) it drops the upvars of the generator.
59 //! For generators with state 1 (returned) and state 2 (poisoned) it does nothing.
60 //! Otherwise it drops all the values in scope at the last suspension point.
63 use rustc::hir::def_id::DefId;
65 use rustc::mir::visit::{PlaceContext, Visitor, MutVisitor};
66 use rustc::ty::{self, TyCtxt, AdtDef, Ty};
67 use rustc::ty::subst::Substs;
69 use util::liveness::{self, IdentityMap};
70 use rustc_data_structures::fx::FxHashMap;
71 use rustc_data_structures::indexed_vec::Idx;
72 use rustc_data_structures::bit_set::BitSet;
76 use transform::{MirPass, MirSource};
77 use transform::simplify;
78 use transform::no_landing_pads::no_landing_pads;
79 use dataflow::{do_dataflow, DebugFormatted, state_for_location};
80 use dataflow::{MaybeStorageLive, HaveBeenBorrowedLocals};
82 pub struct StateTransform;
84 struct RenameLocalVisitor {
89 impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor {
90 fn visit_local(&mut self,
92 _: PlaceContext<'tcx>,
94 if *local == self.from {
100 struct DerefArgVisitor;
102 impl<'tcx> MutVisitor<'tcx> for DerefArgVisitor {
103 fn visit_local(&mut self,
105 _: PlaceContext<'tcx>,
107 assert_ne!(*local, self_arg());
110 fn visit_place(&mut self,
111 place: &mut Place<'tcx>,
112 context: PlaceContext<'tcx>,
113 location: Location) {
114 if *place == Place::Local(self_arg()) {
115 *place = Place::Projection(Box::new(Projection {
117 elem: ProjectionElem::Deref,
120 self.super_place(place, context, location);
125 fn self_arg() -> Local {
129 struct SuspensionPoint {
132 drop: Option<BasicBlock>,
133 storage_liveness: liveness::LiveVarSet<Local>,
136 struct TransformVisitor<'a, 'tcx: 'a> {
137 tcx: TyCtxt<'a, 'tcx, 'tcx>,
138 state_adt_ref: &'tcx AdtDef,
139 state_substs: &'tcx Substs<'tcx>,
141 // The index of the generator state in the generator struct
144 // Mapping from Local to (type of local, generator struct index)
145 // FIXME(eddyb) This should use `IndexVec<Local, Option<_>>`.
146 remap: FxHashMap<Local, (Ty<'tcx>, usize)>,
148 // A map from a suspension point in a block to the locals which have live storage at that point
149 // FIXME(eddyb) This should use `IndexVec<BasicBlock, Option<_>>`.
150 storage_liveness: FxHashMap<BasicBlock, liveness::LiveVarSet<Local>>,
152 // A list of suspension points, generated during the transform
153 suspension_points: Vec<SuspensionPoint>,
155 // The original RETURN_PLACE local
156 new_ret_local: Local,
159 impl<'a, 'tcx> TransformVisitor<'a, 'tcx> {
160 // Make a GeneratorState rvalue
161 fn make_state(&self, idx: usize, val: Operand<'tcx>) -> Rvalue<'tcx> {
162 let adt = AggregateKind::Adt(self.state_adt_ref, idx, self.state_substs, None, None);
163 Rvalue::Aggregate(box adt, vec![val])
166 // Create a Place referencing a generator struct field
167 fn make_field(&self, idx: usize, ty: Ty<'tcx>) -> Place<'tcx> {
168 let base = Place::Local(self_arg());
169 let field = Projection {
171 elem: ProjectionElem::Field(Field::new(idx), ty),
173 Place::Projection(Box::new(field))
176 // Create a statement which changes the generator state
177 fn set_state(&self, state_disc: u32, source_info: SourceInfo) -> Statement<'tcx> {
178 let state = self.make_field(self.state_field, self.tcx.types.u32);
179 let val = Operand::Constant(box Constant {
180 span: source_info.span,
181 ty: self.tcx.types.u32,
183 literal: ty::Const::from_bits(
186 ty::ParamEnv::empty().and(self.tcx.types.u32)
191 kind: StatementKind::Assign(state, Rvalue::Use(val)),
196 impl<'a, 'tcx> MutVisitor<'tcx> for TransformVisitor<'a, 'tcx> {
197 fn visit_local(&mut self,
199 _: PlaceContext<'tcx>,
201 assert_eq!(self.remap.get(local), None);
204 fn visit_place(&mut self,
205 place: &mut Place<'tcx>,
206 context: PlaceContext<'tcx>,
207 location: Location) {
208 if let Place::Local(l) = *place {
209 // Replace an Local in the remap with a generator struct access
210 if let Some(&(ty, idx)) = self.remap.get(&l) {
211 *place = self.make_field(idx, ty);
214 self.super_place(place, context, location);
218 fn visit_basic_block_data(&mut self,
220 data: &mut BasicBlockData<'tcx>) {
221 // Remove StorageLive and StorageDead statements for remapped locals
222 data.retain_statements(|s| {
224 StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
225 !self.remap.contains_key(&l)
231 let ret_val = match data.terminator().kind {
232 TerminatorKind::Return => Some((1,
234 Operand::Move(Place::Local(self.new_ret_local)),
236 TerminatorKind::Yield { ref value, resume, drop } => Some((0,
243 if let Some((state_idx, resume, v, drop)) = ret_val {
244 let source_info = data.terminator().source_info;
245 // We must assign the value first in case it gets declared dead below
246 data.statements.push(Statement {
248 kind: StatementKind::Assign(Place::Local(RETURN_PLACE),
249 self.make_state(state_idx, v)),
251 let state = if let Some(resume) = resume { // Yield
252 let state = 3 + self.suspension_points.len() as u32;
254 self.suspension_points.push(SuspensionPoint {
258 storage_liveness: self.storage_liveness.get(&block).unwrap().clone(),
263 1 // state for returned
265 data.statements.push(self.set_state(state, source_info));
266 data.terminator.as_mut().unwrap().kind = TerminatorKind::Return;
269 self.super_basic_block_data(block, data);
273 fn make_generator_state_argument_indirect<'a, 'tcx>(
274 tcx: TyCtxt<'a, 'tcx, 'tcx>,
276 mir: &mut Mir<'tcx>) {
277 let gen_ty = mir.local_decls.raw[1].ty;
279 let region = ty::ReFree(ty::FreeRegion {
281 bound_region: ty::BoundRegion::BrEnv,
284 let region = tcx.mk_region(region);
286 let ref_gen_ty = tcx.mk_ref(region, ty::TypeAndMut {
288 mutbl: hir::MutMutable
291 // Replace the by value generator argument
292 mir.local_decls.raw[1].ty = ref_gen_ty;
294 // Add a deref to accesses of the generator state
295 DerefArgVisitor.visit_mir(mir);
298 fn replace_result_variable<'tcx>(
302 let source_info = source_info(mir);
303 let new_ret = LocalDecl {
304 mutability: Mutability::Mut,
309 visibility_scope: source_info.scope,
311 is_user_variable: None,
313 let new_ret_local = Local::new(mir.local_decls.len());
314 mir.local_decls.push(new_ret);
315 mir.local_decls.swap(RETURN_PLACE, new_ret_local);
325 struct StorageIgnored(liveness::LiveVarSet<Local>);
327 impl<'tcx> Visitor<'tcx> for StorageIgnored {
328 fn visit_statement(&mut self,
330 statement: &Statement<'tcx>,
331 _location: Location) {
332 match statement.kind {
333 StatementKind::StorageLive(l) |
334 StatementKind::StorageDead(l) => { self.0.remove(l); }
340 struct BorrowedLocals(liveness::LiveVarSet<Local>);
342 fn mark_as_borrowed<'tcx>(place: &Place<'tcx>, locals: &mut BorrowedLocals) {
344 Place::Local(l) => { locals.0.insert(l); },
346 Place::Static(..) => (),
347 Place::Projection(ref proj) => {
349 // For derefs we don't look any further.
350 // If it pointed to a Local, it would already be borrowed elsewhere
351 ProjectionElem::Deref => (),
352 _ => mark_as_borrowed(&proj.base, locals)
358 impl<'tcx> Visitor<'tcx> for BorrowedLocals {
359 fn visit_rvalue(&mut self,
360 rvalue: &Rvalue<'tcx>,
361 location: Location) {
362 if let Rvalue::Ref(_, _, ref place) = *rvalue {
363 mark_as_borrowed(place, self);
366 self.super_rvalue(rvalue, location)
370 fn locals_live_across_suspend_points(
371 tcx: TyCtxt<'a, 'tcx, 'tcx>,
376 liveness::LiveVarSet<Local>,
377 FxHashMap<BasicBlock, liveness::LiveVarSet<Local>>,
379 let dead_unwinds = BitSet::new_empty(mir.basic_blocks().len());
380 let node_id = tcx.hir.as_local_node_id(source.def_id).unwrap();
382 // Calculate when MIR locals have live storage. This gives us an upper bound of their
384 let storage_live_analysis = MaybeStorageLive::new(mir);
386 do_dataflow(tcx, mir, node_id, &[], &dead_unwinds, storage_live_analysis,
387 |bd, p| DebugFormatted::new(&bd.mir().local_decls[p]));
389 // Find the MIR locals which do not use StorageLive/StorageDead statements.
390 // The storage of these locals are always live.
391 let mut ignored = StorageIgnored(BitSet::new_filled(mir.local_decls.len()));
392 ignored.visit_mir(mir);
394 // Calculate the MIR locals which have been previously
395 // borrowed (even if they are still active).
396 // This is only used for immovable generators.
397 let borrowed_locals = if !movable {
398 let analysis = HaveBeenBorrowedLocals::new(mir);
400 do_dataflow(tcx, mir, node_id, &[], &dead_unwinds, analysis,
401 |bd, p| DebugFormatted::new(&bd.mir().local_decls[p]));
402 Some((analysis, result))
407 // Calculate the liveness of MIR locals ignoring borrows.
408 let mut set = liveness::LiveVarSet::new_empty(mir.local_decls.len());
409 let mut liveness = liveness::liveness_of_locals(
411 &IdentityMap::new(mir),
415 "generator_liveness",
418 &IdentityMap::new(mir),
422 let mut storage_liveness_map = FxHashMap::default();
424 for (block, data) in mir.basic_blocks().iter_enumerated() {
425 if let TerminatorKind::Yield { .. } = data.terminator().kind {
428 statement_index: data.statements.len(),
431 if let Some((ref analysis, ref result)) = borrowed_locals {
432 let borrowed_locals = state_for_location(loc,
436 // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
437 // This is correct for movable generators since borrows cannot live across
438 // suspension points. However for immovable generators we need to account for
439 // borrows, so we conseratively assume that all borrowed locals are live until
440 // we find a StorageDead statement referencing the locals.
441 // To do this we just union our `liveness` result with `borrowed_locals`, which
442 // contains all the locals which has been borrowed before this suspension point.
443 // If a borrow is converted to a raw reference, we must also assume that it lives
444 // forever. Note that the final liveness is still bounded by the storage liveness
445 // of the local, which happens using the `intersect` operation below.
446 liveness.outs[block].union(&borrowed_locals);
449 let mut storage_liveness = state_for_location(loc,
450 &storage_live_analysis,
454 // Store the storage liveness for later use so we can restore the state
455 // after a suspension point
456 storage_liveness_map.insert(block, storage_liveness.clone());
458 // Mark locals without storage statements as always having live storage
459 storage_liveness.union(&ignored.0);
461 // Locals live are live at this point only if they are used across
462 // suspension points (the `liveness` variable)
463 // and their storage is live (the `storage_liveness` variable)
464 storage_liveness.intersect(&liveness.outs[block]);
466 let live_locals = storage_liveness;
468 // Add the locals life at this suspension point to the set of locals which live across
469 // any suspension points
470 set.union(&live_locals);
474 // The generator argument is ignored
475 set.remove(self_arg());
477 (set, storage_liveness_map)
480 fn compute_layout<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
482 upvars: Vec<Ty<'tcx>>,
486 -> (FxHashMap<Local, (Ty<'tcx>, usize)>,
487 GeneratorLayout<'tcx>,
488 FxHashMap<BasicBlock, liveness::LiveVarSet<Local>>)
490 // Use a liveness analysis to compute locals which are live across a suspension point
491 let (live_locals, storage_liveness) = locals_live_across_suspend_points(tcx,
495 // Erase regions from the types passed in from typeck so we can compare them with
497 let allowed_upvars = tcx.erase_regions(&upvars);
498 let allowed = match interior.sty {
499 ty::GeneratorWitness(s) => tcx.erase_late_bound_regions(&s),
503 for (local, decl) in mir.local_decls.iter_enumerated() {
504 // Ignore locals which are internal or not live
505 if !live_locals.contains(local) || decl.internal {
509 // Sanity check that typeck knows about the type of locals which are
510 // live across a suspension point
511 if !allowed.contains(&decl.ty) && !allowed_upvars.contains(&decl.ty) {
513 "Broken MIR: generator contains type {} in MIR, \
514 but typeck only knows about {}",
520 let upvar_len = mir.upvar_decls.len();
521 let dummy_local = LocalDecl::new_internal(tcx.mk_unit(), mir.span);
523 // Gather live locals and their indices replacing values in mir.local_decls with a dummy
524 // to avoid changing local indices
525 let live_decls = live_locals.iter().map(|local| {
526 let var = mem::replace(&mut mir.local_decls[local], dummy_local.clone());
530 // Create a map from local indices to generator struct indices.
531 // These are offset by (upvar_len + 1) because of fields which comes before locals.
532 // We also create a vector of the LocalDecls of these locals.
533 let (remap, vars) = live_decls.enumerate().map(|(idx, (local, var))| {
534 ((local, (var.ty, upvar_len + 1 + idx)), var)
537 let layout = GeneratorLayout {
541 (remap, layout, storage_liveness)
544 fn insert_switch<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
546 cases: Vec<(u32, BasicBlock)>,
547 transform: &TransformVisitor<'a, 'tcx>,
548 default: TerminatorKind<'tcx>) {
549 let default_block = insert_term_block(mir, default);
551 let switch = TerminatorKind::SwitchInt {
552 discr: Operand::Copy(transform.make_field(transform.state_field, tcx.types.u32)),
553 switch_ty: tcx.types.u32,
554 values: Cow::from(cases.iter().map(|&(i, _)| i.into()).collect::<Vec<_>>()),
555 targets: cases.iter().map(|&(_, d)| d).chain(once(default_block)).collect(),
558 let source_info = source_info(mir);
559 mir.basic_blocks_mut().raw.insert(0, BasicBlockData {
560 statements: Vec::new(),
561 terminator: Some(Terminator {
568 let blocks = mir.basic_blocks_mut().iter_mut();
570 for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
571 *target = BasicBlock::new(target.index() + 1);
575 fn elaborate_generator_drops<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
577 mir: &mut Mir<'tcx>) {
578 use util::elaborate_drops::{elaborate_drop, Unwind};
579 use util::patch::MirPatch;
580 use shim::DropShimElaborator;
582 // Note that `elaborate_drops` only drops the upvars of a generator, and
583 // this is ok because `open_drop` can only be reached within that own
584 // generator's resume function.
586 let param_env = tcx.param_env(def_id);
587 let gen = self_arg();
589 for block in mir.basic_blocks().indices() {
590 let (target, unwind, source_info) = match mir.basic_blocks()[block].terminator() {
593 kind: TerminatorKind::Drop {
594 location: Place::Local(local),
598 } if local == gen => (target, unwind, source_info),
601 let unwind = if let Some(unwind) = unwind {
607 let mut elaborator = DropShimElaborator {
609 patch: MirPatch::new(mir),
628 fn create_generator_drop_shim<'a, 'tcx>(
629 tcx: TyCtxt<'a, 'tcx, 'tcx>,
630 transform: &TransformVisitor<'a, 'tcx>,
635 drop_clean: BasicBlock) -> Mir<'tcx> {
636 let mut mir = mir.clone();
638 let source_info = source_info(&mir);
640 let mut cases = create_cases(&mut mir, transform, |point| point.drop);
642 cases.insert(0, (0, drop_clean));
644 // The returned state (1) and the poisoned state (2) falls through to
645 // the default case which is just to return
647 insert_switch(tcx, &mut mir, cases, &transform, TerminatorKind::Return);
649 for block in mir.basic_blocks_mut() {
650 let kind = &mut block.terminator_mut().kind;
651 if let TerminatorKind::GeneratorDrop = *kind {
652 *kind = TerminatorKind::Return;
656 // Replace the return variable
657 mir.local_decls[RETURN_PLACE] = LocalDecl {
658 mutability: Mutability::Mut,
663 visibility_scope: source_info.scope,
665 is_user_variable: None,
668 make_generator_state_argument_indirect(tcx, def_id, &mut mir);
670 // Change the generator argument from &mut to *mut
671 mir.local_decls[self_arg()] = LocalDecl {
672 mutability: Mutability::Mut,
673 ty: tcx.mk_ptr(ty::TypeAndMut {
675 mutbl: hir::Mutability::MutMutable,
680 visibility_scope: source_info.scope,
682 is_user_variable: None,
685 no_landing_pads(tcx, &mut mir);
687 // Make sure we remove dead blocks to remove
688 // unrelated code from the resume part of the function
689 simplify::remove_dead_blocks(&mut mir);
691 dump_mir(tcx, None, "generator_drop", &0, source, &mut mir, |_, _| Ok(()) );
696 fn insert_term_block<'tcx>(mir: &mut Mir<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
697 let term_block = BasicBlock::new(mir.basic_blocks().len());
698 let source_info = source_info(mir);
699 mir.basic_blocks_mut().push(BasicBlockData {
700 statements: Vec::new(),
701 terminator: Some(Terminator {
710 fn insert_panic_block<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
712 message: AssertMessage<'tcx>) -> BasicBlock {
713 let assert_block = BasicBlock::new(mir.basic_blocks().len());
714 let term = TerminatorKind::Assert {
715 cond: Operand::Constant(box Constant {
719 literal: ty::Const::from_bool(tcx, false),
723 target: assert_block,
727 let source_info = source_info(mir);
728 mir.basic_blocks_mut().push(BasicBlockData {
729 statements: Vec::new(),
730 terminator: Some(Terminator {
740 fn create_generator_resume_function<'a, 'tcx>(
741 tcx: TyCtxt<'a, 'tcx, 'tcx>,
742 transform: TransformVisitor<'a, 'tcx>,
745 mir: &mut Mir<'tcx>) {
746 // Poison the generator when it unwinds
747 for block in mir.basic_blocks_mut() {
748 let source_info = block.terminator().source_info;
749 if let &TerminatorKind::Resume = &block.terminator().kind {
750 block.statements.push(transform.set_state(1, source_info));
754 let mut cases = create_cases(mir, &transform, |point| Some(point.resume));
756 use rustc::mir::interpret::EvalErrorKind::{
757 GeneratorResumedAfterPanic,
758 GeneratorResumedAfterReturn,
761 // Jump to the entry point on the 0 state
762 cases.insert(0, (0, BasicBlock::new(0)));
763 // Panic when resumed on the returned (1) state
764 cases.insert(1, (1, insert_panic_block(tcx, mir, GeneratorResumedAfterReturn)));
765 // Panic when resumed on the poisoned (2) state
766 cases.insert(2, (2, insert_panic_block(tcx, mir, GeneratorResumedAfterPanic)));
768 insert_switch(tcx, mir, cases, &transform, TerminatorKind::Unreachable);
770 make_generator_state_argument_indirect(tcx, def_id, mir);
772 no_landing_pads(tcx, mir);
774 // Make sure we remove dead blocks to remove
775 // unrelated code from the drop part of the function
776 simplify::remove_dead_blocks(mir);
778 dump_mir(tcx, None, "generator_resume", &0, source, mir, |_, _| Ok(()) );
781 fn source_info<'a, 'tcx>(mir: &Mir<'tcx>) -> SourceInfo {
784 scope: OUTERMOST_SOURCE_SCOPE,
788 fn insert_clean_drop<'a, 'tcx>(mir: &mut Mir<'tcx>) -> BasicBlock {
789 let return_block = insert_term_block(mir, TerminatorKind::Return);
791 // Create a block to destroy an unresumed generators. This can only destroy upvars.
792 let drop_clean = BasicBlock::new(mir.basic_blocks().len());
793 let term = TerminatorKind::Drop {
794 location: Place::Local(self_arg()),
795 target: return_block,
798 let source_info = source_info(mir);
799 mir.basic_blocks_mut().push(BasicBlockData {
800 statements: Vec::new(),
801 terminator: Some(Terminator {
811 fn create_cases<'a, 'tcx, F>(mir: &mut Mir<'tcx>,
812 transform: &TransformVisitor<'a, 'tcx>,
813 target: F) -> Vec<(u32, BasicBlock)>
814 where F: Fn(&SuspensionPoint) -> Option<BasicBlock> {
815 let source_info = source_info(mir);
817 transform.suspension_points.iter().filter_map(|point| {
818 // Find the target for this suspension point, if applicable
819 target(point).map(|target| {
820 let block = BasicBlock::new(mir.basic_blocks().len());
821 let mut statements = Vec::new();
823 // Create StorageLive instructions for locals with live storage
824 for i in 0..(mir.local_decls.len()) {
825 let l = Local::new(i);
826 if point.storage_liveness.contains(l) && !transform.remap.contains_key(&l) {
827 statements.push(Statement {
829 kind: StatementKind::StorageLive(l),
834 // Then jump to the real target
835 mir.basic_blocks_mut().push(BasicBlockData {
837 terminator: Some(Terminator {
839 kind: TerminatorKind::Goto {
851 impl MirPass for StateTransform {
852 fn run_pass<'a, 'tcx>(&self,
853 tcx: TyCtxt<'a, 'tcx, 'tcx>,
855 mir: &mut Mir<'tcx>) {
856 let yield_ty = if let Some(yield_ty) = mir.yield_ty {
859 // This only applies to generators
863 assert!(mir.generator_drop.is_none());
865 let def_id = source.def_id;
867 // The first argument is the generator type passed by value
868 let gen_ty = mir.local_decls.raw[1].ty;
870 // Get the interior types and substs which typeck computed
871 let (upvars, interior, movable) = match gen_ty.sty {
872 ty::Generator(_, substs, movability) => {
873 (substs.upvar_tys(def_id, tcx).collect(),
874 substs.witness(def_id, tcx),
875 movability == hir::GeneratorMovability::Movable)
880 // Compute GeneratorState<yield_ty, return_ty>
881 let state_did = tcx.lang_items().gen_state().unwrap();
882 let state_adt_ref = tcx.adt_def(state_did);
883 let state_substs = tcx.intern_substs(&[
885 mir.return_ty().into(),
887 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
889 // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
890 // RETURN_PLACE then is a fresh unused local with type ret_ty.
891 let new_ret_local = replace_result_variable(ret_ty, mir);
893 // Extract locals which are live across suspension point into `layout`
894 // `remap` gives a mapping from local indices onto generator struct indices
895 // `storage_liveness` tells us which locals have live storage at suspension points
896 let (remap, layout, storage_liveness) = compute_layout(
904 let state_field = mir.upvar_decls.len();
906 // Run the transformation which converts Places from Local to generator struct
907 // accesses for locals in `remap`.
908 // It also rewrites `return x` and `yield y` as writing a new generator state and returning
909 // GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
910 let mut transform = TransformVisitor {
916 suspension_points: Vec::new(),
920 transform.visit_mir(mir);
922 // Update our MIR struct to reflect the changed we've made
925 mir.spread_arg = None;
926 mir.generator_layout = Some(layout);
928 // Insert `drop(generator_struct)` which is used to drop upvars for generators in
929 // the unresumed (0) state.
930 // This is expanded to a drop ladder in `elaborate_generator_drops`.
931 let drop_clean = insert_clean_drop(mir);
933 dump_mir(tcx, None, "generator_pre-elab", &0, source, mir, |_, _| Ok(()) );
935 // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
936 // If any upvars are moved out of, drop elaboration will handle upvar destruction.
937 // However we need to also elaborate the code generated by `insert_clean_drop`.
938 elaborate_generator_drops(tcx, def_id, mir);
940 dump_mir(tcx, None, "generator_post-transform", &0, source, mir, |_, _| Ok(()) );
942 // Create a copy of our MIR and use it to create the drop shim for the generator
943 let drop_shim = create_generator_drop_shim(tcx,
951 mir.generator_drop = Some(box drop_shim);
953 // Create the Generator::resume function
954 create_generator_resume_function(tcx, transform, def_id, source, mir);