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.base_local() == Some(self_arg()) {
107 replace_base(place, Place::Projection(Box::new(Projection {
108 base: Place::Base(PlaceBase::Local(self_arg())),
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.base_local() == Some(self_arg()) {
134 replace_base(place, Place::Projection(Box::new(Projection {
135 base: Place::Base(PlaceBase::Local(self_arg())),
136 elem: ProjectionElem::Field(Field::new(0), self.ref_gen_ty),
139 self.super_place(place, context, location);
144 fn replace_base(place: &mut Place<'tcx>, new_base: Place<'tcx>) {
145 if let Place::Projection(proj) = place {
146 replace_base(&mut proj.base, new_base);
152 fn self_arg() -> Local {
156 /// Generator have not been resumed yet
157 const UNRESUMED: usize = GeneratorSubsts::UNRESUMED;
158 /// Generator has returned / is completed
159 const RETURNED: usize = GeneratorSubsts::RETURNED;
160 /// Generator has been poisoned
161 const POISONED: usize = GeneratorSubsts::POISONED;
163 struct SuspensionPoint {
166 drop: Option<BasicBlock>,
167 storage_liveness: liveness::LiveVarSet,
170 struct TransformVisitor<'a, 'tcx: 'a> {
171 tcx: TyCtxt<'a, 'tcx, 'tcx>,
172 state_adt_ref: &'tcx AdtDef,
173 state_substs: SubstsRef<'tcx>,
175 // The type of the discriminant in the generator struct
178 // Mapping from Local to (type of local, generator struct index)
179 // FIXME(eddyb) This should use `IndexVec<Local, Option<_>>`.
180 remap: FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
182 // A map from a suspension point in a block to the locals which have live storage at that point
183 // FIXME(eddyb) This should use `IndexVec<BasicBlock, Option<_>>`.
184 storage_liveness: FxHashMap<BasicBlock, liveness::LiveVarSet>,
186 // A list of suspension points, generated during the transform
187 suspension_points: Vec<SuspensionPoint>,
189 // The original RETURN_PLACE local
190 new_ret_local: Local,
193 impl<'a, 'tcx> TransformVisitor<'a, 'tcx> {
194 // Make a GeneratorState rvalue
195 fn make_state(&self, idx: VariantIdx, val: Operand<'tcx>) -> Rvalue<'tcx> {
196 let adt = AggregateKind::Adt(self.state_adt_ref, idx, self.state_substs, None, None);
197 Rvalue::Aggregate(box adt, vec![val])
200 // Create a Place referencing a generator struct field
201 fn make_field(&self, variant_index: VariantIdx, idx: usize, ty: Ty<'tcx>) -> Place<'tcx> {
202 let self_place = Place::Base(PlaceBase::Local(self_arg()));
203 let base = self_place.downcast_unnamed(variant_index);
204 let field = Projection {
206 elem: ProjectionElem::Field(Field::new(idx), ty),
208 Place::Projection(Box::new(field))
211 // Create a statement which changes the discriminant
212 fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
213 let self_place = Place::Base(PlaceBase::Local(self_arg()));
216 kind: StatementKind::SetDiscriminant { place: self_place, variant_index: state_disc },
220 // Create a statement which reads the discriminant into a temporary
221 fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
222 let temp_decl = LocalDecl::new_internal(self.tcx.types.isize, body.span);
223 let local_decls_len = body.local_decls.push(temp_decl);
224 let temp = Place::Base(PlaceBase::Local(local_decls_len));
226 let self_place = Place::Base(PlaceBase::Local(self_arg()));
227 let assign = Statement {
228 source_info: source_info(body),
229 kind: StatementKind::Assign(temp.clone(), box Rvalue::Discriminant(self_place)),
235 impl<'a, 'tcx> MutVisitor<'tcx> for TransformVisitor<'a, 'tcx> {
236 fn visit_local(&mut self,
240 assert_eq!(self.remap.get(local), None);
243 fn visit_place(&mut self,
244 place: &mut Place<'tcx>,
245 context: PlaceContext,
246 location: Location) {
247 if let Some(l) = place.base_local() {
248 // Replace an Local in the remap with a generator struct access
249 if let Some(&(ty, variant_index, idx)) = self.remap.get(&l) {
250 replace_base(place, self.make_field(variant_index, idx, ty));
253 self.super_place(place, context, location);
257 fn visit_basic_block_data(&mut self,
259 data: &mut BasicBlockData<'tcx>) {
260 // Remove StorageLive and StorageDead statements for remapped locals
261 data.retain_statements(|s| {
263 StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
264 !self.remap.contains_key(&l)
270 let ret_val = match data.terminator().kind {
271 TerminatorKind::Return => Some((VariantIdx::new(1),
273 Operand::Move(Place::Base(PlaceBase::Local(self.new_ret_local))),
275 TerminatorKind::Yield { ref value, resume, drop } => Some((VariantIdx::new(0),
282 if let Some((state_idx, resume, v, drop)) = ret_val {
283 let source_info = data.terminator().source_info;
284 // We must assign the value first in case it gets declared dead below
285 data.statements.push(Statement {
287 kind: StatementKind::Assign(Place::RETURN_PLACE,
288 box self.make_state(state_idx, v)),
290 let state = if let Some(resume) = resume { // Yield
291 let state = 3 + self.suspension_points.len();
293 self.suspension_points.push(SuspensionPoint {
297 storage_liveness: self.storage_liveness.get(&block).unwrap().clone(),
300 VariantIdx::new(state)
302 VariantIdx::new(RETURNED) // state for returned
304 data.statements.push(self.set_discr(state, source_info));
305 data.terminator.as_mut().unwrap().kind = TerminatorKind::Return;
308 self.super_basic_block_data(block, data);
312 fn make_generator_state_argument_indirect<'a, 'tcx>(
313 tcx: TyCtxt<'a, 'tcx, 'tcx>,
315 body: &mut Body<'tcx>) {
316 let gen_ty = body.local_decls.raw[1].ty;
318 let region = ty::ReFree(ty::FreeRegion {
320 bound_region: ty::BoundRegion::BrEnv,
323 let region = tcx.mk_region(region);
325 let ref_gen_ty = tcx.mk_ref(region, ty::TypeAndMut {
327 mutbl: hir::MutMutable
330 // Replace the by value generator argument
331 body.local_decls.raw[1].ty = ref_gen_ty;
333 // Add a deref to accesses of the generator state
334 DerefArgVisitor.visit_body(body);
337 fn make_generator_state_argument_pinned<'a, 'tcx>(
338 tcx: TyCtxt<'a, 'tcx, 'tcx>,
339 body: &mut Body<'tcx>) {
340 let ref_gen_ty = body.local_decls.raw[1].ty;
342 let pin_did = tcx.lang_items().pin_type().unwrap();
343 let pin_adt_ref = tcx.adt_def(pin_did);
344 let substs = tcx.intern_substs(&[ref_gen_ty.into()]);
345 let pin_ref_gen_ty = tcx.mk_adt(pin_adt_ref, substs);
347 // Replace the by ref generator argument
348 body.local_decls.raw[1].ty = pin_ref_gen_ty;
350 // Add the Pin field access to accesses of the generator state
351 PinArgVisitor { ref_gen_ty }.visit_body(body);
354 fn replace_result_variable<'tcx>(
356 body: &mut Body<'tcx>,
358 let source_info = source_info(body);
359 let new_ret = LocalDecl {
360 mutability: Mutability::Mut,
362 user_ty: UserTypeProjections::none(),
365 visibility_scope: source_info.scope,
368 is_user_variable: None,
370 let new_ret_local = Local::new(body.local_decls.len());
371 body.local_decls.push(new_ret);
372 body.local_decls.swap(RETURN_PLACE, new_ret_local);
382 struct StorageIgnored(liveness::LiveVarSet);
384 impl<'tcx> Visitor<'tcx> for StorageIgnored {
385 fn visit_statement(&mut self,
386 statement: &Statement<'tcx>,
387 _location: Location) {
388 match statement.kind {
389 StatementKind::StorageLive(l) |
390 StatementKind::StorageDead(l) => { self.0.remove(l); }
396 fn locals_live_across_suspend_points(
397 tcx: TyCtxt<'a, 'tcx, 'tcx>,
399 source: MirSource<'tcx>,
402 liveness::LiveVarSet,
403 FxHashMap<BasicBlock, liveness::LiveVarSet>,
406 let dead_unwinds = BitSet::new_empty(body.basic_blocks().len());
407 let def_id = source.def_id();
409 // Calculate when MIR locals have live storage. This gives us an upper bound of their
411 let storage_live_analysis = MaybeStorageLive::new(body);
413 do_dataflow(tcx, body, def_id, &[], &dead_unwinds, storage_live_analysis,
414 |bd, p| DebugFormatted::new(&bd.body().local_decls[p]));
416 // Find the MIR locals which do not use StorageLive/StorageDead statements.
417 // The storage of these locals are always live.
418 let mut ignored = StorageIgnored(BitSet::new_filled(body.local_decls.len()));
419 ignored.visit_body(body);
421 // Calculate the MIR locals which have been previously
422 // borrowed (even if they are still active).
423 // This is only used for immovable generators.
424 let borrowed_locals = if !movable {
425 let analysis = HaveBeenBorrowedLocals::new(body);
427 do_dataflow(tcx, body, def_id, &[], &dead_unwinds, analysis,
428 |bd, p| DebugFormatted::new(&bd.body().local_decls[p]));
429 Some((analysis, result))
434 // Calculate the liveness of MIR locals ignoring borrows.
435 let mut set = liveness::LiveVarSet::new_empty(body.local_decls.len());
436 let mut liveness = liveness::liveness_of_locals(
441 "generator_liveness",
447 let mut storage_liveness_map = FxHashMap::default();
449 let mut suspending_blocks = BitSet::new_empty(body.basic_blocks().len());
451 for (block, data) in body.basic_blocks().iter_enumerated() {
452 if let TerminatorKind::Yield { .. } = data.terminator().kind {
453 suspending_blocks.insert(block);
457 statement_index: data.statements.len(),
460 if let Some((ref analysis, ref result)) = borrowed_locals {
461 let borrowed_locals = state_for_location(loc,
465 // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
466 // This is correct for movable generators since borrows cannot live across
467 // suspension points. However for immovable generators we need to account for
468 // borrows, so we conseratively assume that all borrowed locals are live until
469 // we find a StorageDead statement referencing the locals.
470 // To do this we just union our `liveness` result with `borrowed_locals`, which
471 // contains all the locals which has been borrowed before this suspension point.
472 // If a borrow is converted to a raw reference, we must also assume that it lives
473 // forever. Note that the final liveness is still bounded by the storage liveness
474 // of the local, which happens using the `intersect` operation below.
475 liveness.outs[block].union(&borrowed_locals);
478 let mut storage_liveness = state_for_location(loc,
479 &storage_live_analysis,
483 // Store the storage liveness for later use so we can restore the state
484 // after a suspension point
485 storage_liveness_map.insert(block, storage_liveness.clone());
487 // Mark locals without storage statements as always having live storage
488 storage_liveness.union(&ignored.0);
490 // Locals live are live at this point only if they are used across
491 // suspension points (the `liveness` variable)
492 // and their storage is live (the `storage_liveness` variable)
493 storage_liveness.intersect(&liveness.outs[block]);
495 let live_locals = storage_liveness;
497 // Add the locals life at this suspension point to the set of locals which live across
498 // any suspension points
499 set.union(&live_locals);
503 // The generator argument is ignored
504 set.remove(self_arg());
506 (set, storage_liveness_map, suspending_blocks)
509 fn compute_layout<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
510 source: MirSource<'tcx>,
511 upvars: &Vec<Ty<'tcx>>,
514 body: &mut Body<'tcx>)
515 -> (FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
516 GeneratorLayout<'tcx>,
517 FxHashMap<BasicBlock, liveness::LiveVarSet>)
519 // Use a liveness analysis to compute locals which are live across a suspension point
520 let (live_locals, storage_liveness, suspending_blocks) =
521 locals_live_across_suspend_points(tcx, body, source, movable);
523 // Erase regions from the types passed in from typeck so we can compare them with
525 let allowed_upvars = tcx.erase_regions(upvars);
526 let allowed = match interior.sty {
527 ty::GeneratorWitness(s) => tcx.erase_late_bound_regions(&s),
531 for (local, decl) in body.local_decls.iter_enumerated() {
532 // Ignore locals which are internal or not live
533 if !live_locals.contains(local) || decl.internal {
537 // Sanity check that typeck knows about the type of locals which are
538 // live across a suspension point
539 if !allowed.contains(&decl.ty) && !allowed_upvars.contains(&decl.ty) {
541 "Broken MIR: generator contains type {} in MIR, \
542 but typeck only knows about {}",
548 let dummy_local = LocalDecl::new_internal(tcx.mk_unit(), body.span);
550 // Gather live locals and their indices replacing values in mir.local_decls with a dummy
551 // to avoid changing local indices
552 let live_decls = live_locals.iter().map(|local| {
553 let var = mem::replace(&mut body.local_decls[local], dummy_local.clone());
557 // For now we will access everything via variant #3, leaving empty variants
558 // for the UNRESUMED, RETURNED, and POISONED states.
559 // If there were a yield-less generator without a variant #3, it would not
560 // have any vars to remap, so we would never use this.
561 let variant_index = VariantIdx::new(3);
563 // Create a map from local indices to generator struct indices.
564 // We also create a vector of the LocalDecls of these locals.
565 let mut remap = FxHashMap::default();
566 let mut decls = IndexVec::new();
567 for (idx, (local, var)) in live_decls.enumerate() {
568 remap.insert(local, (var.ty, variant_index, idx));
571 let field_tys = decls.iter().map(|field| field.ty).collect::<IndexVec<_, _>>();
573 // Put every var in each variant, for now.
574 let all_vars = (0..field_tys.len()).map(GeneratorSavedLocal::from).collect();
575 let empty_variants = iter::repeat(IndexVec::new()).take(3);
576 let state_variants = iter::repeat(all_vars).take(suspending_blocks.count());
578 let layout = GeneratorLayout {
580 variant_fields: empty_variants.chain(state_variants).collect(),
581 __local_debuginfo_codegen_only_do_not_use: decls,
584 (remap, layout, storage_liveness)
587 fn insert_switch<'a, 'tcx>(body: &mut Body<'tcx>,
588 cases: Vec<(usize, BasicBlock)>,
589 transform: &TransformVisitor<'a, 'tcx>,
590 default: TerminatorKind<'tcx>) {
591 let default_block = insert_term_block(body, default);
592 let (assign, discr) = transform.get_discr(body);
593 let switch = TerminatorKind::SwitchInt {
594 discr: Operand::Move(discr),
595 switch_ty: transform.discr_ty,
596 values: Cow::from(cases.iter().map(|&(i, _)| i as u128).collect::<Vec<_>>()),
597 targets: cases.iter().map(|&(_, d)| d).chain(iter::once(default_block)).collect(),
600 let source_info = source_info(body);
601 body.basic_blocks_mut().raw.insert(0, BasicBlockData {
602 statements: vec![assign],
603 terminator: Some(Terminator {
610 let blocks = body.basic_blocks_mut().iter_mut();
612 for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
613 *target = BasicBlock::new(target.index() + 1);
617 fn elaborate_generator_drops<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
619 body: &mut Body<'tcx>) {
620 use crate::util::elaborate_drops::{elaborate_drop, Unwind};
621 use crate::util::patch::MirPatch;
622 use crate::shim::DropShimElaborator;
624 // Note that `elaborate_drops` only drops the upvars of a generator, and
625 // this is ok because `open_drop` can only be reached within that own
626 // generator's resume function.
628 let param_env = tcx.param_env(def_id);
629 let gen = self_arg();
631 let mut elaborator = DropShimElaborator {
633 patch: MirPatch::new(body),
638 for (block, block_data) in body.basic_blocks().iter_enumerated() {
639 let (target, unwind, source_info) = match block_data.terminator() {
642 kind: TerminatorKind::Drop {
643 location: Place::Base(PlaceBase::Local(local)),
647 } if local == gen => (target, unwind, source_info),
650 let unwind = if block_data.is_cleanup {
653 Unwind::To(unwind.unwrap_or_else(|| elaborator.patch.resume_block()))
658 &Place::Base(PlaceBase::Local(gen)),
665 elaborator.patch.apply(body);
668 fn create_generator_drop_shim<'a, 'tcx>(
669 tcx: TyCtxt<'a, 'tcx, 'tcx>,
670 transform: &TransformVisitor<'a, 'tcx>,
672 source: MirSource<'tcx>,
675 drop_clean: BasicBlock) -> Body<'tcx> {
676 let mut body = body.clone();
678 let source_info = source_info(&body);
680 let mut cases = create_cases(&mut body, transform, |point| point.drop);
682 cases.insert(0, (UNRESUMED, drop_clean));
684 // The returned state and the poisoned state fall through to the default
685 // case which is just to return
687 insert_switch(&mut body, cases, &transform, TerminatorKind::Return);
689 for block in body.basic_blocks_mut() {
690 let kind = &mut block.terminator_mut().kind;
691 if let TerminatorKind::GeneratorDrop = *kind {
692 *kind = TerminatorKind::Return;
696 // Replace the return variable
697 body.local_decls[RETURN_PLACE] = LocalDecl {
698 mutability: Mutability::Mut,
700 user_ty: UserTypeProjections::none(),
703 visibility_scope: source_info.scope,
706 is_user_variable: None,
709 make_generator_state_argument_indirect(tcx, def_id, &mut body);
711 // Change the generator argument from &mut to *mut
712 body.local_decls[self_arg()] = LocalDecl {
713 mutability: Mutability::Mut,
714 ty: tcx.mk_ptr(ty::TypeAndMut {
716 mutbl: hir::Mutability::MutMutable,
718 user_ty: UserTypeProjections::none(),
721 visibility_scope: source_info.scope,
724 is_user_variable: None,
726 if tcx.sess.opts.debugging_opts.mir_emit_retag {
727 // Alias tracking must know we changed the type
728 body.basic_blocks_mut()[START_BLOCK].statements.insert(0, Statement {
730 kind: StatementKind::Retag(RetagKind::Raw, Place::Base(PlaceBase::Local(self_arg()))),
734 no_landing_pads(tcx, &mut body);
736 // Make sure we remove dead blocks to remove
737 // unrelated code from the resume part of the function
738 simplify::remove_dead_blocks(&mut body);
740 dump_mir(tcx, None, "generator_drop", &0, source, &mut body, |_, _| Ok(()) );
745 fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
746 let term_block = BasicBlock::new(body.basic_blocks().len());
747 let source_info = source_info(body);
748 body.basic_blocks_mut().push(BasicBlockData {
749 statements: Vec::new(),
750 terminator: Some(Terminator {
759 fn insert_panic_block<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
760 body: &mut Body<'tcx>,
761 message: AssertMessage<'tcx>) -> BasicBlock {
762 let assert_block = BasicBlock::new(body.basic_blocks().len());
763 let term = TerminatorKind::Assert {
764 cond: Operand::Constant(box Constant {
768 literal: ty::Const::from_bool(tcx, false),
772 target: assert_block,
776 let source_info = source_info(body);
777 body.basic_blocks_mut().push(BasicBlockData {
778 statements: Vec::new(),
779 terminator: Some(Terminator {
789 fn create_generator_resume_function<'a, 'tcx>(
790 tcx: TyCtxt<'a, 'tcx, 'tcx>,
791 transform: TransformVisitor<'a, 'tcx>,
793 source: MirSource<'tcx>,
794 body: &mut Body<'tcx>) {
795 // Poison the generator when it unwinds
796 for block in body.basic_blocks_mut() {
797 let source_info = block.terminator().source_info;
798 if let &TerminatorKind::Resume = &block.terminator().kind {
799 block.statements.push(
800 transform.set_discr(VariantIdx::new(POISONED), source_info));
804 let mut cases = create_cases(body, &transform, |point| Some(point.resume));
806 use rustc::mir::interpret::InterpError::{
807 GeneratorResumedAfterPanic,
808 GeneratorResumedAfterReturn,
811 // Jump to the entry point on the unresumed
812 cases.insert(0, (UNRESUMED, BasicBlock::new(0)));
813 // Panic when resumed on the returned state
814 cases.insert(1, (RETURNED, insert_panic_block(tcx, body, GeneratorResumedAfterReturn)));
815 // Panic when resumed on the poisoned state
816 cases.insert(2, (POISONED, insert_panic_block(tcx, body, GeneratorResumedAfterPanic)));
818 insert_switch(body, cases, &transform, TerminatorKind::Unreachable);
820 make_generator_state_argument_indirect(tcx, def_id, body);
821 make_generator_state_argument_pinned(tcx, body);
823 no_landing_pads(tcx, body);
825 // Make sure we remove dead blocks to remove
826 // unrelated code from the drop part of the function
827 simplify::remove_dead_blocks(body);
829 dump_mir(tcx, None, "generator_resume", &0, source, body, |_, _| Ok(()) );
832 fn source_info<'a, 'tcx>(body: &Body<'tcx>) -> SourceInfo {
835 scope: OUTERMOST_SOURCE_SCOPE,
839 fn insert_clean_drop<'a, 'tcx>(body: &mut Body<'tcx>) -> BasicBlock {
840 let return_block = insert_term_block(body, TerminatorKind::Return);
842 // Create a block to destroy an unresumed generators. This can only destroy upvars.
843 let drop_clean = BasicBlock::new(body.basic_blocks().len());
844 let term = TerminatorKind::Drop {
845 location: Place::Base(PlaceBase::Local(self_arg())),
846 target: return_block,
849 let source_info = source_info(body);
850 body.basic_blocks_mut().push(BasicBlockData {
851 statements: Vec::new(),
852 terminator: Some(Terminator {
862 fn create_cases<'a, 'tcx, F>(body: &mut Body<'tcx>,
863 transform: &TransformVisitor<'a, 'tcx>,
864 target: F) -> Vec<(usize, BasicBlock)>
865 where F: Fn(&SuspensionPoint) -> Option<BasicBlock> {
866 let source_info = source_info(body);
868 transform.suspension_points.iter().filter_map(|point| {
869 // Find the target for this suspension point, if applicable
870 target(point).map(|target| {
871 let block = BasicBlock::new(body.basic_blocks().len());
872 let mut statements = Vec::new();
874 // Create StorageLive instructions for locals with live storage
875 for i in 0..(body.local_decls.len()) {
876 let l = Local::new(i);
877 if point.storage_liveness.contains(l) && !transform.remap.contains_key(&l) {
878 statements.push(Statement {
880 kind: StatementKind::StorageLive(l),
885 // Then jump to the real target
886 body.basic_blocks_mut().push(BasicBlockData {
888 terminator: Some(Terminator {
890 kind: TerminatorKind::Goto {
902 impl MirPass for StateTransform {
903 fn run_pass<'a, 'tcx>(&self,
904 tcx: TyCtxt<'a, 'tcx, 'tcx>,
905 source: MirSource<'tcx>,
906 body: &mut Body<'tcx>) {
907 let yield_ty = if let Some(yield_ty) = body.yield_ty {
910 // This only applies to generators
914 assert!(body.generator_drop.is_none());
916 let def_id = source.def_id();
918 // The first argument is the generator type passed by value
919 let gen_ty = body.local_decls.raw[1].ty;
921 // Get the interior types and substs which typeck computed
922 let (upvars, interior, discr_ty, movable) = match gen_ty.sty {
923 ty::Generator(_, substs, movability) => {
924 (substs.upvar_tys(def_id, tcx).collect(),
925 substs.witness(def_id, tcx),
926 substs.discr_ty(tcx),
927 movability == hir::GeneratorMovability::Movable)
932 // Compute GeneratorState<yield_ty, return_ty>
933 let state_did = tcx.lang_items().gen_state().unwrap();
934 let state_adt_ref = tcx.adt_def(state_did);
935 let state_substs = tcx.intern_substs(&[
937 body.return_ty().into(),
939 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
941 // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
942 // RETURN_PLACE then is a fresh unused local with type ret_ty.
943 let new_ret_local = replace_result_variable(ret_ty, body);
945 // Extract locals which are live across suspension point into `layout`
946 // `remap` gives a mapping from local indices onto generator struct indices
947 // `storage_liveness` tells us which locals have live storage at suspension points
948 let (remap, layout, storage_liveness) = compute_layout(
956 // Run the transformation which converts Places from Local to generator struct
957 // accesses for locals in `remap`.
958 // It also rewrites `return x` and `yield y` as writing a new generator state and returning
959 // GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
960 let mut transform = TransformVisitor {
966 suspension_points: Vec::new(),
970 transform.visit_body(body);
972 // Update our MIR struct to reflect the changed we've made
973 body.yield_ty = None;
975 body.spread_arg = None;
976 body.generator_layout = Some(layout);
978 // Insert `drop(generator_struct)` which is used to drop upvars for generators in
979 // the unresumed state.
980 // This is expanded to a drop ladder in `elaborate_generator_drops`.
981 let drop_clean = insert_clean_drop(body);
983 dump_mir(tcx, None, "generator_pre-elab", &0, source, body, |_, _| Ok(()) );
985 // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
986 // If any upvars are moved out of, drop elaboration will handle upvar destruction.
987 // However we need to also elaborate the code generated by `insert_clean_drop`.
988 elaborate_generator_drops(tcx, def_id, body);
990 dump_mir(tcx, None, "generator_post-transform", &0, source, body, |_, _| Ok(()) );
992 // Create a copy of our MIR and use it to create the drop shim for the generator
993 let drop_shim = create_generator_drop_shim(tcx,
1001 body.generator_drop = Some(box drop_shim);
1003 // Create the Generator::resume function
1004 create_generator_resume_function(tcx, transform, def_id, source, body);