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.
52 use crate::dataflow
::generic
::{self as dataflow, Analysis}
;
53 use crate::dataflow
::{MaybeBorrowedLocals, MaybeRequiresStorage, MaybeStorageLive}
;
54 use crate::transform
::no_landing_pads
::no_landing_pads
;
55 use crate::transform
::simplify
;
56 use crate::transform
::{MirPass, MirSource}
;
57 use crate::util
::dump_mir
;
58 use crate::util
::liveness
;
59 use rustc
::mir
::visit
::{MutVisitor, PlaceContext, Visitor}
;
61 use rustc
::ty
::layout
::VariantIdx
;
62 use rustc
::ty
::subst
::SubstsRef
;
63 use rustc
::ty
::GeneratorSubsts
;
64 use rustc
::ty
::{self, AdtDef, Ty, TyCtxt}
;
65 use rustc_data_structures
::fx
::FxHashMap
;
67 use rustc_hir
::def_id
::DefId
;
68 use rustc_index
::bit_set
::{BitMatrix, BitSet}
;
69 use rustc_index
::vec
::{Idx, IndexVec}
;
73 pub struct StateTransform
;
75 struct RenameLocalVisitor
<'tcx
> {
81 impl<'tcx
> MutVisitor
<'tcx
> for RenameLocalVisitor
<'tcx
> {
82 fn tcx(&self) -> TyCtxt
<'tcx
> {
86 fn visit_local(&mut self, local
: &mut Local
, _
: PlaceContext
, _
: Location
) {
87 if *local
== self.from
{
92 fn process_projection_elem(&mut self, elem
: &PlaceElem
<'tcx
>) -> Option
<PlaceElem
<'tcx
>> {
94 PlaceElem
::Index(local
) if *local
== self.from
=> Some(PlaceElem
::Index(self.to
)),
100 struct DerefArgVisitor
<'tcx
> {
104 impl<'tcx
> MutVisitor
<'tcx
> for DerefArgVisitor
<'tcx
> {
105 fn tcx(&self) -> TyCtxt
<'tcx
> {
109 fn visit_local(&mut self, local
: &mut Local
, _
: PlaceContext
, _
: Location
) {
110 assert_ne
!(*local
, self_arg());
113 fn visit_place(&mut self, place
: &mut Place
<'tcx
>, context
: PlaceContext
, location
: Location
) {
114 if place
.local
== self_arg() {
119 projection
: self.tcx().intern_place_elems(&[ProjectionElem
::Deref
]),
124 self.visit_place_base(&mut place
.local
, context
, location
);
126 for elem
in place
.projection
.iter() {
127 if let PlaceElem
::Index(local
) = elem
{
128 assert_ne
!(*local
, self_arg());
135 struct PinArgVisitor
<'tcx
> {
136 ref_gen_ty
: Ty
<'tcx
>,
140 impl<'tcx
> MutVisitor
<'tcx
> for PinArgVisitor
<'tcx
> {
141 fn tcx(&self) -> TyCtxt
<'tcx
> {
145 fn visit_local(&mut self, local
: &mut Local
, _
: PlaceContext
, _
: Location
) {
146 assert_ne
!(*local
, self_arg());
149 fn visit_place(&mut self, place
: &mut Place
<'tcx
>, context
: PlaceContext
, location
: Location
) {
150 if place
.local
== self_arg() {
155 projection
: self.tcx().intern_place_elems(&[ProjectionElem
::Field(
163 self.visit_place_base(&mut place
.local
, context
, location
);
165 for elem
in place
.projection
.iter() {
166 if let PlaceElem
::Index(local
) = elem
{
167 assert_ne
!(*local
, self_arg());
174 fn replace_base
<'tcx
>(place
: &mut Place
<'tcx
>, new_base
: Place
<'tcx
>, tcx
: TyCtxt
<'tcx
>) {
175 place
.local
= new_base
.local
;
177 let mut new_projection
= new_base
.projection
.to_vec();
178 new_projection
.append(&mut place
.projection
.to_vec());
180 place
.projection
= tcx
.intern_place_elems(&new_projection
);
183 fn self_arg() -> Local
{
187 /// Generator has not been resumed yet.
188 const UNRESUMED
: usize = GeneratorSubsts
::UNRESUMED
;
189 /// Generator has returned / is completed.
190 const RETURNED
: usize = GeneratorSubsts
::RETURNED
;
191 /// Generator has panicked and is poisoned.
192 const POISONED
: usize = GeneratorSubsts
::POISONED
;
194 /// A `yield` point in the generator.
195 struct SuspensionPoint
<'tcx
> {
196 /// State discriminant used when suspending or resuming at this point.
198 /// The block to jump to after resumption.
200 /// Where to move the resume argument after resumption.
201 resume_arg
: Place
<'tcx
>,
202 /// Which block to jump to if the generator is dropped in this state.
203 drop
: Option
<BasicBlock
>,
204 /// Set of locals that have live storage while at this suspension point.
205 storage_liveness
: liveness
::LiveVarSet
,
208 struct TransformVisitor
<'tcx
> {
210 state_adt_ref
: &'tcx AdtDef
,
211 state_substs
: SubstsRef
<'tcx
>,
213 // The type of the discriminant in the generator struct
216 // Mapping from Local to (type of local, generator struct index)
217 // FIXME(eddyb) This should use `IndexVec<Local, Option<_>>`.
218 remap
: FxHashMap
<Local
, (Ty
<'tcx
>, VariantIdx
, usize)>,
220 // A map from a suspension point in a block to the locals which have live storage at that point
221 // FIXME(eddyb) This should use `IndexVec<BasicBlock, Option<_>>`.
222 storage_liveness
: FxHashMap
<BasicBlock
, liveness
::LiveVarSet
>,
224 // A list of suspension points, generated during the transform
225 suspension_points
: Vec
<SuspensionPoint
<'tcx
>>,
227 // The original RETURN_PLACE local
228 new_ret_local
: Local
,
231 impl TransformVisitor
<'tcx
> {
232 // Make a GeneratorState rvalue
233 fn make_state(&self, idx
: VariantIdx
, val
: Operand
<'tcx
>) -> Rvalue
<'tcx
> {
234 let adt
= AggregateKind
::Adt(self.state_adt_ref
, idx
, self.state_substs
, None
, None
);
235 Rvalue
::Aggregate(box adt
, vec
![val
])
238 // Create a Place referencing a generator struct field
239 fn make_field(&self, variant_index
: VariantIdx
, idx
: usize, ty
: Ty
<'tcx
>) -> Place
<'tcx
> {
240 let self_place
= Place
::from(self_arg());
241 let base
= self.tcx
.mk_place_downcast_unnamed(self_place
, variant_index
);
242 let mut projection
= base
.projection
.to_vec();
243 projection
.push(ProjectionElem
::Field(Field
::new(idx
), ty
));
245 Place { local: base.local, projection: self.tcx.intern_place_elems(&projection) }
248 // Create a statement which changes the discriminant
249 fn set_discr(&self, state_disc
: VariantIdx
, source_info
: SourceInfo
) -> Statement
<'tcx
> {
250 let self_place
= Place
::from(self_arg());
253 kind
: StatementKind
::SetDiscriminant
{
254 place
: box self_place
,
255 variant_index
: state_disc
,
260 // Create a statement which reads the discriminant into a temporary
261 fn get_discr(&self, body
: &mut Body
<'tcx
>) -> (Statement
<'tcx
>, Place
<'tcx
>) {
262 let temp_decl
= LocalDecl
::new_internal(self.tcx
.types
.isize, body
.span
);
263 let local_decls_len
= body
.local_decls
.push(temp_decl
);
264 let temp
= Place
::from(local_decls_len
);
266 let self_place
= Place
::from(self_arg());
267 let assign
= Statement
{
268 source_info
: source_info(body
),
269 kind
: StatementKind
::Assign(box (temp
, Rvalue
::Discriminant(self_place
))),
275 impl MutVisitor
<'tcx
> for TransformVisitor
<'tcx
> {
276 fn tcx(&self) -> TyCtxt
<'tcx
> {
280 fn visit_local(&mut self, local
: &mut Local
, _
: PlaceContext
, _
: Location
) {
281 assert_eq
!(self.remap
.get(local
), None
);
286 place
: &mut Place
<'tcx
>,
287 _context
: PlaceContext
,
290 // Replace an Local in the remap with a generator struct access
291 if let Some(&(ty
, variant_index
, idx
)) = self.remap
.get(&place
.local
) {
292 replace_base(place
, self.make_field(variant_index
, idx
, ty
), self.tcx
);
296 fn visit_basic_block_data(&mut self, block
: BasicBlock
, data
: &mut BasicBlockData
<'tcx
>) {
297 // Remove StorageLive and StorageDead statements for remapped locals
298 data
.retain_statements(|s
| match s
.kind
{
299 StatementKind
::StorageLive(l
) | StatementKind
::StorageDead(l
) => {
300 !self.remap
.contains_key(&l
)
305 let ret_val
= match data
.terminator().kind
{
306 TerminatorKind
::Return
=> Some((
309 Operand
::Move(Place
::from(self.new_ret_local
)),
312 TerminatorKind
::Yield { ref value, resume, resume_arg, drop }
=> {
313 Some((VariantIdx
::new(0), Some((resume
, resume_arg
)), value
.clone(), drop
))
318 if let Some((state_idx
, resume
, v
, drop
)) = ret_val
{
319 let source_info
= data
.terminator().source_info
;
320 // We must assign the value first in case it gets declared dead below
321 data
.statements
.push(Statement
{
323 kind
: StatementKind
::Assign(box (
324 Place
::return_place(),
325 self.make_state(state_idx
, v
),
328 let state
= if let Some((resume
, resume_arg
)) = resume
{
330 let state
= 3 + self.suspension_points
.len();
332 // The resume arg target location might itself be remapped if its base local is
333 // live across a yield.
335 if let Some(&(ty
, variant
, idx
)) = self.remap
.get(&resume_arg
.local
) {
336 self.make_field(variant
, idx
, ty
)
341 self.suspension_points
.push(SuspensionPoint
{
346 storage_liveness
: self.storage_liveness
.get(&block
).unwrap().clone(),
349 VariantIdx
::new(state
)
352 VariantIdx
::new(RETURNED
) // state for returned
354 data
.statements
.push(self.set_discr(state
, source_info
));
355 data
.terminator_mut().kind
= TerminatorKind
::Return
;
358 self.super_basic_block_data(block
, data
);
362 fn make_generator_state_argument_indirect
<'tcx
>(
365 body
: &mut BodyAndCache
<'tcx
>,
367 let gen_ty
= body
.local_decls
.raw
[1].ty
;
369 let region
= ty
::ReFree(ty
::FreeRegion { scope: def_id, bound_region: ty::BoundRegion::BrEnv }
);
371 let region
= tcx
.mk_region(region
);
373 let ref_gen_ty
= tcx
.mk_ref(region
, ty
::TypeAndMut { ty: gen_ty, mutbl: hir::Mutability::Mut }
);
375 // Replace the by value generator argument
376 body
.local_decls
.raw
[1].ty
= ref_gen_ty
;
378 // Add a deref to accesses of the generator state
379 DerefArgVisitor { tcx }
.visit_body(body
);
382 fn make_generator_state_argument_pinned
<'tcx
>(tcx
: TyCtxt
<'tcx
>, body
: &mut BodyAndCache
<'tcx
>) {
383 let ref_gen_ty
= body
.local_decls
.raw
[1].ty
;
385 let pin_did
= tcx
.lang_items().pin_type().unwrap();
386 let pin_adt_ref
= tcx
.adt_def(pin_did
);
387 let substs
= tcx
.intern_substs(&[ref_gen_ty
.into()]);
388 let pin_ref_gen_ty
= tcx
.mk_adt(pin_adt_ref
, substs
);
390 // Replace the by ref generator argument
391 body
.local_decls
.raw
[1].ty
= pin_ref_gen_ty
;
393 // Add the Pin field access to accesses of the generator state
394 PinArgVisitor { ref_gen_ty, tcx }
.visit_body(body
);
397 /// Allocates a new local and replaces all references of `local` with it. Returns the new local.
399 /// `local` will be changed to a new local decl with type `ty`.
401 /// Note that the new local will be uninitialized. It is the caller's responsibility to assign some
402 /// valid value to it before its first use.
403 fn replace_local
<'tcx
>(
406 body
: &mut BodyAndCache
<'tcx
>,
409 let source_info
= source_info(body
);
410 let new_decl
= LocalDecl
{
411 mutability
: Mutability
::Mut
,
413 user_ty
: UserTypeProjections
::none(),
417 local_info
: LocalInfo
::Other
,
419 let new_local
= Local
::new(body
.local_decls
.len());
420 body
.local_decls
.push(new_decl
);
421 body
.local_decls
.swap(local
, new_local
);
423 RenameLocalVisitor { from: local, to: new_local, tcx }
.visit_body(body
);
428 struct StorageIgnored(liveness
::LiveVarSet
);
430 impl<'tcx
> Visitor
<'tcx
> for StorageIgnored
{
431 fn visit_statement(&mut self, statement
: &Statement
<'tcx
>, _location
: Location
) {
432 match statement
.kind
{
433 StatementKind
::StorageLive(l
) | StatementKind
::StorageDead(l
) => {
441 struct LivenessInfo
{
442 /// Which locals are live across any suspension point.
444 /// GeneratorSavedLocal is indexed in terms of the elements in this set;
445 /// i.e. GeneratorSavedLocal::new(1) corresponds to the second local
446 /// included in this set.
447 live_locals
: liveness
::LiveVarSet
,
449 /// The set of saved locals live at each suspension point.
450 live_locals_at_suspension_points
: Vec
<BitSet
<GeneratorSavedLocal
>>,
452 /// For every saved local, the set of other saved locals that are
453 /// storage-live at the same time as this local. We cannot overlap locals in
454 /// the layout which have conflicting storage.
455 storage_conflicts
: BitMatrix
<GeneratorSavedLocal
, GeneratorSavedLocal
>,
457 /// For every suspending block, the locals which are storage-live across
458 /// that suspension point.
459 storage_liveness
: FxHashMap
<BasicBlock
, liveness
::LiveVarSet
>,
462 fn locals_live_across_suspend_points(
464 body
: ReadOnlyBodyAndCache
<'_
, 'tcx
>,
465 source
: MirSource
<'tcx
>,
468 let def_id
= source
.def_id();
469 let body_ref
: &Body
<'_
> = &body
;
471 // Calculate when MIR locals have live storage. This gives us an upper bound of their
473 let mut storage_live
= MaybeStorageLive
474 .into_engine(tcx
, body_ref
, def_id
)
475 .iterate_to_fixpoint()
476 .into_results_cursor(body_ref
);
478 // Find the MIR locals which do not use StorageLive/StorageDead statements.
479 // The storage of these locals are always live.
480 let mut ignored
= StorageIgnored(BitSet
::new_filled(body
.local_decls
.len()));
481 ignored
.visit_body(body
);
483 // Calculate the MIR locals which have been previously
484 // borrowed (even if they are still active).
485 let borrowed_locals_results
=
486 MaybeBorrowedLocals
::all_borrows().into_engine(tcx
, body_ref
, def_id
).iterate_to_fixpoint();
488 let mut borrowed_locals_cursor
=
489 dataflow
::ResultsCursor
::new(body_ref
, &borrowed_locals_results
);
491 // Calculate the MIR locals that we actually need to keep storage around
493 let requires_storage_results
= MaybeRequiresStorage
::new(body
, &borrowed_locals_results
)
494 .into_engine(tcx
, body_ref
, def_id
)
495 .iterate_to_fixpoint();
496 let mut requires_storage_cursor
=
497 dataflow
::ResultsCursor
::new(body_ref
, &requires_storage_results
);
499 // Calculate the liveness of MIR locals ignoring borrows.
500 let mut live_locals
= liveness
::LiveVarSet
::new_empty(body
.local_decls
.len());
501 let mut liveness
= liveness
::liveness_of_locals(body
);
502 liveness
::dump_mir(tcx
, "generator_liveness", source
, body_ref
, &liveness
);
504 let mut storage_liveness_map
= FxHashMap
::default();
505 let mut live_locals_at_suspension_points
= Vec
::new();
507 for (block
, data
) in body
.basic_blocks().iter_enumerated() {
508 if let TerminatorKind
::Yield { .. }
= data
.terminator().kind
{
509 let loc
= Location { block, statement_index: data.statements.len() }
;
512 // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
513 // This is correct for movable generators since borrows cannot live across
514 // suspension points. However for immovable generators we need to account for
515 // borrows, so we conseratively assume that all borrowed locals are live until
516 // we find a StorageDead statement referencing the locals.
517 // To do this we just union our `liveness` result with `borrowed_locals`, which
518 // contains all the locals which has been borrowed before this suspension point.
519 // If a borrow is converted to a raw reference, we must also assume that it lives
520 // forever. Note that the final liveness is still bounded by the storage liveness
521 // of the local, which happens using the `intersect` operation below.
522 borrowed_locals_cursor
.seek_before(loc
);
523 liveness
.outs
[block
].union(borrowed_locals_cursor
.get());
526 storage_live
.seek_before(loc
);
527 let storage_liveness
= storage_live
.get();
529 // Store the storage liveness for later use so we can restore the state
530 // after a suspension point
531 storage_liveness_map
.insert(block
, storage_liveness
.clone());
533 requires_storage_cursor
.seek_before(loc
);
534 let storage_required
= requires_storage_cursor
.get().clone();
536 // Locals live are live at this point only if they are used across
537 // suspension points (the `liveness` variable)
538 // and their storage is required (the `storage_required` variable)
539 let mut live_locals_here
= storage_required
;
540 live_locals_here
.intersect(&liveness
.outs
[block
]);
542 // The generator argument is ignored
543 live_locals_here
.remove(self_arg());
545 debug
!("loc = {:?}, live_locals_here = {:?}", loc
, live_locals_here
);
547 // Add the locals live at this suspension point to the set of locals which live across
548 // any suspension points
549 live_locals
.union(&live_locals_here
);
551 live_locals_at_suspension_points
.push(live_locals_here
);
554 debug
!("live_locals = {:?}", live_locals
);
556 // Renumber our liveness_map bitsets to include only the locals we are
558 let live_locals_at_suspension_points
= live_locals_at_suspension_points
560 .map(|live_here
| renumber_bitset(&live_here
, &live_locals
))
563 let storage_conflicts
=
564 compute_storage_conflicts(body_ref
, &live_locals
, &ignored
, requires_storage_results
);
568 live_locals_at_suspension_points
,
570 storage_liveness
: storage_liveness_map
,
574 /// Renumbers the items present in `stored_locals` and applies the renumbering
577 /// For example, if `stored_locals = [1, 3, 5]`, this would be renumbered to
578 /// `[0, 1, 2]`. Thus, if `input = [3, 5]` we would return `[1, 2]`.
580 input
: &BitSet
<Local
>,
581 stored_locals
: &liveness
::LiveVarSet
,
582 ) -> BitSet
<GeneratorSavedLocal
> {
583 assert
!(stored_locals
.superset(&input
), "{:?} not a superset of {:?}", stored_locals
, input
);
584 let mut out
= BitSet
::new_empty(stored_locals
.count());
585 for (idx
, local
) in stored_locals
.iter().enumerate() {
586 let saved_local
= GeneratorSavedLocal
::from(idx
);
587 if input
.contains(local
) {
588 out
.insert(saved_local
);
591 debug
!("renumber_bitset({:?}, {:?}) => {:?}", input
, stored_locals
, out
);
595 /// For every saved local, looks for which locals are StorageLive at the same
596 /// time. Generates a bitset for every local of all the other locals that may be
597 /// StorageLive simultaneously with that local. This is used in the layout
598 /// computation; see `GeneratorLayout` for more.
599 fn compute_storage_conflicts(
600 body
: &'mir Body
<'tcx
>,
601 stored_locals
: &liveness
::LiveVarSet
,
602 ignored
: &StorageIgnored
,
603 requires_storage
: dataflow
::Results
<'tcx
, MaybeRequiresStorage
<'mir
, 'tcx
>>,
604 ) -> BitMatrix
<GeneratorSavedLocal
, GeneratorSavedLocal
> {
605 assert_eq
!(body
.local_decls
.len(), ignored
.0.domain_size());
606 assert_eq
!(body
.local_decls
.len(), stored_locals
.domain_size());
607 debug
!("compute_storage_conflicts({:?})", body
.span
);
608 debug
!("ignored = {:?}", ignored
.0);
610 // Storage ignored locals are not eligible for overlap, since their storage
612 let mut ineligible_locals
= ignored
.0.clone();
613 ineligible_locals
.intersect(&stored_locals
);
615 // Compute the storage conflicts for all eligible locals.
616 let mut visitor
= StorageConflictVisitor
{
618 stored_locals
: &stored_locals
,
619 local_conflicts
: BitMatrix
::from_row_n(&ineligible_locals
, body
.local_decls
.len()),
622 // Visit only reachable basic blocks. The exact order is not important.
623 let reachable_blocks
= traversal
::preorder(body
).map(|(bb
, _
)| bb
);
624 requires_storage
.visit_with(body
, reachable_blocks
, &mut visitor
);
626 let local_conflicts
= visitor
.local_conflicts
;
628 // Compress the matrix using only stored locals (Local -> GeneratorSavedLocal).
630 // NOTE: Today we store a full conflict bitset for every local. Technically
631 // this is twice as many bits as we need, since the relation is symmetric.
632 // However, in practice these bitsets are not usually large. The layout code
633 // also needs to keep track of how many conflicts each local has, so it's
634 // simpler to keep it this way for now.
635 let mut storage_conflicts
= BitMatrix
::new(stored_locals
.count(), stored_locals
.count());
636 for (idx_a
, local_a
) in stored_locals
.iter().enumerate() {
637 let saved_local_a
= GeneratorSavedLocal
::new(idx_a
);
638 if ineligible_locals
.contains(local_a
) {
639 // Conflicts with everything.
640 storage_conflicts
.insert_all_into_row(saved_local_a
);
642 // Keep overlap information only for stored locals.
643 for (idx_b
, local_b
) in stored_locals
.iter().enumerate() {
644 let saved_local_b
= GeneratorSavedLocal
::new(idx_b
);
645 if local_conflicts
.contains(local_a
, local_b
) {
646 storage_conflicts
.insert(saved_local_a
, saved_local_b
);
654 struct StorageConflictVisitor
<'mir
, 'tcx
, 's
> {
655 body
: &'mir Body
<'tcx
>,
656 stored_locals
: &'s liveness
::LiveVarSet
,
657 // FIXME(tmandry): Consider using sparse bitsets here once we have good
658 // benchmarks for generators.
659 local_conflicts
: BitMatrix
<Local
, Local
>,
662 impl dataflow
::ResultsVisitor
<'mir
, 'tcx
> for StorageConflictVisitor
<'mir
, 'tcx
, '_
> {
663 type FlowState
= BitSet
<Local
>;
667 state
: &Self::FlowState
,
668 _statement
: &'mir Statement
<'tcx
>,
671 self.apply_state(state
, loc
);
676 state
: &Self::FlowState
,
677 _terminator
: &'mir Terminator
<'tcx
>,
680 self.apply_state(state
, loc
);
684 impl<'body
, 'tcx
, 's
> StorageConflictVisitor
<'body
, 'tcx
, 's
> {
685 fn apply_state(&mut self, flow_state
: &BitSet
<Local
>, loc
: Location
) {
686 // Ignore unreachable blocks.
687 match self.body
.basic_blocks()[loc
.block
].terminator().kind
{
688 TerminatorKind
::Unreachable
=> return,
692 let mut eligible_storage_live
= flow_state
.clone();
693 eligible_storage_live
.intersect(&self.stored_locals
);
695 for local
in eligible_storage_live
.iter() {
696 self.local_conflicts
.union_row_with(&eligible_storage_live
, local
);
699 if eligible_storage_live
.count() > 1 {
700 trace
!("at {:?}, eligible_storage_live={:?}", loc
, eligible_storage_live
);
705 fn compute_layout
<'tcx
>(
707 source
: MirSource
<'tcx
>,
708 upvars
: &Vec
<Ty
<'tcx
>>,
711 body
: &mut BodyAndCache
<'tcx
>,
713 FxHashMap
<Local
, (Ty
<'tcx
>, VariantIdx
, usize)>,
714 GeneratorLayout
<'tcx
>,
715 FxHashMap
<BasicBlock
, liveness
::LiveVarSet
>,
717 // Use a liveness analysis to compute locals which are live across a suspension point
720 live_locals_at_suspension_points
,
723 } = locals_live_across_suspend_points(tcx
, read_only
!(body
), source
, movable
);
725 // Erase regions from the types passed in from typeck so we can compare them with
727 let allowed_upvars
= tcx
.erase_regions(upvars
);
728 let allowed
= match interior
.kind
{
729 ty
::GeneratorWitness(s
) => tcx
.erase_late_bound_regions(&s
),
733 for (local
, decl
) in body
.local_decls
.iter_enumerated() {
734 // Ignore locals which are internal or not live
735 if !live_locals
.contains(local
) || decl
.internal
{
739 // Sanity check that typeck knows about the type of locals which are
740 // live across a suspension point
741 if !allowed
.contains(&decl
.ty
) && !allowed_upvars
.contains(&decl
.ty
) {
744 "Broken MIR: generator contains type {} in MIR, \
745 but typeck only knows about {}",
752 // Gather live local types and their indices.
753 let mut locals
= IndexVec
::<GeneratorSavedLocal
, _
>::new();
754 let mut tys
= IndexVec
::<GeneratorSavedLocal
, _
>::new();
755 for (idx
, local
) in live_locals
.iter().enumerate() {
757 tys
.push(body
.local_decls
[local
].ty
);
758 debug
!("generator saved local {:?} => {:?}", GeneratorSavedLocal
::from(idx
), local
);
761 // Leave empty variants for the UNRESUMED, RETURNED, and POISONED states.
762 const RESERVED_VARIANTS
: usize = 3;
764 // Build the generator variant field list.
765 // Create a map from local indices to generator struct indices.
766 let mut variant_fields
: IndexVec
<VariantIdx
, IndexVec
<Field
, GeneratorSavedLocal
>> =
767 iter
::repeat(IndexVec
::new()).take(RESERVED_VARIANTS
).collect();
768 let mut remap
= FxHashMap
::default();
769 for (suspension_point_idx
, live_locals
) in live_locals_at_suspension_points
.iter().enumerate() {
770 let variant_index
= VariantIdx
::from(RESERVED_VARIANTS
+ suspension_point_idx
);
771 let mut fields
= IndexVec
::new();
772 for (idx
, saved_local
) in live_locals
.iter().enumerate() {
773 fields
.push(saved_local
);
774 // Note that if a field is included in multiple variants, we will
775 // just use the first one here. That's fine; fields do not move
776 // around inside generators, so it doesn't matter which variant
777 // index we access them by.
778 remap
.entry(locals
[saved_local
]).or_insert((tys
[saved_local
], variant_index
, idx
));
780 variant_fields
.push(fields
);
782 debug
!("generator variant_fields = {:?}", variant_fields
);
783 debug
!("generator storage_conflicts = {:#?}", storage_conflicts
);
785 let layout
= GeneratorLayout { field_tys: tys, variant_fields, storage_conflicts }
;
787 (remap
, layout
, storage_liveness
)
790 /// Replaces the entry point of `body` with a block that switches on the generator discriminant and
791 /// dispatches to blocks according to `cases`.
793 /// After this function, the former entry point of the function will be bb1.
794 fn insert_switch
<'tcx
>(
795 body
: &mut BodyAndCache
<'tcx
>,
796 cases
: Vec
<(usize, BasicBlock
)>,
797 transform
: &TransformVisitor
<'tcx
>,
798 default: TerminatorKind
<'tcx
>,
800 let default_block
= insert_term_block(body
, default);
801 let (assign
, discr
) = transform
.get_discr(body
);
802 let switch
= TerminatorKind
::SwitchInt
{
803 discr
: Operand
::Move(discr
),
804 switch_ty
: transform
.discr_ty
,
805 values
: Cow
::from(cases
.iter().map(|&(i
, _
)| i
as u128
).collect
::<Vec
<_
>>()),
806 targets
: cases
.iter().map(|&(_
, d
)| d
).chain(iter
::once(default_block
)).collect(),
809 let source_info
= source_info(body
);
810 body
.basic_blocks_mut().raw
.insert(
813 statements
: vec
![assign
],
814 terminator
: Some(Terminator { source_info, kind: switch }
),
819 let blocks
= body
.basic_blocks_mut().iter_mut();
821 for target
in blocks
.flat_map(|b
| b
.terminator_mut().successors_mut()) {
822 *target
= BasicBlock
::new(target
.index() + 1);
826 fn elaborate_generator_drops
<'tcx
>(
829 body
: &mut BodyAndCache
<'tcx
>,
831 use crate::shim
::DropShimElaborator
;
832 use crate::util
::elaborate_drops
::{elaborate_drop, Unwind}
;
833 use crate::util
::patch
::MirPatch
;
835 // Note that `elaborate_drops` only drops the upvars of a generator, and
836 // this is ok because `open_drop` can only be reached within that own
837 // generator's resume function.
839 let param_env
= tcx
.param_env(def_id
);
840 let gen
= self_arg();
842 let mut elaborator
= DropShimElaborator { body, patch: MirPatch::new(body), tcx, param_env }
;
844 for (block
, block_data
) in body
.basic_blocks().iter_enumerated() {
845 let (target
, unwind
, source_info
) = match block_data
.terminator() {
846 Terminator { source_info, kind: TerminatorKind::Drop { location, target, unwind }
} => {
847 if let Some(local
) = location
.as_local() {
849 (target
, unwind
, source_info
)
859 let unwind
= if block_data
.is_cleanup
{
862 Unwind
::To(unwind
.unwrap_or_else(|| elaborator
.patch
.resume_block()))
874 elaborator
.patch
.apply(body
);
877 fn create_generator_drop_shim
<'tcx
>(
879 transform
: &TransformVisitor
<'tcx
>,
881 source
: MirSource
<'tcx
>,
883 body
: &mut BodyAndCache
<'tcx
>,
884 drop_clean
: BasicBlock
,
885 ) -> BodyAndCache
<'tcx
> {
886 let mut body
= body
.clone();
887 body
.arg_count
= 1; // make sure the resume argument is not included here
889 let source_info
= source_info(&body
);
891 let mut cases
= create_cases(&mut body
, transform
, Operation
::Drop
);
893 cases
.insert(0, (UNRESUMED
, drop_clean
));
895 // The returned state and the poisoned state fall through to the default
896 // case which is just to return
898 insert_switch(&mut body
, cases
, &transform
, TerminatorKind
::Return
);
900 for block
in body
.basic_blocks_mut() {
901 let kind
= &mut block
.terminator_mut().kind
;
902 if let TerminatorKind
::GeneratorDrop
= *kind
{
903 *kind
= TerminatorKind
::Return
;
907 // Replace the return variable
908 body
.local_decls
[RETURN_PLACE
] = LocalDecl
{
909 mutability
: Mutability
::Mut
,
911 user_ty
: UserTypeProjections
::none(),
915 local_info
: LocalInfo
::Other
,
918 make_generator_state_argument_indirect(tcx
, def_id
, &mut body
);
920 // Change the generator argument from &mut to *mut
921 body
.local_decls
[self_arg()] = LocalDecl
{
922 mutability
: Mutability
::Mut
,
923 ty
: tcx
.mk_ptr(ty
::TypeAndMut { ty: gen_ty, mutbl: hir::Mutability::Mut }
),
924 user_ty
: UserTypeProjections
::none(),
928 local_info
: LocalInfo
::Other
,
930 if tcx
.sess
.opts
.debugging_opts
.mir_emit_retag
{
931 // Alias tracking must know we changed the type
932 body
.basic_blocks_mut()[START_BLOCK
].statements
.insert(
936 kind
: StatementKind
::Retag(RetagKind
::Raw
, box Place
::from(self_arg())),
941 no_landing_pads(tcx
, &mut body
);
943 // Make sure we remove dead blocks to remove
944 // unrelated code from the resume part of the function
945 simplify
::remove_dead_blocks(&mut body
);
947 dump_mir(tcx
, None
, "generator_drop", &0, source
, &mut body
, |_
, _
| Ok(()));
952 fn insert_term_block
<'tcx
>(
953 body
: &mut BodyAndCache
<'tcx
>,
954 kind
: TerminatorKind
<'tcx
>,
956 let term_block
= BasicBlock
::new(body
.basic_blocks().len());
957 let source_info
= source_info(body
);
958 body
.basic_blocks_mut().push(BasicBlockData
{
959 statements
: Vec
::new(),
960 terminator
: Some(Terminator { source_info, kind }
),
966 fn insert_panic_block
<'tcx
>(
968 body
: &mut BodyAndCache
<'tcx
>,
969 message
: AssertMessage
<'tcx
>,
971 let assert_block
= BasicBlock
::new(body
.basic_blocks().len());
972 let term
= TerminatorKind
::Assert
{
973 cond
: Operand
::Constant(box Constant
{
976 literal
: ty
::Const
::from_bool(tcx
, false),
980 target
: assert_block
,
984 let source_info
= source_info(body
);
985 body
.basic_blocks_mut().push(BasicBlockData
{
986 statements
: Vec
::new(),
987 terminator
: Some(Terminator { source_info, kind: term }
),
994 fn create_generator_resume_function
<'tcx
>(
996 transform
: TransformVisitor
<'tcx
>,
998 source
: MirSource
<'tcx
>,
999 body
: &mut BodyAndCache
<'tcx
>,
1001 // Poison the generator when it unwinds
1002 for block
in body
.basic_blocks_mut() {
1003 let source_info
= block
.terminator().source_info
;
1004 if let &TerminatorKind
::Resume
= &block
.terminator().kind
{
1005 block
.statements
.push(transform
.set_discr(VariantIdx
::new(POISONED
), source_info
));
1009 let mut cases
= create_cases(body
, &transform
, Operation
::Resume
);
1011 use rustc
::mir
::AssertKind
::{ResumedAfterPanic, ResumedAfterReturn}
;
1013 // Jump to the entry point on the unresumed
1014 cases
.insert(0, (UNRESUMED
, BasicBlock
::new(0)));
1016 // Panic when resumed on the returned or poisoned state
1017 let generator_kind
= body
.generator_kind
.unwrap();
1018 cases
.insert(1, (RETURNED
, insert_panic_block(tcx
, body
, ResumedAfterReturn(generator_kind
))));
1019 cases
.insert(2, (POISONED
, insert_panic_block(tcx
, body
, ResumedAfterPanic(generator_kind
))));
1021 insert_switch(body
, cases
, &transform
, TerminatorKind
::Unreachable
);
1023 make_generator_state_argument_indirect(tcx
, def_id
, body
);
1024 make_generator_state_argument_pinned(tcx
, body
);
1026 no_landing_pads(tcx
, body
);
1028 // Make sure we remove dead blocks to remove
1029 // unrelated code from the drop part of the function
1030 simplify
::remove_dead_blocks(body
);
1032 dump_mir(tcx
, None
, "generator_resume", &0, source
, body
, |_
, _
| Ok(()));
1035 fn source_info(body
: &Body
<'_
>) -> SourceInfo
{
1036 SourceInfo { span: body.span, scope: OUTERMOST_SOURCE_SCOPE }
1039 fn insert_clean_drop(body
: &mut BodyAndCache
<'_
>) -> BasicBlock
{
1040 let return_block
= insert_term_block(body
, TerminatorKind
::Return
);
1042 // Create a block to destroy an unresumed generators. This can only destroy upvars.
1043 let drop_clean
= BasicBlock
::new(body
.basic_blocks().len());
1044 let term
= TerminatorKind
::Drop
{
1045 location
: Place
::from(self_arg()),
1046 target
: return_block
,
1049 let source_info
= source_info(body
);
1050 body
.basic_blocks_mut().push(BasicBlockData
{
1051 statements
: Vec
::new(),
1052 terminator
: Some(Terminator { source_info, kind: term }
),
1059 /// An operation that can be performed on a generator.
1060 #[derive(PartialEq, Copy, Clone)]
1067 fn target_block(self, point
: &SuspensionPoint
<'_
>) -> Option
<BasicBlock
> {
1069 Operation
::Resume
=> Some(point
.resume
),
1070 Operation
::Drop
=> point
.drop
,
1075 fn create_cases
<'tcx
>(
1076 body
: &mut BodyAndCache
<'tcx
>,
1077 transform
: &TransformVisitor
<'tcx
>,
1078 operation
: Operation
,
1079 ) -> Vec
<(usize, BasicBlock
)> {
1080 let source_info
= source_info(body
);
1085 .filter_map(|point
| {
1086 // Find the target for this suspension point, if applicable
1087 operation
.target_block(point
).map(|target
| {
1088 let block
= BasicBlock
::new(body
.basic_blocks().len());
1089 let mut statements
= Vec
::new();
1091 // Create StorageLive instructions for locals with live storage
1092 for i
in 0..(body
.local_decls
.len()) {
1094 // The resume argument is live on function entry. Don't insert a
1095 // `StorageLive`, or the following `Assign` will read from uninitialized
1100 let l
= Local
::new(i
);
1101 if point
.storage_liveness
.contains(l
) && !transform
.remap
.contains_key(&l
) {
1103 .push(Statement { source_info, kind: StatementKind::StorageLive(l) }
);
1107 if operation
== Operation
::Resume
{
1108 // Move the resume argument to the destination place of the `Yield` terminator
1109 let resume_arg
= Local
::new(2); // 0 = return, 1 = self
1110 statements
.push(Statement
{
1112 kind
: StatementKind
::Assign(box (
1114 Rvalue
::Use(Operand
::Move(resume_arg
.into())),
1119 // Then jump to the real target
1120 body
.basic_blocks_mut().push(BasicBlockData
{
1122 terminator
: Some(Terminator
{
1124 kind
: TerminatorKind
::Goto { target }
,
1129 (point
.state
, block
)
1135 impl<'tcx
> MirPass
<'tcx
> for StateTransform
{
1136 fn run_pass(&self, tcx
: TyCtxt
<'tcx
>, source
: MirSource
<'tcx
>, body
: &mut BodyAndCache
<'tcx
>) {
1137 let yield_ty
= if let Some(yield_ty
) = body
.yield_ty
{
1140 // This only applies to generators
1144 assert
!(body
.generator_drop
.is_none());
1146 let def_id
= source
.def_id();
1148 // The first argument is the generator type passed by value
1149 let gen_ty
= body
.local_decls
.raw
[1].ty
;
1151 // Get the interior types and substs which typeck computed
1152 let (upvars
, interior
, discr_ty
, movable
) = match gen_ty
.kind
{
1153 ty
::Generator(_
, substs
, movability
) => {
1154 let substs
= substs
.as_generator();
1156 substs
.upvar_tys(def_id
, tcx
).collect(),
1157 substs
.witness(def_id
, tcx
),
1158 substs
.discr_ty(tcx
),
1159 movability
== hir
::Movability
::Movable
,
1165 // Compute GeneratorState<yield_ty, return_ty>
1166 let state_did
= tcx
.lang_items().gen_state().unwrap();
1167 let state_adt_ref
= tcx
.adt_def(state_did
);
1168 let state_substs
= tcx
.intern_substs(&[yield_ty
.into(), body
.return_ty().into()]);
1169 let ret_ty
= tcx
.mk_adt(state_adt_ref
, state_substs
);
1171 // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
1172 // RETURN_PLACE then is a fresh unused local with type ret_ty.
1173 let new_ret_local
= replace_local(RETURN_PLACE
, ret_ty
, body
, tcx
);
1175 // We also replace the resume argument and insert an `Assign`.
1176 // This is needed because the resume argument `_2` might be live across a `yield`, in which
1177 // case there is no `Assign` to it that the transform can turn into a store to the generator
1178 // state. After the yield the slot in the generator state would then be uninitialized.
1179 let resume_local
= Local
::new(2);
1180 let new_resume_local
=
1181 replace_local(resume_local
, body
.local_decls
[resume_local
].ty
, body
, tcx
);
1183 // When first entering the generator, move the resume argument into its new local.
1184 let source_info
= source_info(body
);
1185 let stmts
= &mut body
.basic_blocks_mut()[BasicBlock
::new(0)].statements
;
1190 kind
: StatementKind
::Assign(box (
1191 new_resume_local
.into(),
1192 Rvalue
::Use(Operand
::Move(resume_local
.into())),
1197 // Extract locals which are live across suspension point into `layout`
1198 // `remap` gives a mapping from local indices onto generator struct indices
1199 // `storage_liveness` tells us which locals have live storage at suspension points
1200 let (remap
, layout
, storage_liveness
) =
1201 compute_layout(tcx
, source
, &upvars
, interior
, movable
, body
);
1203 // Run the transformation which converts Places from Local to generator struct
1204 // accesses for locals in `remap`.
1205 // It also rewrites `return x` and `yield y` as writing a new generator state and returning
1206 // GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
1207 let mut transform
= TransformVisitor
{
1213 suspension_points
: Vec
::new(),
1217 transform
.visit_body(body
);
1219 // Update our MIR struct to reflect the changes we've made
1220 body
.yield_ty
= None
;
1221 body
.arg_count
= 2; // self, resume arg
1222 body
.spread_arg
= None
;
1223 body
.generator_layout
= Some(layout
);
1225 // Insert `drop(generator_struct)` which is used to drop upvars for generators in
1226 // the unresumed state.
1227 // This is expanded to a drop ladder in `elaborate_generator_drops`.
1228 let drop_clean
= insert_clean_drop(body
);
1230 dump_mir(tcx
, None
, "generator_pre-elab", &0, source
, body
, |_
, _
| Ok(()));
1232 // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
1233 // If any upvars are moved out of, drop elaboration will handle upvar destruction.
1234 // However we need to also elaborate the code generated by `insert_clean_drop`.
1235 elaborate_generator_drops(tcx
, def_id
, body
);
1237 dump_mir(tcx
, None
, "generator_post-transform", &0, source
, body
, |_
, _
| Ok(()));
1239 // Create a copy of our MIR and use it to create the drop shim for the generator
1241 create_generator_drop_shim(tcx
, &transform
, def_id
, source
, gen_ty
, body
, drop_clean
);
1243 body
.generator_drop
= Some(box drop_shim
);
1245 // Create the Generator::resume function
1246 create_generator_resume_function(tcx
, transform
, def_id
, source
, body
);