-
Notifications
You must be signed in to change notification settings - Fork 12.7k
/
generator.rs
1290 lines (1107 loc) · 48.2 KB
/
generator.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This is the implementation of the pass which transforms generators into state machines.
//!
//! MIR generation for generators creates a function which has a self argument which
//! passes by value. This argument is effectively a generator type which only contains upvars and
//! is only used for this argument inside the MIR for the generator.
//! It is passed by value to enable upvars to be moved out of it. Drop elaboration runs on that
//! MIR before this pass and creates drop flags for MIR locals.
//! It will also drop the generator argument (which only consists of upvars) if any of the upvars
//! are moved out of. This pass elaborates the drops of upvars / generator argument in the case
//! that none of the upvars were moved out of. This is because we cannot have any drops of this
//! generator in the MIR, since it is used to create the drop glue for the generator. We'd get
//! infinite recursion otherwise.
//!
//! This pass creates the implementation for the Generator::resume function and the drop shim
//! for the generator based on the MIR input. It converts the generator argument from Self to
//! &mut Self adding derefs in the MIR as needed. It computes the final layout of the generator
//! struct which looks like this:
//! First upvars are stored
//! It is followed by the generator state field.
//! Then finally the MIR locals which are live across a suspension point are stored.
//!
//! struct Generator {
//! upvars...,
//! state: u32,
//! mir_locals...,
//! }
//!
//! This pass computes the meaning of the state field and the MIR locals which are live
//! across a suspension point. There are however three hardcoded generator states:
//! 0 - Generator have not been resumed yet
//! 1 - Generator has returned / is completed
//! 2 - Generator has been poisoned
//!
//! It also rewrites `return x` and `yield y` as setting a new generator state and returning
//! GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
//! MIR locals which are live across a suspension point are moved to the generator struct
//! with references to them being updated with references to the generator struct.
//!
//! The pass creates two functions which have a switch on the generator state giving
//! the action to take.
//!
//! One of them is the implementation of Generator::resume.
//! For generators with state 0 (unresumed) it starts the execution of the generator.
//! For generators with state 1 (returned) and state 2 (poisoned) it panics.
//! Otherwise it continues the execution from the last suspension point.
//!
//! The other function is the drop glue for the generator.
//! For generators with state 0 (unresumed) it drops the upvars of the generator.
//! For generators with state 1 (returned) and state 2 (poisoned) it does nothing.
//! Otherwise it drops all the values in scope at the last suspension point.
use crate::dataflow::impls::{
MaybeBorrowedLocals, MaybeInitializedLocals, MaybeLiveLocals, MaybeStorageLive,
};
use crate::dataflow::{self, Analysis};
use crate::transform::no_landing_pads::no_landing_pads;
use crate::transform::simplify;
use crate::transform::{MirPass, MirSource};
use crate::util::dump_mir;
use crate::util::storage;
use rustc_data_structures::fx::FxHashMap;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_hir::lang_items::{GeneratorStateLangItem, PinTypeLangItem};
use rustc_index::bit_set::{BitMatrix, BitSet};
use rustc_index::vec::{Idx, IndexVec};
use rustc_middle::mir::visit::{MutVisitor, PlaceContext};
use rustc_middle::mir::*;
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::GeneratorSubsts;
use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
use rustc_target::abi::VariantIdx;
use rustc_target::spec::PanicStrategy;
use std::borrow::Cow;
use std::iter;
pub struct StateTransform;
struct RenameLocalVisitor<'tcx> {
from: Local,
to: Local,
tcx: TyCtxt<'tcx>,
}
impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx
}
fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
if *local == self.from {
*local = self.to;
}
}
fn visit_terminator_kind(&mut self, kind: &mut TerminatorKind<'tcx>, location: Location) {
match kind {
TerminatorKind::Return => {
// Do not replace the implicit `_0` access here, as that's not possible. The
// transform already handles `return` correctly.
}
_ => self.super_terminator_kind(kind, location),
}
}
}
struct DerefArgVisitor<'tcx> {
tcx: TyCtxt<'tcx>,
}
impl<'tcx> MutVisitor<'tcx> for DerefArgVisitor<'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx
}
fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
assert_ne!(*local, SELF_ARG);
}
fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
if place.local == SELF_ARG {
replace_base(
place,
Place {
local: SELF_ARG,
projection: self.tcx().intern_place_elems(&[ProjectionElem::Deref]),
},
self.tcx,
);
} else {
self.visit_local(&mut place.local, context, location);
for elem in place.projection.iter() {
if let PlaceElem::Index(local) = elem {
assert_ne!(local, SELF_ARG);
}
}
}
}
}
struct PinArgVisitor<'tcx> {
ref_gen_ty: Ty<'tcx>,
tcx: TyCtxt<'tcx>,
}
impl<'tcx> MutVisitor<'tcx> for PinArgVisitor<'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx
}
fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
assert_ne!(*local, SELF_ARG);
}
fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
if place.local == SELF_ARG {
replace_base(
place,
Place {
local: SELF_ARG,
projection: self.tcx().intern_place_elems(&[ProjectionElem::Field(
Field::new(0),
self.ref_gen_ty,
)]),
},
self.tcx,
);
} else {
self.visit_local(&mut place.local, context, location);
for elem in place.projection.iter() {
if let PlaceElem::Index(local) = elem {
assert_ne!(local, SELF_ARG);
}
}
}
}
}
fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
place.local = new_base.local;
let mut new_projection = new_base.projection.to_vec();
new_projection.append(&mut place.projection.to_vec());
place.projection = tcx.intern_place_elems(&new_projection);
}
const SELF_ARG: Local = Local::from_u32(1);
/// Generator has not been resumed yet.
const UNRESUMED: usize = GeneratorSubsts::UNRESUMED;
/// Generator has returned / is completed.
const RETURNED: usize = GeneratorSubsts::RETURNED;
/// Generator has panicked and is poisoned.
const POISONED: usize = GeneratorSubsts::POISONED;
/// A `yield` point in the generator.
struct SuspensionPoint<'tcx> {
/// State discriminant used when suspending or resuming at this point.
state: usize,
/// The block to jump to after resumption.
resume: BasicBlock,
/// Where to move the resume argument after resumption.
resume_arg: Place<'tcx>,
/// Which block to jump to if the generator is dropped in this state.
drop: Option<BasicBlock>,
/// Set of locals that have live storage while at this suspension point.
storage_liveness: BitSet<Local>,
}
struct TransformVisitor<'tcx> {
tcx: TyCtxt<'tcx>,
state_adt_ref: &'tcx AdtDef,
state_substs: SubstsRef<'tcx>,
// The type of the discriminant in the generator struct
discr_ty: Ty<'tcx>,
// Mapping from Local to (type of local, generator struct index)
// FIXME(eddyb) This should use `IndexVec<Local, Option<_>>`.
remap: FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
// A map from a suspension point in a block to the locals which have live storage at that point
storage_liveness: IndexVec<BasicBlock, Option<BitSet<Local>>>,
// A list of suspension points, generated during the transform
suspension_points: Vec<SuspensionPoint<'tcx>>,
// The set of locals that have no `StorageLive`/`StorageDead` annotations.
always_live_locals: storage::AlwaysLiveLocals,
// The original RETURN_PLACE local
new_ret_local: Local,
}
impl TransformVisitor<'tcx> {
// Make a GeneratorState rvalue
fn make_state(&self, idx: VariantIdx, val: Operand<'tcx>) -> Rvalue<'tcx> {
let adt = AggregateKind::Adt(self.state_adt_ref, idx, self.state_substs, None, None);
Rvalue::Aggregate(box adt, vec![val])
}
// Create a Place referencing a generator struct field
fn make_field(&self, variant_index: VariantIdx, idx: usize, ty: Ty<'tcx>) -> Place<'tcx> {
let self_place = Place::from(SELF_ARG);
let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
let mut projection = base.projection.to_vec();
projection.push(ProjectionElem::Field(Field::new(idx), ty));
Place { local: base.local, projection: self.tcx.intern_place_elems(&projection) }
}
// Create a statement which changes the discriminant
fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
let self_place = Place::from(SELF_ARG);
Statement {
source_info,
kind: StatementKind::SetDiscriminant {
place: box self_place,
variant_index: state_disc,
},
}
}
// Create a statement which reads the discriminant into a temporary
fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
let temp_decl = LocalDecl::new(self.discr_ty, body.span).internal();
let local_decls_len = body.local_decls.push(temp_decl);
let temp = Place::from(local_decls_len);
let self_place = Place::from(SELF_ARG);
let assign = Statement {
source_info: SourceInfo::outermost(body.span),
kind: StatementKind::Assign(box (temp, Rvalue::Discriminant(self_place))),
};
(assign, temp)
}
}
impl MutVisitor<'tcx> for TransformVisitor<'tcx> {
fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx
}
fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
assert_eq!(self.remap.get(local), None);
}
fn visit_place(
&mut self,
place: &mut Place<'tcx>,
_context: PlaceContext,
_location: Location,
) {
// Replace an Local in the remap with a generator struct access
if let Some(&(ty, variant_index, idx)) = self.remap.get(&place.local) {
replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
}
}
fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
// Remove StorageLive and StorageDead statements for remapped locals
data.retain_statements(|s| match s.kind {
StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
!self.remap.contains_key(&l)
}
_ => true,
});
let ret_val = match data.terminator().kind {
TerminatorKind::Return => Some((
VariantIdx::new(1),
None,
Operand::Move(Place::from(self.new_ret_local)),
None,
)),
TerminatorKind::Yield { ref value, resume, resume_arg, drop } => {
Some((VariantIdx::new(0), Some((resume, resume_arg)), value.clone(), drop))
}
_ => None,
};
if let Some((state_idx, resume, v, drop)) = ret_val {
let source_info = data.terminator().source_info;
// We must assign the value first in case it gets declared dead below
data.statements.push(Statement {
source_info,
kind: StatementKind::Assign(box (
Place::return_place(),
self.make_state(state_idx, v),
)),
});
let state = if let Some((resume, resume_arg)) = resume {
// Yield
let state = 3 + self.suspension_points.len();
// The resume arg target location might itself be remapped if its base local is
// live across a yield.
let resume_arg =
if let Some(&(ty, variant, idx)) = self.remap.get(&resume_arg.local) {
self.make_field(variant, idx, ty)
} else {
resume_arg
};
self.suspension_points.push(SuspensionPoint {
state,
resume,
resume_arg,
drop,
storage_liveness: self.storage_liveness[block].clone().unwrap(),
});
VariantIdx::new(state)
} else {
// Return
VariantIdx::new(RETURNED) // state for returned
};
data.statements.push(self.set_discr(state, source_info));
data.terminator_mut().kind = TerminatorKind::Return;
}
self.super_basic_block_data(block, data);
}
}
fn make_generator_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
let gen_ty = body.local_decls.raw[1].ty;
let ref_gen_ty =
tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty: gen_ty, mutbl: Mutability::Mut });
// Replace the by value generator argument
body.local_decls.raw[1].ty = ref_gen_ty;
// Add a deref to accesses of the generator state
DerefArgVisitor { tcx }.visit_body(body);
}
fn make_generator_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
let ref_gen_ty = body.local_decls.raw[1].ty;
let pin_did = tcx.require_lang_item(PinTypeLangItem, Some(body.span));
let pin_adt_ref = tcx.adt_def(pin_did);
let substs = tcx.intern_substs(&[ref_gen_ty.into()]);
let pin_ref_gen_ty = tcx.mk_adt(pin_adt_ref, substs);
// Replace the by ref generator argument
body.local_decls.raw[1].ty = pin_ref_gen_ty;
// Add the Pin field access to accesses of the generator state
PinArgVisitor { ref_gen_ty, tcx }.visit_body(body);
}
/// Allocates a new local and replaces all references of `local` with it. Returns the new local.
///
/// `local` will be changed to a new local decl with type `ty`.
///
/// Note that the new local will be uninitialized. It is the caller's responsibility to assign some
/// valid value to it before its first use.
fn replace_local<'tcx>(
local: Local,
ty: Ty<'tcx>,
body: &mut Body<'tcx>,
tcx: TyCtxt<'tcx>,
) -> Local {
let new_decl = LocalDecl::new(ty, body.span);
let new_local = body.local_decls.push(new_decl);
body.local_decls.swap(local, new_local);
RenameLocalVisitor { from: local, to: new_local, tcx }.visit_body(body);
new_local
}
struct LivenessInfo {
/// Which locals are live across any suspension point.
///
/// GeneratorSavedLocal is indexed in terms of the elements in this set;
/// i.e. GeneratorSavedLocal::new(1) corresponds to the second local
/// included in this set.
live_locals: BitSet<Local>,
/// The set of saved locals live at each suspension point.
live_locals_at_suspension_points: Vec<BitSet<GeneratorSavedLocal>>,
/// For every saved local, the set of other saved locals that are
/// storage-live at the same time as this local. We cannot overlap locals in
/// the layout which have conflicting storage.
storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
/// For every suspending block, the locals which are storage-live across
/// that suspension point.
storage_liveness: IndexVec<BasicBlock, Option<BitSet<Local>>>,
}
fn locals_live_across_suspend_points(
tcx: TyCtxt<'tcx>,
body: &Body<'tcx>,
source: MirSource<'tcx>,
always_live_locals: &storage::AlwaysLiveLocals,
movable: bool,
) -> LivenessInfo {
let def_id = source.def_id();
// Calculate when MIR locals have live storage. This gives us an upper bound of their
// lifetimes.
let mut storage_live = MaybeStorageLive::new(always_live_locals.clone())
.into_engine(tcx, body, def_id)
.iterate_to_fixpoint()
.into_results_cursor(body);
let mut init = MaybeInitializedLocals
.into_engine(tcx, body, def_id)
.iterate_to_fixpoint()
.into_results_cursor(body);
let mut live = MaybeLiveLocals
.into_engine(tcx, body, def_id)
.iterate_to_fixpoint()
.into_results_cursor(body);
let mut borrowed = MaybeBorrowedLocals::all_borrows()
.into_engine(tcx, body, def_id)
.iterate_to_fixpoint()
.into_results_cursor(body);
// Liveness across yield points is determined by the following boolean equation, where `live`,
// `init` and `borrowed` come from dataflow and `movable` is a property of the generator.
// Movable generators do not allow borrows to live across yield points, so they don't need to
// store a local simply because it is borrowed.
//
// live_across_yield := (live & init) | (!movable & borrowed)
//
let mut locals_live_across_yield_point = |block| {
live.seek_to_block_end(block);
let mut live_locals = live.get().clone();
init.seek_to_block_end(block);
live_locals.intersect(init.get());
if !movable {
borrowed.seek_to_block_end(block);
live_locals.union(borrowed.get());
}
live_locals
};
let mut storage_liveness_map = IndexVec::from_elem(None, body.basic_blocks());
let mut live_locals_at_suspension_points = Vec::new();
let mut live_locals_at_any_suspension_point = BitSet::new_empty(body.local_decls.len());
for (block, data) in body.basic_blocks().iter_enumerated() {
if !matches!(data.terminator().kind, TerminatorKind::Yield { .. }) {
continue;
}
// Store the storage liveness for later use so we can restore the state
// after a suspension point
storage_live.seek_to_block_end(block);
storage_liveness_map[block] = Some(storage_live.get().clone());
let mut live_locals = locals_live_across_yield_point(block);
// The combination of `MaybeInitializedLocals` and `MaybeBorrowedLocals` should be strictly
// more precise than `MaybeStorageLive` because they handle `StorageDead` themselves. This
// assumes that the MIR forbids locals from being initialized/borrowed before reaching
// `StorageLive`.
debug_assert!(storage_live.get().superset(&live_locals));
// Ignore the generator's `self` argument since it is handled seperately.
live_locals.remove(SELF_ARG);
debug!("block = {:?}, live_locals = {:?}", block, live_locals);
live_locals_at_any_suspension_point.union(&live_locals);
live_locals_at_suspension_points.push(live_locals);
}
debug!("live_locals_anywhere = {:?}", live_locals_at_any_suspension_point);
// Renumber our liveness_map bitsets to include only the locals we are
// saving.
let live_locals_at_suspension_points = live_locals_at_suspension_points
.iter()
.map(|live_here| renumber_bitset(&live_here, &live_locals_at_any_suspension_point))
.collect();
let storage_conflicts = compute_storage_conflicts(
body,
&live_locals_at_any_suspension_point,
always_live_locals.clone(),
init,
borrowed,
);
LivenessInfo {
live_locals: live_locals_at_any_suspension_point,
live_locals_at_suspension_points,
storage_conflicts,
storage_liveness: storage_liveness_map,
}
}
/// Renumbers the items present in `stored_locals` and applies the renumbering
/// to 'input`.
///
/// For example, if `stored_locals = [1, 3, 5]`, this would be renumbered to
/// `[0, 1, 2]`. Thus, if `input = [3, 5]` we would return `[1, 2]`.
fn renumber_bitset(
input: &BitSet<Local>,
stored_locals: &BitSet<Local>,
) -> BitSet<GeneratorSavedLocal> {
assert!(stored_locals.superset(&input), "{:?} not a superset of {:?}", stored_locals, input);
let mut out = BitSet::new_empty(stored_locals.count());
for (idx, local) in stored_locals.iter().enumerate() {
let saved_local = GeneratorSavedLocal::from(idx);
if input.contains(local) {
out.insert(saved_local);
}
}
debug!("renumber_bitset({:?}, {:?}) => {:?}", input, stored_locals, out);
out
}
/// Record conflicts between locals at the current dataflow cursor positions.
///
/// You need to seek the cursors before calling this function.
fn record_conflicts_at_curr_loc(
local_conflicts: &mut BitMatrix<Local, Local>,
init: &dataflow::ResultsCursor<'mir, 'tcx, MaybeInitializedLocals>,
borrowed: &dataflow::ResultsCursor<'mir, 'tcx, MaybeBorrowedLocals>,
) {
// A local requires storage if it is initialized or borrowed. For now, a local
// becomes uninitialized if it is moved from, but is still considered "borrowed".
//
// requires_storage := init | borrowed
//
// Just like when determining what locals are live at yield points, there is no need
// to look at storage liveness here, since `init | borrowed` is strictly more precise.
//
// FIXME: This function is called in a loop, so it might be better to pass in a temporary
// bitset rather than cloning here.
let mut requires_storage = init.get().clone();
requires_storage.union(borrowed.get());
for local in requires_storage.iter() {
local_conflicts.union_row_with(&requires_storage, local);
}
// `>1` because the `self` argument always requires storage.
if requires_storage.count() > 1 {
trace!("requires_storage={:?}", requires_storage);
}
}
/// For every saved local, looks for which locals are StorageLive at the same
/// time. Generates a bitset for every local of all the other locals that may be
/// StorageLive simultaneously with that local. This is used in the layout
/// computation; see `GeneratorLayout` for more.
fn compute_storage_conflicts(
body: &'mir Body<'tcx>,
stored_locals: &BitSet<Local>,
always_live_locals: storage::AlwaysLiveLocals,
mut init: dataflow::ResultsCursor<'mir, 'tcx, MaybeInitializedLocals>,
mut borrowed: dataflow::ResultsCursor<'mir, 'tcx, MaybeBorrowedLocals>,
) -> BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal> {
debug!("compute_storage_conflicts({:?})", body.span);
assert_eq!(body.local_decls.len(), stored_locals.domain_size());
// Locals that are always live conflict with all other locals.
//
// FIXME: Why do we need to handle locals without `Storage{Live,Dead}` specially here?
// Shouldn't it be enough to know whether they are initialized?
let always_live_locals = always_live_locals.into_inner();
let mut local_conflicts = BitMatrix::from_row_n(&always_live_locals, body.local_decls.len());
// Visit every reachable statement and terminator. The exact order does not matter. When two
// locals are live at the same point in time, add an entry in the conflict matrix.
for (block, data) in traversal::preorder(body) {
// Ignore unreachable blocks.
if data.terminator().kind == TerminatorKind::Unreachable {
continue;
}
// Observe the dataflow state *before* all possible locations (statement or terminator) in
// each basic block...
for statement_index in 0..=data.statements.len() {
let loc = Location { block, statement_index };
trace!("record conflicts at {:?}", loc);
init.seek_before_primary_effect(loc);
borrowed.seek_before_primary_effect(loc);
record_conflicts_at_curr_loc(&mut local_conflicts, &init, &borrowed);
}
// ...and then observe the state *after* the terminator effect is applied. As long as
// neither `init` nor `borrowed` has a "before" effect, we will observe all possible
// dataflow states here or in the loop above.
trace!("record conflicts at end of {:?}", block);
init.seek_to_block_end(block);
borrowed.seek_to_block_end(block);
record_conflicts_at_curr_loc(&mut local_conflicts, &init, &borrowed);
}
// Compress the matrix using only stored locals (Local -> GeneratorSavedLocal).
//
// NOTE: Today we store a full conflict bitset for every local. Technically
// this is twice as many bits as we need, since the relation is symmetric.
// However, in practice these bitsets are not usually large. The layout code
// also needs to keep track of how many conflicts each local has, so it's
// simpler to keep it this way for now.
let mut storage_conflicts = BitMatrix::new(stored_locals.count(), stored_locals.count());
for (idx_a, local_a) in stored_locals.iter().enumerate() {
let saved_local_a = GeneratorSavedLocal::new(idx_a);
if always_live_locals.contains(local_a) {
// Conflicts with everything.
storage_conflicts.insert_all_into_row(saved_local_a);
} else {
// Keep overlap information only for stored locals.
for (idx_b, local_b) in stored_locals.iter().enumerate() {
let saved_local_b = GeneratorSavedLocal::new(idx_b);
if local_conflicts.contains(local_a, local_b) {
storage_conflicts.insert(saved_local_a, saved_local_b);
}
}
}
}
storage_conflicts
}
fn compute_layout<'tcx>(
tcx: TyCtxt<'tcx>,
source: MirSource<'tcx>,
upvars: &Vec<Ty<'tcx>>,
interior: Ty<'tcx>,
always_live_locals: &storage::AlwaysLiveLocals,
movable: bool,
body: &mut Body<'tcx>,
) -> (
FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
GeneratorLayout<'tcx>,
IndexVec<BasicBlock, Option<BitSet<Local>>>,
) {
// Use a liveness analysis to compute locals which are live across a suspension point
let LivenessInfo {
live_locals,
live_locals_at_suspension_points,
storage_conflicts,
storage_liveness,
} = locals_live_across_suspend_points(tcx, body, source, always_live_locals, movable);
// Erase regions from the types passed in from typeck so we can compare them with
// MIR types
let allowed_upvars = tcx.erase_regions(upvars);
let allowed = match interior.kind {
ty::GeneratorWitness(s) => tcx.erase_late_bound_regions(&s),
_ => bug!(),
};
let param_env = tcx.param_env(source.def_id());
for (local, decl) in body.local_decls.iter_enumerated() {
// Ignore locals which are internal or not live
if !live_locals.contains(local) || decl.internal {
continue;
}
let decl_ty = tcx.normalize_erasing_regions(param_env, decl.ty);
// Sanity check that typeck knows about the type of locals which are
// live across a suspension point
if !allowed.contains(&decl_ty) && !allowed_upvars.contains(&decl_ty) {
span_bug!(
body.span,
"Broken MIR: generator contains type {} in MIR, \
but typeck only knows about {}",
decl.ty,
interior
);
}
}
// Gather live local types and their indices.
let mut locals = IndexVec::<GeneratorSavedLocal, _>::new();
let mut tys = IndexVec::<GeneratorSavedLocal, _>::new();
for (idx, local) in live_locals.iter().enumerate() {
locals.push(local);
tys.push(body.local_decls[local].ty);
debug!("generator saved local {:?} => {:?}", GeneratorSavedLocal::from(idx), local);
}
// Leave empty variants for the UNRESUMED, RETURNED, and POISONED states.
const RESERVED_VARIANTS: usize = 3;
// Build the generator variant field list.
// Create a map from local indices to generator struct indices.
let mut variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>> =
iter::repeat(IndexVec::new()).take(RESERVED_VARIANTS).collect();
let mut remap = FxHashMap::default();
for (suspension_point_idx, live_locals) in live_locals_at_suspension_points.iter().enumerate() {
let variant_index = VariantIdx::from(RESERVED_VARIANTS + suspension_point_idx);
let mut fields = IndexVec::new();
for (idx, saved_local) in live_locals.iter().enumerate() {
fields.push(saved_local);
// Note that if a field is included in multiple variants, we will
// just use the first one here. That's fine; fields do not move
// around inside generators, so it doesn't matter which variant
// index we access them by.
remap.entry(locals[saved_local]).or_insert((tys[saved_local], variant_index, idx));
}
variant_fields.push(fields);
}
debug!("generator variant_fields = {:?}", variant_fields);
debug!("generator storage_conflicts = {:#?}", storage_conflicts);
let layout = GeneratorLayout { field_tys: tys, variant_fields, storage_conflicts };
(remap, layout, storage_liveness)
}
/// Replaces the entry point of `body` with a block that switches on the generator discriminant and
/// dispatches to blocks according to `cases`.
///
/// After this function, the former entry point of the function will be bb1.
fn insert_switch<'tcx>(
body: &mut Body<'tcx>,
cases: Vec<(usize, BasicBlock)>,
transform: &TransformVisitor<'tcx>,
default: TerminatorKind<'tcx>,
) {
let default_block = insert_term_block(body, default);
let (assign, discr) = transform.get_discr(body);
let switch = TerminatorKind::SwitchInt {
discr: Operand::Move(discr),
switch_ty: transform.discr_ty,
values: Cow::from(cases.iter().map(|&(i, _)| i as u128).collect::<Vec<_>>()),
targets: cases.iter().map(|&(_, d)| d).chain(iter::once(default_block)).collect(),
};
let source_info = SourceInfo::outermost(body.span);
body.basic_blocks_mut().raw.insert(
0,
BasicBlockData {
statements: vec![assign],
terminator: Some(Terminator { source_info, kind: switch }),
is_cleanup: false,
},
);
let blocks = body.basic_blocks_mut().iter_mut();
for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
*target = BasicBlock::new(target.index() + 1);
}
}
fn elaborate_generator_drops<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, body: &mut Body<'tcx>) {
use crate::shim::DropShimElaborator;
use crate::util::elaborate_drops::{elaborate_drop, Unwind};
use crate::util::patch::MirPatch;
// Note that `elaborate_drops` only drops the upvars of a generator, and
// this is ok because `open_drop` can only be reached within that own
// generator's resume function.
let param_env = tcx.param_env(def_id);
let mut elaborator = DropShimElaborator { body, patch: MirPatch::new(body), tcx, param_env };
for (block, block_data) in body.basic_blocks().iter_enumerated() {
let (target, unwind, source_info) = match block_data.terminator() {
Terminator { source_info, kind: TerminatorKind::Drop { location, target, unwind } } => {
if let Some(local) = location.as_local() {
if local == SELF_ARG {
(target, unwind, source_info)
} else {
continue;
}
} else {
continue;
}
}
_ => continue,
};
let unwind = if block_data.is_cleanup {
Unwind::InCleanup
} else {
Unwind::To(unwind.unwrap_or_else(|| elaborator.patch.resume_block()))
};
elaborate_drop(
&mut elaborator,
*source_info,
Place::from(SELF_ARG),
(),
*target,
unwind,
block,
);
}
elaborator.patch.apply(body);
}
fn create_generator_drop_shim<'tcx>(
tcx: TyCtxt<'tcx>,
transform: &TransformVisitor<'tcx>,
source: MirSource<'tcx>,
gen_ty: Ty<'tcx>,
body: &mut Body<'tcx>,
drop_clean: BasicBlock,
) -> Body<'tcx> {
let mut body = body.clone();
body.arg_count = 1; // make sure the resume argument is not included here
let source_info = SourceInfo::outermost(body.span);
let mut cases = create_cases(&mut body, transform, Operation::Drop);
cases.insert(0, (UNRESUMED, drop_clean));
// The returned state and the poisoned state fall through to the default
// case which is just to return
insert_switch(&mut body, cases, &transform, TerminatorKind::Return);
for block in body.basic_blocks_mut() {
let kind = &mut block.terminator_mut().kind;
if let TerminatorKind::GeneratorDrop = *kind {
*kind = TerminatorKind::Return;
}
}
// Replace the return variable
body.local_decls[RETURN_PLACE] = LocalDecl::with_source_info(tcx.mk_unit(), source_info);
make_generator_state_argument_indirect(tcx, &mut body);
// Change the generator argument from &mut to *mut
body.local_decls[SELF_ARG] = LocalDecl::with_source_info(
tcx.mk_ptr(ty::TypeAndMut { ty: gen_ty, mutbl: hir::Mutability::Mut }),
source_info,
);
if tcx.sess.opts.debugging_opts.mir_emit_retag {
// Alias tracking must know we changed the type
body.basic_blocks_mut()[START_BLOCK].statements.insert(
0,
Statement {
source_info,
kind: StatementKind::Retag(RetagKind::Raw, box Place::from(SELF_ARG)),
},
)
}
no_landing_pads(tcx, &mut body);
// Make sure we remove dead blocks to remove
// unrelated code from the resume part of the function
simplify::remove_dead_blocks(&mut body);
dump_mir(tcx, None, "generator_drop", &0, source, &body, |_, _| Ok(()));
body
}
fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
let source_info = SourceInfo::outermost(body.span);
body.basic_blocks_mut().push(BasicBlockData {
statements: Vec::new(),
terminator: Some(Terminator { source_info, kind }),
is_cleanup: false,
})
}
fn insert_panic_block<'tcx>(
tcx: TyCtxt<'tcx>,
body: &mut Body<'tcx>,
message: AssertMessage<'tcx>,
) -> BasicBlock {
let assert_block = BasicBlock::new(body.basic_blocks().len());
let term = TerminatorKind::Assert {
cond: Operand::Constant(box Constant {
span: body.span,
user_ty: None,
literal: ty::Const::from_bool(tcx, false),
}),
expected: true,
msg: message,
target: assert_block,
cleanup: None,
};
let source_info = SourceInfo::outermost(body.span);
body.basic_blocks_mut().push(BasicBlockData {
statements: Vec::new(),
terminator: Some(Terminator { source_info, kind: term }),
is_cleanup: false,
});
assert_block
}
fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
// Returning from a function with an uninhabited return type is undefined behavior.
if body.return_ty().conservative_is_privately_uninhabited(tcx) {
return false;
}
// If there's a return terminator the function may return.
for block in body.basic_blocks() {
if let TerminatorKind::Return = block.terminator().kind {
return true;
}
}
// Otherwise the function can't return.
false
}
fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
// Nothing can unwind when landing pads are off.
if tcx.sess.panic_strategy() == PanicStrategy::Abort {
return false;
}
// Unwinds can only start at certain terminators.
for block in body.basic_blocks() {
match block.terminator().kind {
// These never unwind.
TerminatorKind::Goto { .. }
| TerminatorKind::SwitchInt { .. }
| TerminatorKind::Abort
| TerminatorKind::Return
| TerminatorKind::Unreachable
| TerminatorKind::GeneratorDrop
| TerminatorKind::FalseEdges { .. }
| TerminatorKind::FalseUnwind { .. }
| TerminatorKind::InlineAsm { .. } => {}
// Resume will *continue* unwinding, but if there's no other unwinding terminator it
// will never be reached.
TerminatorKind::Resume => {}
TerminatorKind::Yield { .. } => {
unreachable!("`can_unwind` called before generator transform")
}
// These may unwind.
TerminatorKind::Drop { .. }
| TerminatorKind::DropAndReplace { .. }
| TerminatorKind::Call { .. }
| TerminatorKind::Assert { .. } => return true,
}
}
// If we didn't find an unwinding terminator, the function cannot unwind.
false
}
fn create_generator_resume_function<'tcx>(
tcx: TyCtxt<'tcx>,
transform: TransformVisitor<'tcx>,