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
::{self, 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 crate::util
::storage
;
60 use rustc_data_structures
::fx
::FxHashMap
;
62 use rustc_hir
::def_id
::DefId
;
63 use rustc_index
::bit_set
::{BitMatrix, BitSet}
;
64 use rustc_index
::vec
::{Idx, IndexVec}
;
65 use rustc_middle
::mir
::visit
::{MutVisitor, PlaceContext}
;
66 use rustc_middle
::mir
::*;
67 use rustc_middle
::ty
::subst
::SubstsRef
;
68 use rustc_middle
::ty
::GeneratorSubsts
;
69 use rustc_middle
::ty
::{self, AdtDef, Ty, TyCtxt}
;
70 use rustc_target
::abi
::VariantIdx
;
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, local
: &mut Local
, _
: PlaceContext
, _
: Location
) {
88 if *local
== self.from
{
94 struct DerefArgVisitor
<'tcx
> {
98 impl<'tcx
> MutVisitor
<'tcx
> for DerefArgVisitor
<'tcx
> {
99 fn tcx(&self) -> TyCtxt
<'tcx
> {
103 fn visit_local(&mut self, local
: &mut Local
, _
: PlaceContext
, _
: Location
) {
104 assert_ne
!(*local
, SELF_ARG
);
107 fn visit_place(&mut self, place
: &mut Place
<'tcx
>, context
: PlaceContext
, location
: Location
) {
108 if place
.local
== SELF_ARG
{
113 projection
: self.tcx().intern_place_elems(&[ProjectionElem
::Deref
]),
118 self.visit_place_base(&mut place
.local
, context
, location
);
120 for elem
in place
.projection
.iter() {
121 if let PlaceElem
::Index(local
) = elem
{
122 assert_ne
!(*local
, SELF_ARG
);
129 struct PinArgVisitor
<'tcx
> {
130 ref_gen_ty
: Ty
<'tcx
>,
134 impl<'tcx
> MutVisitor
<'tcx
> for PinArgVisitor
<'tcx
> {
135 fn tcx(&self) -> TyCtxt
<'tcx
> {
139 fn visit_local(&mut self, local
: &mut Local
, _
: PlaceContext
, _
: Location
) {
140 assert_ne
!(*local
, SELF_ARG
);
143 fn visit_place(&mut self, place
: &mut Place
<'tcx
>, context
: PlaceContext
, location
: Location
) {
144 if place
.local
== SELF_ARG
{
149 projection
: self.tcx().intern_place_elems(&[ProjectionElem
::Field(
157 self.visit_place_base(&mut place
.local
, context
, location
);
159 for elem
in place
.projection
.iter() {
160 if let PlaceElem
::Index(local
) = elem
{
161 assert_ne
!(*local
, SELF_ARG
);
168 fn replace_base
<'tcx
>(place
: &mut Place
<'tcx
>, new_base
: Place
<'tcx
>, tcx
: TyCtxt
<'tcx
>) {
169 place
.local
= new_base
.local
;
171 let mut new_projection
= new_base
.projection
.to_vec();
172 new_projection
.append(&mut place
.projection
.to_vec());
174 place
.projection
= tcx
.intern_place_elems(&new_projection
);
177 const SELF_ARG
: Local
= Local
::from_u32(1);
179 /// Generator has not been resumed yet.
180 const UNRESUMED
: usize = GeneratorSubsts
::UNRESUMED
;
181 /// Generator has returned / is completed.
182 const RETURNED
: usize = GeneratorSubsts
::RETURNED
;
183 /// Generator has panicked and is poisoned.
184 const POISONED
: usize = GeneratorSubsts
::POISONED
;
186 /// A `yield` point in the generator.
187 struct SuspensionPoint
<'tcx
> {
188 /// State discriminant used when suspending or resuming at this point.
190 /// The block to jump to after resumption.
192 /// Where to move the resume argument after resumption.
193 resume_arg
: Place
<'tcx
>,
194 /// Which block to jump to if the generator is dropped in this state.
195 drop
: Option
<BasicBlock
>,
196 /// Set of locals that have live storage while at this suspension point.
197 storage_liveness
: liveness
::LiveVarSet
,
200 struct TransformVisitor
<'tcx
> {
202 state_adt_ref
: &'tcx AdtDef
,
203 state_substs
: SubstsRef
<'tcx
>,
205 // The type of the discriminant in the generator struct
208 // Mapping from Local to (type of local, generator struct index)
209 // FIXME(eddyb) This should use `IndexVec<Local, Option<_>>`.
210 remap
: FxHashMap
<Local
, (Ty
<'tcx
>, VariantIdx
, usize)>,
212 // A map from a suspension point in a block to the locals which have live storage at that point
213 // FIXME(eddyb) This should use `IndexVec<BasicBlock, Option<_>>`.
214 storage_liveness
: FxHashMap
<BasicBlock
, liveness
::LiveVarSet
>,
216 // A list of suspension points, generated during the transform
217 suspension_points
: Vec
<SuspensionPoint
<'tcx
>>,
219 // The set of locals that have no `StorageLive`/`StorageDead` annotations.
220 always_live_locals
: storage
::AlwaysLiveLocals
,
222 // The original RETURN_PLACE local
223 new_ret_local
: Local
,
226 impl TransformVisitor
<'tcx
> {
227 // Make a GeneratorState rvalue
228 fn make_state(&self, idx
: VariantIdx
, val
: Operand
<'tcx
>) -> Rvalue
<'tcx
> {
229 let adt
= AggregateKind
::Adt(self.state_adt_ref
, idx
, self.state_substs
, None
, None
);
230 Rvalue
::Aggregate(box adt
, vec
![val
])
233 // Create a Place referencing a generator struct field
234 fn make_field(&self, variant_index
: VariantIdx
, idx
: usize, ty
: Ty
<'tcx
>) -> Place
<'tcx
> {
235 let self_place
= Place
::from(SELF_ARG
);
236 let base
= self.tcx
.mk_place_downcast_unnamed(self_place
, variant_index
);
237 let mut projection
= base
.projection
.to_vec();
238 projection
.push(ProjectionElem
::Field(Field
::new(idx
), ty
));
240 Place { local: base.local, projection: self.tcx.intern_place_elems(&projection) }
243 // Create a statement which changes the discriminant
244 fn set_discr(&self, state_disc
: VariantIdx
, source_info
: SourceInfo
) -> Statement
<'tcx
> {
245 let self_place
= Place
::from(SELF_ARG
);
248 kind
: StatementKind
::SetDiscriminant
{
249 place
: box self_place
,
250 variant_index
: state_disc
,
255 // Create a statement which reads the discriminant into a temporary
256 fn get_discr(&self, body
: &mut Body
<'tcx
>) -> (Statement
<'tcx
>, Place
<'tcx
>) {
257 let temp_decl
= LocalDecl
::new_internal(self.tcx
.types
.isize, body
.span
);
258 let local_decls_len
= body
.local_decls
.push(temp_decl
);
259 let temp
= Place
::from(local_decls_len
);
261 let self_place
= Place
::from(SELF_ARG
);
262 let assign
= Statement
{
263 source_info
: source_info(body
),
264 kind
: StatementKind
::Assign(box (temp
, Rvalue
::Discriminant(self_place
))),
270 impl MutVisitor
<'tcx
> for TransformVisitor
<'tcx
> {
271 fn tcx(&self) -> TyCtxt
<'tcx
> {
275 fn visit_local(&mut self, local
: &mut Local
, _
: PlaceContext
, _
: Location
) {
276 assert_eq
!(self.remap
.get(local
), None
);
281 place
: &mut Place
<'tcx
>,
282 _context
: PlaceContext
,
285 // Replace an Local in the remap with a generator struct access
286 if let Some(&(ty
, variant_index
, idx
)) = self.remap
.get(&place
.local
) {
287 replace_base(place
, self.make_field(variant_index
, idx
, ty
), self.tcx
);
291 fn visit_basic_block_data(&mut self, block
: BasicBlock
, data
: &mut BasicBlockData
<'tcx
>) {
292 // Remove StorageLive and StorageDead statements for remapped locals
293 data
.retain_statements(|s
| match s
.kind
{
294 StatementKind
::StorageLive(l
) | StatementKind
::StorageDead(l
) => {
295 !self.remap
.contains_key(&l
)
300 let ret_val
= match data
.terminator().kind
{
301 TerminatorKind
::Return
=> Some((
304 Operand
::Move(Place
::from(self.new_ret_local
)),
307 TerminatorKind
::Yield { ref value, resume, resume_arg, drop }
=> {
308 Some((VariantIdx
::new(0), Some((resume
, resume_arg
)), value
.clone(), drop
))
313 if let Some((state_idx
, resume
, v
, drop
)) = ret_val
{
314 let source_info
= data
.terminator().source_info
;
315 // We must assign the value first in case it gets declared dead below
316 data
.statements
.push(Statement
{
318 kind
: StatementKind
::Assign(box (
319 Place
::return_place(),
320 self.make_state(state_idx
, v
),
323 let state
= if let Some((resume
, resume_arg
)) = resume
{
325 let state
= 3 + self.suspension_points
.len();
327 // The resume arg target location might itself be remapped if its base local is
328 // live across a yield.
330 if let Some(&(ty
, variant
, idx
)) = self.remap
.get(&resume_arg
.local
) {
331 self.make_field(variant
, idx
, ty
)
336 self.suspension_points
.push(SuspensionPoint
{
341 storage_liveness
: self.storage_liveness
.get(&block
).unwrap().clone(),
344 VariantIdx
::new(state
)
347 VariantIdx
::new(RETURNED
) // state for returned
349 data
.statements
.push(self.set_discr(state
, source_info
));
350 data
.terminator_mut().kind
= TerminatorKind
::Return
;
353 self.super_basic_block_data(block
, data
);
357 fn make_generator_state_argument_indirect
<'tcx
>(tcx
: TyCtxt
<'tcx
>, body
: &mut BodyAndCache
<'tcx
>) {
358 let gen_ty
= body
.local_decls
.raw
[1].ty
;
361 tcx
.mk_ref(tcx
.lifetimes
.re_erased
, ty
::TypeAndMut { ty: gen_ty, mutbl: Mutability::Mut }
);
363 // Replace the by value generator argument
364 body
.local_decls
.raw
[1].ty
= ref_gen_ty
;
366 // Add a deref to accesses of the generator state
367 DerefArgVisitor { tcx }
.visit_body(body
);
370 fn make_generator_state_argument_pinned
<'tcx
>(tcx
: TyCtxt
<'tcx
>, body
: &mut BodyAndCache
<'tcx
>) {
371 let ref_gen_ty
= body
.local_decls
.raw
[1].ty
;
373 let pin_did
= tcx
.lang_items().pin_type().unwrap();
374 let pin_adt_ref
= tcx
.adt_def(pin_did
);
375 let substs
= tcx
.intern_substs(&[ref_gen_ty
.into()]);
376 let pin_ref_gen_ty
= tcx
.mk_adt(pin_adt_ref
, substs
);
378 // Replace the by ref generator argument
379 body
.local_decls
.raw
[1].ty
= pin_ref_gen_ty
;
381 // Add the Pin field access to accesses of the generator state
382 PinArgVisitor { ref_gen_ty, tcx }
.visit_body(body
);
385 /// Allocates a new local and replaces all references of `local` with it. Returns the new local.
387 /// `local` will be changed to a new local decl with type `ty`.
389 /// Note that the new local will be uninitialized. It is the caller's responsibility to assign some
390 /// valid value to it before its first use.
391 fn replace_local
<'tcx
>(
394 body
: &mut BodyAndCache
<'tcx
>,
397 let source_info
= source_info(body
);
398 let new_decl
= LocalDecl
{
399 mutability
: Mutability
::Mut
,
401 user_ty
: UserTypeProjections
::none(),
405 local_info
: LocalInfo
::Other
,
407 let new_local
= Local
::new(body
.local_decls
.len());
408 body
.local_decls
.push(new_decl
);
409 body
.local_decls
.swap(local
, new_local
);
411 RenameLocalVisitor { from: local, to: new_local, tcx }
.visit_body(body
);
416 struct LivenessInfo
{
417 /// Which locals are live across any suspension point.
419 /// GeneratorSavedLocal is indexed in terms of the elements in this set;
420 /// i.e. GeneratorSavedLocal::new(1) corresponds to the second local
421 /// included in this set.
422 live_locals
: liveness
::LiveVarSet
,
424 /// The set of saved locals live at each suspension point.
425 live_locals_at_suspension_points
: Vec
<BitSet
<GeneratorSavedLocal
>>,
427 /// For every saved local, the set of other saved locals that are
428 /// storage-live at the same time as this local. We cannot overlap locals in
429 /// the layout which have conflicting storage.
430 storage_conflicts
: BitMatrix
<GeneratorSavedLocal
, GeneratorSavedLocal
>,
432 /// For every suspending block, the locals which are storage-live across
433 /// that suspension point.
434 storage_liveness
: FxHashMap
<BasicBlock
, liveness
::LiveVarSet
>,
437 fn locals_live_across_suspend_points(
439 body
: ReadOnlyBodyAndCache
<'_
, 'tcx
>,
440 source
: MirSource
<'tcx
>,
441 always_live_locals
: &storage
::AlwaysLiveLocals
,
444 let def_id
= source
.def_id();
445 let body_ref
: &Body
<'_
> = &body
;
447 // Calculate when MIR locals have live storage. This gives us an upper bound of their
449 let mut storage_live
= MaybeStorageLive
::new(always_live_locals
.clone())
450 .into_engine(tcx
, body_ref
, def_id
)
451 .iterate_to_fixpoint()
452 .into_results_cursor(body_ref
);
454 // Calculate the MIR locals which have been previously
455 // borrowed (even if they are still active).
456 let borrowed_locals_results
=
457 MaybeBorrowedLocals
::all_borrows().into_engine(tcx
, body_ref
, def_id
).iterate_to_fixpoint();
459 let mut borrowed_locals_cursor
=
460 dataflow
::ResultsCursor
::new(body_ref
, &borrowed_locals_results
);
462 // Calculate the MIR locals that we actually need to keep storage around
464 let requires_storage_results
= MaybeRequiresStorage
::new(body
, &borrowed_locals_results
)
465 .into_engine(tcx
, body_ref
, def_id
)
466 .iterate_to_fixpoint();
467 let mut requires_storage_cursor
=
468 dataflow
::ResultsCursor
::new(body_ref
, &requires_storage_results
);
470 // Calculate the liveness of MIR locals ignoring borrows.
471 let mut live_locals
= liveness
::LiveVarSet
::new_empty(body
.local_decls
.len());
472 let mut liveness
= liveness
::liveness_of_locals(body
);
473 liveness
::dump_mir(tcx
, "generator_liveness", source
, body_ref
, &liveness
);
475 let mut storage_liveness_map
= FxHashMap
::default();
476 let mut live_locals_at_suspension_points
= Vec
::new();
478 for (block
, data
) in body
.basic_blocks().iter_enumerated() {
479 if let TerminatorKind
::Yield { .. }
= data
.terminator().kind
{
480 let loc
= Location { block, statement_index: data.statements.len() }
;
483 // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
484 // This is correct for movable generators since borrows cannot live across
485 // suspension points. However for immovable generators we need to account for
486 // borrows, so we conseratively assume that all borrowed locals are live until
487 // we find a StorageDead statement referencing the locals.
488 // To do this we just union our `liveness` result with `borrowed_locals`, which
489 // contains all the locals which has been borrowed before this suspension point.
490 // If a borrow is converted to a raw reference, we must also assume that it lives
491 // forever. Note that the final liveness is still bounded by the storage liveness
492 // of the local, which happens using the `intersect` operation below.
493 borrowed_locals_cursor
.seek_before(loc
);
494 liveness
.outs
[block
].union(borrowed_locals_cursor
.get());
497 storage_live
.seek_before(loc
);
498 let mut storage_liveness
= storage_live
.get().clone();
500 // Later passes handle the generator's `self` argument separately.
501 storage_liveness
.remove(SELF_ARG
);
503 // Store the storage liveness for later use so we can restore the state
504 // after a suspension point
505 storage_liveness_map
.insert(block
, storage_liveness
);
507 requires_storage_cursor
.seek_before(loc
);
508 let storage_required
= requires_storage_cursor
.get().clone();
510 // Locals live are live at this point only if they are used across
511 // suspension points (the `liveness` variable)
512 // and their storage is required (the `storage_required` variable)
513 let mut live_locals_here
= storage_required
;
514 live_locals_here
.intersect(&liveness
.outs
[block
]);
516 // The generator argument is ignored.
517 live_locals_here
.remove(SELF_ARG
);
519 debug
!("loc = {:?}, live_locals_here = {:?}", loc
, live_locals_here
);
521 // Add the locals live at this suspension point to the set of locals which live across
522 // any suspension points
523 live_locals
.union(&live_locals_here
);
525 live_locals_at_suspension_points
.push(live_locals_here
);
528 debug
!("live_locals = {:?}", live_locals
);
530 // Renumber our liveness_map bitsets to include only the locals we are
532 let live_locals_at_suspension_points
= live_locals_at_suspension_points
534 .map(|live_here
| renumber_bitset(&live_here
, &live_locals
))
537 let storage_conflicts
= compute_storage_conflicts(
540 always_live_locals
.clone(),
541 requires_storage_results
,
546 live_locals_at_suspension_points
,
548 storage_liveness
: storage_liveness_map
,
552 /// Renumbers the items present in `stored_locals` and applies the renumbering
555 /// For example, if `stored_locals = [1, 3, 5]`, this would be renumbered to
556 /// `[0, 1, 2]`. Thus, if `input = [3, 5]` we would return `[1, 2]`.
558 input
: &BitSet
<Local
>,
559 stored_locals
: &liveness
::LiveVarSet
,
560 ) -> BitSet
<GeneratorSavedLocal
> {
561 assert
!(stored_locals
.superset(&input
), "{:?} not a superset of {:?}", stored_locals
, input
);
562 let mut out
= BitSet
::new_empty(stored_locals
.count());
563 for (idx
, local
) in stored_locals
.iter().enumerate() {
564 let saved_local
= GeneratorSavedLocal
::from(idx
);
565 if input
.contains(local
) {
566 out
.insert(saved_local
);
569 debug
!("renumber_bitset({:?}, {:?}) => {:?}", input
, stored_locals
, out
);
573 /// For every saved local, looks for which locals are StorageLive at the same
574 /// time. Generates a bitset for every local of all the other locals that may be
575 /// StorageLive simultaneously with that local. This is used in the layout
576 /// computation; see `GeneratorLayout` for more.
577 fn compute_storage_conflicts(
578 body
: &'mir Body
<'tcx
>,
579 stored_locals
: &liveness
::LiveVarSet
,
580 always_live_locals
: storage
::AlwaysLiveLocals
,
581 requires_storage
: dataflow
::Results
<'tcx
, MaybeRequiresStorage
<'mir
, 'tcx
>>,
582 ) -> BitMatrix
<GeneratorSavedLocal
, GeneratorSavedLocal
> {
583 assert_eq
!(body
.local_decls
.len(), stored_locals
.domain_size());
585 debug
!("compute_storage_conflicts({:?})", body
.span
);
586 debug
!("always_live = {:?}", always_live_locals
);
588 // Locals that are always live or ones that need to be stored across
589 // suspension points are not eligible for overlap.
590 let mut ineligible_locals
= always_live_locals
.into_inner();
591 ineligible_locals
.intersect(stored_locals
);
593 // Compute the storage conflicts for all eligible locals.
594 let mut visitor
= StorageConflictVisitor
{
596 stored_locals
: &stored_locals
,
597 local_conflicts
: BitMatrix
::from_row_n(&ineligible_locals
, body
.local_decls
.len()),
600 // Visit only reachable basic blocks. The exact order is not important.
601 let reachable_blocks
= traversal
::preorder(body
).map(|(bb
, _
)| bb
);
602 requires_storage
.visit_with(body
, reachable_blocks
, &mut visitor
);
604 let local_conflicts
= visitor
.local_conflicts
;
606 // Compress the matrix using only stored locals (Local -> GeneratorSavedLocal).
608 // NOTE: Today we store a full conflict bitset for every local. Technically
609 // this is twice as many bits as we need, since the relation is symmetric.
610 // However, in practice these bitsets are not usually large. The layout code
611 // also needs to keep track of how many conflicts each local has, so it's
612 // simpler to keep it this way for now.
613 let mut storage_conflicts
= BitMatrix
::new(stored_locals
.count(), stored_locals
.count());
614 for (idx_a
, local_a
) in stored_locals
.iter().enumerate() {
615 let saved_local_a
= GeneratorSavedLocal
::new(idx_a
);
616 if ineligible_locals
.contains(local_a
) {
617 // Conflicts with everything.
618 storage_conflicts
.insert_all_into_row(saved_local_a
);
620 // Keep overlap information only for stored locals.
621 for (idx_b
, local_b
) in stored_locals
.iter().enumerate() {
622 let saved_local_b
= GeneratorSavedLocal
::new(idx_b
);
623 if local_conflicts
.contains(local_a
, local_b
) {
624 storage_conflicts
.insert(saved_local_a
, saved_local_b
);
632 struct StorageConflictVisitor
<'mir
, 'tcx
, 's
> {
633 body
: &'mir Body
<'tcx
>,
634 stored_locals
: &'s liveness
::LiveVarSet
,
635 // FIXME(tmandry): Consider using sparse bitsets here once we have good
636 // benchmarks for generators.
637 local_conflicts
: BitMatrix
<Local
, Local
>,
640 impl dataflow
::ResultsVisitor
<'mir
, 'tcx
> for StorageConflictVisitor
<'mir
, 'tcx
, '_
> {
641 type FlowState
= BitSet
<Local
>;
645 state
: &Self::FlowState
,
646 _statement
: &'mir Statement
<'tcx
>,
649 self.apply_state(state
, loc
);
654 state
: &Self::FlowState
,
655 _terminator
: &'mir Terminator
<'tcx
>,
658 self.apply_state(state
, loc
);
662 impl<'body
, 'tcx
, 's
> StorageConflictVisitor
<'body
, 'tcx
, 's
> {
663 fn apply_state(&mut self, flow_state
: &BitSet
<Local
>, loc
: Location
) {
664 // Ignore unreachable blocks.
665 if self.body
.basic_blocks()[loc
.block
].terminator().kind
== TerminatorKind
::Unreachable
{
669 let mut eligible_storage_live
= flow_state
.clone();
670 eligible_storage_live
.intersect(&self.stored_locals
);
672 for local
in eligible_storage_live
.iter() {
673 self.local_conflicts
.union_row_with(&eligible_storage_live
, local
);
676 if eligible_storage_live
.count() > 1 {
677 trace
!("at {:?}, eligible_storage_live={:?}", loc
, eligible_storage_live
);
682 fn compute_layout
<'tcx
>(
684 source
: MirSource
<'tcx
>,
685 upvars
: &Vec
<Ty
<'tcx
>>,
687 always_live_locals
: &storage
::AlwaysLiveLocals
,
689 body
: &mut BodyAndCache
<'tcx
>,
691 FxHashMap
<Local
, (Ty
<'tcx
>, VariantIdx
, usize)>,
692 GeneratorLayout
<'tcx
>,
693 FxHashMap
<BasicBlock
, liveness
::LiveVarSet
>,
695 // Use a liveness analysis to compute locals which are live across a suspension point
698 live_locals_at_suspension_points
,
701 } = locals_live_across_suspend_points(
709 // Erase regions from the types passed in from typeck so we can compare them with
711 let allowed_upvars
= tcx
.erase_regions(upvars
);
712 let allowed
= match interior
.kind
{
713 ty
::GeneratorWitness(s
) => tcx
.erase_late_bound_regions(&s
),
717 let param_env
= tcx
.param_env(source
.def_id());
719 for (local
, decl
) in body
.local_decls
.iter_enumerated() {
720 // Ignore locals which are internal or not live
721 if !live_locals
.contains(local
) || decl
.internal
{
724 let decl_ty
= tcx
.normalize_erasing_regions(param_env
, decl
.ty
);
726 // Sanity check that typeck knows about the type of locals which are
727 // live across a suspension point
728 if !allowed
.contains(&decl_ty
) && !allowed_upvars
.contains(&decl_ty
) {
731 "Broken MIR: generator contains type {} in MIR, \
732 but typeck only knows about {}",
739 // Gather live local types and their indices.
740 let mut locals
= IndexVec
::<GeneratorSavedLocal
, _
>::new();
741 let mut tys
= IndexVec
::<GeneratorSavedLocal
, _
>::new();
742 for (idx
, local
) in live_locals
.iter().enumerate() {
744 tys
.push(body
.local_decls
[local
].ty
);
745 debug
!("generator saved local {:?} => {:?}", GeneratorSavedLocal
::from(idx
), local
);
748 // Leave empty variants for the UNRESUMED, RETURNED, and POISONED states.
749 const RESERVED_VARIANTS
: usize = 3;
751 // Build the generator variant field list.
752 // Create a map from local indices to generator struct indices.
753 let mut variant_fields
: IndexVec
<VariantIdx
, IndexVec
<Field
, GeneratorSavedLocal
>> =
754 iter
::repeat(IndexVec
::new()).take(RESERVED_VARIANTS
).collect();
755 let mut remap
= FxHashMap
::default();
756 for (suspension_point_idx
, live_locals
) in live_locals_at_suspension_points
.iter().enumerate() {
757 let variant_index
= VariantIdx
::from(RESERVED_VARIANTS
+ suspension_point_idx
);
758 let mut fields
= IndexVec
::new();
759 for (idx
, saved_local
) in live_locals
.iter().enumerate() {
760 fields
.push(saved_local
);
761 // Note that if a field is included in multiple variants, we will
762 // just use the first one here. That's fine; fields do not move
763 // around inside generators, so it doesn't matter which variant
764 // index we access them by.
765 remap
.entry(locals
[saved_local
]).or_insert((tys
[saved_local
], variant_index
, idx
));
767 variant_fields
.push(fields
);
769 debug
!("generator variant_fields = {:?}", variant_fields
);
770 debug
!("generator storage_conflicts = {:#?}", storage_conflicts
);
772 let layout
= GeneratorLayout { field_tys: tys, variant_fields, storage_conflicts }
;
774 (remap
, layout
, storage_liveness
)
777 /// Replaces the entry point of `body` with a block that switches on the generator discriminant and
778 /// dispatches to blocks according to `cases`.
780 /// After this function, the former entry point of the function will be bb1.
781 fn insert_switch
<'tcx
>(
782 body
: &mut BodyAndCache
<'tcx
>,
783 cases
: Vec
<(usize, BasicBlock
)>,
784 transform
: &TransformVisitor
<'tcx
>,
785 default: TerminatorKind
<'tcx
>,
787 let default_block
= insert_term_block(body
, default);
788 let (assign
, discr
) = transform
.get_discr(body
);
789 let switch
= TerminatorKind
::SwitchInt
{
790 discr
: Operand
::Move(discr
),
791 switch_ty
: transform
.discr_ty
,
792 values
: Cow
::from(cases
.iter().map(|&(i
, _
)| i
as u128
).collect
::<Vec
<_
>>()),
793 targets
: cases
.iter().map(|&(_
, d
)| d
).chain(iter
::once(default_block
)).collect(),
796 let source_info
= source_info(body
);
797 body
.basic_blocks_mut().raw
.insert(
800 statements
: vec
![assign
],
801 terminator
: Some(Terminator { source_info, kind: switch }
),
806 let blocks
= body
.basic_blocks_mut().iter_mut();
808 for target
in blocks
.flat_map(|b
| b
.terminator_mut().successors_mut()) {
809 *target
= BasicBlock
::new(target
.index() + 1);
813 fn elaborate_generator_drops
<'tcx
>(
816 body
: &mut BodyAndCache
<'tcx
>,
818 use crate::shim
::DropShimElaborator
;
819 use crate::util
::elaborate_drops
::{elaborate_drop, Unwind}
;
820 use crate::util
::patch
::MirPatch
;
822 // Note that `elaborate_drops` only drops the upvars of a generator, and
823 // this is ok because `open_drop` can only be reached within that own
824 // generator's resume function.
826 let param_env
= tcx
.param_env(def_id
);
828 let mut elaborator
= DropShimElaborator { body, patch: MirPatch::new(body), tcx, param_env }
;
830 for (block
, block_data
) in body
.basic_blocks().iter_enumerated() {
831 let (target
, unwind
, source_info
) = match block_data
.terminator() {
832 Terminator { source_info, kind: TerminatorKind::Drop { location, target, unwind }
} => {
833 if let Some(local
) = location
.as_local() {
834 if local
== SELF_ARG
{
835 (target
, unwind
, source_info
)
845 let unwind
= if block_data
.is_cleanup
{
848 Unwind
::To(unwind
.unwrap_or_else(|| elaborator
.patch
.resume_block()))
853 Place
::from(SELF_ARG
),
860 elaborator
.patch
.apply(body
);
863 fn create_generator_drop_shim
<'tcx
>(
865 transform
: &TransformVisitor
<'tcx
>,
866 source
: MirSource
<'tcx
>,
868 body
: &mut BodyAndCache
<'tcx
>,
869 drop_clean
: BasicBlock
,
870 ) -> BodyAndCache
<'tcx
> {
871 let mut body
= body
.clone();
872 body
.arg_count
= 1; // make sure the resume argument is not included here
874 let source_info
= source_info(&body
);
876 let mut cases
= create_cases(&mut body
, transform
, Operation
::Drop
);
878 cases
.insert(0, (UNRESUMED
, drop_clean
));
880 // The returned state and the poisoned state fall through to the default
881 // case which is just to return
883 insert_switch(&mut body
, cases
, &transform
, TerminatorKind
::Return
);
885 for block
in body
.basic_blocks_mut() {
886 let kind
= &mut block
.terminator_mut().kind
;
887 if let TerminatorKind
::GeneratorDrop
= *kind
{
888 *kind
= TerminatorKind
::Return
;
892 // Replace the return variable
893 body
.local_decls
[RETURN_PLACE
] = LocalDecl
{
894 mutability
: Mutability
::Mut
,
896 user_ty
: UserTypeProjections
::none(),
900 local_info
: LocalInfo
::Other
,
903 make_generator_state_argument_indirect(tcx
, &mut body
);
905 // Change the generator argument from &mut to *mut
906 body
.local_decls
[SELF_ARG
] = LocalDecl
{
907 mutability
: Mutability
::Mut
,
908 ty
: tcx
.mk_ptr(ty
::TypeAndMut { ty: gen_ty, mutbl: hir::Mutability::Mut }
),
909 user_ty
: UserTypeProjections
::none(),
913 local_info
: LocalInfo
::Other
,
915 if tcx
.sess
.opts
.debugging_opts
.mir_emit_retag
{
916 // Alias tracking must know we changed the type
917 body
.basic_blocks_mut()[START_BLOCK
].statements
.insert(
921 kind
: StatementKind
::Retag(RetagKind
::Raw
, box Place
::from(SELF_ARG
)),
926 no_landing_pads(tcx
, &mut body
);
928 // Make sure we remove dead blocks to remove
929 // unrelated code from the resume part of the function
930 simplify
::remove_dead_blocks(&mut body
);
932 dump_mir(tcx
, None
, "generator_drop", &0, source
, &body
, |_
, _
| Ok(()));
937 fn insert_term_block
<'tcx
>(
938 body
: &mut BodyAndCache
<'tcx
>,
939 kind
: TerminatorKind
<'tcx
>,
941 let term_block
= BasicBlock
::new(body
.basic_blocks().len());
942 let source_info
= source_info(body
);
943 body
.basic_blocks_mut().push(BasicBlockData
{
944 statements
: Vec
::new(),
945 terminator
: Some(Terminator { source_info, kind }
),
951 fn insert_panic_block
<'tcx
>(
953 body
: &mut BodyAndCache
<'tcx
>,
954 message
: AssertMessage
<'tcx
>,
956 let assert_block
= BasicBlock
::new(body
.basic_blocks().len());
957 let term
= TerminatorKind
::Assert
{
958 cond
: Operand
::Constant(box Constant
{
961 literal
: ty
::Const
::from_bool(tcx
, false),
965 target
: assert_block
,
969 let source_info
= source_info(body
);
970 body
.basic_blocks_mut().push(BasicBlockData
{
971 statements
: Vec
::new(),
972 terminator
: Some(Terminator { source_info, kind: term }
),
979 fn can_return
<'tcx
>(tcx
: TyCtxt
<'tcx
>, body
: &Body
<'tcx
>) -> bool
{
980 // Returning from a function with an uninhabited return type is undefined behavior.
981 if body
.return_ty().conservative_is_privately_uninhabited(tcx
) {
985 // If there's a return terminator the function may return.
986 for block
in body
.basic_blocks() {
987 if let TerminatorKind
::Return
= block
.terminator().kind
{
992 // Otherwise the function can't return.
996 fn can_unwind
<'tcx
>(tcx
: TyCtxt
<'tcx
>, body
: &Body
<'tcx
>) -> bool
{
997 // Nothing can unwind when landing pads are off.
998 if tcx
.sess
.no_landing_pads() {
1002 // Unwinds can only start at certain terminators.
1003 for block
in body
.basic_blocks() {
1004 match block
.terminator().kind
{
1005 // These never unwind.
1006 TerminatorKind
::Goto { .. }
1007 | TerminatorKind
::SwitchInt { .. }
1008 | TerminatorKind
::Abort
1009 | TerminatorKind
::Return
1010 | TerminatorKind
::Unreachable
1011 | TerminatorKind
::GeneratorDrop
1012 | TerminatorKind
::FalseEdges { .. }
1013 | TerminatorKind
::FalseUnwind { .. }
=> {}
1015 // Resume will *continue* unwinding, but if there's no other unwinding terminator it
1016 // will never be reached.
1017 TerminatorKind
::Resume
=> {}
1019 TerminatorKind
::Yield { .. }
=> {
1020 unreachable
!("`can_unwind` called before generator transform")
1023 // These may unwind.
1024 TerminatorKind
::Drop { .. }
1025 | TerminatorKind
::DropAndReplace { .. }
1026 | TerminatorKind
::Call { .. }
1027 | TerminatorKind
::Assert { .. }
=> return true,
1031 // If we didn't find an unwinding terminator, the function cannot unwind.
1035 fn create_generator_resume_function
<'tcx
>(
1037 transform
: TransformVisitor
<'tcx
>,
1038 source
: MirSource
<'tcx
>,
1039 body
: &mut BodyAndCache
<'tcx
>,
1042 let can_unwind
= can_unwind(tcx
, body
);
1044 // Poison the generator when it unwinds
1046 let poison_block
= BasicBlock
::new(body
.basic_blocks().len());
1047 let source_info
= source_info(body
);
1048 body
.basic_blocks_mut().push(BasicBlockData
{
1049 statements
: vec
![transform
.set_discr(VariantIdx
::new(POISONED
), source_info
)],
1050 terminator
: Some(Terminator { source_info, kind: TerminatorKind::Resume }
),
1054 for (idx
, block
) in body
.basic_blocks_mut().iter_enumerated_mut() {
1055 let source_info
= block
.terminator().source_info
;
1057 if let TerminatorKind
::Resume
= block
.terminator().kind
{
1058 // An existing `Resume` terminator is redirected to jump to our dedicated
1059 // "poisoning block" above.
1060 if idx
!= poison_block
{
1061 *block
.terminator_mut() = Terminator
{
1063 kind
: TerminatorKind
::Goto { target: poison_block }
,
1066 } else if !block
.is_cleanup
{
1067 // Any terminators that *can* unwind but don't have an unwind target set are also
1068 // pointed at our poisoning block (unless they're part of the cleanup path).
1069 if let Some(unwind @ None
) = block
.terminator_mut().unwind_mut() {
1070 *unwind
= Some(poison_block
);
1076 let mut cases
= create_cases(body
, &transform
, Operation
::Resume
);
1078 use rustc_middle
::mir
::AssertKind
::{ResumedAfterPanic, ResumedAfterReturn}
;
1080 // Jump to the entry point on the unresumed
1081 cases
.insert(0, (UNRESUMED
, BasicBlock
::new(0)));
1083 // Panic when resumed on the returned or poisoned state
1084 let generator_kind
= body
.generator_kind
.unwrap();
1089 (POISONED
, insert_panic_block(tcx
, body
, ResumedAfterPanic(generator_kind
))),
1096 (RETURNED
, insert_panic_block(tcx
, body
, ResumedAfterReturn(generator_kind
))),
1100 insert_switch(body
, cases
, &transform
, TerminatorKind
::Unreachable
);
1102 make_generator_state_argument_indirect(tcx
, body
);
1103 make_generator_state_argument_pinned(tcx
, body
);
1105 no_landing_pads(tcx
, body
);
1107 // Make sure we remove dead blocks to remove
1108 // unrelated code from the drop part of the function
1109 simplify
::remove_dead_blocks(body
);
1111 dump_mir(tcx
, None
, "generator_resume", &0, source
, body
, |_
, _
| Ok(()));
1114 fn source_info(body
: &Body
<'_
>) -> SourceInfo
{
1115 SourceInfo { span: body.span, scope: OUTERMOST_SOURCE_SCOPE }
1118 fn insert_clean_drop(body
: &mut BodyAndCache
<'_
>) -> BasicBlock
{
1119 let return_block
= insert_term_block(body
, TerminatorKind
::Return
);
1121 // Create a block to destroy an unresumed generators. This can only destroy upvars.
1122 let drop_clean
= BasicBlock
::new(body
.basic_blocks().len());
1123 let term
= TerminatorKind
::Drop
{
1124 location
: Place
::from(SELF_ARG
),
1125 target
: return_block
,
1128 let source_info
= source_info(body
);
1129 body
.basic_blocks_mut().push(BasicBlockData
{
1130 statements
: Vec
::new(),
1131 terminator
: Some(Terminator { source_info, kind: term }
),
1138 /// An operation that can be performed on a generator.
1139 #[derive(PartialEq, Copy, Clone)]
1146 fn target_block(self, point
: &SuspensionPoint
<'_
>) -> Option
<BasicBlock
> {
1148 Operation
::Resume
=> Some(point
.resume
),
1149 Operation
::Drop
=> point
.drop
,
1154 fn create_cases
<'tcx
>(
1155 body
: &mut BodyAndCache
<'tcx
>,
1156 transform
: &TransformVisitor
<'tcx
>,
1157 operation
: Operation
,
1158 ) -> Vec
<(usize, BasicBlock
)> {
1159 let source_info
= source_info(body
);
1164 .filter_map(|point
| {
1165 // Find the target for this suspension point, if applicable
1166 operation
.target_block(point
).map(|target
| {
1167 let block
= BasicBlock
::new(body
.basic_blocks().len());
1168 let mut statements
= Vec
::new();
1170 // Create StorageLive instructions for locals with live storage
1171 for i
in 0..(body
.local_decls
.len()) {
1173 // The resume argument is live on function entry. Don't insert a
1174 // `StorageLive`, or the following `Assign` will read from uninitialized
1179 let l
= Local
::new(i
);
1180 let needs_storage_live
= point
.storage_liveness
.contains(l
)
1181 && !transform
.remap
.contains_key(&l
)
1182 && !transform
.always_live_locals
.contains(l
);
1183 if needs_storage_live
{
1185 .push(Statement { source_info, kind: StatementKind::StorageLive(l) }
);
1189 if operation
== Operation
::Resume
{
1190 // Move the resume argument to the destination place of the `Yield` terminator
1191 let resume_arg
= Local
::new(2); // 0 = return, 1 = self
1192 statements
.push(Statement
{
1194 kind
: StatementKind
::Assign(box (
1196 Rvalue
::Use(Operand
::Move(resume_arg
.into())),
1201 // Then jump to the real target
1202 body
.basic_blocks_mut().push(BasicBlockData
{
1204 terminator
: Some(Terminator
{
1206 kind
: TerminatorKind
::Goto { target }
,
1211 (point
.state
, block
)
1217 impl<'tcx
> MirPass
<'tcx
> for StateTransform
{
1218 fn run_pass(&self, tcx
: TyCtxt
<'tcx
>, source
: MirSource
<'tcx
>, body
: &mut BodyAndCache
<'tcx
>) {
1219 let yield_ty
= if let Some(yield_ty
) = body
.yield_ty
{
1222 // This only applies to generators
1226 assert
!(body
.generator_drop
.is_none());
1228 let def_id
= source
.def_id();
1230 // The first argument is the generator type passed by value
1231 let gen_ty
= body
.local_decls
.raw
[1].ty
;
1233 // Get the interior types and substs which typeck computed
1234 let (upvars
, interior
, discr_ty
, movable
) = match gen_ty
.kind
{
1235 ty
::Generator(_
, substs
, movability
) => {
1236 let substs
= substs
.as_generator();
1238 substs
.upvar_tys().collect(),
1240 substs
.discr_ty(tcx
),
1241 movability
== hir
::Movability
::Movable
,
1247 // Compute GeneratorState<yield_ty, return_ty>
1248 let state_did
= tcx
.lang_items().gen_state().unwrap();
1249 let state_adt_ref
= tcx
.adt_def(state_did
);
1250 let state_substs
= tcx
.intern_substs(&[yield_ty
.into(), body
.return_ty().into()]);
1251 let ret_ty
= tcx
.mk_adt(state_adt_ref
, state_substs
);
1253 // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
1254 // RETURN_PLACE then is a fresh unused local with type ret_ty.
1255 let new_ret_local
= replace_local(RETURN_PLACE
, ret_ty
, body
, tcx
);
1257 // We also replace the resume argument and insert an `Assign`.
1258 // This is needed because the resume argument `_2` might be live across a `yield`, in which
1259 // case there is no `Assign` to it that the transform can turn into a store to the generator
1260 // state. After the yield the slot in the generator state would then be uninitialized.
1261 let resume_local
= Local
::new(2);
1262 let new_resume_local
=
1263 replace_local(resume_local
, body
.local_decls
[resume_local
].ty
, body
, tcx
);
1265 // When first entering the generator, move the resume argument into its new local.
1266 let source_info
= source_info(body
);
1267 let stmts
= &mut body
.basic_blocks_mut()[BasicBlock
::new(0)].statements
;
1272 kind
: StatementKind
::Assign(box (
1273 new_resume_local
.into(),
1274 Rvalue
::Use(Operand
::Move(resume_local
.into())),
1279 let always_live_locals
= storage
::AlwaysLiveLocals
::new(&body
);
1281 // Extract locals which are live across suspension point into `layout`
1282 // `remap` gives a mapping from local indices onto generator struct indices
1283 // `storage_liveness` tells us which locals have live storage at suspension points
1284 let (remap
, layout
, storage_liveness
) =
1285 compute_layout(tcx
, source
, &upvars
, interior
, &always_live_locals
, movable
, body
);
1287 let can_return
= can_return(tcx
, body
);
1289 // Run the transformation which converts Places from Local to generator struct
1290 // accesses for locals in `remap`.
1291 // It also rewrites `return x` and `yield y` as writing a new generator state and returning
1292 // GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
1293 let mut transform
= TransformVisitor
{
1300 suspension_points
: Vec
::new(),
1304 transform
.visit_body(body
);
1306 // Update our MIR struct to reflect the changes we've made
1307 body
.yield_ty
= None
;
1308 body
.arg_count
= 2; // self, resume arg
1309 body
.spread_arg
= None
;
1310 body
.generator_layout
= Some(layout
);
1312 // Insert `drop(generator_struct)` which is used to drop upvars for generators in
1313 // the unresumed state.
1314 // This is expanded to a drop ladder in `elaborate_generator_drops`.
1315 let drop_clean
= insert_clean_drop(body
);
1317 dump_mir(tcx
, None
, "generator_pre-elab", &0, source
, body
, |_
, _
| Ok(()));
1319 // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
1320 // If any upvars are moved out of, drop elaboration will handle upvar destruction.
1321 // However we need to also elaborate the code generated by `insert_clean_drop`.
1322 elaborate_generator_drops(tcx
, def_id
, body
);
1324 dump_mir(tcx
, None
, "generator_post-transform", &0, source
, body
, |_
, _
| Ok(()));
1326 // Create a copy of our MIR and use it to create the drop shim for the generator
1328 create_generator_drop_shim(tcx
, &transform
, source
, gen_ty
, body
, drop_clean
);
1330 body
.generator_drop
= Some(box drop_shim
);
1332 // Create the Generator::resume function
1333 create_generator_resume_function(tcx
, transform
, source
, body
, can_return
);