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, GeneratorKind};
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_index::vec::{Idx, IndexVec};
62 use rustc_index::bit_set::{BitSet, BitMatrix};
65 use crate::transform::{MirPass, MirSource};
66 use crate::transform::simplify;
67 use crate::transform::no_landing_pads::no_landing_pads;
68 use crate::dataflow::{DataflowResults, DataflowResultsConsumer, FlowAtLocation};
69 use crate::dataflow::{do_dataflow, DebugFormatted, DataflowResultsCursor};
70 use crate::dataflow::{MaybeStorageLive, HaveBeenBorrowedLocals, RequiresStorage};
71 use crate::util::dump_mir;
72 use crate::util::liveness;
74 pub struct StateTransform;
76 struct RenameLocalVisitor<'tcx> {
82 impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
83 fn tcx(&self) -> TyCtxt<'tcx> {
87 fn visit_local(&mut self,
91 if *local == self.from {
96 fn process_projection_elem(
98 elem: &PlaceElem<'tcx>,
99 ) -> Option<PlaceElem<'tcx>> {
101 PlaceElem::Index(local) if *local == self.from => {
102 Some(PlaceElem::Index(self.to))
109 struct DerefArgVisitor<'tcx> {
113 impl<'tcx> MutVisitor<'tcx> for DerefArgVisitor<'tcx> {
114 fn tcx(&self) -> TyCtxt<'tcx> {
118 fn visit_local(&mut self,
122 assert_ne!(*local, self_arg());
125 fn visit_place(&mut self,
126 place: &mut Place<'tcx>,
127 context: PlaceContext,
128 location: Location) {
129 if place.base == PlaceBase::Local(self_arg()) {
130 replace_base(place, Place {
131 base: PlaceBase::Local(self_arg()),
132 projection: self.tcx().intern_place_elems(&vec![ProjectionElem::Deref]),
135 self.visit_place_base(&mut place.base, context, location);
137 for elem in place.projection.iter() {
138 if let PlaceElem::Index(local) = elem {
139 assert_ne!(*local, self_arg());
146 struct PinArgVisitor<'tcx> {
147 ref_gen_ty: Ty<'tcx>,
151 impl<'tcx> MutVisitor<'tcx> for PinArgVisitor<'tcx> {
152 fn tcx(&self) -> TyCtxt<'tcx> {
156 fn visit_local(&mut self,
160 assert_ne!(*local, self_arg());
163 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
164 if place.base == PlaceBase::Local(self_arg()) {
168 base: PlaceBase::Local(self_arg()),
169 projection: self.tcx().intern_place_elems(&vec![ProjectionElem::Field(
177 self.visit_place_base(&mut place.base, context, location);
179 for elem in place.projection.iter() {
180 if let PlaceElem::Index(local) = elem {
181 assert_ne!(*local, self_arg());
188 fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
189 place.base = new_base.base;
191 let mut new_projection = new_base.projection.to_vec();
192 new_projection.append(&mut place.projection.to_vec());
194 place.projection = tcx.intern_place_elems(&new_projection);
197 fn self_arg() -> Local {
201 /// Generator have not been resumed yet
202 const UNRESUMED: usize = GeneratorSubsts::UNRESUMED;
203 /// Generator has returned / is completed
204 const RETURNED: usize = GeneratorSubsts::RETURNED;
205 /// Generator has been poisoned
206 const POISONED: usize = GeneratorSubsts::POISONED;
208 struct SuspensionPoint {
211 drop: Option<BasicBlock>,
212 storage_liveness: liveness::LiveVarSet,
215 struct TransformVisitor<'tcx> {
217 state_adt_ref: &'tcx AdtDef,
218 state_substs: SubstsRef<'tcx>,
220 // The type of the discriminant in the generator struct
223 // Mapping from Local to (type of local, generator struct index)
224 // FIXME(eddyb) This should use `IndexVec<Local, Option<_>>`.
225 remap: FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
227 // A map from a suspension point in a block to the locals which have live storage at that point
228 // FIXME(eddyb) This should use `IndexVec<BasicBlock, Option<_>>`.
229 storage_liveness: FxHashMap<BasicBlock, liveness::LiveVarSet>,
231 // A list of suspension points, generated during the transform
232 suspension_points: Vec<SuspensionPoint>,
234 // The original RETURN_PLACE local
235 new_ret_local: Local,
238 impl TransformVisitor<'tcx> {
239 // Make a GeneratorState rvalue
240 fn make_state(&self, idx: VariantIdx, val: Operand<'tcx>) -> Rvalue<'tcx> {
241 let adt = AggregateKind::Adt(self.state_adt_ref, idx, self.state_substs, None, None);
242 Rvalue::Aggregate(box adt, vec![val])
245 // Create a Place referencing a generator struct field
246 fn make_field(&self, variant_index: VariantIdx, idx: usize, ty: Ty<'tcx>) -> Place<'tcx> {
247 let self_place = Place::from(self_arg());
248 let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
249 let mut projection = base.projection.to_vec();
250 projection.push(ProjectionElem::Field(Field::new(idx), ty));
254 projection: self.tcx.intern_place_elems(&projection),
258 // Create a statement which changes the discriminant
259 fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
260 let self_place = Place::from(self_arg());
263 kind: StatementKind::SetDiscriminant {
264 place: box self_place,
265 variant_index: state_disc,
270 // Create a statement which reads the discriminant into a temporary
271 fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
272 let temp_decl = LocalDecl::new_internal(self.tcx.types.isize, body.span);
273 let local_decls_len = body.local_decls.push(temp_decl);
274 let temp = Place::from(local_decls_len);
276 let self_place = Place::from(self_arg());
277 let assign = Statement {
278 source_info: source_info(body),
279 kind: StatementKind::Assign(box(temp.clone(), Rvalue::Discriminant(self_place))),
285 impl MutVisitor<'tcx> for TransformVisitor<'tcx> {
286 fn tcx(&self) -> TyCtxt<'tcx> {
290 fn visit_local(&mut self,
294 assert_eq!(self.remap.get(local), None);
299 place: &mut Place<'tcx>,
300 context: PlaceContext,
303 if let PlaceBase::Local(l) = place.base {
304 // Replace an Local in the remap with a generator struct access
305 if let Some(&(ty, variant_index, idx)) = self.remap.get(&l) {
306 replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
309 self.visit_place_base(&mut place.base, context, location);
311 for elem in place.projection.iter() {
312 if let PlaceElem::Index(local) = elem {
313 assert_ne!(*local, self_arg());
319 fn visit_basic_block_data(&mut self,
321 data: &mut BasicBlockData<'tcx>) {
322 // Remove StorageLive and StorageDead statements for remapped locals
323 data.retain_statements(|s| {
325 StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
326 !self.remap.contains_key(&l)
332 let ret_val = match data.terminator().kind {
333 TerminatorKind::Return => Some((VariantIdx::new(1),
335 Operand::Move(Place::from(self.new_ret_local)),
337 TerminatorKind::Yield { ref value, resume, drop } => Some((VariantIdx::new(0),
344 if let Some((state_idx, resume, v, drop)) = ret_val {
345 let source_info = data.terminator().source_info;
346 // We must assign the value first in case it gets declared dead below
347 data.statements.push(Statement {
349 kind: StatementKind::Assign(
351 Place::return_place(),
352 self.make_state(state_idx, v)
356 let state = if let Some(resume) = resume { // Yield
357 let state = 3 + self.suspension_points.len();
359 self.suspension_points.push(SuspensionPoint {
363 storage_liveness: self.storage_liveness.get(&block).unwrap().clone(),
366 VariantIdx::new(state)
368 VariantIdx::new(RETURNED) // state for returned
370 data.statements.push(self.set_discr(state, source_info));
371 data.terminator.as_mut().unwrap().kind = TerminatorKind::Return;
374 self.super_basic_block_data(block, data);
378 fn make_generator_state_argument_indirect<'tcx>(
381 body: &mut Body<'tcx>,
383 let gen_ty = body.local_decls.raw[1].ty;
385 let region = ty::ReFree(ty::FreeRegion {
387 bound_region: ty::BoundRegion::BrEnv,
390 let region = tcx.mk_region(region);
392 let ref_gen_ty = tcx.mk_ref(region, ty::TypeAndMut {
394 mutbl: hir::Mutability::Mutable
397 // Replace the by value generator argument
398 body.local_decls.raw[1].ty = ref_gen_ty;
400 // Add a deref to accesses of the generator state
401 DerefArgVisitor { tcx }.visit_body(body);
404 fn make_generator_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
405 let ref_gen_ty = body.local_decls.raw[1].ty;
407 let pin_did = tcx.lang_items().pin_type().unwrap();
408 let pin_adt_ref = tcx.adt_def(pin_did);
409 let substs = tcx.intern_substs(&[ref_gen_ty.into()]);
410 let pin_ref_gen_ty = tcx.mk_adt(pin_adt_ref, substs);
412 // Replace the by ref generator argument
413 body.local_decls.raw[1].ty = pin_ref_gen_ty;
415 // Add the Pin field access to accesses of the generator state
416 PinArgVisitor { ref_gen_ty, tcx }.visit_body(body);
419 fn replace_result_variable<'tcx>(
421 body: &mut Body<'tcx>,
424 let source_info = source_info(body);
425 let new_ret = LocalDecl {
426 mutability: Mutability::Mut,
428 user_ty: UserTypeProjections::none(),
432 local_info: LocalInfo::Other
434 let new_ret_local = Local::new(body.local_decls.len());
435 body.local_decls.push(new_ret);
436 body.local_decls.swap(RETURN_PLACE, new_ret_local);
447 struct StorageIgnored(liveness::LiveVarSet);
449 impl<'tcx> Visitor<'tcx> for StorageIgnored {
450 fn visit_statement(&mut self,
451 statement: &Statement<'tcx>,
452 _location: Location) {
453 match statement.kind {
454 StatementKind::StorageLive(l) |
455 StatementKind::StorageDead(l) => { self.0.remove(l); }
461 struct LivenessInfo {
462 /// Which locals are live across any suspension point.
464 /// GeneratorSavedLocal is indexed in terms of the elements in this set;
465 /// i.e. GeneratorSavedLocal::new(1) corresponds to the second local
466 /// included in this set.
467 live_locals: liveness::LiveVarSet,
469 /// The set of saved locals live at each suspension point.
470 live_locals_at_suspension_points: Vec<BitSet<GeneratorSavedLocal>>,
472 /// For every saved local, the set of other saved locals that are
473 /// storage-live at the same time as this local. We cannot overlap locals in
474 /// the layout which have conflicting storage.
475 storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
477 /// For every suspending block, the locals which are storage-live across
478 /// that suspension point.
479 storage_liveness: FxHashMap<BasicBlock, liveness::LiveVarSet>,
482 fn locals_live_across_suspend_points(
485 source: MirSource<'tcx>,
488 let dead_unwinds = BitSet::new_empty(body.basic_blocks().len());
489 let def_id = source.def_id();
491 // Calculate when MIR locals have live storage. This gives us an upper bound of their
493 let storage_live_analysis = MaybeStorageLive::new(body);
494 let storage_live_results =
495 do_dataflow(tcx, body, def_id, &[], &dead_unwinds, storage_live_analysis,
496 |bd, p| DebugFormatted::new(&bd.body().local_decls[p]));
497 let mut storage_live_cursor = DataflowResultsCursor::new(&storage_live_results, body);
499 // Find the MIR locals which do not use StorageLive/StorageDead statements.
500 // The storage of these locals are always live.
501 let mut ignored = StorageIgnored(BitSet::new_filled(body.local_decls.len()));
502 ignored.visit_body(body);
504 // Calculate the MIR locals which have been previously
505 // borrowed (even if they are still active).
506 let borrowed_locals_analysis = HaveBeenBorrowedLocals::new(body);
507 let borrowed_locals_results =
508 do_dataflow(tcx, body, def_id, &[], &dead_unwinds, borrowed_locals_analysis,
509 |bd, p| DebugFormatted::new(&bd.body().local_decls[p]));
510 let mut borrowed_locals_cursor = DataflowResultsCursor::new(&borrowed_locals_results, body);
512 // Calculate the MIR locals that we actually need to keep storage around
514 let requires_storage_analysis = RequiresStorage::new(body, &borrowed_locals_results);
515 let requires_storage_results =
516 do_dataflow(tcx, body, def_id, &[], &dead_unwinds, requires_storage_analysis,
517 |bd, p| DebugFormatted::new(&bd.body().local_decls[p]));
518 let mut requires_storage_cursor = DataflowResultsCursor::new(&requires_storage_results, body);
520 // Calculate the liveness of MIR locals ignoring borrows.
521 let mut live_locals = liveness::LiveVarSet::new_empty(body.local_decls.len());
522 let mut liveness = liveness::liveness_of_locals(
527 "generator_liveness",
533 let mut storage_liveness_map = FxHashMap::default();
534 let mut live_locals_at_suspension_points = Vec::new();
536 for (block, data) in body.basic_blocks().iter_enumerated() {
537 if let TerminatorKind::Yield { .. } = data.terminator().kind {
540 statement_index: data.statements.len(),
544 // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
545 // This is correct for movable generators since borrows cannot live across
546 // suspension points. However for immovable generators we need to account for
547 // borrows, so we conseratively assume that all borrowed locals are live until
548 // we find a StorageDead statement referencing the locals.
549 // To do this we just union our `liveness` result with `borrowed_locals`, which
550 // contains all the locals which has been borrowed before this suspension point.
551 // If a borrow is converted to a raw reference, we must also assume that it lives
552 // forever. Note that the final liveness is still bounded by the storage liveness
553 // of the local, which happens using the `intersect` operation below.
554 borrowed_locals_cursor.seek(loc);
555 liveness.outs[block].union(borrowed_locals_cursor.get());
558 storage_live_cursor.seek(loc);
559 let storage_liveness = storage_live_cursor.get();
561 // Store the storage liveness for later use so we can restore the state
562 // after a suspension point
563 storage_liveness_map.insert(block, storage_liveness.clone());
565 requires_storage_cursor.seek(loc);
566 let storage_required = requires_storage_cursor.get().clone();
568 // Locals live are live at this point only if they are used across
569 // suspension points (the `liveness` variable)
570 // and their storage is required (the `storage_required` variable)
571 let mut live_locals_here = storage_required;
572 live_locals_here.intersect(&liveness.outs[block]);
574 // The generator argument is ignored
575 live_locals_here.remove(self_arg());
577 debug!("loc = {:?}, live_locals_here = {:?}", loc, live_locals_here);
579 // Add the locals live at this suspension point to the set of locals which live across
580 // any suspension points
581 live_locals.union(&live_locals_here);
583 live_locals_at_suspension_points.push(live_locals_here);
586 debug!("live_locals = {:?}", live_locals);
588 // Renumber our liveness_map bitsets to include only the locals we are
590 let live_locals_at_suspension_points = live_locals_at_suspension_points
592 .map(|live_here| renumber_bitset(&live_here, &live_locals))
595 let storage_conflicts = compute_storage_conflicts(
599 requires_storage_results);
603 live_locals_at_suspension_points,
605 storage_liveness: storage_liveness_map,
609 /// Renumbers the items present in `stored_locals` and applies the renumbering
612 /// For example, if `stored_locals = [1, 3, 5]`, this would be renumbered to
613 /// `[0, 1, 2]`. Thus, if `input = [3, 5]` we would return `[1, 2]`.
614 fn renumber_bitset(input: &BitSet<Local>, stored_locals: &liveness::LiveVarSet)
615 -> BitSet<GeneratorSavedLocal> {
616 assert!(stored_locals.superset(&input), "{:?} not a superset of {:?}", stored_locals, input);
617 let mut out = BitSet::new_empty(stored_locals.count());
618 for (idx, local) in stored_locals.iter().enumerate() {
619 let saved_local = GeneratorSavedLocal::from(idx);
620 if input.contains(local) {
621 out.insert(saved_local);
624 debug!("renumber_bitset({:?}, {:?}) => {:?}", input, stored_locals, out);
628 /// For every saved local, looks for which locals are StorageLive at the same
629 /// time. Generates a bitset for every local of all the other locals that may be
630 /// StorageLive simultaneously with that local. This is used in the layout
631 /// computation; see `GeneratorLayout` for more.
632 fn compute_storage_conflicts(
633 body: &'mir Body<'tcx>,
634 stored_locals: &liveness::LiveVarSet,
635 ignored: &StorageIgnored,
636 requires_storage: DataflowResults<'tcx, RequiresStorage<'mir, 'tcx>>,
637 ) -> BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal> {
638 assert_eq!(body.local_decls.len(), ignored.0.domain_size());
639 assert_eq!(body.local_decls.len(), stored_locals.domain_size());
640 debug!("compute_storage_conflicts({:?})", body.span);
641 debug!("ignored = {:?}", ignored.0);
643 // Storage ignored locals are not eligible for overlap, since their storage
645 let mut ineligible_locals = ignored.0.clone();
646 ineligible_locals.intersect(&stored_locals);
648 // Compute the storage conflicts for all eligible locals.
649 let mut visitor = StorageConflictVisitor {
651 stored_locals: &stored_locals,
652 local_conflicts: BitMatrix::from_row_n(&ineligible_locals, body.local_decls.len()),
654 let mut state = FlowAtLocation::new(requires_storage);
655 visitor.analyze_results(&mut state);
656 let local_conflicts = visitor.local_conflicts;
658 // Compress the matrix using only stored locals (Local -> GeneratorSavedLocal).
660 // NOTE: Today we store a full conflict bitset for every local. Technically
661 // this is twice as many bits as we need, since the relation is symmetric.
662 // However, in practice these bitsets are not usually large. The layout code
663 // also needs to keep track of how many conflicts each local has, so it's
664 // simpler to keep it this way for now.
665 let mut storage_conflicts = BitMatrix::new(stored_locals.count(), stored_locals.count());
666 for (idx_a, local_a) in stored_locals.iter().enumerate() {
667 let saved_local_a = GeneratorSavedLocal::new(idx_a);
668 if ineligible_locals.contains(local_a) {
669 // Conflicts with everything.
670 storage_conflicts.insert_all_into_row(saved_local_a);
672 // Keep overlap information only for stored locals.
673 for (idx_b, local_b) in stored_locals.iter().enumerate() {
674 let saved_local_b = GeneratorSavedLocal::new(idx_b);
675 if local_conflicts.contains(local_a, local_b) {
676 storage_conflicts.insert(saved_local_a, saved_local_b);
684 struct StorageConflictVisitor<'body, 'tcx, 's> {
685 body: &'body Body<'tcx>,
686 stored_locals: &'s liveness::LiveVarSet,
687 // FIXME(tmandry): Consider using sparse bitsets here once we have good
688 // benchmarks for generators.
689 local_conflicts: BitMatrix<Local, Local>,
692 impl<'body, 'tcx, 's> DataflowResultsConsumer<'body, 'tcx>
693 for StorageConflictVisitor<'body, 'tcx, 's>
695 type FlowState = FlowAtLocation<'tcx, RequiresStorage<'body, 'tcx>>;
697 fn body(&self) -> &'body Body<'tcx> {
701 fn visit_block_entry(&mut self,
703 flow_state: &Self::FlowState) {
704 // statement_index is only used for logging, so this is fine.
705 self.apply_state(flow_state, Location { block, statement_index: 0 });
708 fn visit_statement_entry(&mut self,
710 _stmt: &Statement<'tcx>,
711 flow_state: &Self::FlowState) {
712 self.apply_state(flow_state, loc);
715 fn visit_terminator_entry(&mut self,
717 _term: &Terminator<'tcx>,
718 flow_state: &Self::FlowState) {
719 self.apply_state(flow_state, loc);
723 impl<'body, 'tcx, 's> StorageConflictVisitor<'body, 'tcx, 's> {
724 fn apply_state(&mut self,
725 flow_state: &FlowAtLocation<'tcx, RequiresStorage<'body, 'tcx>>,
727 // Ignore unreachable blocks.
728 match self.body.basic_blocks()[loc.block].terminator().kind {
729 TerminatorKind::Unreachable => return,
733 let mut eligible_storage_live = flow_state.as_dense().clone();
734 eligible_storage_live.intersect(&self.stored_locals);
736 for local in eligible_storage_live.iter() {
737 self.local_conflicts.union_row_with(&eligible_storage_live, local);
740 if eligible_storage_live.count() > 1 {
741 trace!("at {:?}, eligible_storage_live={:?}", loc, eligible_storage_live);
746 fn compute_layout<'tcx>(
748 source: MirSource<'tcx>,
749 upvars: &Vec<Ty<'tcx>>,
752 body: &mut Body<'tcx>,
754 FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
755 GeneratorLayout<'tcx>,
756 FxHashMap<BasicBlock, liveness::LiveVarSet>,
758 // Use a liveness analysis to compute locals which are live across a suspension point
760 live_locals, live_locals_at_suspension_points, storage_conflicts, storage_liveness
761 } = locals_live_across_suspend_points(tcx, body, source, movable);
763 // Erase regions from the types passed in from typeck so we can compare them with
765 let allowed_upvars = tcx.erase_regions(upvars);
766 let allowed = match interior.kind {
767 ty::GeneratorWitness(s) => tcx.erase_late_bound_regions(&s),
771 for (local, decl) in body.local_decls.iter_enumerated() {
772 // Ignore locals which are internal or not live
773 if !live_locals.contains(local) || decl.internal {
777 // Sanity check that typeck knows about the type of locals which are
778 // live across a suspension point
779 if !allowed.contains(&decl.ty) && !allowed_upvars.contains(&decl.ty) {
781 "Broken MIR: generator contains type {} in MIR, \
782 but typeck only knows about {}",
788 // Gather live local types and their indices.
789 let mut locals = IndexVec::<GeneratorSavedLocal, _>::new();
790 let mut tys = IndexVec::<GeneratorSavedLocal, _>::new();
791 for (idx, local) in live_locals.iter().enumerate() {
793 tys.push(body.local_decls[local].ty);
794 debug!("generator saved local {:?} => {:?}", GeneratorSavedLocal::from(idx), local);
797 // Leave empty variants for the UNRESUMED, RETURNED, and POISONED states.
798 const RESERVED_VARIANTS: usize = 3;
800 // Build the generator variant field list.
801 // Create a map from local indices to generator struct indices.
802 let mut variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>> =
803 iter::repeat(IndexVec::new()).take(RESERVED_VARIANTS).collect();
804 let mut remap = FxHashMap::default();
805 for (suspension_point_idx, live_locals) in live_locals_at_suspension_points.iter().enumerate() {
806 let variant_index = VariantIdx::from(RESERVED_VARIANTS + suspension_point_idx);
807 let mut fields = IndexVec::new();
808 for (idx, saved_local) in live_locals.iter().enumerate() {
809 fields.push(saved_local);
810 // Note that if a field is included in multiple variants, we will
811 // just use the first one here. That's fine; fields do not move
812 // around inside generators, so it doesn't matter which variant
813 // index we access them by.
814 remap.entry(locals[saved_local]).or_insert((tys[saved_local], variant_index, idx));
816 variant_fields.push(fields);
818 debug!("generator variant_fields = {:?}", variant_fields);
819 debug!("generator storage_conflicts = {:#?}", storage_conflicts);
821 let layout = GeneratorLayout {
827 (remap, layout, storage_liveness)
830 fn insert_switch<'tcx>(
831 body: &mut Body<'tcx>,
832 cases: Vec<(usize, BasicBlock)>,
833 transform: &TransformVisitor<'tcx>,
834 default: TerminatorKind<'tcx>,
836 let default_block = insert_term_block(body, default);
837 let (assign, discr) = transform.get_discr(body);
838 let switch = TerminatorKind::SwitchInt {
839 discr: Operand::Move(discr),
840 switch_ty: transform.discr_ty,
841 values: Cow::from(cases.iter().map(|&(i, _)| i as u128).collect::<Vec<_>>()),
842 targets: cases.iter().map(|&(_, d)| d).chain(iter::once(default_block)).collect(),
845 let source_info = source_info(body);
846 body.basic_blocks_mut().raw.insert(0, BasicBlockData {
847 statements: vec![assign],
848 terminator: Some(Terminator {
855 let blocks = body.basic_blocks_mut().iter_mut();
857 for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
858 *target = BasicBlock::new(target.index() + 1);
862 fn elaborate_generator_drops<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, body: &mut Body<'tcx>) {
863 use crate::util::elaborate_drops::{elaborate_drop, Unwind};
864 use crate::util::patch::MirPatch;
865 use crate::shim::DropShimElaborator;
867 // Note that `elaborate_drops` only drops the upvars of a generator, and
868 // this is ok because `open_drop` can only be reached within that own
869 // generator's resume function.
871 let param_env = tcx.param_env(def_id);
872 let gen = self_arg();
874 let mut elaborator = DropShimElaborator {
876 patch: MirPatch::new(body),
881 for (block, block_data) in body.basic_blocks().iter_enumerated() {
882 let (target, unwind, source_info) = match block_data.terminator() {
885 kind: TerminatorKind::Drop {
891 if let Some(local) = location.as_local() {
893 (target, unwind, source_info)
903 let unwind = if block_data.is_cleanup {
906 Unwind::To(unwind.unwrap_or_else(|| elaborator.patch.resume_block()))
918 elaborator.patch.apply(body);
921 fn create_generator_drop_shim<'tcx>(
923 transform: &TransformVisitor<'tcx>,
925 source: MirSource<'tcx>,
928 drop_clean: BasicBlock,
930 let mut body = body.clone();
932 let source_info = source_info(&body);
934 let mut cases = create_cases(&mut body, transform, |point| point.drop);
936 cases.insert(0, (UNRESUMED, drop_clean));
938 // The returned state and the poisoned state fall through to the default
939 // case which is just to return
941 insert_switch(&mut body, cases, &transform, TerminatorKind::Return);
943 for block in body.basic_blocks_mut() {
944 let kind = &mut block.terminator_mut().kind;
945 if let TerminatorKind::GeneratorDrop = *kind {
946 *kind = TerminatorKind::Return;
950 // Replace the return variable
951 body.local_decls[RETURN_PLACE] = LocalDecl {
952 mutability: Mutability::Mut,
954 user_ty: UserTypeProjections::none(),
958 local_info: LocalInfo::Other
961 make_generator_state_argument_indirect(tcx, def_id, &mut body);
963 // Change the generator argument from &mut to *mut
964 body.local_decls[self_arg()] = LocalDecl {
965 mutability: Mutability::Mut,
966 ty: tcx.mk_ptr(ty::TypeAndMut {
968 mutbl: hir::Mutability::Mutable,
970 user_ty: UserTypeProjections::none(),
974 local_info: LocalInfo::Other
976 if tcx.sess.opts.debugging_opts.mir_emit_retag {
977 // Alias tracking must know we changed the type
978 body.basic_blocks_mut()[START_BLOCK].statements.insert(0, Statement {
980 kind: StatementKind::Retag(RetagKind::Raw, box Place::from(self_arg())),
984 no_landing_pads(tcx, &mut body);
986 // Make sure we remove dead blocks to remove
987 // unrelated code from the resume part of the function
988 simplify::remove_dead_blocks(&mut body);
990 dump_mir(tcx, None, "generator_drop", &0, source, &mut body, |_, _| Ok(()) );
995 fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
996 let term_block = BasicBlock::new(body.basic_blocks().len());
997 let source_info = source_info(body);
998 body.basic_blocks_mut().push(BasicBlockData {
999 statements: Vec::new(),
1000 terminator: Some(Terminator {
1009 fn insert_panic_block<'tcx>(
1011 body: &mut Body<'tcx>,
1012 message: AssertMessage<'tcx>,
1014 let assert_block = BasicBlock::new(body.basic_blocks().len());
1015 let term = TerminatorKind::Assert {
1016 cond: Operand::Constant(box Constant {
1019 literal: ty::Const::from_bool(tcx, false),
1023 target: assert_block,
1027 let source_info = source_info(body);
1028 body.basic_blocks_mut().push(BasicBlockData {
1029 statements: Vec::new(),
1030 terminator: Some(Terminator {
1040 fn create_generator_resume_function<'tcx>(
1042 transform: TransformVisitor<'tcx>,
1044 source: MirSource<'tcx>,
1045 body: &mut Body<'tcx>,
1047 // Poison the generator when it unwinds
1048 for block in body.basic_blocks_mut() {
1049 let source_info = block.terminator().source_info;
1050 if let &TerminatorKind::Resume = &block.terminator().kind {
1051 block.statements.push(
1052 transform.set_discr(VariantIdx::new(POISONED), source_info));
1056 let mut cases = create_cases(body, &transform, |point| Some(point.resume));
1058 use rustc::mir::interpret::PanicInfo::{
1059 GeneratorResumedAfterPanic,
1060 GeneratorResumedAfterReturn,
1061 AsyncResumedAfterReturn,
1062 AsyncResumedAfterPanic,
1065 // Jump to the entry point on the unresumed
1066 cases.insert(0, (UNRESUMED, BasicBlock::new(0)));
1068 // Panic when resumed on the returned or poisoned state
1069 match body.generator_kind {
1070 Some(GeneratorKind::Async(_)) => {
1071 cases.insert(1, (RETURNED, insert_panic_block(tcx, body, AsyncResumedAfterReturn)));
1072 cases.insert(2, (POISONED, insert_panic_block(tcx, body, AsyncResumedAfterPanic)));
1074 Some(GeneratorKind::Gen) => {
1075 cases.insert(1, (RETURNED, insert_panic_block(tcx, body, GeneratorResumedAfterReturn)));
1076 cases.insert(2, (POISONED, insert_panic_block(tcx, body, GeneratorResumedAfterPanic)));
1079 // N/A because we would never create a resume function if there was no generator_kind
1083 insert_switch(body, cases, &transform, TerminatorKind::Unreachable);
1085 make_generator_state_argument_indirect(tcx, def_id, body);
1086 make_generator_state_argument_pinned(tcx, body);
1088 no_landing_pads(tcx, body);
1090 // Make sure we remove dead blocks to remove
1091 // unrelated code from the drop part of the function
1092 simplify::remove_dead_blocks(body);
1094 dump_mir(tcx, None, "generator_resume", &0, source, body, |_, _| Ok(()) );
1097 fn source_info(body: &Body<'_>) -> SourceInfo {
1100 scope: OUTERMOST_SOURCE_SCOPE,
1104 fn insert_clean_drop(body: &mut Body<'_>) -> BasicBlock {
1105 let return_block = insert_term_block(body, TerminatorKind::Return);
1107 // Create a block to destroy an unresumed generators. This can only destroy upvars.
1108 let drop_clean = BasicBlock::new(body.basic_blocks().len());
1109 let term = TerminatorKind::Drop {
1110 location: Place::from(self_arg()),
1111 target: return_block,
1114 let source_info = source_info(body);
1115 body.basic_blocks_mut().push(BasicBlockData {
1116 statements: Vec::new(),
1117 terminator: Some(Terminator {
1127 fn create_cases<'tcx, F>(
1128 body: &mut Body<'tcx>,
1129 transform: &TransformVisitor<'tcx>,
1131 ) -> Vec<(usize, BasicBlock)>
1133 F: Fn(&SuspensionPoint) -> Option<BasicBlock>,
1135 let source_info = source_info(body);
1137 transform.suspension_points.iter().filter_map(|point| {
1138 // Find the target for this suspension point, if applicable
1139 target(point).map(|target| {
1140 let block = BasicBlock::new(body.basic_blocks().len());
1141 let mut statements = Vec::new();
1143 // Create StorageLive instructions for locals with live storage
1144 for i in 0..(body.local_decls.len()) {
1145 let l = Local::new(i);
1146 if point.storage_liveness.contains(l) && !transform.remap.contains_key(&l) {
1147 statements.push(Statement {
1149 kind: StatementKind::StorageLive(l),
1154 // Then jump to the real target
1155 body.basic_blocks_mut().push(BasicBlockData {
1157 terminator: Some(Terminator {
1159 kind: TerminatorKind::Goto {
1166 (point.state, block)
1171 impl<'tcx> MirPass<'tcx> for StateTransform {
1172 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>) {
1173 let yield_ty = if let Some(yield_ty) = body.yield_ty {
1176 // This only applies to generators
1180 assert!(body.generator_drop.is_none());
1182 let def_id = source.def_id();
1184 // The first argument is the generator type passed by value
1185 let gen_ty = body.local_decls.raw[1].ty;
1187 // Get the interior types and substs which typeck computed
1188 let (upvars, interior, discr_ty, movable) = match gen_ty.kind {
1189 ty::Generator(_, substs, movability) => {
1190 let substs = substs.as_generator();
1191 (substs.upvar_tys(def_id, tcx).collect(),
1192 substs.witness(def_id, tcx),
1193 substs.discr_ty(tcx),
1194 movability == hir::Movability::Movable)
1199 // Compute GeneratorState<yield_ty, return_ty>
1200 let state_did = tcx.lang_items().gen_state().unwrap();
1201 let state_adt_ref = tcx.adt_def(state_did);
1202 let state_substs = tcx.intern_substs(&[
1204 body.return_ty().into(),
1206 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
1208 // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
1209 // RETURN_PLACE then is a fresh unused local with type ret_ty.
1210 let new_ret_local = replace_result_variable(ret_ty, body, tcx);
1212 // Extract locals which are live across suspension point into `layout`
1213 // `remap` gives a mapping from local indices onto generator struct indices
1214 // `storage_liveness` tells us which locals have live storage at suspension points
1215 let (remap, layout, storage_liveness) = compute_layout(
1223 // Run the transformation which converts Places from Local to generator struct
1224 // accesses for locals in `remap`.
1225 // It also rewrites `return x` and `yield y` as writing a new generator state and returning
1226 // GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
1227 let mut transform = TransformVisitor {
1233 suspension_points: Vec::new(),
1237 transform.visit_body(body);
1239 // Update our MIR struct to reflect the changed we've made
1240 body.yield_ty = None;
1242 body.spread_arg = None;
1243 body.generator_layout = Some(layout);
1245 // Insert `drop(generator_struct)` which is used to drop upvars for generators in
1246 // the unresumed state.
1247 // This is expanded to a drop ladder in `elaborate_generator_drops`.
1248 let drop_clean = insert_clean_drop(body);
1250 dump_mir(tcx, None, "generator_pre-elab", &0, source, body, |_, _| Ok(()) );
1252 // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
1253 // If any upvars are moved out of, drop elaboration will handle upvar destruction.
1254 // However we need to also elaborate the code generated by `insert_clean_drop`.
1255 elaborate_generator_drops(tcx, def_id, body);
1257 dump_mir(tcx, None, "generator_post-transform", &0, source, body, |_, _| Ok(()) );
1259 // Create a copy of our MIR and use it to create the drop shim for the generator
1260 let drop_shim = create_generator_drop_shim(tcx,
1268 body.generator_drop = Some(box drop_shim);
1270 // Create the Generator::resume function
1271 create_generator_resume_function(tcx, transform, def_id, source, body);