]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/generator.rs
Auto merge of #55014 - ljedrz:lazyboye_unwraps, r=matthewjasper
[rust.git] / src / librustc_mir / transform / generator.rs
1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! This is the implementation of the pass which transforms generators into state machines.
12 //!
13 //! MIR generation for generators creates a function which has a self argument which
14 //! passes by value. This argument is effectively a generator type which only contains upvars and
15 //! is only used for this argument inside the MIR for the generator.
16 //! It is passed by value to enable upvars to be moved out of it. Drop elaboration runs on that
17 //! MIR before this pass and creates drop flags for MIR locals.
18 //! It will also drop the generator argument (which only consists of upvars) if any of the upvars
19 //! are moved out of. This pass elaborates the drops of upvars / generator argument in the case
20 //! that none of the upvars were moved out of. This is because we cannot have any drops of this
21 //! generator in the MIR, since it is used to create the drop glue for the generator. We'd get
22 //! infinite recursion otherwise.
23 //!
24 //! This pass creates the implementation for the Generator::resume function and the drop shim
25 //! for the generator based on the MIR input. It converts the generator argument from Self to
26 //! &mut Self adding derefs in the MIR as needed. It computes the final layout of the generator
27 //! struct which looks like this:
28 //!     First upvars are stored
29 //!     It is followed by the generator state field.
30 //!     Then finally the MIR locals which are live across a suspension point are stored.
31 //!
32 //!     struct Generator {
33 //!         upvars...,
34 //!         state: u32,
35 //!         mir_locals...,
36 //!     }
37 //!
38 //! This pass computes the meaning of the state field and the MIR locals which are live
39 //! across a suspension point. There are however two hardcoded generator states:
40 //!     0 - Generator have not been resumed yet
41 //!     1 - Generator has returned / is completed
42 //!     2 - Generator has been poisoned
43 //!
44 //! It also rewrites `return x` and `yield y` as setting a new generator state and returning
45 //! GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
46 //! MIR locals which are live across a suspension point are moved to the generator struct
47 //! with references to them being updated with references to the generator struct.
48 //!
49 //! The pass creates two functions which have a switch on the generator state giving
50 //! the action to take.
51 //!
52 //! One of them is the implementation of Generator::resume.
53 //! For generators with state 0 (unresumed) it starts the execution of the generator.
54 //! For generators with state 1 (returned) and state 2 (poisoned) it panics.
55 //! Otherwise it continues the execution from the last suspension point.
56 //!
57 //! The other function is the drop glue for the generator.
58 //! For generators with state 0 (unresumed) it drops the upvars of the generator.
59 //! For generators with state 1 (returned) and state 2 (poisoned) it does nothing.
60 //! Otherwise it drops all the values in scope at the last suspension point.
61
62 use rustc::hir;
63 use rustc::hir::def_id::DefId;
64 use rustc::mir::*;
65 use rustc::mir::visit::{PlaceContext, Visitor, MutVisitor};
66 use rustc::ty::{self, TyCtxt, AdtDef, Ty};
67 use rustc::ty::subst::Substs;
68 use util::dump_mir;
69 use util::liveness::{self, IdentityMap};
70 use rustc_data_structures::fx::FxHashMap;
71 use rustc_data_structures::indexed_vec::Idx;
72 use rustc_data_structures::bit_set::BitSet;
73 use std::borrow::Cow;
74 use std::iter::once;
75 use std::mem;
76 use transform::{MirPass, MirSource};
77 use transform::simplify;
78 use transform::no_landing_pads::no_landing_pads;
79 use dataflow::{do_dataflow, DebugFormatted, state_for_location};
80 use dataflow::{MaybeStorageLive, HaveBeenBorrowedLocals};
81
82 pub struct StateTransform;
83
84 struct RenameLocalVisitor {
85     from: Local,
86     to: Local,
87 }
88
89 impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor {
90     fn visit_local(&mut self,
91                    local: &mut Local,
92                    _: PlaceContext<'tcx>,
93                    _: Location) {
94         if *local == self.from {
95             *local = self.to;
96         }
97     }
98 }
99
100 struct DerefArgVisitor;
101
102 impl<'tcx> MutVisitor<'tcx> for DerefArgVisitor {
103     fn visit_local(&mut self,
104                    local: &mut Local,
105                    _: PlaceContext<'tcx>,
106                    _: Location) {
107         assert_ne!(*local, self_arg());
108     }
109
110     fn visit_place(&mut self,
111                     place: &mut Place<'tcx>,
112                     context: PlaceContext<'tcx>,
113                     location: Location) {
114         if *place == Place::Local(self_arg()) {
115             *place = Place::Projection(Box::new(Projection {
116                 base: place.clone(),
117                 elem: ProjectionElem::Deref,
118             }));
119         } else {
120             self.super_place(place, context, location);
121         }
122     }
123 }
124
125 fn self_arg() -> Local {
126     Local::new(1)
127 }
128
129 struct SuspensionPoint {
130     state: u32,
131     resume: BasicBlock,
132     drop: Option<BasicBlock>,
133     storage_liveness: liveness::LiveVarSet<Local>,
134 }
135
136 struct TransformVisitor<'a, 'tcx: 'a> {
137     tcx: TyCtxt<'a, 'tcx, 'tcx>,
138     state_adt_ref: &'tcx AdtDef,
139     state_substs: &'tcx Substs<'tcx>,
140
141     // The index of the generator state in the generator struct
142     state_field: usize,
143
144     // Mapping from Local to (type of local, generator struct index)
145     // FIXME(eddyb) This should use `IndexVec<Local, Option<_>>`.
146     remap: FxHashMap<Local, (Ty<'tcx>, usize)>,
147
148     // A map from a suspension point in a block to the locals which have live storage at that point
149     // FIXME(eddyb) This should use `IndexVec<BasicBlock, Option<_>>`.
150     storage_liveness: FxHashMap<BasicBlock, liveness::LiveVarSet<Local>>,
151
152     // A list of suspension points, generated during the transform
153     suspension_points: Vec<SuspensionPoint>,
154
155     // The original RETURN_PLACE local
156     new_ret_local: Local,
157 }
158
159 impl<'a, 'tcx> TransformVisitor<'a, 'tcx> {
160     // Make a GeneratorState rvalue
161     fn make_state(&self, idx: usize, val: Operand<'tcx>) -> Rvalue<'tcx> {
162         let adt = AggregateKind::Adt(self.state_adt_ref, idx, self.state_substs, None, None);
163         Rvalue::Aggregate(box adt, vec![val])
164     }
165
166     // Create a Place referencing a generator struct field
167     fn make_field(&self, idx: usize, ty: Ty<'tcx>) -> Place<'tcx> {
168         let base = Place::Local(self_arg());
169         let field = Projection {
170             base: base,
171             elem: ProjectionElem::Field(Field::new(idx), ty),
172         };
173         Place::Projection(Box::new(field))
174     }
175
176     // Create a statement which changes the generator state
177     fn set_state(&self, state_disc: u32, source_info: SourceInfo) -> Statement<'tcx> {
178         let state = self.make_field(self.state_field, self.tcx.types.u32);
179         let val = Operand::Constant(box Constant {
180             span: source_info.span,
181             ty: self.tcx.types.u32,
182             user_ty: None,
183             literal: ty::Const::from_bits(
184                 self.tcx,
185                 state_disc.into(),
186                 ty::ParamEnv::empty().and(self.tcx.types.u32)
187             ),
188         });
189         Statement {
190             source_info,
191             kind: StatementKind::Assign(state, box Rvalue::Use(val)),
192         }
193     }
194 }
195
196 impl<'a, 'tcx> MutVisitor<'tcx> for TransformVisitor<'a, 'tcx> {
197     fn visit_local(&mut self,
198                    local: &mut Local,
199                    _: PlaceContext<'tcx>,
200                    _: Location) {
201         assert_eq!(self.remap.get(local), None);
202     }
203
204     fn visit_place(&mut self,
205                     place: &mut Place<'tcx>,
206                     context: PlaceContext<'tcx>,
207                     location: Location) {
208         if let Place::Local(l) = *place {
209             // Replace an Local in the remap with a generator struct access
210             if let Some(&(ty, idx)) = self.remap.get(&l) {
211                 *place = self.make_field(idx, ty);
212             }
213         } else {
214             self.super_place(place, context, location);
215         }
216     }
217
218     fn visit_basic_block_data(&mut self,
219                               block: BasicBlock,
220                               data: &mut BasicBlockData<'tcx>) {
221         // Remove StorageLive and StorageDead statements for remapped locals
222         data.retain_statements(|s| {
223             match s.kind {
224                 StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
225                     !self.remap.contains_key(&l)
226                 }
227                 _ => true
228             }
229         });
230
231         let ret_val = match data.terminator().kind {
232             TerminatorKind::Return => Some((1,
233                 None,
234                 Operand::Move(Place::Local(self.new_ret_local)),
235                 None)),
236             TerminatorKind::Yield { ref value, resume, drop } => Some((0,
237                 Some(resume),
238                 value.clone(),
239                 drop)),
240             _ => None
241         };
242
243         if let Some((state_idx, resume, v, drop)) = ret_val {
244             let source_info = data.terminator().source_info;
245             // We must assign the value first in case it gets declared dead below
246             data.statements.push(Statement {
247                 source_info,
248                 kind: StatementKind::Assign(Place::Local(RETURN_PLACE),
249                                             box self.make_state(state_idx, v)),
250             });
251             let state = if let Some(resume) = resume { // Yield
252                 let state = 3 + self.suspension_points.len() as u32;
253
254                 self.suspension_points.push(SuspensionPoint {
255                     state,
256                     resume,
257                     drop,
258                     storage_liveness: self.storage_liveness.get(&block).unwrap().clone(),
259                 });
260
261                 state
262             } else { // Return
263                  1 // state for returned
264             };
265             data.statements.push(self.set_state(state, source_info));
266             data.terminator.as_mut().unwrap().kind = TerminatorKind::Return;
267         }
268
269         self.super_basic_block_data(block, data);
270     }
271 }
272
273 fn make_generator_state_argument_indirect<'a, 'tcx>(
274                 tcx: TyCtxt<'a, 'tcx, 'tcx>,
275                 def_id: DefId,
276                 mir: &mut Mir<'tcx>) {
277     let gen_ty = mir.local_decls.raw[1].ty;
278
279     let region = ty::ReFree(ty::FreeRegion {
280         scope: def_id,
281         bound_region: ty::BoundRegion::BrEnv,
282     });
283
284     let region = tcx.mk_region(region);
285
286     let ref_gen_ty = tcx.mk_ref(region, ty::TypeAndMut {
287         ty: gen_ty,
288         mutbl: hir::MutMutable
289     });
290
291     // Replace the by value generator argument
292     mir.local_decls.raw[1].ty = ref_gen_ty;
293
294     // Add a deref to accesses of the generator state
295     DerefArgVisitor.visit_mir(mir);
296 }
297
298 fn replace_result_variable<'tcx>(
299     ret_ty: Ty<'tcx>,
300     mir: &mut Mir<'tcx>,
301 ) -> Local {
302     let source_info = source_info(mir);
303     let new_ret = LocalDecl {
304         mutability: Mutability::Mut,
305         ty: ret_ty,
306         user_ty: None,
307         name: None,
308         source_info,
309         visibility_scope: source_info.scope,
310         internal: false,
311         is_block_tail: None,
312         is_user_variable: None,
313     };
314     let new_ret_local = Local::new(mir.local_decls.len());
315     mir.local_decls.push(new_ret);
316     mir.local_decls.swap(RETURN_PLACE, new_ret_local);
317
318     RenameLocalVisitor {
319         from: RETURN_PLACE,
320         to: new_ret_local,
321     }.visit_mir(mir);
322
323     new_ret_local
324 }
325
326 struct StorageIgnored(liveness::LiveVarSet<Local>);
327
328 impl<'tcx> Visitor<'tcx> for StorageIgnored {
329     fn visit_statement(&mut self,
330                        _block: BasicBlock,
331                        statement: &Statement<'tcx>,
332                        _location: Location) {
333         match statement.kind {
334             StatementKind::StorageLive(l) |
335             StatementKind::StorageDead(l) => { self.0.remove(l); }
336             _ => (),
337         }
338     }
339 }
340
341 struct BorrowedLocals(liveness::LiveVarSet<Local>);
342
343 fn mark_as_borrowed<'tcx>(place: &Place<'tcx>, locals: &mut BorrowedLocals) {
344     match *place {
345         Place::Local(l) => { locals.0.insert(l); },
346         Place::Promoted(_) |
347         Place::Static(..) => (),
348         Place::Projection(ref proj) => {
349             match proj.elem {
350                 // For derefs we don't look any further.
351                 // If it pointed to a Local, it would already be borrowed elsewhere
352                 ProjectionElem::Deref => (),
353                 _ => mark_as_borrowed(&proj.base, locals)
354             }
355         }
356     }
357 }
358
359 impl<'tcx> Visitor<'tcx> for BorrowedLocals {
360     fn visit_rvalue(&mut self,
361                     rvalue: &Rvalue<'tcx>,
362                     location: Location) {
363         if let Rvalue::Ref(_, _, ref place) = *rvalue {
364             mark_as_borrowed(place, self);
365         }
366
367         self.super_rvalue(rvalue, location)
368     }
369 }
370
371 fn locals_live_across_suspend_points(
372     tcx: TyCtxt<'a, 'tcx, 'tcx>,
373     mir: &Mir<'tcx>,
374     source: MirSource,
375     movable: bool,
376 ) -> (
377     liveness::LiveVarSet<Local>,
378     FxHashMap<BasicBlock, liveness::LiveVarSet<Local>>,
379 ) {
380     let dead_unwinds = BitSet::new_empty(mir.basic_blocks().len());
381     let node_id = tcx.hir.as_local_node_id(source.def_id).unwrap();
382
383     // Calculate when MIR locals have live storage. This gives us an upper bound of their
384     // lifetimes.
385     let storage_live_analysis = MaybeStorageLive::new(mir);
386     let storage_live =
387         do_dataflow(tcx, mir, node_id, &[], &dead_unwinds, storage_live_analysis,
388                     |bd, p| DebugFormatted::new(&bd.mir().local_decls[p]));
389
390     // Find the MIR locals which do not use StorageLive/StorageDead statements.
391     // The storage of these locals are always live.
392     let mut ignored = StorageIgnored(BitSet::new_filled(mir.local_decls.len()));
393     ignored.visit_mir(mir);
394
395     // Calculate the MIR locals which have been previously
396     // borrowed (even if they are still active).
397     // This is only used for immovable generators.
398     let borrowed_locals = if !movable {
399         let analysis = HaveBeenBorrowedLocals::new(mir);
400         let result =
401             do_dataflow(tcx, mir, node_id, &[], &dead_unwinds, analysis,
402                         |bd, p| DebugFormatted::new(&bd.mir().local_decls[p]));
403         Some((analysis, result))
404     } else {
405         None
406     };
407
408     // Calculate the liveness of MIR locals ignoring borrows.
409     let mut set = liveness::LiveVarSet::new_empty(mir.local_decls.len());
410     let mut liveness = liveness::liveness_of_locals(
411         mir,
412         &IdentityMap::new(mir),
413     );
414     liveness::dump_mir(
415         tcx,
416         "generator_liveness",
417         source,
418         mir,
419         &IdentityMap::new(mir),
420         &liveness,
421     );
422
423     let mut storage_liveness_map = FxHashMap::default();
424
425     for (block, data) in mir.basic_blocks().iter_enumerated() {
426         if let TerminatorKind::Yield { .. } = data.terminator().kind {
427             let loc = Location {
428                 block: block,
429                 statement_index: data.statements.len(),
430             };
431
432             if let Some((ref analysis, ref result)) = borrowed_locals {
433                 let borrowed_locals = state_for_location(loc,
434                                                          analysis,
435                                                          result,
436                                                          mir);
437                 // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
438                 // This is correct for movable generators since borrows cannot live across
439                 // suspension points. However for immovable generators we need to account for
440                 // borrows, so we conseratively assume that all borrowed locals are live until
441                 // we find a StorageDead statement referencing the locals.
442                 // To do this we just union our `liveness` result with `borrowed_locals`, which
443                 // contains all the locals which has been borrowed before this suspension point.
444                 // If a borrow is converted to a raw reference, we must also assume that it lives
445                 // forever. Note that the final liveness is still bounded by the storage liveness
446                 // of the local, which happens using the `intersect` operation below.
447                 liveness.outs[block].union(&borrowed_locals);
448             }
449
450             let mut storage_liveness = state_for_location(loc,
451                                                           &storage_live_analysis,
452                                                           &storage_live,
453                                                           mir);
454
455             // Store the storage liveness for later use so we can restore the state
456             // after a suspension point
457             storage_liveness_map.insert(block, storage_liveness.clone());
458
459             // Mark locals without storage statements as always having live storage
460             storage_liveness.union(&ignored.0);
461
462             // Locals live are live at this point only if they are used across
463             // suspension points (the `liveness` variable)
464             // and their storage is live (the `storage_liveness` variable)
465             storage_liveness.intersect(&liveness.outs[block]);
466
467             let live_locals = storage_liveness;
468
469             // Add the locals life at this suspension point to the set of locals which live across
470             // any suspension points
471             set.union(&live_locals);
472         }
473     }
474
475     // The generator argument is ignored
476     set.remove(self_arg());
477
478     (set, storage_liveness_map)
479 }
480
481 fn compute_layout<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
482                             source: MirSource,
483                             upvars: Vec<Ty<'tcx>>,
484                             interior: Ty<'tcx>,
485                             movable: bool,
486                             mir: &mut Mir<'tcx>)
487     -> (FxHashMap<Local, (Ty<'tcx>, usize)>,
488         GeneratorLayout<'tcx>,
489         FxHashMap<BasicBlock, liveness::LiveVarSet<Local>>)
490 {
491     // Use a liveness analysis to compute locals which are live across a suspension point
492     let (live_locals, storage_liveness) = locals_live_across_suspend_points(tcx,
493                                                                             mir,
494                                                                             source,
495                                                                             movable);
496     // Erase regions from the types passed in from typeck so we can compare them with
497     // MIR types
498     let allowed_upvars = tcx.erase_regions(&upvars);
499     let allowed = match interior.sty {
500         ty::GeneratorWitness(s) => tcx.erase_late_bound_regions(&s),
501         _ => bug!(),
502     };
503
504     for (local, decl) in mir.local_decls.iter_enumerated() {
505         // Ignore locals which are internal or not live
506         if !live_locals.contains(local) || decl.internal {
507             continue;
508         }
509
510         // Sanity check that typeck knows about the type of locals which are
511         // live across a suspension point
512         if !allowed.contains(&decl.ty) && !allowed_upvars.contains(&decl.ty) {
513             span_bug!(mir.span,
514                       "Broken MIR: generator contains type {} in MIR, \
515                        but typeck only knows about {}",
516                       decl.ty,
517                       interior);
518         }
519     }
520
521     let upvar_len = mir.upvar_decls.len();
522     let dummy_local = LocalDecl::new_internal(tcx.mk_unit(), mir.span);
523
524     // Gather live locals and their indices replacing values in mir.local_decls with a dummy
525     // to avoid changing local indices
526     let live_decls = live_locals.iter().map(|local| {
527         let var = mem::replace(&mut mir.local_decls[local], dummy_local.clone());
528         (local, var)
529     });
530
531     // Create a map from local indices to generator struct indices.
532     // These are offset by (upvar_len + 1) because of fields which comes before locals.
533     // We also create a vector of the LocalDecls of these locals.
534     let (remap, vars) = live_decls.enumerate().map(|(idx, (local, var))| {
535         ((local, (var.ty, upvar_len + 1 + idx)), var)
536     }).unzip();
537
538     let layout = GeneratorLayout {
539         fields: vars
540     };
541
542     (remap, layout, storage_liveness)
543 }
544
545 fn insert_switch<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
546                            mir: &mut Mir<'tcx>,
547                            cases: Vec<(u32, BasicBlock)>,
548                            transform: &TransformVisitor<'a, 'tcx>,
549                            default: TerminatorKind<'tcx>) {
550     let default_block = insert_term_block(mir, default);
551
552     let switch = TerminatorKind::SwitchInt {
553         discr: Operand::Copy(transform.make_field(transform.state_field, tcx.types.u32)),
554         switch_ty: tcx.types.u32,
555         values: Cow::from(cases.iter().map(|&(i, _)| i.into()).collect::<Vec<_>>()),
556         targets: cases.iter().map(|&(_, d)| d).chain(once(default_block)).collect(),
557     };
558
559     let source_info = source_info(mir);
560     mir.basic_blocks_mut().raw.insert(0, BasicBlockData {
561         statements: Vec::new(),
562         terminator: Some(Terminator {
563             source_info,
564             kind: switch,
565         }),
566         is_cleanup: false,
567     });
568
569     let blocks = mir.basic_blocks_mut().iter_mut();
570
571     for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
572         *target = BasicBlock::new(target.index() + 1);
573     }
574 }
575
576 fn elaborate_generator_drops<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
577                                        def_id: DefId,
578                                        mir: &mut Mir<'tcx>) {
579     use util::elaborate_drops::{elaborate_drop, Unwind};
580     use util::patch::MirPatch;
581     use shim::DropShimElaborator;
582
583     // Note that `elaborate_drops` only drops the upvars of a generator, and
584     // this is ok because `open_drop` can only be reached within that own
585     // generator's resume function.
586
587     let param_env = tcx.param_env(def_id);
588     let gen = self_arg();
589
590     for block in mir.basic_blocks().indices() {
591         let (target, unwind, source_info) = match mir.basic_blocks()[block].terminator() {
592             &Terminator {
593                 source_info,
594                 kind: TerminatorKind::Drop {
595                     location: Place::Local(local),
596                     target,
597                     unwind
598                 }
599             } if local == gen => (target, unwind, source_info),
600             _ => continue,
601         };
602         let unwind = if let Some(unwind) = unwind {
603             Unwind::To(unwind)
604         } else {
605             Unwind::InCleanup
606         };
607         let patch = {
608             let mut elaborator = DropShimElaborator {
609                 mir: &mir,
610                 patch: MirPatch::new(mir),
611                 tcx,
612                 param_env
613             };
614             elaborate_drop(
615                 &mut elaborator,
616                 source_info,
617                 &Place::Local(gen),
618                 (),
619                 target,
620                 unwind,
621                 block
622             );
623             elaborator.patch
624         };
625         patch.apply(mir);
626     }
627 }
628
629 fn create_generator_drop_shim<'a, 'tcx>(
630                 tcx: TyCtxt<'a, 'tcx, 'tcx>,
631                 transform: &TransformVisitor<'a, 'tcx>,
632                 def_id: DefId,
633                 source: MirSource,
634                 gen_ty: Ty<'tcx>,
635                 mir: &Mir<'tcx>,
636                 drop_clean: BasicBlock) -> Mir<'tcx> {
637     let mut mir = mir.clone();
638
639     let source_info = source_info(&mir);
640
641     let mut cases = create_cases(&mut mir, transform, |point| point.drop);
642
643     cases.insert(0, (0, drop_clean));
644
645     // The returned state (1) and the poisoned state (2) falls through to
646     // the default case which is just to return
647
648     insert_switch(tcx, &mut mir, cases, &transform, TerminatorKind::Return);
649
650     for block in mir.basic_blocks_mut() {
651         let kind = &mut block.terminator_mut().kind;
652         if let TerminatorKind::GeneratorDrop = *kind {
653             *kind = TerminatorKind::Return;
654         }
655     }
656
657     // Replace the return variable
658     mir.local_decls[RETURN_PLACE] = LocalDecl {
659         mutability: Mutability::Mut,
660         ty: tcx.mk_unit(),
661         user_ty: None,
662         name: None,
663         source_info,
664         visibility_scope: source_info.scope,
665         internal: false,
666         is_block_tail: None,
667         is_user_variable: None,
668     };
669
670     make_generator_state_argument_indirect(tcx, def_id, &mut mir);
671
672     // Change the generator argument from &mut to *mut
673     mir.local_decls[self_arg()] = LocalDecl {
674         mutability: Mutability::Mut,
675         ty: tcx.mk_ptr(ty::TypeAndMut {
676             ty: gen_ty,
677             mutbl: hir::Mutability::MutMutable,
678         }),
679         user_ty: None,
680         name: None,
681         source_info,
682         visibility_scope: source_info.scope,
683         internal: false,
684         is_block_tail: None,
685         is_user_variable: None,
686     };
687
688     no_landing_pads(tcx, &mut mir);
689
690     // Make sure we remove dead blocks to remove
691     // unrelated code from the resume part of the function
692     simplify::remove_dead_blocks(&mut mir);
693
694     dump_mir(tcx, None, "generator_drop", &0, source, &mut mir, |_, _| Ok(()) );
695
696     mir
697 }
698
699 fn insert_term_block<'tcx>(mir: &mut Mir<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
700     let term_block = BasicBlock::new(mir.basic_blocks().len());
701     let source_info = source_info(mir);
702     mir.basic_blocks_mut().push(BasicBlockData {
703         statements: Vec::new(),
704         terminator: Some(Terminator {
705             source_info,
706             kind,
707         }),
708         is_cleanup: false,
709     });
710     term_block
711 }
712
713 fn insert_panic_block<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
714                                 mir: &mut Mir<'tcx>,
715                                 message: AssertMessage<'tcx>) -> BasicBlock {
716     let assert_block = BasicBlock::new(mir.basic_blocks().len());
717     let term = TerminatorKind::Assert {
718         cond: Operand::Constant(box Constant {
719             span: mir.span,
720             ty: tcx.types.bool,
721             user_ty: None,
722             literal: ty::Const::from_bool(tcx, false),
723         }),
724         expected: true,
725         msg: message,
726         target: assert_block,
727         cleanup: None,
728     };
729
730     let source_info = source_info(mir);
731     mir.basic_blocks_mut().push(BasicBlockData {
732         statements: Vec::new(),
733         terminator: Some(Terminator {
734             source_info,
735             kind: term,
736         }),
737         is_cleanup: false,
738     });
739
740     assert_block
741 }
742
743 fn create_generator_resume_function<'a, 'tcx>(
744         tcx: TyCtxt<'a, 'tcx, 'tcx>,
745         transform: TransformVisitor<'a, 'tcx>,
746         def_id: DefId,
747         source: MirSource,
748         mir: &mut Mir<'tcx>) {
749     // Poison the generator when it unwinds
750     for block in mir.basic_blocks_mut() {
751         let source_info = block.terminator().source_info;
752         if let &TerminatorKind::Resume = &block.terminator().kind {
753             block.statements.push(transform.set_state(1, source_info));
754         }
755     }
756
757     let mut cases = create_cases(mir, &transform, |point| Some(point.resume));
758
759     use rustc::mir::interpret::EvalErrorKind::{
760         GeneratorResumedAfterPanic,
761         GeneratorResumedAfterReturn,
762     };
763
764     // Jump to the entry point on the 0 state
765     cases.insert(0, (0, BasicBlock::new(0)));
766     // Panic when resumed on the returned (1) state
767     cases.insert(1, (1, insert_panic_block(tcx, mir, GeneratorResumedAfterReturn)));
768     // Panic when resumed on the poisoned (2) state
769     cases.insert(2, (2, insert_panic_block(tcx, mir, GeneratorResumedAfterPanic)));
770
771     insert_switch(tcx, mir, cases, &transform, TerminatorKind::Unreachable);
772
773     make_generator_state_argument_indirect(tcx, def_id, mir);
774
775     no_landing_pads(tcx, mir);
776
777     // Make sure we remove dead blocks to remove
778     // unrelated code from the drop part of the function
779     simplify::remove_dead_blocks(mir);
780
781     dump_mir(tcx, None, "generator_resume", &0, source, mir, |_, _| Ok(()) );
782 }
783
784 fn source_info<'a, 'tcx>(mir: &Mir<'tcx>) -> SourceInfo {
785     SourceInfo {
786         span: mir.span,
787         scope: OUTERMOST_SOURCE_SCOPE,
788     }
789 }
790
791 fn insert_clean_drop<'a, 'tcx>(mir: &mut Mir<'tcx>) -> BasicBlock {
792     let return_block = insert_term_block(mir, TerminatorKind::Return);
793
794     // Create a block to destroy an unresumed generators. This can only destroy upvars.
795     let drop_clean = BasicBlock::new(mir.basic_blocks().len());
796     let term = TerminatorKind::Drop {
797         location: Place::Local(self_arg()),
798         target: return_block,
799         unwind: None,
800     };
801     let source_info = source_info(mir);
802     mir.basic_blocks_mut().push(BasicBlockData {
803         statements: Vec::new(),
804         terminator: Some(Terminator {
805             source_info,
806             kind: term,
807         }),
808         is_cleanup: false,
809     });
810
811     drop_clean
812 }
813
814 fn create_cases<'a, 'tcx, F>(mir: &mut Mir<'tcx>,
815                           transform: &TransformVisitor<'a, 'tcx>,
816                           target: F) -> Vec<(u32, BasicBlock)>
817     where F: Fn(&SuspensionPoint) -> Option<BasicBlock> {
818     let source_info = source_info(mir);
819
820     transform.suspension_points.iter().filter_map(|point| {
821         // Find the target for this suspension point, if applicable
822         target(point).map(|target| {
823             let block = BasicBlock::new(mir.basic_blocks().len());
824             let mut statements = Vec::new();
825
826             // Create StorageLive instructions for locals with live storage
827             for i in 0..(mir.local_decls.len()) {
828                 let l = Local::new(i);
829                 if point.storage_liveness.contains(l) && !transform.remap.contains_key(&l) {
830                     statements.push(Statement {
831                         source_info,
832                         kind: StatementKind::StorageLive(l),
833                     });
834                 }
835             }
836
837             // Then jump to the real target
838             mir.basic_blocks_mut().push(BasicBlockData {
839                 statements,
840                 terminator: Some(Terminator {
841                     source_info,
842                     kind: TerminatorKind::Goto {
843                         target,
844                     },
845                 }),
846                 is_cleanup: false,
847             });
848
849             (point.state, block)
850         })
851     }).collect()
852 }
853
854 impl MirPass for StateTransform {
855     fn run_pass<'a, 'tcx>(&self,
856                     tcx: TyCtxt<'a, 'tcx, 'tcx>,
857                     source: MirSource,
858                     mir: &mut Mir<'tcx>) {
859         let yield_ty = if let Some(yield_ty) = mir.yield_ty {
860             yield_ty
861         } else {
862             // This only applies to generators
863             return
864         };
865
866         assert!(mir.generator_drop.is_none());
867
868         let def_id = source.def_id;
869
870         // The first argument is the generator type passed by value
871         let gen_ty = mir.local_decls.raw[1].ty;
872
873         // Get the interior types and substs which typeck computed
874         let (upvars, interior, movable) = match gen_ty.sty {
875             ty::Generator(_, substs, movability) => {
876                 (substs.upvar_tys(def_id, tcx).collect(),
877                  substs.witness(def_id, tcx),
878                  movability == hir::GeneratorMovability::Movable)
879             }
880             _ => bug!(),
881         };
882
883         // Compute GeneratorState<yield_ty, return_ty>
884         let state_did = tcx.lang_items().gen_state().unwrap();
885         let state_adt_ref = tcx.adt_def(state_did);
886         let state_substs = tcx.intern_substs(&[
887             yield_ty.into(),
888             mir.return_ty().into(),
889         ]);
890         let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
891
892         // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
893         // RETURN_PLACE then is a fresh unused local with type ret_ty.
894         let new_ret_local = replace_result_variable(ret_ty, mir);
895
896         // Extract locals which are live across suspension point into `layout`
897         // `remap` gives a mapping from local indices onto generator struct indices
898         // `storage_liveness` tells us which locals have live storage at suspension points
899         let (remap, layout, storage_liveness) = compute_layout(
900             tcx,
901             source,
902             upvars,
903             interior,
904             movable,
905             mir);
906
907         let state_field = mir.upvar_decls.len();
908
909         // Run the transformation which converts Places from Local to generator struct
910         // accesses for locals in `remap`.
911         // It also rewrites `return x` and `yield y` as writing a new generator state and returning
912         // GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
913         let mut transform = TransformVisitor {
914             tcx,
915             state_adt_ref,
916             state_substs,
917             remap,
918             storage_liveness,
919             suspension_points: Vec::new(),
920             new_ret_local,
921             state_field,
922         };
923         transform.visit_mir(mir);
924
925         // Update our MIR struct to reflect the changed we've made
926         mir.yield_ty = None;
927         mir.arg_count = 1;
928         mir.spread_arg = None;
929         mir.generator_layout = Some(layout);
930
931         // Insert `drop(generator_struct)` which is used to drop upvars for generators in
932         // the unresumed (0) state.
933         // This is expanded to a drop ladder in `elaborate_generator_drops`.
934         let drop_clean = insert_clean_drop(mir);
935
936         dump_mir(tcx, None, "generator_pre-elab", &0, source, mir, |_, _| Ok(()) );
937
938         // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
939         // If any upvars are moved out of, drop elaboration will handle upvar destruction.
940         // However we need to also elaborate the code generated by `insert_clean_drop`.
941         elaborate_generator_drops(tcx, def_id, mir);
942
943         dump_mir(tcx, None, "generator_post-transform", &0, source, mir, |_, _| Ok(()) );
944
945         // Create a copy of our MIR and use it to create the drop shim for the generator
946         let drop_shim = create_generator_drop_shim(tcx,
947             &transform,
948             def_id,
949             source,
950             gen_ty,
951             &mir,
952             drop_clean);
953
954         mir.generator_drop = Some(box drop_shim);
955
956         // Create the Generator::resume function
957         create_generator_resume_function(tcx, transform, def_id, source, mir);
958     }
959 }