1 //! This is the implementation of the pass which transforms generators into state machines.
3 //! MIR generation for generators creates a function which has a self argument which
4 //! passes by value. This argument is effectively a generator type which only contains upvars and
5 //! is only used for this argument inside the MIR for the generator.
6 //! It is passed by value to enable upvars to be moved out of it. Drop elaboration runs on that
7 //! MIR before this pass and creates drop flags for MIR locals.
8 //! It will also drop the generator argument (which only consists of upvars) if any of the upvars
9 //! are moved out of. This pass elaborates the drops of upvars / generator argument in the case
10 //! that none of the upvars were moved out of. This is because we cannot have any drops of this
11 //! generator in the MIR, since it is used to create the drop glue for the generator. We'd get
12 //! infinite recursion otherwise.
14 //! This pass creates the implementation for the Generator::resume function and the drop shim
15 //! for the generator based on the MIR input. It converts the generator argument from Self to
16 //! &mut Self adding derefs in the MIR as needed. It computes the final layout of the generator
17 //! struct which looks like this:
18 //! First upvars are stored
19 //! It is followed by the generator state field.
20 //! Then finally the MIR locals which are live across a suspension point are stored.
22 //! struct Generator {
28 //! This pass computes the meaning of the state field and the MIR locals which are live
29 //! across a suspension point. There are however three hardcoded generator states:
30 //! 0 - Generator have not been resumed yet
31 //! 1 - Generator has returned / is completed
32 //! 2 - Generator has been poisoned
34 //! It also rewrites `return x` and `yield y` as setting a new generator state and returning
35 //! GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
36 //! MIR locals which are live across a suspension point are moved to the generator struct
37 //! with references to them being updated with references to the generator struct.
39 //! The pass creates two functions which have a switch on the generator state giving
40 //! the action to take.
42 //! One of them is the implementation of Generator::resume.
43 //! For generators with state 0 (unresumed) it starts the execution of the generator.
44 //! For generators with state 1 (returned) and state 2 (poisoned) it panics.
45 //! Otherwise it continues the execution from the last suspension point.
47 //! The other function is the drop glue for the generator.
48 //! For generators with state 0 (unresumed) it drops the upvars of the generator.
49 //! For generators with state 1 (returned) and state 2 (poisoned) it does nothing.
50 //! Otherwise it drops all the values in scope at the last suspension point.
53 use rustc::hir::def_id::DefId;
55 use rustc::mir::visit::{PlaceContext, Visitor, MutVisitor};
56 use rustc::ty::{self, TyCtxt, AdtDef, Ty};
57 use rustc::ty::GeneratorSubsts;
58 use rustc::ty::layout::VariantIdx;
59 use rustc::ty::subst::SubstsRef;
60 use rustc_data_structures::fx::FxHashMap;
61 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
62 use rustc_data_structures::bit_set::BitSet;
66 use crate::transform::{MirPass, MirSource};
67 use crate::transform::simplify;
68 use crate::transform::no_landing_pads::no_landing_pads;
69 use crate::dataflow::{do_dataflow, DebugFormatted, state_for_location};
70 use crate::dataflow::{MaybeStorageLive, HaveBeenBorrowedLocals};
71 use crate::util::dump_mir;
72 use crate::util::liveness;
74 pub struct StateTransform;
76 struct RenameLocalVisitor {
81 impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor {
82 fn visit_local(&mut self,
86 if *local == self.from {
92 struct DerefArgVisitor;
94 impl<'tcx> MutVisitor<'tcx> for DerefArgVisitor {
95 fn visit_local(&mut self,
99 assert_ne!(*local, self_arg());
102 fn visit_place(&mut self,
103 place: &mut Place<'tcx>,
104 context: PlaceContext,
105 location: Location) {
106 if *place == Place::Base(PlaceBase::Local(self_arg())) {
107 *place = Place::Projection(Box::new(Projection {
109 elem: ProjectionElem::Deref,
112 self.super_place(place, context, location);
117 struct PinArgVisitor<'tcx> {
118 ref_gen_ty: Ty<'tcx>,
121 impl<'tcx> MutVisitor<'tcx> for PinArgVisitor<'tcx> {
122 fn visit_local(&mut self,
126 assert_ne!(*local, self_arg());
129 fn visit_place(&mut self,
130 place: &mut Place<'tcx>,
131 context: PlaceContext,
132 location: Location) {
133 if *place == Place::Base(PlaceBase::Local(self_arg())) {
134 *place = Place::Projection(Box::new(Projection {
136 elem: ProjectionElem::Field(Field::new(0), self.ref_gen_ty),
139 self.super_place(place, context, location);
144 fn self_arg() -> Local {
148 /// Generator have not been resumed yet
149 const UNRESUMED: usize = GeneratorSubsts::UNRESUMED;
150 /// Generator has returned / is completed
151 const RETURNED: usize = GeneratorSubsts::RETURNED;
152 /// Generator has been poisoned
153 const POISONED: usize = GeneratorSubsts::POISONED;
155 struct SuspensionPoint {
158 drop: Option<BasicBlock>,
159 storage_liveness: liveness::LiveVarSet,
162 struct TransformVisitor<'a, 'tcx: 'a> {
163 tcx: TyCtxt<'a, 'tcx, 'tcx>,
164 state_adt_ref: &'tcx AdtDef,
165 state_substs: SubstsRef<'tcx>,
167 // The type of the discriminant in the generator struct
170 // Mapping from Local to (type of local, generator struct index)
171 // FIXME(eddyb) This should use `IndexVec<Local, Option<_>>`.
172 remap: FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
174 // A map from a suspension point in a block to the locals which have live storage at that point
175 // FIXME(eddyb) This should use `IndexVec<BasicBlock, Option<_>>`.
176 storage_liveness: FxHashMap<BasicBlock, liveness::LiveVarSet>,
178 // A list of suspension points, generated during the transform
179 suspension_points: Vec<SuspensionPoint>,
181 // The original RETURN_PLACE local
182 new_ret_local: Local,
185 impl<'a, 'tcx> TransformVisitor<'a, 'tcx> {
186 // Make a GeneratorState rvalue
187 fn make_state(&self, idx: VariantIdx, val: Operand<'tcx>) -> Rvalue<'tcx> {
188 let adt = AggregateKind::Adt(self.state_adt_ref, idx, self.state_substs, None, None);
189 Rvalue::Aggregate(box adt, vec![val])
192 // Create a Place referencing a generator struct field
193 fn make_field(&self, variant_index: VariantIdx, idx: usize, ty: Ty<'tcx>) -> Place<'tcx> {
194 let self_place = Place::Base(PlaceBase::Local(self_arg()));
195 let base = self_place.downcast_unnamed(variant_index);
196 let field = Projection {
198 elem: ProjectionElem::Field(Field::new(idx), ty),
200 Place::Projection(Box::new(field))
203 // Create a statement which changes the discriminant
204 fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
205 let self_place = Place::Base(PlaceBase::Local(self_arg()));
208 kind: StatementKind::SetDiscriminant { place: self_place, variant_index: state_disc },
212 // Create a statement which reads the discriminant into a temporary
213 fn get_discr(&self, mir: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
214 let temp_decl = LocalDecl::new_internal(self.tcx.types.isize, mir.span);
215 let local_decls_len = mir.local_decls.push(temp_decl);
216 let temp = Place::Base(PlaceBase::Local(local_decls_len));
218 let self_place = Place::Base(PlaceBase::Local(self_arg()));
219 let assign = Statement {
220 source_info: source_info(mir),
221 kind: StatementKind::Assign(temp.clone(), box Rvalue::Discriminant(self_place)),
227 impl<'a, 'tcx> MutVisitor<'tcx> for TransformVisitor<'a, 'tcx> {
228 fn visit_local(&mut self,
232 assert_eq!(self.remap.get(local), None);
235 fn visit_place(&mut self,
236 place: &mut Place<'tcx>,
237 context: PlaceContext,
238 location: Location) {
239 if let Place::Base(PlaceBase::Local(l)) = *place {
240 // Replace an Local in the remap with a generator struct access
241 if let Some(&(ty, variant_index, idx)) = self.remap.get(&l) {
242 *place = self.make_field(variant_index, idx, ty);
245 self.super_place(place, context, location);
249 fn visit_basic_block_data(&mut self,
251 data: &mut BasicBlockData<'tcx>) {
252 // Remove StorageLive and StorageDead statements for remapped locals
253 data.retain_statements(|s| {
255 StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
256 !self.remap.contains_key(&l)
262 let ret_val = match data.terminator().kind {
263 TerminatorKind::Return => Some((VariantIdx::new(1),
265 Operand::Move(Place::Base(PlaceBase::Local(self.new_ret_local))),
267 TerminatorKind::Yield { ref value, resume, drop } => Some((VariantIdx::new(0),
274 if let Some((state_idx, resume, v, drop)) = ret_val {
275 let source_info = data.terminator().source_info;
276 // We must assign the value first in case it gets declared dead below
277 data.statements.push(Statement {
279 kind: StatementKind::Assign(Place::RETURN_PLACE,
280 box self.make_state(state_idx, v)),
282 let state = if let Some(resume) = resume { // Yield
283 let state = 3 + self.suspension_points.len();
285 self.suspension_points.push(SuspensionPoint {
289 storage_liveness: self.storage_liveness.get(&block).unwrap().clone(),
292 VariantIdx::new(state)
294 VariantIdx::new(RETURNED) // state for returned
296 data.statements.push(self.set_discr(state, source_info));
297 data.terminator.as_mut().unwrap().kind = TerminatorKind::Return;
300 self.super_basic_block_data(block, data);
304 fn make_generator_state_argument_indirect<'a, 'tcx>(
305 tcx: TyCtxt<'a, 'tcx, 'tcx>,
307 mir: &mut Body<'tcx>) {
308 let gen_ty = mir.local_decls.raw[1].ty;
310 let region = ty::ReFree(ty::FreeRegion {
312 bound_region: ty::BoundRegion::BrEnv,
315 let region = tcx.mk_region(region);
317 let ref_gen_ty = tcx.mk_ref(region, ty::TypeAndMut {
319 mutbl: hir::MutMutable
322 // Replace the by value generator argument
323 mir.local_decls.raw[1].ty = ref_gen_ty;
325 // Add a deref to accesses of the generator state
326 DerefArgVisitor.visit_body(mir);
329 fn make_generator_state_argument_pinned<'a, 'tcx>(
330 tcx: TyCtxt<'a, 'tcx, 'tcx>,
331 mir: &mut Body<'tcx>) {
332 let ref_gen_ty = mir.local_decls.raw[1].ty;
334 let pin_did = tcx.lang_items().pin_type().unwrap();
335 let pin_adt_ref = tcx.adt_def(pin_did);
336 let substs = tcx.intern_substs(&[ref_gen_ty.into()]);
337 let pin_ref_gen_ty = tcx.mk_adt(pin_adt_ref, substs);
339 // Replace the by ref generator argument
340 mir.local_decls.raw[1].ty = pin_ref_gen_ty;
342 // Add the Pin field access to accesses of the generator state
343 PinArgVisitor { ref_gen_ty }.visit_body(mir);
346 fn replace_result_variable<'tcx>(
348 mir: &mut Body<'tcx>,
350 let source_info = source_info(mir);
351 let new_ret = LocalDecl {
352 mutability: Mutability::Mut,
354 user_ty: UserTypeProjections::none(),
357 visibility_scope: source_info.scope,
360 is_user_variable: None,
362 let new_ret_local = Local::new(mir.local_decls.len());
363 mir.local_decls.push(new_ret);
364 mir.local_decls.swap(RETURN_PLACE, new_ret_local);
374 struct StorageIgnored(liveness::LiveVarSet);
376 impl<'tcx> Visitor<'tcx> for StorageIgnored {
377 fn visit_statement(&mut self,
378 statement: &Statement<'tcx>,
379 _location: Location) {
380 match statement.kind {
381 StatementKind::StorageLive(l) |
382 StatementKind::StorageDead(l) => { self.0.remove(l); }
388 fn locals_live_across_suspend_points(
389 tcx: TyCtxt<'a, 'tcx, 'tcx>,
391 source: MirSource<'tcx>,
394 liveness::LiveVarSet,
395 FxHashMap<BasicBlock, liveness::LiveVarSet>,
398 let dead_unwinds = BitSet::new_empty(mir.basic_blocks().len());
399 let def_id = source.def_id();
401 // Calculate when MIR locals have live storage. This gives us an upper bound of their
403 let storage_live_analysis = MaybeStorageLive::new(mir);
405 do_dataflow(tcx, mir, def_id, &[], &dead_unwinds, storage_live_analysis,
406 |bd, p| DebugFormatted::new(&bd.mir().local_decls[p]));
408 // Find the MIR locals which do not use StorageLive/StorageDead statements.
409 // The storage of these locals are always live.
410 let mut ignored = StorageIgnored(BitSet::new_filled(mir.local_decls.len()));
411 ignored.visit_body(mir);
413 // Calculate the MIR locals which have been previously
414 // borrowed (even if they are still active).
415 // This is only used for immovable generators.
416 let borrowed_locals = if !movable {
417 let analysis = HaveBeenBorrowedLocals::new(mir);
419 do_dataflow(tcx, mir, def_id, &[], &dead_unwinds, analysis,
420 |bd, p| DebugFormatted::new(&bd.mir().local_decls[p]));
421 Some((analysis, result))
426 // Calculate the liveness of MIR locals ignoring borrows.
427 let mut set = liveness::LiveVarSet::new_empty(mir.local_decls.len());
428 let mut liveness = liveness::liveness_of_locals(
433 "generator_liveness",
439 let mut storage_liveness_map = FxHashMap::default();
441 let mut suspending_blocks = BitSet::new_empty(mir.basic_blocks().len());
443 for (block, data) in mir.basic_blocks().iter_enumerated() {
444 if let TerminatorKind::Yield { .. } = data.terminator().kind {
445 suspending_blocks.insert(block);
449 statement_index: data.statements.len(),
452 if let Some((ref analysis, ref result)) = borrowed_locals {
453 let borrowed_locals = state_for_location(loc,
457 // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
458 // This is correct for movable generators since borrows cannot live across
459 // suspension points. However for immovable generators we need to account for
460 // borrows, so we conseratively assume that all borrowed locals are live until
461 // we find a StorageDead statement referencing the locals.
462 // To do this we just union our `liveness` result with `borrowed_locals`, which
463 // contains all the locals which has been borrowed before this suspension point.
464 // If a borrow is converted to a raw reference, we must also assume that it lives
465 // forever. Note that the final liveness is still bounded by the storage liveness
466 // of the local, which happens using the `intersect` operation below.
467 liveness.outs[block].union(&borrowed_locals);
470 let mut storage_liveness = state_for_location(loc,
471 &storage_live_analysis,
475 // Store the storage liveness for later use so we can restore the state
476 // after a suspension point
477 storage_liveness_map.insert(block, storage_liveness.clone());
479 // Mark locals without storage statements as always having live storage
480 storage_liveness.union(&ignored.0);
482 // Locals live are live at this point only if they are used across
483 // suspension points (the `liveness` variable)
484 // and their storage is live (the `storage_liveness` variable)
485 storage_liveness.intersect(&liveness.outs[block]);
487 let live_locals = storage_liveness;
489 // Add the locals life at this suspension point to the set of locals which live across
490 // any suspension points
491 set.union(&live_locals);
495 // The generator argument is ignored
496 set.remove(self_arg());
498 (set, storage_liveness_map, suspending_blocks)
501 fn compute_layout<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
502 source: MirSource<'tcx>,
503 upvars: &Vec<Ty<'tcx>>,
506 mir: &mut Body<'tcx>)
507 -> (FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
508 GeneratorLayout<'tcx>,
509 FxHashMap<BasicBlock, liveness::LiveVarSet>)
511 // Use a liveness analysis to compute locals which are live across a suspension point
512 let (live_locals, storage_liveness, suspending_blocks) =
513 locals_live_across_suspend_points(tcx, mir, source, movable);
515 // Erase regions from the types passed in from typeck so we can compare them with
517 let allowed_upvars = tcx.erase_regions(upvars);
518 let allowed = match interior.sty {
519 ty::GeneratorWitness(s) => tcx.erase_late_bound_regions(&s),
523 for (local, decl) in mir.local_decls.iter_enumerated() {
524 // Ignore locals which are internal or not live
525 if !live_locals.contains(local) || decl.internal {
529 // Sanity check that typeck knows about the type of locals which are
530 // live across a suspension point
531 if !allowed.contains(&decl.ty) && !allowed_upvars.contains(&decl.ty) {
533 "Broken MIR: generator contains type {} in MIR, \
534 but typeck only knows about {}",
540 let dummy_local = LocalDecl::new_internal(tcx.mk_unit(), mir.span);
542 // Gather live locals and their indices replacing values in mir.local_decls with a dummy
543 // to avoid changing local indices
544 let live_decls = live_locals.iter().map(|local| {
545 let var = mem::replace(&mut mir.local_decls[local], dummy_local.clone());
549 // For now we will access everything via variant #3, leaving empty variants
550 // for the UNRESUMED, RETURNED, and POISONED states.
551 // If there were a yield-less generator without a variant #3, it would not
552 // have any vars to remap, so we would never use this.
553 let variant_index = VariantIdx::new(3);
555 // Create a map from local indices to generator struct indices.
556 // We also create a vector of the LocalDecls of these locals.
557 let mut remap = FxHashMap::default();
558 let mut decls = IndexVec::new();
559 for (idx, (local, var)) in live_decls.enumerate() {
560 remap.insert(local, (var.ty, variant_index, idx));
563 let field_tys = decls.iter().map(|field| field.ty).collect::<IndexVec<_, _>>();
565 // Put every var in each variant, for now.
566 let all_vars = (0..field_tys.len()).map(GeneratorSavedLocal::from).collect();
567 let empty_variants = iter::repeat(IndexVec::new()).take(3);
568 let state_variants = iter::repeat(all_vars).take(suspending_blocks.count());
570 let layout = GeneratorLayout {
572 variant_fields: empty_variants.chain(state_variants).collect(),
573 __local_debuginfo_codegen_only_do_not_use: decls,
576 (remap, layout, storage_liveness)
579 fn insert_switch<'a, 'tcx>(mir: &mut Body<'tcx>,
580 cases: Vec<(usize, BasicBlock)>,
581 transform: &TransformVisitor<'a, 'tcx>,
582 default: TerminatorKind<'tcx>) {
583 let default_block = insert_term_block(mir, default);
584 let (assign, discr) = transform.get_discr(mir);
585 let switch = TerminatorKind::SwitchInt {
586 discr: Operand::Move(discr),
587 switch_ty: transform.discr_ty,
588 values: Cow::from(cases.iter().map(|&(i, _)| i as u128).collect::<Vec<_>>()),
589 targets: cases.iter().map(|&(_, d)| d).chain(iter::once(default_block)).collect(),
592 let source_info = source_info(mir);
593 mir.basic_blocks_mut().raw.insert(0, BasicBlockData {
594 statements: vec![assign],
595 terminator: Some(Terminator {
602 let blocks = mir.basic_blocks_mut().iter_mut();
604 for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
605 *target = BasicBlock::new(target.index() + 1);
609 fn elaborate_generator_drops<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
611 mir: &mut Body<'tcx>) {
612 use crate::util::elaborate_drops::{elaborate_drop, Unwind};
613 use crate::util::patch::MirPatch;
614 use crate::shim::DropShimElaborator;
616 // Note that `elaborate_drops` only drops the upvars of a generator, and
617 // this is ok because `open_drop` can only be reached within that own
618 // generator's resume function.
620 let param_env = tcx.param_env(def_id);
621 let gen = self_arg();
623 let mut elaborator = DropShimElaborator {
625 patch: MirPatch::new(mir),
630 for (block, block_data) in mir.basic_blocks().iter_enumerated() {
631 let (target, unwind, source_info) = match block_data.terminator() {
634 kind: TerminatorKind::Drop {
635 location: Place::Base(PlaceBase::Local(local)),
639 } if local == gen => (target, unwind, source_info),
642 let unwind = if block_data.is_cleanup {
645 Unwind::To(unwind.unwrap_or_else(|| elaborator.patch.resume_block()))
650 &Place::Base(PlaceBase::Local(gen)),
657 elaborator.patch.apply(mir);
660 fn create_generator_drop_shim<'a, 'tcx>(
661 tcx: TyCtxt<'a, 'tcx, 'tcx>,
662 transform: &TransformVisitor<'a, 'tcx>,
664 source: MirSource<'tcx>,
667 drop_clean: BasicBlock) -> Body<'tcx> {
668 let mut mir = mir.clone();
670 let source_info = source_info(&mir);
672 let mut cases = create_cases(&mut mir, transform, |point| point.drop);
674 cases.insert(0, (UNRESUMED, drop_clean));
676 // The returned state and the poisoned state fall through to the default
677 // case which is just to return
679 insert_switch(&mut mir, cases, &transform, TerminatorKind::Return);
681 for block in mir.basic_blocks_mut() {
682 let kind = &mut block.terminator_mut().kind;
683 if let TerminatorKind::GeneratorDrop = *kind {
684 *kind = TerminatorKind::Return;
688 // Replace the return variable
689 mir.local_decls[RETURN_PLACE] = LocalDecl {
690 mutability: Mutability::Mut,
692 user_ty: UserTypeProjections::none(),
695 visibility_scope: source_info.scope,
698 is_user_variable: None,
701 make_generator_state_argument_indirect(tcx, def_id, &mut mir);
703 // Change the generator argument from &mut to *mut
704 mir.local_decls[self_arg()] = LocalDecl {
705 mutability: Mutability::Mut,
706 ty: tcx.mk_ptr(ty::TypeAndMut {
708 mutbl: hir::Mutability::MutMutable,
710 user_ty: UserTypeProjections::none(),
713 visibility_scope: source_info.scope,
716 is_user_variable: None,
718 if tcx.sess.opts.debugging_opts.mir_emit_retag {
719 // Alias tracking must know we changed the type
720 mir.basic_blocks_mut()[START_BLOCK].statements.insert(0, Statement {
722 kind: StatementKind::Retag(RetagKind::Raw, Place::Base(PlaceBase::Local(self_arg()))),
726 no_landing_pads(tcx, &mut mir);
728 // Make sure we remove dead blocks to remove
729 // unrelated code from the resume part of the function
730 simplify::remove_dead_blocks(&mut mir);
732 dump_mir(tcx, None, "generator_drop", &0, source, &mut mir, |_, _| Ok(()) );
737 fn insert_term_block<'tcx>(mir: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
738 let term_block = BasicBlock::new(mir.basic_blocks().len());
739 let source_info = source_info(mir);
740 mir.basic_blocks_mut().push(BasicBlockData {
741 statements: Vec::new(),
742 terminator: Some(Terminator {
751 fn insert_panic_block<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
752 mir: &mut Body<'tcx>,
753 message: AssertMessage<'tcx>) -> BasicBlock {
754 let assert_block = BasicBlock::new(mir.basic_blocks().len());
755 let term = TerminatorKind::Assert {
756 cond: Operand::Constant(box Constant {
760 literal: ty::Const::from_bool(tcx, false),
764 target: assert_block,
768 let source_info = source_info(mir);
769 mir.basic_blocks_mut().push(BasicBlockData {
770 statements: Vec::new(),
771 terminator: Some(Terminator {
781 fn create_generator_resume_function<'a, 'tcx>(
782 tcx: TyCtxt<'a, 'tcx, 'tcx>,
783 transform: TransformVisitor<'a, 'tcx>,
785 source: MirSource<'tcx>,
786 mir: &mut Body<'tcx>) {
787 // Poison the generator when it unwinds
788 for block in mir.basic_blocks_mut() {
789 let source_info = block.terminator().source_info;
790 if let &TerminatorKind::Resume = &block.terminator().kind {
791 block.statements.push(
792 transform.set_discr(VariantIdx::new(POISONED), source_info));
796 let mut cases = create_cases(mir, &transform, |point| Some(point.resume));
798 use rustc::mir::interpret::InterpError::{
799 GeneratorResumedAfterPanic,
800 GeneratorResumedAfterReturn,
803 // Jump to the entry point on the unresumed
804 cases.insert(0, (UNRESUMED, BasicBlock::new(0)));
805 // Panic when resumed on the returned state
806 cases.insert(1, (RETURNED, insert_panic_block(tcx, mir, GeneratorResumedAfterReturn)));
807 // Panic when resumed on the poisoned state
808 cases.insert(2, (POISONED, insert_panic_block(tcx, mir, GeneratorResumedAfterPanic)));
810 insert_switch(mir, cases, &transform, TerminatorKind::Unreachable);
812 make_generator_state_argument_indirect(tcx, def_id, mir);
813 make_generator_state_argument_pinned(tcx, mir);
815 no_landing_pads(tcx, mir);
817 // Make sure we remove dead blocks to remove
818 // unrelated code from the drop part of the function
819 simplify::remove_dead_blocks(mir);
821 dump_mir(tcx, None, "generator_resume", &0, source, mir, |_, _| Ok(()) );
824 fn source_info<'a, 'tcx>(mir: &Body<'tcx>) -> SourceInfo {
827 scope: OUTERMOST_SOURCE_SCOPE,
831 fn insert_clean_drop<'a, 'tcx>(mir: &mut Body<'tcx>) -> BasicBlock {
832 let return_block = insert_term_block(mir, TerminatorKind::Return);
834 // Create a block to destroy an unresumed generators. This can only destroy upvars.
835 let drop_clean = BasicBlock::new(mir.basic_blocks().len());
836 let term = TerminatorKind::Drop {
837 location: Place::Base(PlaceBase::Local(self_arg())),
838 target: return_block,
841 let source_info = source_info(mir);
842 mir.basic_blocks_mut().push(BasicBlockData {
843 statements: Vec::new(),
844 terminator: Some(Terminator {
854 fn create_cases<'a, 'tcx, F>(mir: &mut Body<'tcx>,
855 transform: &TransformVisitor<'a, 'tcx>,
856 target: F) -> Vec<(usize, BasicBlock)>
857 where F: Fn(&SuspensionPoint) -> Option<BasicBlock> {
858 let source_info = source_info(mir);
860 transform.suspension_points.iter().filter_map(|point| {
861 // Find the target for this suspension point, if applicable
862 target(point).map(|target| {
863 let block = BasicBlock::new(mir.basic_blocks().len());
864 let mut statements = Vec::new();
866 // Create StorageLive instructions for locals with live storage
867 for i in 0..(mir.local_decls.len()) {
868 let l = Local::new(i);
869 if point.storage_liveness.contains(l) && !transform.remap.contains_key(&l) {
870 statements.push(Statement {
872 kind: StatementKind::StorageLive(l),
877 // Then jump to the real target
878 mir.basic_blocks_mut().push(BasicBlockData {
880 terminator: Some(Terminator {
882 kind: TerminatorKind::Goto {
894 impl MirPass for StateTransform {
895 fn run_pass<'a, 'tcx>(&self,
896 tcx: TyCtxt<'a, 'tcx, 'tcx>,
897 source: MirSource<'tcx>,
898 mir: &mut Body<'tcx>) {
899 let yield_ty = if let Some(yield_ty) = mir.yield_ty {
902 // This only applies to generators
906 assert!(mir.generator_drop.is_none());
908 let def_id = source.def_id();
910 // The first argument is the generator type passed by value
911 let gen_ty = mir.local_decls.raw[1].ty;
913 // Get the interior types and substs which typeck computed
914 let (upvars, interior, discr_ty, movable) = match gen_ty.sty {
915 ty::Generator(_, substs, movability) => {
916 (substs.upvar_tys(def_id, tcx).collect(),
917 substs.witness(def_id, tcx),
918 substs.discr_ty(tcx),
919 movability == hir::GeneratorMovability::Movable)
924 // Compute GeneratorState<yield_ty, return_ty>
925 let state_did = tcx.lang_items().gen_state().unwrap();
926 let state_adt_ref = tcx.adt_def(state_did);
927 let state_substs = tcx.intern_substs(&[
929 mir.return_ty().into(),
931 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
933 // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
934 // RETURN_PLACE then is a fresh unused local with type ret_ty.
935 let new_ret_local = replace_result_variable(ret_ty, mir);
937 // Extract locals which are live across suspension point into `layout`
938 // `remap` gives a mapping from local indices onto generator struct indices
939 // `storage_liveness` tells us which locals have live storage at suspension points
940 let (remap, layout, storage_liveness) = compute_layout(
948 // Run the transformation which converts Places from Local to generator struct
949 // accesses for locals in `remap`.
950 // It also rewrites `return x` and `yield y` as writing a new generator state and returning
951 // GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
952 let mut transform = TransformVisitor {
958 suspension_points: Vec::new(),
962 transform.visit_body(mir);
964 // Update our MIR struct to reflect the changed we've made
967 mir.spread_arg = None;
968 mir.generator_layout = Some(layout);
970 // Insert `drop(generator_struct)` which is used to drop upvars for generators in
971 // the unresumed state.
972 // This is expanded to a drop ladder in `elaborate_generator_drops`.
973 let drop_clean = insert_clean_drop(mir);
975 dump_mir(tcx, None, "generator_pre-elab", &0, source, mir, |_, _| Ok(()) );
977 // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
978 // If any upvars are moved out of, drop elaboration will handle upvar destruction.
979 // However we need to also elaborate the code generated by `insert_clean_drop`.
980 elaborate_generator_drops(tcx, def_id, mir);
982 dump_mir(tcx, None, "generator_post-transform", &0, source, mir, |_, _| Ok(()) );
984 // Create a copy of our MIR and use it to create the drop shim for the generator
985 let drop_shim = create_generator_drop_shim(tcx,
993 mir.generator_drop = Some(box drop_shim);
995 // Create the Generator::resume function
996 create_generator_resume_function(tcx, transform, def_id, source, mir);