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