]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/generator.rs
Rollup merge of #103488 - oli-obk:impl_trait_for_tait, r=lcnr
[rust.git] / compiler / rustc_mir_transform / src / generator.rs
1 //! This is the implementation of the pass which transforms generators into state machines.
2 //!
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.
13 //!
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.
21 //!     ```ignore (illustrative)
22 //!     struct Generator {
23 //!         upvars...,
24 //!         state: u32,
25 //!         mir_locals...,
26 //!     }
27 //!     ```
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
33 //!
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.
38 //!
39 //! The pass creates two functions which have a switch on the generator state giving
40 //! the action to take.
41 //!
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.
46 //!
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.
51
52 use crate::deref_separator::deref_finder;
53 use crate::simplify;
54 use crate::util::expand_aggregate;
55 use crate::MirPass;
56 use rustc_data_structures::fx::FxHashMap;
57 use rustc_hir as hir;
58 use rustc_hir::lang_items::LangItem;
59 use rustc_index::bit_set::{BitMatrix, BitSet, GrowableBitSet};
60 use rustc_index::vec::{Idx, IndexVec};
61 use rustc_middle::mir::dump_mir;
62 use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor};
63 use rustc_middle::mir::*;
64 use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
65 use rustc_middle::ty::{GeneratorSubsts, SubstsRef};
66 use rustc_mir_dataflow::impls::{
67     MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive,
68 };
69 use rustc_mir_dataflow::storage::always_storage_live_locals;
70 use rustc_mir_dataflow::{self, Analysis};
71 use rustc_target::abi::VariantIdx;
72 use rustc_target::spec::PanicStrategy;
73 use std::{iter, ops};
74
75 pub struct StateTransform;
76
77 struct RenameLocalVisitor<'tcx> {
78     from: Local,
79     to: Local,
80     tcx: TyCtxt<'tcx>,
81 }
82
83 impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
84     fn tcx(&self) -> TyCtxt<'tcx> {
85         self.tcx
86     }
87
88     fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
89         if *local == self.from {
90             *local = self.to;
91         }
92     }
93
94     fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
95         match terminator.kind {
96             TerminatorKind::Return => {
97                 // Do not replace the implicit `_0` access here, as that's not possible. The
98                 // transform already handles `return` correctly.
99             }
100             _ => self.super_terminator(terminator, location),
101         }
102     }
103 }
104
105 struct DerefArgVisitor<'tcx> {
106     tcx: TyCtxt<'tcx>,
107 }
108
109 impl<'tcx> MutVisitor<'tcx> for DerefArgVisitor<'tcx> {
110     fn tcx(&self) -> TyCtxt<'tcx> {
111         self.tcx
112     }
113
114     fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
115         assert_ne!(*local, SELF_ARG);
116     }
117
118     fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
119         if place.local == SELF_ARG {
120             replace_base(
121                 place,
122                 Place {
123                     local: SELF_ARG,
124                     projection: self.tcx().intern_place_elems(&[ProjectionElem::Deref]),
125                 },
126                 self.tcx,
127             );
128         } else {
129             self.visit_local(&mut place.local, context, location);
130
131             for elem in place.projection.iter() {
132                 if let PlaceElem::Index(local) = elem {
133                     assert_ne!(local, SELF_ARG);
134                 }
135             }
136         }
137     }
138 }
139
140 struct PinArgVisitor<'tcx> {
141     ref_gen_ty: Ty<'tcx>,
142     tcx: TyCtxt<'tcx>,
143 }
144
145 impl<'tcx> MutVisitor<'tcx> for PinArgVisitor<'tcx> {
146     fn tcx(&self) -> TyCtxt<'tcx> {
147         self.tcx
148     }
149
150     fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
151         assert_ne!(*local, SELF_ARG);
152     }
153
154     fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
155         if place.local == SELF_ARG {
156             replace_base(
157                 place,
158                 Place {
159                     local: SELF_ARG,
160                     projection: self.tcx().intern_place_elems(&[ProjectionElem::Field(
161                         Field::new(0),
162                         self.ref_gen_ty,
163                     )]),
164                 },
165                 self.tcx,
166             );
167         } else {
168             self.visit_local(&mut place.local, context, location);
169
170             for elem in place.projection.iter() {
171                 if let PlaceElem::Index(local) = elem {
172                     assert_ne!(local, SELF_ARG);
173                 }
174             }
175         }
176     }
177 }
178
179 fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
180     place.local = new_base.local;
181
182     let mut new_projection = new_base.projection.to_vec();
183     new_projection.append(&mut place.projection.to_vec());
184
185     place.projection = tcx.intern_place_elems(&new_projection);
186 }
187
188 const SELF_ARG: Local = Local::from_u32(1);
189
190 /// Generator has not been resumed yet.
191 const UNRESUMED: usize = GeneratorSubsts::UNRESUMED;
192 /// Generator has returned / is completed.
193 const RETURNED: usize = GeneratorSubsts::RETURNED;
194 /// Generator has panicked and is poisoned.
195 const POISONED: usize = GeneratorSubsts::POISONED;
196
197 /// Number of variants to reserve in generator state. Corresponds to
198 /// `UNRESUMED` (beginning of a generator) and `RETURNED`/`POISONED`
199 /// (end of a generator) states.
200 const RESERVED_VARIANTS: usize = 3;
201
202 /// A `yield` point in the generator.
203 struct SuspensionPoint<'tcx> {
204     /// State discriminant used when suspending or resuming at this point.
205     state: usize,
206     /// The block to jump to after resumption.
207     resume: BasicBlock,
208     /// Where to move the resume argument after resumption.
209     resume_arg: Place<'tcx>,
210     /// Which block to jump to if the generator is dropped in this state.
211     drop: Option<BasicBlock>,
212     /// Set of locals that have live storage while at this suspension point.
213     storage_liveness: GrowableBitSet<Local>,
214 }
215
216 struct TransformVisitor<'tcx> {
217     tcx: TyCtxt<'tcx>,
218     state_adt_ref: AdtDef<'tcx>,
219     state_substs: SubstsRef<'tcx>,
220
221     // The type of the discriminant in the generator struct
222     discr_ty: Ty<'tcx>,
223
224     // Mapping from Local to (type of local, generator struct index)
225     // FIXME(eddyb) This should use `IndexVec<Local, Option<_>>`.
226     remap: FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
227
228     // A map from a suspension point in a block to the locals which have live storage at that point
229     storage_liveness: IndexVec<BasicBlock, Option<BitSet<Local>>>,
230
231     // A list of suspension points, generated during the transform
232     suspension_points: Vec<SuspensionPoint<'tcx>>,
233
234     // The set of locals that have no `StorageLive`/`StorageDead` annotations.
235     always_live_locals: BitSet<Local>,
236
237     // The original RETURN_PLACE local
238     new_ret_local: Local,
239 }
240
241 impl<'tcx> TransformVisitor<'tcx> {
242     // Make a GeneratorState variant assignment. `core::ops::GeneratorState` only has single
243     // element tuple variants, so we can just write to the downcasted first field and then set the
244     // discriminant to the appropriate variant.
245     fn make_state(
246         &self,
247         idx: VariantIdx,
248         val: Operand<'tcx>,
249         source_info: SourceInfo,
250     ) -> impl Iterator<Item = Statement<'tcx>> {
251         let kind = AggregateKind::Adt(self.state_adt_ref.did(), idx, self.state_substs, None, None);
252         assert_eq!(self.state_adt_ref.variant(idx).fields.len(), 1);
253         let ty = self
254             .tcx
255             .bound_type_of(self.state_adt_ref.variant(idx).fields[0].did)
256             .subst(self.tcx, self.state_substs);
257         expand_aggregate(
258             Place::return_place(),
259             std::iter::once((val, ty)),
260             kind,
261             source_info,
262             self.tcx,
263         )
264     }
265
266     // Create a Place referencing a generator struct field
267     fn make_field(&self, variant_index: VariantIdx, idx: usize, ty: Ty<'tcx>) -> Place<'tcx> {
268         let self_place = Place::from(SELF_ARG);
269         let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
270         let mut projection = base.projection.to_vec();
271         projection.push(ProjectionElem::Field(Field::new(idx), ty));
272
273         Place { local: base.local, projection: self.tcx.intern_place_elems(&projection) }
274     }
275
276     // Create a statement which changes the discriminant
277     fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
278         let self_place = Place::from(SELF_ARG);
279         Statement {
280             source_info,
281             kind: StatementKind::SetDiscriminant {
282                 place: Box::new(self_place),
283                 variant_index: state_disc,
284             },
285         }
286     }
287
288     // Create a statement which reads the discriminant into a temporary
289     fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
290         let temp_decl = LocalDecl::new(self.discr_ty, body.span).internal();
291         let local_decls_len = body.local_decls.push(temp_decl);
292         let temp = Place::from(local_decls_len);
293
294         let self_place = Place::from(SELF_ARG);
295         let assign = Statement {
296             source_info: SourceInfo::outermost(body.span),
297             kind: StatementKind::Assign(Box::new((temp, Rvalue::Discriminant(self_place)))),
298         };
299         (assign, temp)
300     }
301 }
302
303 impl<'tcx> MutVisitor<'tcx> for TransformVisitor<'tcx> {
304     fn tcx(&self) -> TyCtxt<'tcx> {
305         self.tcx
306     }
307
308     fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
309         assert_eq!(self.remap.get(local), None);
310     }
311
312     fn visit_place(
313         &mut self,
314         place: &mut Place<'tcx>,
315         _context: PlaceContext,
316         _location: Location,
317     ) {
318         // Replace an Local in the remap with a generator struct access
319         if let Some(&(ty, variant_index, idx)) = self.remap.get(&place.local) {
320             replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
321         }
322     }
323
324     fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
325         // Remove StorageLive and StorageDead statements for remapped locals
326         data.retain_statements(|s| match s.kind {
327             StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
328                 !self.remap.contains_key(&l)
329             }
330             _ => true,
331         });
332
333         let ret_val = match data.terminator().kind {
334             TerminatorKind::Return => Some((
335                 VariantIdx::new(1),
336                 None,
337                 Operand::Move(Place::from(self.new_ret_local)),
338                 None,
339             )),
340             TerminatorKind::Yield { ref value, resume, resume_arg, drop } => {
341                 Some((VariantIdx::new(0), Some((resume, resume_arg)), value.clone(), drop))
342             }
343             _ => None,
344         };
345
346         if let Some((state_idx, resume, v, drop)) = ret_val {
347             let source_info = data.terminator().source_info;
348             // We must assign the value first in case it gets declared dead below
349             data.statements.extend(self.make_state(state_idx, v, source_info));
350             let state = if let Some((resume, mut resume_arg)) = resume {
351                 // Yield
352                 let state = RESERVED_VARIANTS + self.suspension_points.len();
353
354                 // The resume arg target location might itself be remapped if its base local is
355                 // live across a yield.
356                 let resume_arg =
357                     if let Some(&(ty, variant, idx)) = self.remap.get(&resume_arg.local) {
358                         replace_base(&mut resume_arg, self.make_field(variant, idx, ty), self.tcx);
359                         resume_arg
360                     } else {
361                         resume_arg
362                     };
363
364                 self.suspension_points.push(SuspensionPoint {
365                     state,
366                     resume,
367                     resume_arg,
368                     drop,
369                     storage_liveness: self.storage_liveness[block].clone().unwrap().into(),
370                 });
371
372                 VariantIdx::new(state)
373             } else {
374                 // Return
375                 VariantIdx::new(RETURNED) // state for returned
376             };
377             data.statements.push(self.set_discr(state, source_info));
378             data.terminator_mut().kind = TerminatorKind::Return;
379         }
380
381         self.super_basic_block_data(block, data);
382     }
383 }
384
385 fn make_generator_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
386     let gen_ty = body.local_decls.raw[1].ty;
387
388     let ref_gen_ty =
389         tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty: gen_ty, mutbl: Mutability::Mut });
390
391     // Replace the by value generator argument
392     body.local_decls.raw[1].ty = ref_gen_ty;
393
394     // Add a deref to accesses of the generator state
395     DerefArgVisitor { tcx }.visit_body(body);
396 }
397
398 fn make_generator_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
399     let ref_gen_ty = body.local_decls.raw[1].ty;
400
401     let pin_did = tcx.require_lang_item(LangItem::Pin, Some(body.span));
402     let pin_adt_ref = tcx.adt_def(pin_did);
403     let substs = tcx.intern_substs(&[ref_gen_ty.into()]);
404     let pin_ref_gen_ty = tcx.mk_adt(pin_adt_ref, substs);
405
406     // Replace the by ref generator argument
407     body.local_decls.raw[1].ty = pin_ref_gen_ty;
408
409     // Add the Pin field access to accesses of the generator state
410     PinArgVisitor { ref_gen_ty, tcx }.visit_body(body);
411 }
412
413 /// Allocates a new local and replaces all references of `local` with it. Returns the new local.
414 ///
415 /// `local` will be changed to a new local decl with type `ty`.
416 ///
417 /// Note that the new local will be uninitialized. It is the caller's responsibility to assign some
418 /// valid value to it before its first use.
419 fn replace_local<'tcx>(
420     local: Local,
421     ty: Ty<'tcx>,
422     body: &mut Body<'tcx>,
423     tcx: TyCtxt<'tcx>,
424 ) -> Local {
425     let new_decl = LocalDecl::new(ty, body.span);
426     let new_local = body.local_decls.push(new_decl);
427     body.local_decls.swap(local, new_local);
428
429     RenameLocalVisitor { from: local, to: new_local, tcx }.visit_body(body);
430
431     new_local
432 }
433
434 struct LivenessInfo {
435     /// Which locals are live across any suspension point.
436     saved_locals: GeneratorSavedLocals,
437
438     /// The set of saved locals live at each suspension point.
439     live_locals_at_suspension_points: Vec<BitSet<GeneratorSavedLocal>>,
440
441     /// Parallel vec to the above with SourceInfo for each yield terminator.
442     source_info_at_suspension_points: Vec<SourceInfo>,
443
444     /// For every saved local, the set of other saved locals that are
445     /// storage-live at the same time as this local. We cannot overlap locals in
446     /// the layout which have conflicting storage.
447     storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
448
449     /// For every suspending block, the locals which are storage-live across
450     /// that suspension point.
451     storage_liveness: IndexVec<BasicBlock, Option<BitSet<Local>>>,
452 }
453
454 fn locals_live_across_suspend_points<'tcx>(
455     tcx: TyCtxt<'tcx>,
456     body: &Body<'tcx>,
457     always_live_locals: &BitSet<Local>,
458     movable: bool,
459 ) -> LivenessInfo {
460     let body_ref: &Body<'_> = &body;
461
462     // Calculate when MIR locals have live storage. This gives us an upper bound of their
463     // lifetimes.
464     let mut storage_live = MaybeStorageLive::new(always_live_locals.clone())
465         .into_engine(tcx, body_ref)
466         .iterate_to_fixpoint()
467         .into_results_cursor(body_ref);
468
469     // Calculate the MIR locals which have been previously
470     // borrowed (even if they are still active).
471     let borrowed_locals_results =
472         MaybeBorrowedLocals.into_engine(tcx, body_ref).pass_name("generator").iterate_to_fixpoint();
473
474     let mut borrowed_locals_cursor =
475         rustc_mir_dataflow::ResultsCursor::new(body_ref, &borrowed_locals_results);
476
477     // Calculate the MIR locals that we actually need to keep storage around
478     // for.
479     let requires_storage_results = MaybeRequiresStorage::new(body, &borrowed_locals_results)
480         .into_engine(tcx, body_ref)
481         .iterate_to_fixpoint();
482     let mut requires_storage_cursor =
483         rustc_mir_dataflow::ResultsCursor::new(body_ref, &requires_storage_results);
484
485     // Calculate the liveness of MIR locals ignoring borrows.
486     let mut liveness = MaybeLiveLocals
487         .into_engine(tcx, body_ref)
488         .pass_name("generator")
489         .iterate_to_fixpoint()
490         .into_results_cursor(body_ref);
491
492     let mut storage_liveness_map = IndexVec::from_elem(None, &body.basic_blocks);
493     let mut live_locals_at_suspension_points = Vec::new();
494     let mut source_info_at_suspension_points = Vec::new();
495     let mut live_locals_at_any_suspension_point = BitSet::new_empty(body.local_decls.len());
496
497     for (block, data) in body.basic_blocks.iter_enumerated() {
498         if let TerminatorKind::Yield { .. } = data.terminator().kind {
499             let loc = Location { block, statement_index: data.statements.len() };
500
501             liveness.seek_to_block_end(block);
502             let mut live_locals: BitSet<_> = BitSet::new_empty(body.local_decls.len());
503             live_locals.union(liveness.get());
504
505             if !movable {
506                 // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
507                 // This is correct for movable generators since borrows cannot live across
508                 // suspension points. However for immovable generators we need to account for
509                 // borrows, so we conservatively assume that all borrowed locals are live until
510                 // we find a StorageDead statement referencing the locals.
511                 // To do this we just union our `liveness` result with `borrowed_locals`, which
512                 // contains all the locals which has been borrowed before this suspension point.
513                 // If a borrow is converted to a raw reference, we must also assume that it lives
514                 // forever. Note that the final liveness is still bounded by the storage liveness
515                 // of the local, which happens using the `intersect` operation below.
516                 borrowed_locals_cursor.seek_before_primary_effect(loc);
517                 live_locals.union(borrowed_locals_cursor.get());
518             }
519
520             // Store the storage liveness for later use so we can restore the state
521             // after a suspension point
522             storage_live.seek_before_primary_effect(loc);
523             storage_liveness_map[block] = Some(storage_live.get().clone());
524
525             // Locals live are live at this point only if they are used across
526             // suspension points (the `liveness` variable)
527             // and their storage is required (the `storage_required` variable)
528             requires_storage_cursor.seek_before_primary_effect(loc);
529             live_locals.intersect(requires_storage_cursor.get());
530
531             // The generator argument is ignored.
532             live_locals.remove(SELF_ARG);
533
534             debug!("loc = {:?}, live_locals = {:?}", loc, live_locals);
535
536             // Add the locals live at this suspension point to the set of locals which live across
537             // any suspension points
538             live_locals_at_any_suspension_point.union(&live_locals);
539
540             live_locals_at_suspension_points.push(live_locals);
541             source_info_at_suspension_points.push(data.terminator().source_info);
542         }
543     }
544
545     debug!("live_locals_anywhere = {:?}", live_locals_at_any_suspension_point);
546     let saved_locals = GeneratorSavedLocals(live_locals_at_any_suspension_point);
547
548     // Renumber our liveness_map bitsets to include only the locals we are
549     // saving.
550     let live_locals_at_suspension_points = live_locals_at_suspension_points
551         .iter()
552         .map(|live_here| saved_locals.renumber_bitset(&live_here))
553         .collect();
554
555     let storage_conflicts = compute_storage_conflicts(
556         body_ref,
557         &saved_locals,
558         always_live_locals.clone(),
559         requires_storage_results,
560     );
561
562     LivenessInfo {
563         saved_locals,
564         live_locals_at_suspension_points,
565         source_info_at_suspension_points,
566         storage_conflicts,
567         storage_liveness: storage_liveness_map,
568     }
569 }
570
571 /// The set of `Local`s that must be saved across yield points.
572 ///
573 /// `GeneratorSavedLocal` is indexed in terms of the elements in this set;
574 /// i.e. `GeneratorSavedLocal::new(1)` corresponds to the second local
575 /// included in this set.
576 struct GeneratorSavedLocals(BitSet<Local>);
577
578 impl GeneratorSavedLocals {
579     /// Returns an iterator over each `GeneratorSavedLocal` along with the `Local` it corresponds
580     /// to.
581     fn iter_enumerated(&self) -> impl '_ + Iterator<Item = (GeneratorSavedLocal, Local)> {
582         self.iter().enumerate().map(|(i, l)| (GeneratorSavedLocal::from(i), l))
583     }
584
585     /// Transforms a `BitSet<Local>` that contains only locals saved across yield points to the
586     /// equivalent `BitSet<GeneratorSavedLocal>`.
587     fn renumber_bitset(&self, input: &BitSet<Local>) -> BitSet<GeneratorSavedLocal> {
588         assert!(self.superset(&input), "{:?} not a superset of {:?}", self.0, input);
589         let mut out = BitSet::new_empty(self.count());
590         for (saved_local, local) in self.iter_enumerated() {
591             if input.contains(local) {
592                 out.insert(saved_local);
593             }
594         }
595         out
596     }
597
598     fn get(&self, local: Local) -> Option<GeneratorSavedLocal> {
599         if !self.contains(local) {
600             return None;
601         }
602
603         let idx = self.iter().take_while(|&l| l < local).count();
604         Some(GeneratorSavedLocal::new(idx))
605     }
606 }
607
608 impl ops::Deref for GeneratorSavedLocals {
609     type Target = BitSet<Local>;
610
611     fn deref(&self) -> &Self::Target {
612         &self.0
613     }
614 }
615
616 /// For every saved local, looks for which locals are StorageLive at the same
617 /// time. Generates a bitset for every local of all the other locals that may be
618 /// StorageLive simultaneously with that local. This is used in the layout
619 /// computation; see `GeneratorLayout` for more.
620 fn compute_storage_conflicts<'mir, 'tcx>(
621     body: &'mir Body<'tcx>,
622     saved_locals: &GeneratorSavedLocals,
623     always_live_locals: BitSet<Local>,
624     requires_storage: rustc_mir_dataflow::Results<'tcx, MaybeRequiresStorage<'mir, 'tcx>>,
625 ) -> BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal> {
626     assert_eq!(body.local_decls.len(), saved_locals.domain_size());
627
628     debug!("compute_storage_conflicts({:?})", body.span);
629     debug!("always_live = {:?}", always_live_locals);
630
631     // Locals that are always live or ones that need to be stored across
632     // suspension points are not eligible for overlap.
633     let mut ineligible_locals = always_live_locals;
634     ineligible_locals.intersect(&**saved_locals);
635
636     // Compute the storage conflicts for all eligible locals.
637     let mut visitor = StorageConflictVisitor {
638         body,
639         saved_locals: &saved_locals,
640         local_conflicts: BitMatrix::from_row_n(&ineligible_locals, body.local_decls.len()),
641     };
642
643     requires_storage.visit_reachable_with(body, &mut visitor);
644
645     let local_conflicts = visitor.local_conflicts;
646
647     // Compress the matrix using only stored locals (Local -> GeneratorSavedLocal).
648     //
649     // NOTE: Today we store a full conflict bitset for every local. Technically
650     // this is twice as many bits as we need, since the relation is symmetric.
651     // However, in practice these bitsets are not usually large. The layout code
652     // also needs to keep track of how many conflicts each local has, so it's
653     // simpler to keep it this way for now.
654     let mut storage_conflicts = BitMatrix::new(saved_locals.count(), saved_locals.count());
655     for (saved_local_a, local_a) in saved_locals.iter_enumerated() {
656         if ineligible_locals.contains(local_a) {
657             // Conflicts with everything.
658             storage_conflicts.insert_all_into_row(saved_local_a);
659         } else {
660             // Keep overlap information only for stored locals.
661             for (saved_local_b, local_b) in saved_locals.iter_enumerated() {
662                 if local_conflicts.contains(local_a, local_b) {
663                     storage_conflicts.insert(saved_local_a, saved_local_b);
664                 }
665             }
666         }
667     }
668     storage_conflicts
669 }
670
671 struct StorageConflictVisitor<'mir, 'tcx, 's> {
672     body: &'mir Body<'tcx>,
673     saved_locals: &'s GeneratorSavedLocals,
674     // FIXME(tmandry): Consider using sparse bitsets here once we have good
675     // benchmarks for generators.
676     local_conflicts: BitMatrix<Local, Local>,
677 }
678
679 impl<'mir, 'tcx> rustc_mir_dataflow::ResultsVisitor<'mir, 'tcx>
680     for StorageConflictVisitor<'mir, 'tcx, '_>
681 {
682     type FlowState = BitSet<Local>;
683
684     fn visit_statement_before_primary_effect(
685         &mut self,
686         state: &Self::FlowState,
687         _statement: &'mir Statement<'tcx>,
688         loc: Location,
689     ) {
690         self.apply_state(state, loc);
691     }
692
693     fn visit_terminator_before_primary_effect(
694         &mut self,
695         state: &Self::FlowState,
696         _terminator: &'mir Terminator<'tcx>,
697         loc: Location,
698     ) {
699         self.apply_state(state, loc);
700     }
701 }
702
703 impl StorageConflictVisitor<'_, '_, '_> {
704     fn apply_state(&mut self, flow_state: &BitSet<Local>, loc: Location) {
705         // Ignore unreachable blocks.
706         if self.body.basic_blocks[loc.block].terminator().kind == TerminatorKind::Unreachable {
707             return;
708         }
709
710         let mut eligible_storage_live = flow_state.clone();
711         eligible_storage_live.intersect(&**self.saved_locals);
712
713         for local in eligible_storage_live.iter() {
714             self.local_conflicts.union_row_with(&eligible_storage_live, local);
715         }
716
717         if eligible_storage_live.count() > 1 {
718             trace!("at {:?}, eligible_storage_live={:?}", loc, eligible_storage_live);
719         }
720     }
721 }
722
723 /// Validates the typeck view of the generator against the actual set of types saved between
724 /// yield points.
725 fn sanitize_witness<'tcx>(
726     tcx: TyCtxt<'tcx>,
727     body: &Body<'tcx>,
728     witness: Ty<'tcx>,
729     upvars: Vec<Ty<'tcx>>,
730     saved_locals: &GeneratorSavedLocals,
731 ) {
732     let did = body.source.def_id();
733     let param_env = tcx.param_env(did);
734
735     let allowed_upvars = tcx.normalize_erasing_regions(param_env, upvars);
736     let allowed = match witness.kind() {
737         &ty::GeneratorWitness(interior_tys) => {
738             tcx.normalize_erasing_late_bound_regions(param_env, interior_tys)
739         }
740         _ => {
741             tcx.sess.delay_span_bug(
742                 body.span,
743                 &format!("unexpected generator witness type {:?}", witness.kind()),
744             );
745             return;
746         }
747     };
748
749     for (local, decl) in body.local_decls.iter_enumerated() {
750         // Ignore locals which are internal or not saved between yields.
751         if !saved_locals.contains(local) || decl.internal {
752             continue;
753         }
754         let decl_ty = tcx.normalize_erasing_regions(param_env, decl.ty);
755
756         // Sanity check that typeck knows about the type of locals which are
757         // live across a suspension point
758         if !allowed.contains(&decl_ty) && !allowed_upvars.contains(&decl_ty) {
759             span_bug!(
760                 body.span,
761                 "Broken MIR: generator contains type {} in MIR, \
762                        but typeck only knows about {} and {:?}",
763                 decl_ty,
764                 allowed,
765                 allowed_upvars
766             );
767         }
768     }
769 }
770
771 fn compute_layout<'tcx>(
772     liveness: LivenessInfo,
773     body: &mut Body<'tcx>,
774 ) -> (
775     FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
776     GeneratorLayout<'tcx>,
777     IndexVec<BasicBlock, Option<BitSet<Local>>>,
778 ) {
779     let LivenessInfo {
780         saved_locals,
781         live_locals_at_suspension_points,
782         source_info_at_suspension_points,
783         storage_conflicts,
784         storage_liveness,
785     } = liveness;
786
787     // Gather live local types and their indices.
788     let mut locals = IndexVec::<GeneratorSavedLocal, _>::new();
789     let mut tys = IndexVec::<GeneratorSavedLocal, _>::new();
790     for (saved_local, local) in saved_locals.iter_enumerated() {
791         locals.push(local);
792         tys.push(body.local_decls[local].ty);
793         debug!("generator saved local {:?} => {:?}", saved_local, local);
794     }
795
796     // Leave empty variants for the UNRESUMED, RETURNED, and POISONED states.
797     // In debuginfo, these will correspond to the beginning (UNRESUMED) or end
798     // (RETURNED, POISONED) of the function.
799     let body_span = body.source_scopes[OUTERMOST_SOURCE_SCOPE].span;
800     let mut variant_source_info: IndexVec<VariantIdx, SourceInfo> = [
801         SourceInfo::outermost(body_span.shrink_to_lo()),
802         SourceInfo::outermost(body_span.shrink_to_hi()),
803         SourceInfo::outermost(body_span.shrink_to_hi()),
804     ]
805     .iter()
806     .copied()
807     .collect();
808
809     // Build the generator variant field list.
810     // Create a map from local indices to generator struct indices.
811     let mut variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>> =
812         iter::repeat(IndexVec::new()).take(RESERVED_VARIANTS).collect();
813     let mut remap = FxHashMap::default();
814     for (suspension_point_idx, live_locals) in live_locals_at_suspension_points.iter().enumerate() {
815         let variant_index = VariantIdx::from(RESERVED_VARIANTS + suspension_point_idx);
816         let mut fields = IndexVec::new();
817         for (idx, saved_local) in live_locals.iter().enumerate() {
818             fields.push(saved_local);
819             // Note that if a field is included in multiple variants, we will
820             // just use the first one here. That's fine; fields do not move
821             // around inside generators, so it doesn't matter which variant
822             // index we access them by.
823             remap.entry(locals[saved_local]).or_insert((tys[saved_local], variant_index, idx));
824         }
825         variant_fields.push(fields);
826         variant_source_info.push(source_info_at_suspension_points[suspension_point_idx]);
827     }
828     debug!("generator variant_fields = {:?}", variant_fields);
829     debug!("generator storage_conflicts = {:#?}", storage_conflicts);
830
831     let layout =
832         GeneratorLayout { field_tys: tys, variant_fields, variant_source_info, storage_conflicts };
833
834     (remap, layout, storage_liveness)
835 }
836
837 /// Replaces the entry point of `body` with a block that switches on the generator discriminant and
838 /// dispatches to blocks according to `cases`.
839 ///
840 /// After this function, the former entry point of the function will be bb1.
841 fn insert_switch<'tcx>(
842     body: &mut Body<'tcx>,
843     cases: Vec<(usize, BasicBlock)>,
844     transform: &TransformVisitor<'tcx>,
845     default: TerminatorKind<'tcx>,
846 ) {
847     let default_block = insert_term_block(body, default);
848     let (assign, discr) = transform.get_discr(body);
849     let switch_targets =
850         SwitchTargets::new(cases.iter().map(|(i, bb)| ((*i) as u128, *bb)), default_block);
851     let switch = TerminatorKind::SwitchInt {
852         discr: Operand::Move(discr),
853         switch_ty: transform.discr_ty,
854         targets: switch_targets,
855     };
856
857     let source_info = SourceInfo::outermost(body.span);
858     body.basic_blocks_mut().raw.insert(
859         0,
860         BasicBlockData {
861             statements: vec![assign],
862             terminator: Some(Terminator { source_info, kind: switch }),
863             is_cleanup: false,
864         },
865     );
866
867     let blocks = body.basic_blocks_mut().iter_mut();
868
869     for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
870         *target = BasicBlock::new(target.index() + 1);
871     }
872 }
873
874 fn elaborate_generator_drops<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
875     use crate::shim::DropShimElaborator;
876     use rustc_middle::mir::patch::MirPatch;
877     use rustc_mir_dataflow::elaborate_drops::{elaborate_drop, Unwind};
878
879     // Note that `elaborate_drops` only drops the upvars of a generator, and
880     // this is ok because `open_drop` can only be reached within that own
881     // generator's resume function.
882
883     let def_id = body.source.def_id();
884     let param_env = tcx.param_env(def_id);
885
886     let mut elaborator = DropShimElaborator { body, patch: MirPatch::new(body), tcx, param_env };
887
888     for (block, block_data) in body.basic_blocks.iter_enumerated() {
889         let (target, unwind, source_info) = match block_data.terminator() {
890             Terminator { source_info, kind: TerminatorKind::Drop { place, target, unwind } } => {
891                 if let Some(local) = place.as_local() {
892                     if local == SELF_ARG {
893                         (target, unwind, source_info)
894                     } else {
895                         continue;
896                     }
897                 } else {
898                     continue;
899                 }
900             }
901             _ => continue,
902         };
903         let unwind = if block_data.is_cleanup {
904             Unwind::InCleanup
905         } else {
906             Unwind::To(unwind.unwrap_or_else(|| elaborator.patch.resume_block()))
907         };
908         elaborate_drop(
909             &mut elaborator,
910             *source_info,
911             Place::from(SELF_ARG),
912             (),
913             *target,
914             unwind,
915             block,
916         );
917     }
918     elaborator.patch.apply(body);
919 }
920
921 fn create_generator_drop_shim<'tcx>(
922     tcx: TyCtxt<'tcx>,
923     transform: &TransformVisitor<'tcx>,
924     gen_ty: Ty<'tcx>,
925     body: &mut Body<'tcx>,
926     drop_clean: BasicBlock,
927 ) -> Body<'tcx> {
928     let mut body = body.clone();
929     body.arg_count = 1; // make sure the resume argument is not included here
930
931     let source_info = SourceInfo::outermost(body.span);
932
933     let mut cases = create_cases(&mut body, transform, Operation::Drop);
934
935     cases.insert(0, (UNRESUMED, drop_clean));
936
937     // The returned state and the poisoned state fall through to the default
938     // case which is just to return
939
940     insert_switch(&mut body, cases, &transform, TerminatorKind::Return);
941
942     for block in body.basic_blocks_mut() {
943         let kind = &mut block.terminator_mut().kind;
944         if let TerminatorKind::GeneratorDrop = *kind {
945             *kind = TerminatorKind::Return;
946         }
947     }
948
949     // Replace the return variable
950     body.local_decls[RETURN_PLACE] = LocalDecl::with_source_info(tcx.mk_unit(), source_info);
951
952     make_generator_state_argument_indirect(tcx, &mut body);
953
954     // Change the generator argument from &mut to *mut
955     body.local_decls[SELF_ARG] = LocalDecl::with_source_info(
956         tcx.mk_ptr(ty::TypeAndMut { ty: gen_ty, mutbl: hir::Mutability::Mut }),
957         source_info,
958     );
959     if tcx.sess.opts.unstable_opts.mir_emit_retag {
960         // Alias tracking must know we changed the type
961         body.basic_blocks_mut()[START_BLOCK].statements.insert(
962             0,
963             Statement {
964                 source_info,
965                 kind: StatementKind::Retag(RetagKind::Raw, Box::new(Place::from(SELF_ARG))),
966             },
967         )
968     }
969
970     // Make sure we remove dead blocks to remove
971     // unrelated code from the resume part of the function
972     simplify::remove_dead_blocks(tcx, &mut body);
973
974     dump_mir(tcx, None, "generator_drop", &0, &body, |_, _| Ok(()));
975
976     body
977 }
978
979 fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
980     let source_info = SourceInfo::outermost(body.span);
981     body.basic_blocks_mut().push(BasicBlockData {
982         statements: Vec::new(),
983         terminator: Some(Terminator { source_info, kind }),
984         is_cleanup: false,
985     })
986 }
987
988 fn insert_panic_block<'tcx>(
989     tcx: TyCtxt<'tcx>,
990     body: &mut Body<'tcx>,
991     message: AssertMessage<'tcx>,
992 ) -> BasicBlock {
993     let assert_block = BasicBlock::new(body.basic_blocks.len());
994     let term = TerminatorKind::Assert {
995         cond: Operand::Constant(Box::new(Constant {
996             span: body.span,
997             user_ty: None,
998             literal: ConstantKind::from_bool(tcx, false),
999         })),
1000         expected: true,
1001         msg: message,
1002         target: assert_block,
1003         cleanup: None,
1004     };
1005
1006     let source_info = SourceInfo::outermost(body.span);
1007     body.basic_blocks_mut().push(BasicBlockData {
1008         statements: Vec::new(),
1009         terminator: Some(Terminator { source_info, kind: term }),
1010         is_cleanup: false,
1011     });
1012
1013     assert_block
1014 }
1015
1016 fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
1017     // Returning from a function with an uninhabited return type is undefined behavior.
1018     if body.return_ty().is_privately_uninhabited(tcx, param_env) {
1019         return false;
1020     }
1021
1022     // If there's a return terminator the function may return.
1023     for block in body.basic_blocks.iter() {
1024         if let TerminatorKind::Return = block.terminator().kind {
1025             return true;
1026         }
1027     }
1028
1029     // Otherwise the function can't return.
1030     false
1031 }
1032
1033 fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
1034     // Nothing can unwind when landing pads are off.
1035     if tcx.sess.panic_strategy() == PanicStrategy::Abort {
1036         return false;
1037     }
1038
1039     // Unwinds can only start at certain terminators.
1040     for block in body.basic_blocks.iter() {
1041         match block.terminator().kind {
1042             // These never unwind.
1043             TerminatorKind::Goto { .. }
1044             | TerminatorKind::SwitchInt { .. }
1045             | TerminatorKind::Abort
1046             | TerminatorKind::Return
1047             | TerminatorKind::Unreachable
1048             | TerminatorKind::GeneratorDrop
1049             | TerminatorKind::FalseEdge { .. }
1050             | TerminatorKind::FalseUnwind { .. } => {}
1051
1052             // Resume will *continue* unwinding, but if there's no other unwinding terminator it
1053             // will never be reached.
1054             TerminatorKind::Resume => {}
1055
1056             TerminatorKind::Yield { .. } => {
1057                 unreachable!("`can_unwind` called before generator transform")
1058             }
1059
1060             // These may unwind.
1061             TerminatorKind::Drop { .. }
1062             | TerminatorKind::DropAndReplace { .. }
1063             | TerminatorKind::Call { .. }
1064             | TerminatorKind::InlineAsm { .. }
1065             | TerminatorKind::Assert { .. } => return true,
1066         }
1067     }
1068
1069     // If we didn't find an unwinding terminator, the function cannot unwind.
1070     false
1071 }
1072
1073 fn create_generator_resume_function<'tcx>(
1074     tcx: TyCtxt<'tcx>,
1075     transform: TransformVisitor<'tcx>,
1076     body: &mut Body<'tcx>,
1077     can_return: bool,
1078 ) {
1079     let can_unwind = can_unwind(tcx, body);
1080
1081     // Poison the generator when it unwinds
1082     if can_unwind {
1083         let source_info = SourceInfo::outermost(body.span);
1084         let poison_block = body.basic_blocks_mut().push(BasicBlockData {
1085             statements: vec![transform.set_discr(VariantIdx::new(POISONED), source_info)],
1086             terminator: Some(Terminator { source_info, kind: TerminatorKind::Resume }),
1087             is_cleanup: true,
1088         });
1089
1090         for (idx, block) in body.basic_blocks_mut().iter_enumerated_mut() {
1091             let source_info = block.terminator().source_info;
1092
1093             if let TerminatorKind::Resume = block.terminator().kind {
1094                 // An existing `Resume` terminator is redirected to jump to our dedicated
1095                 // "poisoning block" above.
1096                 if idx != poison_block {
1097                     *block.terminator_mut() = Terminator {
1098                         source_info,
1099                         kind: TerminatorKind::Goto { target: poison_block },
1100                     };
1101                 }
1102             } else if !block.is_cleanup {
1103                 // Any terminators that *can* unwind but don't have an unwind target set are also
1104                 // pointed at our poisoning block (unless they're part of the cleanup path).
1105                 if let Some(unwind @ None) = block.terminator_mut().unwind_mut() {
1106                     *unwind = Some(poison_block);
1107                 }
1108             }
1109         }
1110     }
1111
1112     let mut cases = create_cases(body, &transform, Operation::Resume);
1113
1114     use rustc_middle::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
1115
1116     // Jump to the entry point on the unresumed
1117     cases.insert(0, (UNRESUMED, BasicBlock::new(0)));
1118
1119     // Panic when resumed on the returned or poisoned state
1120     let generator_kind = body.generator_kind().unwrap();
1121
1122     if can_unwind {
1123         cases.insert(
1124             1,
1125             (POISONED, insert_panic_block(tcx, body, ResumedAfterPanic(generator_kind))),
1126         );
1127     }
1128
1129     if can_return {
1130         cases.insert(
1131             1,
1132             (RETURNED, insert_panic_block(tcx, body, ResumedAfterReturn(generator_kind))),
1133         );
1134     }
1135
1136     insert_switch(body, cases, &transform, TerminatorKind::Unreachable);
1137
1138     make_generator_state_argument_indirect(tcx, body);
1139     make_generator_state_argument_pinned(tcx, body);
1140
1141     // Make sure we remove dead blocks to remove
1142     // unrelated code from the drop part of the function
1143     simplify::remove_dead_blocks(tcx, body);
1144
1145     dump_mir(tcx, None, "generator_resume", &0, body, |_, _| Ok(()));
1146 }
1147
1148 fn insert_clean_drop(body: &mut Body<'_>) -> BasicBlock {
1149     let return_block = insert_term_block(body, TerminatorKind::Return);
1150
1151     let term =
1152         TerminatorKind::Drop { place: Place::from(SELF_ARG), target: return_block, unwind: None };
1153     let source_info = SourceInfo::outermost(body.span);
1154
1155     // Create a block to destroy an unresumed generators. This can only destroy upvars.
1156     body.basic_blocks_mut().push(BasicBlockData {
1157         statements: Vec::new(),
1158         terminator: Some(Terminator { source_info, kind: term }),
1159         is_cleanup: false,
1160     })
1161 }
1162
1163 /// An operation that can be performed on a generator.
1164 #[derive(PartialEq, Copy, Clone)]
1165 enum Operation {
1166     Resume,
1167     Drop,
1168 }
1169
1170 impl Operation {
1171     fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
1172         match self {
1173             Operation::Resume => Some(point.resume),
1174             Operation::Drop => point.drop,
1175         }
1176     }
1177 }
1178
1179 fn create_cases<'tcx>(
1180     body: &mut Body<'tcx>,
1181     transform: &TransformVisitor<'tcx>,
1182     operation: Operation,
1183 ) -> Vec<(usize, BasicBlock)> {
1184     let source_info = SourceInfo::outermost(body.span);
1185
1186     transform
1187         .suspension_points
1188         .iter()
1189         .filter_map(|point| {
1190             // Find the target for this suspension point, if applicable
1191             operation.target_block(point).map(|target| {
1192                 let mut statements = Vec::new();
1193
1194                 // Create StorageLive instructions for locals with live storage
1195                 for i in 0..(body.local_decls.len()) {
1196                     if i == 2 {
1197                         // The resume argument is live on function entry. Don't insert a
1198                         // `StorageLive`, or the following `Assign` will read from uninitialized
1199                         // memory.
1200                         continue;
1201                     }
1202
1203                     let l = Local::new(i);
1204                     let needs_storage_live = point.storage_liveness.contains(l)
1205                         && !transform.remap.contains_key(&l)
1206                         && !transform.always_live_locals.contains(l);
1207                     if needs_storage_live {
1208                         statements
1209                             .push(Statement { source_info, kind: StatementKind::StorageLive(l) });
1210                     }
1211                 }
1212
1213                 if operation == Operation::Resume {
1214                     // Move the resume argument to the destination place of the `Yield` terminator
1215                     let resume_arg = Local::new(2); // 0 = return, 1 = self
1216                     statements.push(Statement {
1217                         source_info,
1218                         kind: StatementKind::Assign(Box::new((
1219                             point.resume_arg,
1220                             Rvalue::Use(Operand::Move(resume_arg.into())),
1221                         ))),
1222                     });
1223                 }
1224
1225                 // Then jump to the real target
1226                 let block = body.basic_blocks_mut().push(BasicBlockData {
1227                     statements,
1228                     terminator: Some(Terminator {
1229                         source_info,
1230                         kind: TerminatorKind::Goto { target },
1231                     }),
1232                     is_cleanup: false,
1233                 });
1234
1235                 (point.state, block)
1236             })
1237         })
1238         .collect()
1239 }
1240
1241 impl<'tcx> MirPass<'tcx> for StateTransform {
1242     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
1243         let Some(yield_ty) = body.yield_ty() else {
1244             // This only applies to generators
1245             return;
1246         };
1247
1248         assert!(body.generator_drop().is_none());
1249
1250         // The first argument is the generator type passed by value
1251         let gen_ty = body.local_decls.raw[1].ty;
1252
1253         // Get the interior types and substs which typeck computed
1254         let (upvars, interior, discr_ty, movable) = match *gen_ty.kind() {
1255             ty::Generator(_, substs, movability) => {
1256                 let substs = substs.as_generator();
1257                 (
1258                     substs.upvar_tys().collect(),
1259                     substs.witness(),
1260                     substs.discr_ty(tcx),
1261                     movability == hir::Movability::Movable,
1262                 )
1263             }
1264             _ => {
1265                 tcx.sess
1266                     .delay_span_bug(body.span, &format!("unexpected generator type {}", gen_ty));
1267                 return;
1268             }
1269         };
1270
1271         // Compute GeneratorState<yield_ty, return_ty>
1272         let state_did = tcx.require_lang_item(LangItem::GeneratorState, None);
1273         let state_adt_ref = tcx.adt_def(state_did);
1274         let state_substs = tcx.intern_substs(&[yield_ty.into(), body.return_ty().into()]);
1275         let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
1276
1277         // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
1278         // RETURN_PLACE then is a fresh unused local with type ret_ty.
1279         let new_ret_local = replace_local(RETURN_PLACE, ret_ty, body, tcx);
1280
1281         // We also replace the resume argument and insert an `Assign`.
1282         // This is needed because the resume argument `_2` might be live across a `yield`, in which
1283         // case there is no `Assign` to it that the transform can turn into a store to the generator
1284         // state. After the yield the slot in the generator state would then be uninitialized.
1285         let resume_local = Local::new(2);
1286         let new_resume_local =
1287             replace_local(resume_local, body.local_decls[resume_local].ty, body, tcx);
1288
1289         // When first entering the generator, move the resume argument into its new local.
1290         let source_info = SourceInfo::outermost(body.span);
1291         let stmts = &mut body.basic_blocks_mut()[BasicBlock::new(0)].statements;
1292         stmts.insert(
1293             0,
1294             Statement {
1295                 source_info,
1296                 kind: StatementKind::Assign(Box::new((
1297                     new_resume_local.into(),
1298                     Rvalue::Use(Operand::Move(resume_local.into())),
1299                 ))),
1300             },
1301         );
1302
1303         let always_live_locals = always_storage_live_locals(&body);
1304
1305         let liveness_info =
1306             locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1307
1308         sanitize_witness(tcx, body, interior, upvars, &liveness_info.saved_locals);
1309
1310         if tcx.sess.opts.unstable_opts.validate_mir {
1311             let mut vis = EnsureGeneratorFieldAssignmentsNeverAlias {
1312                 assigned_local: None,
1313                 saved_locals: &liveness_info.saved_locals,
1314                 storage_conflicts: &liveness_info.storage_conflicts,
1315             };
1316
1317             vis.visit_body(body);
1318         }
1319
1320         // Extract locals which are live across suspension point into `layout`
1321         // `remap` gives a mapping from local indices onto generator struct indices
1322         // `storage_liveness` tells us which locals have live storage at suspension points
1323         let (remap, layout, storage_liveness) = compute_layout(liveness_info, body);
1324
1325         let can_return = can_return(tcx, body, tcx.param_env(body.source.def_id()));
1326
1327         // Run the transformation which converts Places from Local to generator struct
1328         // accesses for locals in `remap`.
1329         // It also rewrites `return x` and `yield y` as writing a new generator state and returning
1330         // GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
1331         let mut transform = TransformVisitor {
1332             tcx,
1333             state_adt_ref,
1334             state_substs,
1335             remap,
1336             storage_liveness,
1337             always_live_locals,
1338             suspension_points: Vec::new(),
1339             new_ret_local,
1340             discr_ty,
1341         };
1342         transform.visit_body(body);
1343
1344         // Update our MIR struct to reflect the changes we've made
1345         body.arg_count = 2; // self, resume arg
1346         body.spread_arg = None;
1347
1348         body.generator.as_mut().unwrap().yield_ty = None;
1349         body.generator.as_mut().unwrap().generator_layout = Some(layout);
1350
1351         // Insert `drop(generator_struct)` which is used to drop upvars for generators in
1352         // the unresumed state.
1353         // This is expanded to a drop ladder in `elaborate_generator_drops`.
1354         let drop_clean = insert_clean_drop(body);
1355
1356         dump_mir(tcx, None, "generator_pre-elab", &0, body, |_, _| Ok(()));
1357
1358         // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
1359         // If any upvars are moved out of, drop elaboration will handle upvar destruction.
1360         // However we need to also elaborate the code generated by `insert_clean_drop`.
1361         elaborate_generator_drops(tcx, body);
1362
1363         dump_mir(tcx, None, "generator_post-transform", &0, body, |_, _| Ok(()));
1364
1365         // Create a copy of our MIR and use it to create the drop shim for the generator
1366         let drop_shim = create_generator_drop_shim(tcx, &transform, gen_ty, body, drop_clean);
1367
1368         body.generator.as_mut().unwrap().generator_drop = Some(drop_shim);
1369
1370         // Create the Generator::resume function
1371         create_generator_resume_function(tcx, transform, body, can_return);
1372
1373         // Run derefer to fix Derefs that are not in the first place
1374         deref_finder(tcx, body);
1375     }
1376 }
1377
1378 /// Looks for any assignments between locals (e.g., `_4 = _5`) that will both be converted to fields
1379 /// in the generator state machine but whose storage is not marked as conflicting
1380 ///
1381 /// Validation needs to happen immediately *before* `TransformVisitor` is invoked, not after.
1382 ///
1383 /// This condition would arise when the assignment is the last use of `_5` but the initial
1384 /// definition of `_4` if we weren't extra careful to mark all locals used inside a statement as
1385 /// conflicting. Non-conflicting generator saved locals may be stored at the same location within
1386 /// the generator state machine, which would result in ill-formed MIR: the left-hand and right-hand
1387 /// sides of an assignment may not alias. This caused a miscompilation in [#73137].
1388 ///
1389 /// [#73137]: https://github.com/rust-lang/rust/issues/73137
1390 struct EnsureGeneratorFieldAssignmentsNeverAlias<'a> {
1391     saved_locals: &'a GeneratorSavedLocals,
1392     storage_conflicts: &'a BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
1393     assigned_local: Option<GeneratorSavedLocal>,
1394 }
1395
1396 impl EnsureGeneratorFieldAssignmentsNeverAlias<'_> {
1397     fn saved_local_for_direct_place(&self, place: Place<'_>) -> Option<GeneratorSavedLocal> {
1398         if place.is_indirect() {
1399             return None;
1400         }
1401
1402         self.saved_locals.get(place.local)
1403     }
1404
1405     fn check_assigned_place(&mut self, place: Place<'_>, f: impl FnOnce(&mut Self)) {
1406         if let Some(assigned_local) = self.saved_local_for_direct_place(place) {
1407             assert!(self.assigned_local.is_none(), "`check_assigned_place` must not recurse");
1408
1409             self.assigned_local = Some(assigned_local);
1410             f(self);
1411             self.assigned_local = None;
1412         }
1413     }
1414 }
1415
1416 impl<'tcx> Visitor<'tcx> for EnsureGeneratorFieldAssignmentsNeverAlias<'_> {
1417     fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1418         let Some(lhs) = self.assigned_local else {
1419             // This visitor only invokes `visit_place` for the right-hand side of an assignment
1420             // and only after setting `self.assigned_local`. However, the default impl of
1421             // `Visitor::super_body` may call `visit_place` with a `NonUseContext` for places
1422             // with debuginfo. Ignore them here.
1423             assert!(!context.is_use());
1424             return;
1425         };
1426
1427         let Some(rhs) = self.saved_local_for_direct_place(*place) else { return };
1428
1429         if !self.storage_conflicts.contains(lhs, rhs) {
1430             bug!(
1431                 "Assignment between generator saved locals whose storage is not \
1432                     marked as conflicting: {:?}: {:?} = {:?}",
1433                 location,
1434                 lhs,
1435                 rhs,
1436             );
1437         }
1438     }
1439
1440     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1441         match &statement.kind {
1442             StatementKind::Assign(box (lhs, rhs)) => {
1443                 self.check_assigned_place(*lhs, |this| this.visit_rvalue(rhs, location));
1444             }
1445
1446             StatementKind::FakeRead(..)
1447             | StatementKind::SetDiscriminant { .. }
1448             | StatementKind::Deinit(..)
1449             | StatementKind::StorageLive(_)
1450             | StatementKind::StorageDead(_)
1451             | StatementKind::Retag(..)
1452             | StatementKind::AscribeUserType(..)
1453             | StatementKind::Coverage(..)
1454             | StatementKind::Intrinsic(..)
1455             | StatementKind::Nop => {}
1456         }
1457     }
1458
1459     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1460         // Checking for aliasing in terminators is probably overkill, but until we have actual
1461         // semantics, we should be conservative here.
1462         match &terminator.kind {
1463             TerminatorKind::Call {
1464                 func,
1465                 args,
1466                 destination,
1467                 target: Some(_),
1468                 cleanup: _,
1469                 from_hir_call: _,
1470                 fn_span: _,
1471             } => {
1472                 self.check_assigned_place(*destination, |this| {
1473                     this.visit_operand(func, location);
1474                     for arg in args {
1475                         this.visit_operand(arg, location);
1476                     }
1477                 });
1478             }
1479
1480             TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
1481                 self.check_assigned_place(*resume_arg, |this| this.visit_operand(value, location));
1482             }
1483
1484             // FIXME: Does `asm!` have any aliasing requirements?
1485             TerminatorKind::InlineAsm { .. } => {}
1486
1487             TerminatorKind::Call { .. }
1488             | TerminatorKind::Goto { .. }
1489             | TerminatorKind::SwitchInt { .. }
1490             | TerminatorKind::Resume
1491             | TerminatorKind::Abort
1492             | TerminatorKind::Return
1493             | TerminatorKind::Unreachable
1494             | TerminatorKind::Drop { .. }
1495             | TerminatorKind::DropAndReplace { .. }
1496             | TerminatorKind::Assert { .. }
1497             | TerminatorKind::GeneratorDrop
1498             | TerminatorKind::FalseEdge { .. }
1499             | TerminatorKind::FalseUnwind { .. } => {}
1500         }
1501     }
1502 }