]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/generator.rs
Rollup merge of #44562 - eddyb:ugh-rustdoc, r=nikomatsakis
[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::middle::const_val::ConstVal;
65 use rustc::mir::*;
66 use rustc::mir::transform::{MirPass, MirSource};
67 use rustc::mir::visit::{LvalueContext, Visitor, MutVisitor};
68 use rustc::ty::{self, TyCtxt, AdtDef, Ty, GeneratorInterior};
69 use rustc::ty::subst::{Kind, Substs};
70 use util::dump_mir;
71 use util::liveness;
72 use rustc_const_math::ConstInt;
73 use rustc_data_structures::indexed_vec::Idx;
74 use rustc_data_structures::indexed_set::IdxSetBuf;
75 use std::collections::HashMap;
76 use std::borrow::Cow;
77 use std::iter::once;
78 use std::mem;
79 use transform::simplify;
80 use transform::no_landing_pads::no_landing_pads;
81 use dataflow::{self, MaybeStorageLive, state_for_location};
82
83 pub struct StateTransform;
84
85 struct RenameLocalVisitor {
86     from: Local,
87     to: Local,
88 }
89
90 impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor {
91     fn visit_local(&mut self,
92                    local: &mut Local,
93                    _: LvalueContext<'tcx>,
94                    _: Location) {
95         if *local == self.from {
96             *local = self.to;
97         }
98     }
99 }
100
101 struct DerefArgVisitor;
102
103 impl<'tcx> MutVisitor<'tcx> for DerefArgVisitor {
104     fn visit_local(&mut self,
105                    local: &mut Local,
106                    _: LvalueContext<'tcx>,
107                    _: Location) {
108         assert_ne!(*local, self_arg());
109     }
110
111     fn visit_lvalue(&mut self,
112                     lvalue: &mut Lvalue<'tcx>,
113                     context: LvalueContext<'tcx>,
114                     location: Location) {
115         if *lvalue == Lvalue::Local(self_arg()) {
116             *lvalue = Lvalue::Projection(Box::new(Projection {
117                 base: lvalue.clone(),
118                 elem: ProjectionElem::Deref,
119             }));
120         } else {
121             self.super_lvalue(lvalue, context, location);
122         }
123     }
124 }
125
126 fn self_arg() -> Local {
127     Local::new(1)
128 }
129
130 struct SuspensionPoint {
131     state: u32,
132     resume: BasicBlock,
133     drop: Option<BasicBlock>,
134     storage_liveness: liveness::LocalSet,
135 }
136
137 struct TransformVisitor<'a, 'tcx: 'a> {
138     tcx: TyCtxt<'a, 'tcx, 'tcx>,
139     state_adt_ref: &'tcx AdtDef,
140     state_substs: &'tcx Substs<'tcx>,
141
142     // The index of the generator state in the generator struct
143     state_field: usize,
144
145     // Mapping from Local to (type of local, generator struct index)
146     remap: HashMap<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     storage_liveness: HashMap<BasicBlock, liveness::LocalSet>,
150
151     // A list of suspension points, generated during the transform
152     suspension_points: Vec<SuspensionPoint>,
153
154     // The original RETURN_POINTER local
155     new_ret_local: Local,
156 }
157
158 impl<'a, 'tcx> TransformVisitor<'a, 'tcx> {
159     // Make a GeneratorState rvalue
160     fn make_state(&self, idx: usize, val: Operand<'tcx>) -> Rvalue<'tcx> {
161         let adt = AggregateKind::Adt(self.state_adt_ref, idx, self.state_substs, None);
162         Rvalue::Aggregate(box adt, vec![val])
163     }
164
165     // Create a Lvalue referencing a generator struct field
166     fn make_field(&self, idx: usize, ty: Ty<'tcx>) -> Lvalue<'tcx> {
167         let base = Lvalue::Local(self_arg());
168         let field = Projection {
169             base: base,
170             elem: ProjectionElem::Field(Field::new(idx), ty),
171         };
172         Lvalue::Projection(Box::new(field))
173     }
174
175     // Create a statement which changes the generator state
176     fn set_state(&self, state_disc: u32, source_info: SourceInfo) -> Statement<'tcx> {
177         let state = self.make_field(self.state_field, self.tcx.types.u32);
178         let val = Operand::Constant(box Constant {
179             span: source_info.span,
180             ty: self.tcx.types.u32,
181             literal: Literal::Value {
182                 value: self.tcx.mk_const(ty::Const {
183                     val: ConstVal::Integral(ConstInt::U32(state_disc)),
184                     ty: self.tcx.types.u32
185                 }),
186             },
187         });
188         Statement {
189             source_info,
190             kind: StatementKind::Assign(state, Rvalue::Use(val)),
191         }
192     }
193 }
194
195 impl<'a, 'tcx> MutVisitor<'tcx> for TransformVisitor<'a, 'tcx> {
196     fn visit_local(&mut self,
197                    local: &mut Local,
198                    _: LvalueContext<'tcx>,
199                    _: Location) {
200         assert_eq!(self.remap.get(local), None);
201     }
202
203     fn visit_lvalue(&mut self,
204                     lvalue: &mut Lvalue<'tcx>,
205                     context: LvalueContext<'tcx>,
206                     location: Location) {
207         if let Lvalue::Local(l) = *lvalue {
208             // Replace an Local in the remap with a generator struct access
209             if let Some(&(ty, idx)) = self.remap.get(&l) {
210                 *lvalue = self.make_field(idx, ty);
211             }
212         } else {
213             self.super_lvalue(lvalue, context, location);
214         }
215     }
216
217     fn visit_basic_block_data(&mut self,
218                               block: BasicBlock,
219                               data: &mut BasicBlockData<'tcx>) {
220         // Remove StorageLive and StorageDead statements for remapped locals
221         data.retain_statements(|s| {
222             match s.kind {
223                 StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
224                     !self.remap.contains_key(&l)
225                 }
226                 _ => true
227             }
228         });
229
230         let ret_val = match data.terminator().kind {
231             TerminatorKind::Return => Some((1,
232                 None,
233                 Operand::Consume(Lvalue::Local(self.new_ret_local)),
234                 None)),
235             TerminatorKind::Yield { ref value, resume, drop } => Some((0,
236                 Some(resume),
237                 value.clone(),
238                 drop)),
239             _ => None
240         };
241
242         if let Some((state_idx, resume, v, drop)) = ret_val {
243             let source_info = data.terminator().source_info;
244             // We must assign the value first in case it gets declared dead below
245             data.statements.push(Statement {
246                 source_info,
247                 kind: StatementKind::Assign(Lvalue::Local(RETURN_POINTER),
248                     self.make_state(state_idx, v)),
249             });
250             let state = if let Some(resume) = resume { // Yield
251                 let state = 3 + self.suspension_points.len() as u32;
252
253                 self.suspension_points.push(SuspensionPoint {
254                     state,
255                     resume,
256                     drop,
257                     storage_liveness: self.storage_liveness.get(&block).unwrap().clone(),
258                 });
259
260                 state
261             } else { // Return
262                  1 // state for returned
263             };
264             data.statements.push(self.set_state(state, source_info));
265             data.terminator.as_mut().unwrap().kind = TerminatorKind::Return;
266         }
267
268         self.super_basic_block_data(block, data);
269     }
270 }
271
272 fn make_generator_state_argument_indirect<'a, 'tcx>(
273                 tcx: TyCtxt<'a, 'tcx, 'tcx>,
274                 def_id: DefId,
275                 mir: &mut Mir<'tcx>) {
276     let gen_ty = mir.local_decls.raw[1].ty;
277
278     let region = ty::ReFree(ty::FreeRegion {
279         scope: def_id,
280         bound_region: ty::BoundRegion::BrEnv,
281     });
282
283     let region = tcx.mk_region(region);
284
285     let ref_gen_ty = tcx.mk_ref(region, ty::TypeAndMut {
286         ty: gen_ty,
287         mutbl: hir::MutMutable
288     });
289
290     // Replace the by value generator argument
291     mir.local_decls.raw[1].ty = ref_gen_ty;
292
293     // Add a deref to accesses of the generator state
294     DerefArgVisitor.visit_mir(mir);
295 }
296
297 fn replace_result_variable<'tcx>(ret_ty: Ty<'tcx>,
298                             mir: &mut Mir<'tcx>) -> Local {
299     let new_ret = LocalDecl {
300         mutability: Mutability::Mut,
301         ty: ret_ty,
302         name: None,
303         source_info: source_info(mir),
304         internal: false,
305         is_user_variable: false,
306     };
307     let new_ret_local = Local::new(mir.local_decls.len());
308     mir.local_decls.push(new_ret);
309     mir.local_decls.swap(0, new_ret_local.index());
310
311     RenameLocalVisitor {
312         from: RETURN_POINTER,
313         to: new_ret_local,
314     }.visit_mir(mir);
315
316     new_ret_local
317 }
318
319 struct StorageIgnored(liveness::LocalSet);
320
321 impl<'tcx> Visitor<'tcx> for StorageIgnored {
322     fn visit_statement(&mut self,
323                        _block: BasicBlock,
324                        statement: &Statement<'tcx>,
325                        _location: Location) {
326         match statement.kind {
327             StatementKind::StorageLive(l) |
328             StatementKind::StorageDead(l) => { self.0.remove(&l); }
329             _ => (),
330         }
331     }
332 }
333
334 fn locals_live_across_suspend_points<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
335                                                mir: &Mir<'tcx>,
336                                                source: MirSource) ->
337                                                (liveness::LocalSet,
338                                                 HashMap<BasicBlock, liveness::LocalSet>) {
339     let dead_unwinds = IdxSetBuf::new_empty(mir.basic_blocks().len());
340     let node_id = source.item_id();
341     let analysis = MaybeStorageLive::new(mir);
342     let storage_live =
343         dataflow::do_dataflow(tcx, mir, node_id, &[], &dead_unwinds, analysis,
344                               |bd, p| &bd.mir().local_decls[p]);
345
346     let mut ignored = StorageIgnored(IdxSetBuf::new_filled(mir.local_decls.len()));
347     ignored.visit_mir(mir);
348
349     let mut set = liveness::LocalSet::new_empty(mir.local_decls.len());
350     let liveness = liveness::liveness_of_locals(mir);
351     liveness::dump_mir(tcx, "generator_liveness", source, mir, &liveness);
352
353     let mut storage_liveness_map = HashMap::new();
354
355     for (block, data) in mir.basic_blocks().iter_enumerated() {
356         if let TerminatorKind::Yield { .. } = data.terminator().kind {
357             let loc = Location {
358                 block: block,
359                 statement_index: data.statements.len(),
360             };
361
362             let storage_liveness = state_for_location(loc, &analysis, &storage_live);
363
364             storage_liveness_map.insert(block, storage_liveness.clone());
365
366             let mut live_locals = storage_liveness;
367
368             // Mark locals without storage statements as always having live storage
369             live_locals.union(&ignored.0);
370
371             // Locals live are live at this point only if they are used across suspension points
372             // and their storage is live
373             live_locals.intersect(&liveness.outs[block]);
374
375             // Add the locals life at this suspension point to the set of locals which live across
376             // any suspension points
377             set.union(&live_locals);
378         }
379     }
380
381     // The generator argument is ignored
382     set.remove(&self_arg());
383
384     (set, storage_liveness_map)
385 }
386
387 fn compute_layout<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
388                             source: MirSource,
389                             interior: GeneratorInterior<'tcx>,
390                             mir: &mut Mir<'tcx>)
391     -> (HashMap<Local, (Ty<'tcx>, usize)>,
392         GeneratorLayout<'tcx>,
393         HashMap<BasicBlock, liveness::LocalSet>)
394 {
395     // Use a liveness analysis to compute locals which are live across a suspension point
396     let (live_locals, storage_liveness) = locals_live_across_suspend_points(tcx, mir, source);
397
398     // Erase regions from the types passed in from typeck so we can compare them with
399     // MIR types
400     let allowed = tcx.erase_regions(&interior.as_slice());
401
402     for (local, decl) in mir.local_decls.iter_enumerated() {
403         // Ignore locals which are internal or not live
404         if !live_locals.contains(&local) || decl.internal {
405             continue;
406         }
407
408         // Sanity check that typeck knows about the type of locals which are
409         // live across a suspension point
410         if !allowed.contains(&decl.ty) {
411             span_bug!(mir.span,
412                       "Broken MIR: generator contains type {} in MIR, \
413                        but typeck only knows about {}",
414                       decl.ty,
415                       interior);
416         }
417     }
418
419     let upvar_len = mir.upvar_decls.len();
420     let dummy_local = LocalDecl::new_internal(tcx.mk_nil(), mir.span);
421
422     // Gather live locals and their indices replacing values in mir.local_decls with a dummy
423     // to avoid changing local indices
424     let live_decls = live_locals.iter().map(|local| {
425         let var = mem::replace(&mut mir.local_decls[local], dummy_local.clone());
426         (local, var)
427     });
428
429     // Create a map from local indices to generator struct indices.
430     // These are offset by (upvar_len + 1) because of fields which comes before locals.
431     // We also create a vector of the LocalDecls of these locals.
432     let (remap, vars) = live_decls.enumerate().map(|(idx, (local, var))| {
433         ((local, (var.ty, upvar_len + 1 + idx)), var)
434     }).unzip();
435
436     let layout = GeneratorLayout {
437         fields: vars
438     };
439
440     (remap, layout, storage_liveness)
441 }
442
443 fn insert_switch<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
444                            mir: &mut Mir<'tcx>,
445                            cases: Vec<(u32, BasicBlock)>,
446                            transform: &TransformVisitor<'a, 'tcx>) {
447     let return_block = insert_return_block(mir);
448
449     let switch = TerminatorKind::SwitchInt {
450         discr: Operand::Consume(transform.make_field(transform.state_field, tcx.types.u32)),
451         switch_ty: tcx.types.u32,
452         values: Cow::from(cases.iter().map(|&(i, _)| ConstInt::U32(i)).collect::<Vec<_>>()),
453         targets: cases.iter().map(|&(_, d)| d).chain(once(return_block)).collect(),
454     };
455
456     let source_info = source_info(mir);
457     mir.basic_blocks_mut().raw.insert(0, BasicBlockData {
458         statements: Vec::new(),
459         terminator: Some(Terminator {
460             source_info,
461             kind: switch,
462         }),
463         is_cleanup: false,
464     });
465
466     let blocks = mir.basic_blocks_mut().iter_mut();
467
468     for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
469         *target = BasicBlock::new(target.index() + 1);
470     }
471 }
472
473 fn elaborate_generator_drops<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
474                                        def_id: DefId,
475                                        mir: &mut Mir<'tcx>) {
476     use util::elaborate_drops::{elaborate_drop, Unwind};
477     use util::patch::MirPatch;
478     use shim::DropShimElaborator;
479
480     // Note that `elaborate_drops` only drops the upvars of a generator, and
481     // this is ok because `open_drop` can only be reached within that own
482     // generator's resume function.
483
484     let param_env = tcx.param_env(def_id);
485     let gen = self_arg();
486
487     for block in mir.basic_blocks().indices() {
488         let (target, unwind, source_info) = match mir.basic_blocks()[block].terminator() {
489             &Terminator {
490                 source_info,
491                 kind: TerminatorKind::Drop {
492                     location: Lvalue::Local(local),
493                     target,
494                     unwind
495                 }
496             } if local == gen => (target, unwind, source_info),
497             _ => continue,
498         };
499         let unwind = if let Some(unwind) = unwind {
500             Unwind::To(unwind)
501         } else {
502             Unwind::InCleanup
503         };
504         let patch = {
505             let mut elaborator = DropShimElaborator {
506                 mir: &mir,
507                 patch: MirPatch::new(mir),
508                 tcx,
509                 param_env
510             };
511             elaborate_drop(
512                 &mut elaborator,
513                 source_info,
514                 &Lvalue::Local(gen),
515                 (),
516                 target,
517                 unwind,
518                 block
519             );
520             elaborator.patch
521         };
522         patch.apply(mir);
523     }
524 }
525
526 fn create_generator_drop_shim<'a, 'tcx>(
527                 tcx: TyCtxt<'a, 'tcx, 'tcx>,
528                 transform: &TransformVisitor<'a, 'tcx>,
529                 def_id: DefId,
530                 source: MirSource,
531                 gen_ty: Ty<'tcx>,
532                 mir: &Mir<'tcx>,
533                 drop_clean: BasicBlock) -> Mir<'tcx> {
534     let mut mir = mir.clone();
535
536     let source_info = source_info(&mir);
537
538     let mut cases = create_cases(&mut mir, transform, |point| point.drop);
539
540     cases.insert(0, (0, drop_clean));
541
542     // The returned state (1) and the poisoned state (2) falls through to
543     // the default case which is just to return
544
545     insert_switch(tcx, &mut mir, cases, &transform);
546
547     for block in mir.basic_blocks_mut() {
548         let kind = &mut block.terminator_mut().kind;
549         if let TerminatorKind::GeneratorDrop = *kind {
550             *kind = TerminatorKind::Return;
551         }
552     }
553
554     // Replace the return variable
555     mir.return_ty = tcx.mk_nil();
556     mir.local_decls[RETURN_POINTER] = LocalDecl {
557         mutability: Mutability::Mut,
558         ty: tcx.mk_nil(),
559         name: None,
560         source_info,
561         internal: false,
562         is_user_variable: false,
563     };
564
565     make_generator_state_argument_indirect(tcx, def_id, &mut mir);
566
567     // Change the generator argument from &mut to *mut
568     mir.local_decls[self_arg()] = LocalDecl {
569         mutability: Mutability::Mut,
570         ty: tcx.mk_ptr(ty::TypeAndMut {
571             ty: gen_ty,
572             mutbl: hir::Mutability::MutMutable,
573         }),
574         name: None,
575         source_info,
576         internal: false,
577         is_user_variable: false,
578     };
579
580     no_landing_pads(tcx, &mut mir);
581
582     // Make sure we remove dead blocks to remove
583     // unrelated code from the resume part of the function
584     simplify::remove_dead_blocks(&mut mir);
585
586     dump_mir(tcx, None, "generator_drop", &0, source, &mut mir);
587
588     mir
589 }
590
591 fn insert_return_block<'tcx>(mir: &mut Mir<'tcx>) -> BasicBlock {
592     let return_block = BasicBlock::new(mir.basic_blocks().len());
593     let source_info = source_info(mir);
594     mir.basic_blocks_mut().push(BasicBlockData {
595         statements: Vec::new(),
596         terminator: Some(Terminator {
597             source_info,
598             kind: TerminatorKind::Return,
599         }),
600         is_cleanup: false,
601     });
602     return_block
603 }
604
605 fn insert_panic_block<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
606                                 mir: &mut Mir<'tcx>,
607                                 message: AssertMessage<'tcx>) -> BasicBlock {
608     let assert_block = BasicBlock::new(mir.basic_blocks().len());
609     let term = TerminatorKind::Assert {
610         cond: Operand::Constant(box Constant {
611             span: mir.span,
612             ty: tcx.types.bool,
613             literal: Literal::Value {
614                 value: tcx.mk_const(ty::Const {
615                     val: ConstVal::Bool(false),
616                     ty: tcx.types.bool
617                 }),
618             },
619         }),
620         expected: true,
621         msg: message,
622         target: assert_block,
623         cleanup: None,
624     };
625
626     let source_info = source_info(mir);
627     mir.basic_blocks_mut().push(BasicBlockData {
628         statements: Vec::new(),
629         terminator: Some(Terminator {
630             source_info,
631             kind: term,
632         }),
633         is_cleanup: false,
634     });
635
636     assert_block
637 }
638
639 fn create_generator_resume_function<'a, 'tcx>(
640         tcx: TyCtxt<'a, 'tcx, 'tcx>,
641         transform: TransformVisitor<'a, 'tcx>,
642         def_id: DefId,
643         source: MirSource,
644         mir: &mut Mir<'tcx>) {
645     // Poison the generator when it unwinds
646     for block in mir.basic_blocks_mut() {
647         let source_info = block.terminator().source_info;
648         if let &TerminatorKind::Resume = &block.terminator().kind {
649             block.statements.push(transform.set_state(1, source_info));
650         }
651     }
652
653     let mut cases = create_cases(mir, &transform, |point| Some(point.resume));
654
655     // Jump to the entry point on the 0 state
656     cases.insert(0, (0, BasicBlock::new(0)));
657     // Panic when resumed on the returned (1) state
658     cases.insert(1, (1, insert_panic_block(tcx, mir, AssertMessage::GeneratorResumedAfterReturn)));
659     // Panic when resumed on the poisoned (2) state
660     cases.insert(2, (2, insert_panic_block(tcx, mir, AssertMessage::GeneratorResumedAfterPanic)));
661
662     insert_switch(tcx, mir, cases, &transform);
663
664     make_generator_state_argument_indirect(tcx, def_id, mir);
665
666     no_landing_pads(tcx, mir);
667
668     // Make sure we remove dead blocks to remove
669     // unrelated code from the drop part of the function
670     simplify::remove_dead_blocks(mir);
671
672     dump_mir(tcx, None, "generator_resume", &0, source, mir);
673 }
674
675 fn source_info<'a, 'tcx>(mir: &Mir<'tcx>) -> SourceInfo {
676     SourceInfo {
677         span: mir.span,
678         scope: ARGUMENT_VISIBILITY_SCOPE,
679     }
680 }
681
682 fn insert_clean_drop<'a, 'tcx>(mir: &mut Mir<'tcx>) -> BasicBlock {
683     let return_block = insert_return_block(mir);
684
685     // Create a block to destroy an unresumed generators. This can only destroy upvars.
686     let drop_clean = BasicBlock::new(mir.basic_blocks().len());
687     let term = TerminatorKind::Drop {
688         location: Lvalue::Local(self_arg()),
689         target: return_block,
690         unwind: None,
691     };
692     let source_info = source_info(mir);
693     mir.basic_blocks_mut().push(BasicBlockData {
694         statements: Vec::new(),
695         terminator: Some(Terminator {
696             source_info,
697             kind: term,
698         }),
699         is_cleanup: false,
700     });
701
702     drop_clean
703 }
704
705 fn create_cases<'a, 'tcx, F>(mir: &mut Mir<'tcx>,
706                           transform: &TransformVisitor<'a, 'tcx>,
707                           target: F) -> Vec<(u32, BasicBlock)>
708     where F: Fn(&SuspensionPoint) -> Option<BasicBlock> {
709     let source_info = source_info(mir);
710
711     transform.suspension_points.iter().filter_map(|point| {
712         // Find the target for this suspension point, if applicable
713         target(point).map(|target| {
714             let block = BasicBlock::new(mir.basic_blocks().len());
715             let mut statements = Vec::new();
716
717             // Create StorageLive instructions for locals with live storage
718             for i in 0..(mir.local_decls.len()) {
719                 let l = Local::new(i);
720                 if point.storage_liveness.contains(&l) && !transform.remap.contains_key(&l) {
721                     statements.push(Statement {
722                         source_info,
723                         kind: StatementKind::StorageLive(l),
724                     });
725                 }
726             }
727
728             // Then jump to the real target
729             mir.basic_blocks_mut().push(BasicBlockData {
730                 statements,
731                 terminator: Some(Terminator {
732                     source_info,
733                     kind: TerminatorKind::Goto {
734                         target,
735                     },
736                 }),
737                 is_cleanup: false,
738             });
739
740             (point.state, block)
741         })
742     }).collect()
743 }
744
745 impl MirPass for StateTransform {
746     fn run_pass<'a, 'tcx>(&self,
747                     tcx: TyCtxt<'a, 'tcx, 'tcx>,
748                     source: MirSource,
749                     mir: &mut Mir<'tcx>) {
750         let yield_ty = if let Some(yield_ty) = mir.yield_ty {
751             yield_ty
752         } else {
753             // This only applies to generators
754             return
755         };
756
757         assert!(mir.generator_drop.is_none());
758
759         let node_id = source.item_id();
760         let def_id = tcx.hir.local_def_id(source.item_id());
761         let hir_id = tcx.hir.node_to_hir_id(node_id);
762
763         // Get the interior types which typeck computed
764         let interior = *tcx.typeck_tables_of(def_id).generator_interiors().get(hir_id).unwrap();
765
766         // The first argument is the generator type passed by value
767         let gen_ty = mir.local_decls.raw[1].ty;
768
769         // Compute GeneratorState<yield_ty, return_ty>
770         let state_did = tcx.lang_items().gen_state().unwrap();
771         let state_adt_ref = tcx.adt_def(state_did);
772         let state_substs = tcx.mk_substs([Kind::from(yield_ty),
773             Kind::from(mir.return_ty)].iter());
774         let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
775
776         // We rename RETURN_POINTER which has type mir.return_ty to new_ret_local
777         // RETURN_POINTER then is a fresh unused local with type ret_ty.
778         let new_ret_local = replace_result_variable(ret_ty, mir);
779
780         // Extract locals which are live across suspension point into `layout`
781         // `remap` gives a mapping from local indices onto generator struct indices
782         // `storage_liveness` tells us which locals have live storage at suspension points
783         let (remap, layout, storage_liveness) = compute_layout(tcx, source, interior, mir);
784
785         let state_field = mir.upvar_decls.len();
786
787         // Run the transformation which converts Lvalues from Local to generator struct
788         // accesses for locals in `remap`.
789         // It also rewrites `return x` and `yield y` as writing a new generator state and returning
790         // GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
791         let mut transform = TransformVisitor {
792             tcx,
793             state_adt_ref,
794             state_substs,
795             remap,
796             storage_liveness,
797             suspension_points: Vec::new(),
798             new_ret_local,
799             state_field,
800         };
801         transform.visit_mir(mir);
802
803         // Update our MIR struct to reflect the changed we've made
804         mir.return_ty = ret_ty;
805         mir.yield_ty = None;
806         mir.arg_count = 1;
807         mir.spread_arg = None;
808         mir.generator_layout = Some(layout);
809
810         // Insert `drop(generator_struct)` which is used to drop upvars for generators in
811         // the unresumed (0) state.
812         // This is expanded to a drop ladder in `elaborate_generator_drops`.
813         let drop_clean = insert_clean_drop(mir);
814
815         dump_mir(tcx, None, "generator_pre-elab", &0, source, mir);
816
817         // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
818         // If any upvars are moved out of, drop elaboration will handle upvar destruction.
819         // However we need to also elaborate the code generated by `insert_clean_drop`.
820         elaborate_generator_drops(tcx, def_id, mir);
821
822         dump_mir(tcx, None, "generator_post-transform", &0, source, mir);
823
824         // Create a copy of our MIR and use it to create the drop shim for the generator
825         let drop_shim = create_generator_drop_shim(tcx,
826             &transform,
827             def_id,
828             source,
829             gen_ty,
830             &mir,
831             drop_clean);
832
833         mir.generator_drop = Some(box drop_shim);
834
835         // Create the Generator::resume function
836         create_generator_resume_function(tcx, transform, def_id, source, mir);
837     }
838 }