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