]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/generator.rs
Rollup merge of #69861 - Dylnuge:dylnuge/locale-doc, r=Mark-Simulacrum
[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::generic::{self as dataflow, Analysis};
53 use crate::dataflow::{MaybeBorrowedLocals, MaybeRequiresStorage, MaybeStorageLive};
54 use crate::transform::no_landing_pads::no_landing_pads;
55 use crate::transform::simplify;
56 use crate::transform::{MirPass, MirSource};
57 use crate::util::dump_mir;
58 use crate::util::liveness;
59 use rustc::mir::visit::{MutVisitor, PlaceContext, Visitor};
60 use rustc::mir::*;
61 use rustc::ty::layout::VariantIdx;
62 use rustc::ty::subst::SubstsRef;
63 use rustc::ty::GeneratorSubsts;
64 use rustc::ty::{self, AdtDef, Ty, TyCtxt};
65 use rustc_data_structures::fx::FxHashMap;
66 use rustc_hir as hir;
67 use rustc_hir::def_id::DefId;
68 use rustc_index::bit_set::{BitMatrix, BitSet};
69 use rustc_index::vec::{Idx, IndexVec};
70 use std::borrow::Cow;
71 use std::iter;
72
73 pub struct StateTransform;
74
75 struct RenameLocalVisitor<'tcx> {
76     from: Local,
77     to: Local,
78     tcx: TyCtxt<'tcx>,
79 }
80
81 impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
82     fn tcx(&self) -> TyCtxt<'tcx> {
83         self.tcx
84     }
85
86     fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
87         if *local == self.from {
88             *local = self.to;
89         }
90     }
91
92     fn process_projection_elem(&mut self, elem: &PlaceElem<'tcx>) -> Option<PlaceElem<'tcx>> {
93         match elem {
94             PlaceElem::Index(local) if *local == self.from => Some(PlaceElem::Index(self.to)),
95             _ => None,
96         }
97     }
98 }
99
100 struct DerefArgVisitor<'tcx> {
101     tcx: TyCtxt<'tcx>,
102 }
103
104 impl<'tcx> MutVisitor<'tcx> for DerefArgVisitor<'tcx> {
105     fn tcx(&self) -> TyCtxt<'tcx> {
106         self.tcx
107     }
108
109     fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
110         assert_ne!(*local, self_arg());
111     }
112
113     fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
114         if place.local == self_arg() {
115             replace_base(
116                 place,
117                 Place {
118                     local: self_arg(),
119                     projection: self.tcx().intern_place_elems(&[ProjectionElem::Deref]),
120                 },
121                 self.tcx,
122             );
123         } else {
124             self.visit_place_base(&mut place.local, context, location);
125
126             for elem in place.projection.iter() {
127                 if let PlaceElem::Index(local) = elem {
128                     assert_ne!(*local, self_arg());
129                 }
130             }
131         }
132     }
133 }
134
135 struct PinArgVisitor<'tcx> {
136     ref_gen_ty: Ty<'tcx>,
137     tcx: TyCtxt<'tcx>,
138 }
139
140 impl<'tcx> MutVisitor<'tcx> for PinArgVisitor<'tcx> {
141     fn tcx(&self) -> TyCtxt<'tcx> {
142         self.tcx
143     }
144
145     fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
146         assert_ne!(*local, self_arg());
147     }
148
149     fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
150         if place.local == self_arg() {
151             replace_base(
152                 place,
153                 Place {
154                     local: self_arg(),
155                     projection: self.tcx().intern_place_elems(&[ProjectionElem::Field(
156                         Field::new(0),
157                         self.ref_gen_ty,
158                     )]),
159                 },
160                 self.tcx,
161             );
162         } else {
163             self.visit_place_base(&mut place.local, context, location);
164
165             for elem in place.projection.iter() {
166                 if let PlaceElem::Index(local) = elem {
167                     assert_ne!(*local, self_arg());
168                 }
169             }
170         }
171     }
172 }
173
174 fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
175     place.local = new_base.local;
176
177     let mut new_projection = new_base.projection.to_vec();
178     new_projection.append(&mut place.projection.to_vec());
179
180     place.projection = tcx.intern_place_elems(&new_projection);
181 }
182
183 fn self_arg() -> Local {
184     Local::new(1)
185 }
186
187 /// Generator has not been resumed yet.
188 const UNRESUMED: usize = GeneratorSubsts::UNRESUMED;
189 /// Generator has returned / is completed.
190 const RETURNED: usize = GeneratorSubsts::RETURNED;
191 /// Generator has panicked and is poisoned.
192 const POISONED: usize = GeneratorSubsts::POISONED;
193
194 /// A `yield` point in the generator.
195 struct SuspensionPoint<'tcx> {
196     /// State discriminant used when suspending or resuming at this point.
197     state: usize,
198     /// The block to jump to after resumption.
199     resume: BasicBlock,
200     /// Where to move the resume argument after resumption.
201     resume_arg: Place<'tcx>,
202     /// Which block to jump to if the generator is dropped in this state.
203     drop: Option<BasicBlock>,
204     /// Set of locals that have live storage while at this suspension point.
205     storage_liveness: liveness::LiveVarSet,
206 }
207
208 struct TransformVisitor<'tcx> {
209     tcx: TyCtxt<'tcx>,
210     state_adt_ref: &'tcx AdtDef,
211     state_substs: SubstsRef<'tcx>,
212
213     // The type of the discriminant in the generator struct
214     discr_ty: Ty<'tcx>,
215
216     // Mapping from Local to (type of local, generator struct index)
217     // FIXME(eddyb) This should use `IndexVec<Local, Option<_>>`.
218     remap: FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
219
220     // A map from a suspension point in a block to the locals which have live storage at that point
221     // FIXME(eddyb) This should use `IndexVec<BasicBlock, Option<_>>`.
222     storage_liveness: FxHashMap<BasicBlock, liveness::LiveVarSet>,
223
224     // A list of suspension points, generated during the transform
225     suspension_points: Vec<SuspensionPoint<'tcx>>,
226
227     // The original RETURN_PLACE local
228     new_ret_local: Local,
229 }
230
231 impl TransformVisitor<'tcx> {
232     // Make a GeneratorState rvalue
233     fn make_state(&self, idx: VariantIdx, val: Operand<'tcx>) -> Rvalue<'tcx> {
234         let adt = AggregateKind::Adt(self.state_adt_ref, idx, self.state_substs, None, None);
235         Rvalue::Aggregate(box adt, vec![val])
236     }
237
238     // Create a Place referencing a generator struct field
239     fn make_field(&self, variant_index: VariantIdx, idx: usize, ty: Ty<'tcx>) -> Place<'tcx> {
240         let self_place = Place::from(self_arg());
241         let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
242         let mut projection = base.projection.to_vec();
243         projection.push(ProjectionElem::Field(Field::new(idx), ty));
244
245         Place { local: base.local, projection: self.tcx.intern_place_elems(&projection) }
246     }
247
248     // Create a statement which changes the discriminant
249     fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
250         let self_place = Place::from(self_arg());
251         Statement {
252             source_info,
253             kind: StatementKind::SetDiscriminant {
254                 place: box self_place,
255                 variant_index: state_disc,
256             },
257         }
258     }
259
260     // Create a statement which reads the discriminant into a temporary
261     fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
262         let temp_decl = LocalDecl::new_internal(self.tcx.types.isize, body.span);
263         let local_decls_len = body.local_decls.push(temp_decl);
264         let temp = Place::from(local_decls_len);
265
266         let self_place = Place::from(self_arg());
267         let assign = Statement {
268             source_info: source_info(body),
269             kind: StatementKind::Assign(box (temp, Rvalue::Discriminant(self_place))),
270         };
271         (assign, temp)
272     }
273 }
274
275 impl MutVisitor<'tcx> for TransformVisitor<'tcx> {
276     fn tcx(&self) -> TyCtxt<'tcx> {
277         self.tcx
278     }
279
280     fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
281         assert_eq!(self.remap.get(local), None);
282     }
283
284     fn visit_place(
285         &mut self,
286         place: &mut Place<'tcx>,
287         _context: PlaceContext,
288         _location: Location,
289     ) {
290         // Replace an Local in the remap with a generator struct access
291         if let Some(&(ty, variant_index, idx)) = self.remap.get(&place.local) {
292             replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
293         }
294     }
295
296     fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
297         // Remove StorageLive and StorageDead statements for remapped locals
298         data.retain_statements(|s| match s.kind {
299             StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
300                 !self.remap.contains_key(&l)
301             }
302             _ => true,
303         });
304
305         let ret_val = match data.terminator().kind {
306             TerminatorKind::Return => Some((
307                 VariantIdx::new(1),
308                 None,
309                 Operand::Move(Place::from(self.new_ret_local)),
310                 None,
311             )),
312             TerminatorKind::Yield { ref value, resume, resume_arg, drop } => {
313                 Some((VariantIdx::new(0), Some((resume, resume_arg)), value.clone(), drop))
314             }
315             _ => None,
316         };
317
318         if let Some((state_idx, resume, v, drop)) = ret_val {
319             let source_info = data.terminator().source_info;
320             // We must assign the value first in case it gets declared dead below
321             data.statements.push(Statement {
322                 source_info,
323                 kind: StatementKind::Assign(box (
324                     Place::return_place(),
325                     self.make_state(state_idx, v),
326                 )),
327             });
328             let state = if let Some((resume, resume_arg)) = resume {
329                 // Yield
330                 let state = 3 + self.suspension_points.len();
331
332                 // The resume arg target location might itself be remapped if its base local is
333                 // live across a yield.
334                 let resume_arg =
335                     if let Some(&(ty, variant, idx)) = self.remap.get(&resume_arg.local) {
336                         self.make_field(variant, idx, ty)
337                     } else {
338                         resume_arg
339                     };
340
341                 self.suspension_points.push(SuspensionPoint {
342                     state,
343                     resume,
344                     resume_arg,
345                     drop,
346                     storage_liveness: self.storage_liveness.get(&block).unwrap().clone(),
347                 });
348
349                 VariantIdx::new(state)
350             } else {
351                 // Return
352                 VariantIdx::new(RETURNED) // state for returned
353             };
354             data.statements.push(self.set_discr(state, source_info));
355             data.terminator_mut().kind = TerminatorKind::Return;
356         }
357
358         self.super_basic_block_data(block, data);
359     }
360 }
361
362 fn make_generator_state_argument_indirect<'tcx>(
363     tcx: TyCtxt<'tcx>,
364     def_id: DefId,
365     body: &mut BodyAndCache<'tcx>,
366 ) {
367     let gen_ty = body.local_decls.raw[1].ty;
368
369     let region = ty::ReFree(ty::FreeRegion { scope: def_id, bound_region: ty::BoundRegion::BrEnv });
370
371     let region = tcx.mk_region(region);
372
373     let ref_gen_ty = tcx.mk_ref(region, ty::TypeAndMut { ty: gen_ty, mutbl: hir::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 BodyAndCache<'tcx>) {
383     let ref_gen_ty = body.local_decls.raw[1].ty;
384
385     let pin_did = tcx.lang_items().pin_type().unwrap();
386     let pin_adt_ref = tcx.adt_def(pin_did);
387     let substs = tcx.intern_substs(&[ref_gen_ty.into()]);
388     let pin_ref_gen_ty = tcx.mk_adt(pin_adt_ref, substs);
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 BodyAndCache<'tcx>,
407     tcx: TyCtxt<'tcx>,
408 ) -> Local {
409     let source_info = source_info(body);
410     let new_decl = LocalDecl {
411         mutability: Mutability::Mut,
412         ty,
413         user_ty: UserTypeProjections::none(),
414         source_info,
415         internal: false,
416         is_block_tail: None,
417         local_info: LocalInfo::Other,
418     };
419     let new_local = Local::new(body.local_decls.len());
420     body.local_decls.push(new_decl);
421     body.local_decls.swap(local, new_local);
422
423     RenameLocalVisitor { from: local, to: new_local, tcx }.visit_body(body);
424
425     new_local
426 }
427
428 struct StorageIgnored(liveness::LiveVarSet);
429
430 impl<'tcx> Visitor<'tcx> for StorageIgnored {
431     fn visit_statement(&mut self, statement: &Statement<'tcx>, _location: Location) {
432         match statement.kind {
433             StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
434                 self.0.remove(l);
435             }
436             _ => (),
437         }
438     }
439 }
440
441 struct LivenessInfo {
442     /// Which locals are live across any suspension point.
443     ///
444     /// GeneratorSavedLocal is indexed in terms of the elements in this set;
445     /// i.e. GeneratorSavedLocal::new(1) corresponds to the second local
446     /// included in this set.
447     live_locals: liveness::LiveVarSet,
448
449     /// The set of saved locals live at each suspension point.
450     live_locals_at_suspension_points: Vec<BitSet<GeneratorSavedLocal>>,
451
452     /// For every saved local, the set of other saved locals that are
453     /// storage-live at the same time as this local. We cannot overlap locals in
454     /// the layout which have conflicting storage.
455     storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
456
457     /// For every suspending block, the locals which are storage-live across
458     /// that suspension point.
459     storage_liveness: FxHashMap<BasicBlock, liveness::LiveVarSet>,
460 }
461
462 fn locals_live_across_suspend_points(
463     tcx: TyCtxt<'tcx>,
464     body: ReadOnlyBodyAndCache<'_, 'tcx>,
465     source: MirSource<'tcx>,
466     movable: bool,
467 ) -> LivenessInfo {
468     let def_id = source.def_id();
469     let body_ref: &Body<'_> = &body;
470
471     // Calculate when MIR locals have live storage. This gives us an upper bound of their
472     // lifetimes.
473     let mut storage_live = MaybeStorageLive
474         .into_engine(tcx, body_ref, def_id)
475         .iterate_to_fixpoint()
476         .into_results_cursor(body_ref);
477
478     // Find the MIR locals which do not use StorageLive/StorageDead statements.
479     // The storage of these locals are always live.
480     let mut ignored = StorageIgnored(BitSet::new_filled(body.local_decls.len()));
481     ignored.visit_body(body);
482
483     // Calculate the MIR locals which have been previously
484     // borrowed (even if they are still active).
485     let borrowed_locals_results =
486         MaybeBorrowedLocals::all_borrows().into_engine(tcx, body_ref, def_id).iterate_to_fixpoint();
487
488     let mut borrowed_locals_cursor =
489         dataflow::ResultsCursor::new(body_ref, &borrowed_locals_results);
490
491     // Calculate the MIR locals that we actually need to keep storage around
492     // for.
493     let requires_storage_results = MaybeRequiresStorage::new(body, &borrowed_locals_results)
494         .into_engine(tcx, body_ref, def_id)
495         .iterate_to_fixpoint();
496     let mut requires_storage_cursor =
497         dataflow::ResultsCursor::new(body_ref, &requires_storage_results);
498
499     // Calculate the liveness of MIR locals ignoring borrows.
500     let mut live_locals = liveness::LiveVarSet::new_empty(body.local_decls.len());
501     let mut liveness = liveness::liveness_of_locals(body);
502     liveness::dump_mir(tcx, "generator_liveness", source, body_ref, &liveness);
503
504     let mut storage_liveness_map = FxHashMap::default();
505     let mut live_locals_at_suspension_points = Vec::new();
506
507     for (block, data) in body.basic_blocks().iter_enumerated() {
508         if let TerminatorKind::Yield { .. } = data.terminator().kind {
509             let loc = Location { block, statement_index: data.statements.len() };
510
511             if !movable {
512                 // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
513                 // This is correct for movable generators since borrows cannot live across
514                 // suspension points. However for immovable generators we need to account for
515                 // borrows, so we conseratively assume that all borrowed locals are live until
516                 // we find a StorageDead statement referencing the locals.
517                 // To do this we just union our `liveness` result with `borrowed_locals`, which
518                 // contains all the locals which has been borrowed before this suspension point.
519                 // If a borrow is converted to a raw reference, we must also assume that it lives
520                 // forever. Note that the final liveness is still bounded by the storage liveness
521                 // of the local, which happens using the `intersect` operation below.
522                 borrowed_locals_cursor.seek_before(loc);
523                 liveness.outs[block].union(borrowed_locals_cursor.get());
524             }
525
526             storage_live.seek_before(loc);
527             let storage_liveness = storage_live.get();
528
529             // Store the storage liveness for later use so we can restore the state
530             // after a suspension point
531             storage_liveness_map.insert(block, storage_liveness.clone());
532
533             requires_storage_cursor.seek_before(loc);
534             let storage_required = requires_storage_cursor.get().clone();
535
536             // Locals live are live at this point only if they are used across
537             // suspension points (the `liveness` variable)
538             // and their storage is required (the `storage_required` variable)
539             let mut live_locals_here = storage_required;
540             live_locals_here.intersect(&liveness.outs[block]);
541
542             // The generator argument is ignored
543             live_locals_here.remove(self_arg());
544
545             debug!("loc = {:?}, live_locals_here = {:?}", loc, live_locals_here);
546
547             // Add the locals live at this suspension point to the set of locals which live across
548             // any suspension points
549             live_locals.union(&live_locals_here);
550
551             live_locals_at_suspension_points.push(live_locals_here);
552         }
553     }
554     debug!("live_locals = {:?}", live_locals);
555
556     // Renumber our liveness_map bitsets to include only the locals we are
557     // saving.
558     let live_locals_at_suspension_points = live_locals_at_suspension_points
559         .iter()
560         .map(|live_here| renumber_bitset(&live_here, &live_locals))
561         .collect();
562
563     let storage_conflicts =
564         compute_storage_conflicts(body_ref, &live_locals, &ignored, requires_storage_results);
565
566     LivenessInfo {
567         live_locals,
568         live_locals_at_suspension_points,
569         storage_conflicts,
570         storage_liveness: storage_liveness_map,
571     }
572 }
573
574 /// Renumbers the items present in `stored_locals` and applies the renumbering
575 /// to 'input`.
576 ///
577 /// For example, if `stored_locals = [1, 3, 5]`, this would be renumbered to
578 /// `[0, 1, 2]`. Thus, if `input = [3, 5]` we would return `[1, 2]`.
579 fn renumber_bitset(
580     input: &BitSet<Local>,
581     stored_locals: &liveness::LiveVarSet,
582 ) -> BitSet<GeneratorSavedLocal> {
583     assert!(stored_locals.superset(&input), "{:?} not a superset of {:?}", stored_locals, input);
584     let mut out = BitSet::new_empty(stored_locals.count());
585     for (idx, local) in stored_locals.iter().enumerate() {
586         let saved_local = GeneratorSavedLocal::from(idx);
587         if input.contains(local) {
588             out.insert(saved_local);
589         }
590     }
591     debug!("renumber_bitset({:?}, {:?}) => {:?}", input, stored_locals, out);
592     out
593 }
594
595 /// For every saved local, looks for which locals are StorageLive at the same
596 /// time. Generates a bitset for every local of all the other locals that may be
597 /// StorageLive simultaneously with that local. This is used in the layout
598 /// computation; see `GeneratorLayout` for more.
599 fn compute_storage_conflicts(
600     body: &'mir Body<'tcx>,
601     stored_locals: &liveness::LiveVarSet,
602     ignored: &StorageIgnored,
603     requires_storage: dataflow::Results<'tcx, MaybeRequiresStorage<'mir, 'tcx>>,
604 ) -> BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal> {
605     assert_eq!(body.local_decls.len(), ignored.0.domain_size());
606     assert_eq!(body.local_decls.len(), stored_locals.domain_size());
607     debug!("compute_storage_conflicts({:?})", body.span);
608     debug!("ignored = {:?}", ignored.0);
609
610     // Storage ignored locals are not eligible for overlap, since their storage
611     // is always live.
612     let mut ineligible_locals = ignored.0.clone();
613     ineligible_locals.intersect(&stored_locals);
614
615     // Compute the storage conflicts for all eligible locals.
616     let mut visitor = StorageConflictVisitor {
617         body,
618         stored_locals: &stored_locals,
619         local_conflicts: BitMatrix::from_row_n(&ineligible_locals, body.local_decls.len()),
620     };
621
622     // Visit only reachable basic blocks. The exact order is not important.
623     let reachable_blocks = traversal::preorder(body).map(|(bb, _)| bb);
624     requires_storage.visit_with(body, reachable_blocks, &mut visitor);
625
626     let local_conflicts = visitor.local_conflicts;
627
628     // Compress the matrix using only stored locals (Local -> GeneratorSavedLocal).
629     //
630     // NOTE: Today we store a full conflict bitset for every local. Technically
631     // this is twice as many bits as we need, since the relation is symmetric.
632     // However, in practice these bitsets are not usually large. The layout code
633     // also needs to keep track of how many conflicts each local has, so it's
634     // simpler to keep it this way for now.
635     let mut storage_conflicts = BitMatrix::new(stored_locals.count(), stored_locals.count());
636     for (idx_a, local_a) in stored_locals.iter().enumerate() {
637         let saved_local_a = GeneratorSavedLocal::new(idx_a);
638         if ineligible_locals.contains(local_a) {
639             // Conflicts with everything.
640             storage_conflicts.insert_all_into_row(saved_local_a);
641         } else {
642             // Keep overlap information only for stored locals.
643             for (idx_b, local_b) in stored_locals.iter().enumerate() {
644                 let saved_local_b = GeneratorSavedLocal::new(idx_b);
645                 if local_conflicts.contains(local_a, local_b) {
646                     storage_conflicts.insert(saved_local_a, saved_local_b);
647                 }
648             }
649         }
650     }
651     storage_conflicts
652 }
653
654 struct StorageConflictVisitor<'mir, 'tcx, 's> {
655     body: &'mir Body<'tcx>,
656     stored_locals: &'s liveness::LiveVarSet,
657     // FIXME(tmandry): Consider using sparse bitsets here once we have good
658     // benchmarks for generators.
659     local_conflicts: BitMatrix<Local, Local>,
660 }
661
662 impl dataflow::ResultsVisitor<'mir, 'tcx> for StorageConflictVisitor<'mir, 'tcx, '_> {
663     type FlowState = BitSet<Local>;
664
665     fn visit_statement(
666         &mut self,
667         state: &Self::FlowState,
668         _statement: &'mir Statement<'tcx>,
669         loc: Location,
670     ) {
671         self.apply_state(state, loc);
672     }
673
674     fn visit_terminator(
675         &mut self,
676         state: &Self::FlowState,
677         _terminator: &'mir Terminator<'tcx>,
678         loc: Location,
679     ) {
680         self.apply_state(state, loc);
681     }
682 }
683
684 impl<'body, 'tcx, 's> StorageConflictVisitor<'body, 'tcx, 's> {
685     fn apply_state(&mut self, flow_state: &BitSet<Local>, loc: Location) {
686         // Ignore unreachable blocks.
687         match self.body.basic_blocks()[loc.block].terminator().kind {
688             TerminatorKind::Unreachable => return,
689             _ => (),
690         };
691
692         let mut eligible_storage_live = flow_state.clone();
693         eligible_storage_live.intersect(&self.stored_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 fn compute_layout<'tcx>(
706     tcx: TyCtxt<'tcx>,
707     source: MirSource<'tcx>,
708     upvars: &Vec<Ty<'tcx>>,
709     interior: Ty<'tcx>,
710     movable: bool,
711     body: &mut BodyAndCache<'tcx>,
712 ) -> (
713     FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
714     GeneratorLayout<'tcx>,
715     FxHashMap<BasicBlock, liveness::LiveVarSet>,
716 ) {
717     // Use a liveness analysis to compute locals which are live across a suspension point
718     let LivenessInfo {
719         live_locals,
720         live_locals_at_suspension_points,
721         storage_conflicts,
722         storage_liveness,
723     } = locals_live_across_suspend_points(tcx, read_only!(body), source, movable);
724
725     // Erase regions from the types passed in from typeck so we can compare them with
726     // MIR types
727     let allowed_upvars = tcx.erase_regions(upvars);
728     let allowed = match interior.kind {
729         ty::GeneratorWitness(s) => tcx.erase_late_bound_regions(&s),
730         _ => bug!(),
731     };
732
733     for (local, decl) in body.local_decls.iter_enumerated() {
734         // Ignore locals which are internal or not live
735         if !live_locals.contains(local) || decl.internal {
736             continue;
737         }
738
739         // Sanity check that typeck knows about the type of locals which are
740         // live across a suspension point
741         if !allowed.contains(&decl.ty) && !allowed_upvars.contains(&decl.ty) {
742             span_bug!(
743                 body.span,
744                 "Broken MIR: generator contains type {} in MIR, \
745                        but typeck only knows about {}",
746                 decl.ty,
747                 interior
748             );
749         }
750     }
751
752     // Gather live local types and their indices.
753     let mut locals = IndexVec::<GeneratorSavedLocal, _>::new();
754     let mut tys = IndexVec::<GeneratorSavedLocal, _>::new();
755     for (idx, local) in live_locals.iter().enumerate() {
756         locals.push(local);
757         tys.push(body.local_decls[local].ty);
758         debug!("generator saved local {:?} => {:?}", GeneratorSavedLocal::from(idx), local);
759     }
760
761     // Leave empty variants for the UNRESUMED, RETURNED, and POISONED states.
762     const RESERVED_VARIANTS: usize = 3;
763
764     // Build the generator variant field list.
765     // Create a map from local indices to generator struct indices.
766     let mut variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>> =
767         iter::repeat(IndexVec::new()).take(RESERVED_VARIANTS).collect();
768     let mut remap = FxHashMap::default();
769     for (suspension_point_idx, live_locals) in live_locals_at_suspension_points.iter().enumerate() {
770         let variant_index = VariantIdx::from(RESERVED_VARIANTS + suspension_point_idx);
771         let mut fields = IndexVec::new();
772         for (idx, saved_local) in live_locals.iter().enumerate() {
773             fields.push(saved_local);
774             // Note that if a field is included in multiple variants, we will
775             // just use the first one here. That's fine; fields do not move
776             // around inside generators, so it doesn't matter which variant
777             // index we access them by.
778             remap.entry(locals[saved_local]).or_insert((tys[saved_local], variant_index, idx));
779         }
780         variant_fields.push(fields);
781     }
782     debug!("generator variant_fields = {:?}", variant_fields);
783     debug!("generator storage_conflicts = {:#?}", storage_conflicts);
784
785     let layout = GeneratorLayout { field_tys: tys, variant_fields, storage_conflicts };
786
787     (remap, layout, storage_liveness)
788 }
789
790 /// Replaces the entry point of `body` with a block that switches on the generator discriminant and
791 /// dispatches to blocks according to `cases`.
792 ///
793 /// After this function, the former entry point of the function will be bb1.
794 fn insert_switch<'tcx>(
795     body: &mut BodyAndCache<'tcx>,
796     cases: Vec<(usize, BasicBlock)>,
797     transform: &TransformVisitor<'tcx>,
798     default: TerminatorKind<'tcx>,
799 ) {
800     let default_block = insert_term_block(body, default);
801     let (assign, discr) = transform.get_discr(body);
802     let switch = TerminatorKind::SwitchInt {
803         discr: Operand::Move(discr),
804         switch_ty: transform.discr_ty,
805         values: Cow::from(cases.iter().map(|&(i, _)| i as u128).collect::<Vec<_>>()),
806         targets: cases.iter().map(|&(_, d)| d).chain(iter::once(default_block)).collect(),
807     };
808
809     let source_info = source_info(body);
810     body.basic_blocks_mut().raw.insert(
811         0,
812         BasicBlockData {
813             statements: vec![assign],
814             terminator: Some(Terminator { source_info, kind: switch }),
815             is_cleanup: false,
816         },
817     );
818
819     let blocks = body.basic_blocks_mut().iter_mut();
820
821     for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
822         *target = BasicBlock::new(target.index() + 1);
823     }
824 }
825
826 fn elaborate_generator_drops<'tcx>(
827     tcx: TyCtxt<'tcx>,
828     def_id: DefId,
829     body: &mut BodyAndCache<'tcx>,
830 ) {
831     use crate::shim::DropShimElaborator;
832     use crate::util::elaborate_drops::{elaborate_drop, Unwind};
833     use crate::util::patch::MirPatch;
834
835     // Note that `elaborate_drops` only drops the upvars of a generator, and
836     // this is ok because `open_drop` can only be reached within that own
837     // generator's resume function.
838
839     let param_env = tcx.param_env(def_id);
840     let gen = self_arg();
841
842     let mut elaborator = DropShimElaborator { body, patch: MirPatch::new(body), tcx, param_env };
843
844     for (block, block_data) in body.basic_blocks().iter_enumerated() {
845         let (target, unwind, source_info) = match block_data.terminator() {
846             Terminator { source_info, kind: TerminatorKind::Drop { location, target, unwind } } => {
847                 if let Some(local) = location.as_local() {
848                     if local == gen {
849                         (target, unwind, source_info)
850                     } else {
851                         continue;
852                     }
853                 } else {
854                     continue;
855                 }
856             }
857             _ => continue,
858         };
859         let unwind = if block_data.is_cleanup {
860             Unwind::InCleanup
861         } else {
862             Unwind::To(unwind.unwrap_or_else(|| elaborator.patch.resume_block()))
863         };
864         elaborate_drop(
865             &mut elaborator,
866             *source_info,
867             &Place::from(gen),
868             (),
869             *target,
870             unwind,
871             block,
872         );
873     }
874     elaborator.patch.apply(body);
875 }
876
877 fn create_generator_drop_shim<'tcx>(
878     tcx: TyCtxt<'tcx>,
879     transform: &TransformVisitor<'tcx>,
880     def_id: DefId,
881     source: MirSource<'tcx>,
882     gen_ty: Ty<'tcx>,
883     body: &mut BodyAndCache<'tcx>,
884     drop_clean: BasicBlock,
885 ) -> BodyAndCache<'tcx> {
886     let mut body = body.clone();
887     body.arg_count = 1; // make sure the resume argument is not included here
888
889     let source_info = source_info(&body);
890
891     let mut cases = create_cases(&mut body, transform, Operation::Drop);
892
893     cases.insert(0, (UNRESUMED, drop_clean));
894
895     // The returned state and the poisoned state fall through to the default
896     // case which is just to return
897
898     insert_switch(&mut body, cases, &transform, TerminatorKind::Return);
899
900     for block in body.basic_blocks_mut() {
901         let kind = &mut block.terminator_mut().kind;
902         if let TerminatorKind::GeneratorDrop = *kind {
903             *kind = TerminatorKind::Return;
904         }
905     }
906
907     // Replace the return variable
908     body.local_decls[RETURN_PLACE] = LocalDecl {
909         mutability: Mutability::Mut,
910         ty: tcx.mk_unit(),
911         user_ty: UserTypeProjections::none(),
912         source_info,
913         internal: false,
914         is_block_tail: None,
915         local_info: LocalInfo::Other,
916     };
917
918     make_generator_state_argument_indirect(tcx, def_id, &mut body);
919
920     // Change the generator argument from &mut to *mut
921     body.local_decls[self_arg()] = LocalDecl {
922         mutability: Mutability::Mut,
923         ty: tcx.mk_ptr(ty::TypeAndMut { ty: gen_ty, mutbl: hir::Mutability::Mut }),
924         user_ty: UserTypeProjections::none(),
925         source_info,
926         internal: false,
927         is_block_tail: None,
928         local_info: LocalInfo::Other,
929     };
930     if tcx.sess.opts.debugging_opts.mir_emit_retag {
931         // Alias tracking must know we changed the type
932         body.basic_blocks_mut()[START_BLOCK].statements.insert(
933             0,
934             Statement {
935                 source_info,
936                 kind: StatementKind::Retag(RetagKind::Raw, box Place::from(self_arg())),
937             },
938         )
939     }
940
941     no_landing_pads(tcx, &mut body);
942
943     // Make sure we remove dead blocks to remove
944     // unrelated code from the resume part of the function
945     simplify::remove_dead_blocks(&mut body);
946
947     dump_mir(tcx, None, "generator_drop", &0, source, &mut body, |_, _| Ok(()));
948
949     body
950 }
951
952 fn insert_term_block<'tcx>(
953     body: &mut BodyAndCache<'tcx>,
954     kind: TerminatorKind<'tcx>,
955 ) -> BasicBlock {
956     let term_block = BasicBlock::new(body.basic_blocks().len());
957     let source_info = source_info(body);
958     body.basic_blocks_mut().push(BasicBlockData {
959         statements: Vec::new(),
960         terminator: Some(Terminator { source_info, kind }),
961         is_cleanup: false,
962     });
963     term_block
964 }
965
966 fn insert_panic_block<'tcx>(
967     tcx: TyCtxt<'tcx>,
968     body: &mut BodyAndCache<'tcx>,
969     message: AssertMessage<'tcx>,
970 ) -> BasicBlock {
971     let assert_block = BasicBlock::new(body.basic_blocks().len());
972     let term = TerminatorKind::Assert {
973         cond: Operand::Constant(box Constant {
974             span: body.span,
975             user_ty: None,
976             literal: ty::Const::from_bool(tcx, false),
977         }),
978         expected: true,
979         msg: message,
980         target: assert_block,
981         cleanup: None,
982     };
983
984     let source_info = source_info(body);
985     body.basic_blocks_mut().push(BasicBlockData {
986         statements: Vec::new(),
987         terminator: Some(Terminator { source_info, kind: term }),
988         is_cleanup: false,
989     });
990
991     assert_block
992 }
993
994 fn create_generator_resume_function<'tcx>(
995     tcx: TyCtxt<'tcx>,
996     transform: TransformVisitor<'tcx>,
997     def_id: DefId,
998     source: MirSource<'tcx>,
999     body: &mut BodyAndCache<'tcx>,
1000 ) {
1001     // Poison the generator when it unwinds
1002     for block in body.basic_blocks_mut() {
1003         let source_info = block.terminator().source_info;
1004         if let &TerminatorKind::Resume = &block.terminator().kind {
1005             block.statements.push(transform.set_discr(VariantIdx::new(POISONED), source_info));
1006         }
1007     }
1008
1009     let mut cases = create_cases(body, &transform, Operation::Resume);
1010
1011     use rustc::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
1012
1013     // Jump to the entry point on the unresumed
1014     cases.insert(0, (UNRESUMED, BasicBlock::new(0)));
1015
1016     // Panic when resumed on the returned or poisoned state
1017     let generator_kind = body.generator_kind.unwrap();
1018     cases.insert(1, (RETURNED, insert_panic_block(tcx, body, ResumedAfterReturn(generator_kind))));
1019     cases.insert(2, (POISONED, insert_panic_block(tcx, body, ResumedAfterPanic(generator_kind))));
1020
1021     insert_switch(body, cases, &transform, TerminatorKind::Unreachable);
1022
1023     make_generator_state_argument_indirect(tcx, def_id, body);
1024     make_generator_state_argument_pinned(tcx, body);
1025
1026     no_landing_pads(tcx, body);
1027
1028     // Make sure we remove dead blocks to remove
1029     // unrelated code from the drop part of the function
1030     simplify::remove_dead_blocks(body);
1031
1032     dump_mir(tcx, None, "generator_resume", &0, source, body, |_, _| Ok(()));
1033 }
1034
1035 fn source_info(body: &Body<'_>) -> SourceInfo {
1036     SourceInfo { span: body.span, scope: OUTERMOST_SOURCE_SCOPE }
1037 }
1038
1039 fn insert_clean_drop(body: &mut BodyAndCache<'_>) -> BasicBlock {
1040     let return_block = insert_term_block(body, TerminatorKind::Return);
1041
1042     // Create a block to destroy an unresumed generators. This can only destroy upvars.
1043     let drop_clean = BasicBlock::new(body.basic_blocks().len());
1044     let term = TerminatorKind::Drop {
1045         location: Place::from(self_arg()),
1046         target: return_block,
1047         unwind: None,
1048     };
1049     let source_info = source_info(body);
1050     body.basic_blocks_mut().push(BasicBlockData {
1051         statements: Vec::new(),
1052         terminator: Some(Terminator { source_info, kind: term }),
1053         is_cleanup: false,
1054     });
1055
1056     drop_clean
1057 }
1058
1059 /// An operation that can be performed on a generator.
1060 #[derive(PartialEq, Copy, Clone)]
1061 enum Operation {
1062     Resume,
1063     Drop,
1064 }
1065
1066 impl Operation {
1067     fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
1068         match self {
1069             Operation::Resume => Some(point.resume),
1070             Operation::Drop => point.drop,
1071         }
1072     }
1073 }
1074
1075 fn create_cases<'tcx>(
1076     body: &mut BodyAndCache<'tcx>,
1077     transform: &TransformVisitor<'tcx>,
1078     operation: Operation,
1079 ) -> Vec<(usize, BasicBlock)> {
1080     let source_info = source_info(body);
1081
1082     transform
1083         .suspension_points
1084         .iter()
1085         .filter_map(|point| {
1086             // Find the target for this suspension point, if applicable
1087             operation.target_block(point).map(|target| {
1088                 let block = BasicBlock::new(body.basic_blocks().len());
1089                 let mut statements = Vec::new();
1090
1091                 // Create StorageLive instructions for locals with live storage
1092                 for i in 0..(body.local_decls.len()) {
1093                     if i == 2 {
1094                         // The resume argument is live on function entry. Don't insert a
1095                         // `StorageLive`, or the following `Assign` will read from uninitialized
1096                         // memory.
1097                         continue;
1098                     }
1099
1100                     let l = Local::new(i);
1101                     if point.storage_liveness.contains(l) && !transform.remap.contains_key(&l) {
1102                         statements
1103                             .push(Statement { source_info, kind: StatementKind::StorageLive(l) });
1104                     }
1105                 }
1106
1107                 if operation == Operation::Resume {
1108                     // Move the resume argument to the destination place of the `Yield` terminator
1109                     let resume_arg = Local::new(2); // 0 = return, 1 = self
1110                     statements.push(Statement {
1111                         source_info,
1112                         kind: StatementKind::Assign(box (
1113                             point.resume_arg,
1114                             Rvalue::Use(Operand::Move(resume_arg.into())),
1115                         )),
1116                     });
1117                 }
1118
1119                 // Then jump to the real target
1120                 body.basic_blocks_mut().push(BasicBlockData {
1121                     statements,
1122                     terminator: Some(Terminator {
1123                         source_info,
1124                         kind: TerminatorKind::Goto { target },
1125                     }),
1126                     is_cleanup: false,
1127                 });
1128
1129                 (point.state, block)
1130             })
1131         })
1132         .collect()
1133 }
1134
1135 impl<'tcx> MirPass<'tcx> for StateTransform {
1136     fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut BodyAndCache<'tcx>) {
1137         let yield_ty = if let Some(yield_ty) = body.yield_ty {
1138             yield_ty
1139         } else {
1140             // This only applies to generators
1141             return;
1142         };
1143
1144         assert!(body.generator_drop.is_none());
1145
1146         let def_id = source.def_id();
1147
1148         // The first argument is the generator type passed by value
1149         let gen_ty = body.local_decls.raw[1].ty;
1150
1151         // Get the interior types and substs which typeck computed
1152         let (upvars, interior, discr_ty, movable) = match gen_ty.kind {
1153             ty::Generator(_, substs, movability) => {
1154                 let substs = substs.as_generator();
1155                 (
1156                     substs.upvar_tys(def_id, tcx).collect(),
1157                     substs.witness(def_id, tcx),
1158                     substs.discr_ty(tcx),
1159                     movability == hir::Movability::Movable,
1160                 )
1161             }
1162             _ => bug!(),
1163         };
1164
1165         // Compute GeneratorState<yield_ty, return_ty>
1166         let state_did = tcx.lang_items().gen_state().unwrap();
1167         let state_adt_ref = tcx.adt_def(state_did);
1168         let state_substs = tcx.intern_substs(&[yield_ty.into(), body.return_ty().into()]);
1169         let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
1170
1171         // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
1172         // RETURN_PLACE then is a fresh unused local with type ret_ty.
1173         let new_ret_local = replace_local(RETURN_PLACE, ret_ty, body, tcx);
1174
1175         // We also replace the resume argument and insert an `Assign`.
1176         // This is needed because the resume argument `_2` might be live across a `yield`, in which
1177         // case there is no `Assign` to it that the transform can turn into a store to the generator
1178         // state. After the yield the slot in the generator state would then be uninitialized.
1179         let resume_local = Local::new(2);
1180         let new_resume_local =
1181             replace_local(resume_local, body.local_decls[resume_local].ty, body, tcx);
1182
1183         // When first entering the generator, move the resume argument into its new local.
1184         let source_info = source_info(body);
1185         let stmts = &mut body.basic_blocks_mut()[BasicBlock::new(0)].statements;
1186         stmts.insert(
1187             0,
1188             Statement {
1189                 source_info,
1190                 kind: StatementKind::Assign(box (
1191                     new_resume_local.into(),
1192                     Rvalue::Use(Operand::Move(resume_local.into())),
1193                 )),
1194             },
1195         );
1196
1197         // Extract locals which are live across suspension point into `layout`
1198         // `remap` gives a mapping from local indices onto generator struct indices
1199         // `storage_liveness` tells us which locals have live storage at suspension points
1200         let (remap, layout, storage_liveness) =
1201             compute_layout(tcx, source, &upvars, interior, movable, body);
1202
1203         // Run the transformation which converts Places from Local to generator struct
1204         // accesses for locals in `remap`.
1205         // It also rewrites `return x` and `yield y` as writing a new generator state and returning
1206         // GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
1207         let mut transform = TransformVisitor {
1208             tcx,
1209             state_adt_ref,
1210             state_substs,
1211             remap,
1212             storage_liveness,
1213             suspension_points: Vec::new(),
1214             new_ret_local,
1215             discr_ty,
1216         };
1217         transform.visit_body(body);
1218
1219         // Update our MIR struct to reflect the changes we've made
1220         body.yield_ty = None;
1221         body.arg_count = 2; // self, resume arg
1222         body.spread_arg = None;
1223         body.generator_layout = Some(layout);
1224
1225         // Insert `drop(generator_struct)` which is used to drop upvars for generators in
1226         // the unresumed state.
1227         // This is expanded to a drop ladder in `elaborate_generator_drops`.
1228         let drop_clean = insert_clean_drop(body);
1229
1230         dump_mir(tcx, None, "generator_pre-elab", &0, source, body, |_, _| Ok(()));
1231
1232         // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
1233         // If any upvars are moved out of, drop elaboration will handle upvar destruction.
1234         // However we need to also elaborate the code generated by `insert_clean_drop`.
1235         elaborate_generator_drops(tcx, def_id, body);
1236
1237         dump_mir(tcx, None, "generator_post-transform", &0, source, body, |_, _| Ok(()));
1238
1239         // Create a copy of our MIR and use it to create the drop shim for the generator
1240         let drop_shim =
1241             create_generator_drop_shim(tcx, &transform, def_id, source, gen_ty, body, drop_clean);
1242
1243         body.generator_drop = Some(box drop_shim);
1244
1245         // Create the Generator::resume function
1246         create_generator_resume_function(tcx, transform, def_id, source, body);
1247     }
1248 }