forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscope.rs
1542 lines (1383 loc) · 60.5 KB
/
scope.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
/*!
Managing the scope stack. The scopes are tied to lexical scopes, so as
we descend the THIR, we push a scope on the stack, build its
contents, and then pop it off. Every scope is named by a
`region::Scope`.
### SEME Regions
When pushing a new [Scope], we record the current point in the graph (a
basic block); this marks the entry to the scope. We then generate more
stuff in the control-flow graph. Whenever the scope is exited, either
via a `break` or `return` or just by fallthrough, that marks an exit
from the scope. Each lexical scope thus corresponds to a single-entry,
multiple-exit (SEME) region in the control-flow graph.
For now, we record the `region::Scope` to each SEME region for later reference
(see caveat in next paragraph). This is because destruction scopes are tied to
them. This may change in the future so that MIR lowering determines its own
destruction scopes.
### Not so SEME Regions
In the course of building matches, it sometimes happens that certain code
(namely guards) gets executed multiple times. This means that the scope lexical
scope may in fact correspond to multiple, disjoint SEME regions. So in fact our
mapping is from one scope to a vector of SEME regions. Since the SEME regions
are disjoint, the mapping is still one-to-one for the set of SEME regions that
we're currently in.
Also in matches, the scopes assigned to arms are not always even SEME regions!
Each arm has a single region with one entry for each pattern. We manually
manipulate the scheduled drops in this scope to avoid dropping things multiple
times.
### Drops
The primary purpose for scopes is to insert drops: while building
the contents, we also accumulate places that need to be dropped upon
exit from each scope. This is done by calling `schedule_drop`. Once a
drop is scheduled, whenever we branch out we will insert drops of all
those places onto the outgoing edge. Note that we don't know the full
set of scheduled drops up front, and so whenever we exit from the
scope we only drop the values scheduled thus far. For example, consider
the scope S corresponding to this loop:
```
# let cond = true;
loop {
let x = ..;
if cond { break; }
let y = ..;
}
```
When processing the `let x`, we will add one drop to the scope for
`x`. The break will then insert a drop for `x`. When we process `let
y`, we will add another drop (in fact, to a subscope, but let's ignore
that for now); any later drops would also drop `y`.
### Early exit
There are numerous "normal" ways to early exit a scope: `break`,
`continue`, `return` (panics are handled separately). Whenever an
early exit occurs, the method `break_scope` is called. It is given the
current point in execution where the early exit occurs, as well as the
scope you want to branch to (note that all early exits from to some
other enclosing scope). `break_scope` will record the set of drops currently
scheduled in a [DropTree]. Later, before `in_breakable_scope` exits, the drops
will be added to the CFG.
Panics are handled in a similar fashion, except that the drops are added to the
MIR once the rest of the function has finished being lowered. If a terminator
can panic, call `diverge_from(block)` with the block containing the terminator
`block`.
### Breakable scopes
In addition to the normal scope stack, we track a loop scope stack
that contains only loops and breakable blocks. It tracks where a `break`,
`continue` or `return` should go to.
*/
use std::mem;
use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder, CFG};
use rustc_data_structures::fx::FxHashMap;
use rustc_hir::HirId;
use rustc_index::{IndexSlice, IndexVec};
use rustc_middle::middle::region;
use rustc_middle::mir::*;
use rustc_middle::thir::{ExprId, LintLevel};
use rustc_session::lint::Level;
use rustc_span::source_map::Spanned;
use rustc_span::{Span, DUMMY_SP};
#[derive(Debug)]
pub struct Scopes<'tcx> {
scopes: Vec<Scope>,
/// The current set of breakable scopes. See module comment for more details.
breakable_scopes: Vec<BreakableScope<'tcx>>,
/// The scope of the innermost if-then currently being lowered.
if_then_scope: Option<IfThenScope>,
/// Drops that need to be done on unwind paths. See the comment on
/// [DropTree] for more details.
unwind_drops: DropTree,
/// Drops that need to be done on paths to the `CoroutineDrop` terminator.
coroutine_drops: DropTree,
}
#[derive(Debug)]
struct Scope {
/// The source scope this scope was created in.
source_scope: SourceScope,
/// the region span of this scope within source code.
region_scope: region::Scope,
/// set of places to drop when exiting this scope. This starts
/// out empty but grows as variables are declared during the
/// building process. This is a stack, so we always drop from the
/// end of the vector (top of the stack) first.
drops: Vec<DropData>,
moved_locals: Vec<Local>,
/// The drop index that will drop everything in and below this scope on an
/// unwind path.
cached_unwind_block: Option<DropIdx>,
/// The drop index that will drop everything in and below this scope on a
/// coroutine drop path.
cached_coroutine_drop_block: Option<DropIdx>,
}
#[derive(Clone, Copy, Debug)]
struct DropData {
/// The `Span` where drop obligation was incurred (typically where place was
/// declared)
source_info: SourceInfo,
/// local to drop
local: Local,
/// Whether this is a value Drop or a StorageDead.
kind: DropKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum DropKind {
Value,
Storage,
}
#[derive(Debug)]
struct BreakableScope<'tcx> {
/// Region scope of the loop
region_scope: region::Scope,
/// The destination of the loop/block expression itself (i.e., where to put
/// the result of a `break` or `return` expression)
break_destination: Place<'tcx>,
/// Drops that happen on the `break`/`return` path.
break_drops: DropTree,
/// Drops that happen on the `continue` path.
continue_drops: Option<DropTree>,
}
#[derive(Debug)]
struct IfThenScope {
/// The if-then scope or arm scope
region_scope: region::Scope,
/// Drops that happen on the `else` path.
else_drops: DropTree,
}
/// The target of an expression that breaks out of a scope
#[derive(Clone, Copy, Debug)]
pub(crate) enum BreakableTarget {
Continue(region::Scope),
Break(region::Scope),
Return,
}
rustc_index::newtype_index! {
#[orderable]
struct DropIdx {}
}
const ROOT_NODE: DropIdx = DropIdx::from_u32(0);
/// A tree of drops that we have deferred lowering. It's used for:
///
/// * Drops on unwind paths
/// * Drops on coroutine drop paths (when a suspended coroutine is dropped)
/// * Drops on return and loop exit paths
/// * Drops on the else path in an `if let` chain
///
/// Once no more nodes could be added to the tree, we lower it to MIR in one go
/// in `build_mir`.
#[derive(Debug)]
struct DropTree {
/// Nodes in the drop tree, containing drop data and a link to the next node.
drops: IndexVec<DropIdx, DropNode>,
/// Map for finding the index of an existing node, given its contents.
existing_drops_map: FxHashMap<DropNodeKey, DropIdx>,
/// Edges into the `DropTree` that need to be added once it's lowered.
entry_points: Vec<(DropIdx, BasicBlock)>,
}
/// A single node in the drop tree.
#[derive(Debug)]
struct DropNode {
/// Info about the drop to be performed at this node in the drop tree.
data: DropData,
/// Index of the "next" drop to perform (in drop order, not declaration order).
next: DropIdx,
}
/// Subset of [`DropNode`] used for reverse lookup in a hash table.
#[derive(Debug, PartialEq, Eq, Hash)]
struct DropNodeKey {
next: DropIdx,
local: Local,
kind: DropKind,
}
impl Scope {
/// Whether there's anything to do for the cleanup path, that is,
/// when unwinding through this scope. This includes destructors,
/// but not StorageDead statements, which don't get emitted at all
/// for unwinding, for several reasons:
/// * clang doesn't emit llvm.lifetime.end for C++ unwinding
/// * LLVM's memory dependency analysis can't handle it atm
/// * polluting the cleanup MIR with StorageDead creates
/// landing pads even though there's no actual destructors
/// * freeing up stack space has no effect during unwinding
/// Note that for coroutines we do emit StorageDeads, for the
/// use of optimizations in the MIR coroutine transform.
fn needs_cleanup(&self) -> bool {
self.drops.iter().any(|drop| match drop.kind {
DropKind::Value => true,
DropKind::Storage => false,
})
}
fn invalidate_cache(&mut self) {
self.cached_unwind_block = None;
self.cached_coroutine_drop_block = None;
}
}
/// A trait that determined how [DropTree] creates its blocks and
/// links to any entry nodes.
trait DropTreeBuilder<'tcx> {
/// Create a new block for the tree. This should call either
/// `cfg.start_new_block()` or `cfg.start_new_cleanup_block()`.
fn make_block(cfg: &mut CFG<'tcx>) -> BasicBlock;
/// Links a block outside the drop tree, `from`, to the block `to` inside
/// the drop tree.
fn link_entry_point(cfg: &mut CFG<'tcx>, from: BasicBlock, to: BasicBlock);
}
impl DropTree {
fn new() -> Self {
// The root node of the tree doesn't represent a drop, but instead
// represents the block in the tree that should be jumped to once all
// of the required drops have been performed.
let fake_source_info = SourceInfo::outermost(DUMMY_SP);
let fake_data =
DropData { source_info: fake_source_info, local: Local::MAX, kind: DropKind::Storage };
let drops = IndexVec::from_raw(vec![DropNode { data: fake_data, next: DropIdx::MAX }]);
Self { drops, entry_points: Vec::new(), existing_drops_map: FxHashMap::default() }
}
/// Adds a node to the drop tree, consisting of drop data and the index of
/// the "next" drop (in drop order), which could be the sentinel [`ROOT_NODE`].
///
/// If there is already an equivalent node in the tree, nothing is added, and
/// that node's index is returned. Otherwise, the new node's index is returned.
fn add_drop(&mut self, data: DropData, next: DropIdx) -> DropIdx {
let drops = &mut self.drops;
*self
.existing_drops_map
.entry(DropNodeKey { next, local: data.local, kind: data.kind })
// Create a new node, and also add its index to the map.
.or_insert_with(|| drops.push(DropNode { data, next }))
}
/// Registers `from` as an entry point to this drop tree, at `to`.
///
/// During [`Self::build_mir`], `from` will be linked to the corresponding
/// block within the drop tree.
fn add_entry_point(&mut self, from: BasicBlock, to: DropIdx) {
debug_assert!(to < self.drops.next_index());
self.entry_points.push((to, from));
}
/// Builds the MIR for a given drop tree.
///
/// `blocks` should have the same length as `self.drops`, and may have its
/// first value set to some already existing block.
fn build_mir<'tcx, T: DropTreeBuilder<'tcx>>(
&mut self,
cfg: &mut CFG<'tcx>,
blocks: &mut IndexVec<DropIdx, Option<BasicBlock>>,
) {
debug!("DropTree::build_mir(drops = {:#?})", self);
assert_eq!(blocks.len(), self.drops.len());
self.assign_blocks::<T>(cfg, blocks);
self.link_blocks(cfg, blocks)
}
/// Assign blocks for all of the drops in the drop tree that need them.
fn assign_blocks<'tcx, T: DropTreeBuilder<'tcx>>(
&mut self,
cfg: &mut CFG<'tcx>,
blocks: &mut IndexVec<DropIdx, Option<BasicBlock>>,
) {
// StorageDead statements can share blocks with each other and also with
// a Drop terminator. We iterate through the drops to find which drops
// need their own block.
#[derive(Clone, Copy)]
enum Block {
// This drop is unreachable
None,
// This drop is only reachable through the `StorageDead` with the
// specified index.
Shares(DropIdx),
// This drop has more than one way of being reached, or it is
// branched to from outside the tree, or its predecessor is a
// `Value` drop.
Own,
}
let mut needs_block = IndexVec::from_elem(Block::None, &self.drops);
if blocks[ROOT_NODE].is_some() {
// In some cases (such as drops for `continue`) the root node
// already has a block. In this case, make sure that we don't
// override it.
needs_block[ROOT_NODE] = Block::Own;
}
// Sort so that we only need to check the last value.
let entry_points = &mut self.entry_points;
entry_points.sort();
for (drop_idx, drop_node) in self.drops.iter_enumerated().rev() {
if entry_points.last().is_some_and(|entry_point| entry_point.0 == drop_idx) {
let block = *blocks[drop_idx].get_or_insert_with(|| T::make_block(cfg));
needs_block[drop_idx] = Block::Own;
while entry_points.last().is_some_and(|entry_point| entry_point.0 == drop_idx) {
let entry_block = entry_points.pop().unwrap().1;
T::link_entry_point(cfg, entry_block, block);
}
}
match needs_block[drop_idx] {
Block::None => continue,
Block::Own => {
blocks[drop_idx].get_or_insert_with(|| T::make_block(cfg));
}
Block::Shares(pred) => {
blocks[drop_idx] = blocks[pred];
}
}
if let DropKind::Value = drop_node.data.kind {
needs_block[drop_node.next] = Block::Own;
} else if drop_idx != ROOT_NODE {
match &mut needs_block[drop_node.next] {
pred @ Block::None => *pred = Block::Shares(drop_idx),
pred @ Block::Shares(_) => *pred = Block::Own,
Block::Own => (),
}
}
}
debug!("assign_blocks: blocks = {:#?}", blocks);
assert!(entry_points.is_empty());
}
fn link_blocks<'tcx>(
&self,
cfg: &mut CFG<'tcx>,
blocks: &IndexSlice<DropIdx, Option<BasicBlock>>,
) {
for (drop_idx, drop_node) in self.drops.iter_enumerated().rev() {
let Some(block) = blocks[drop_idx] else { continue };
match drop_node.data.kind {
DropKind::Value => {
let terminator = TerminatorKind::Drop {
target: blocks[drop_node.next].unwrap(),
// The caller will handle this if needed.
unwind: UnwindAction::Terminate(UnwindTerminateReason::InCleanup),
place: drop_node.data.local.into(),
replace: false,
};
cfg.terminate(block, drop_node.data.source_info, terminator);
}
// Root nodes don't correspond to a drop.
DropKind::Storage if drop_idx == ROOT_NODE => {}
DropKind::Storage => {
let stmt = Statement {
source_info: drop_node.data.source_info,
kind: StatementKind::StorageDead(drop_node.data.local),
};
cfg.push(block, stmt);
let target = blocks[drop_node.next].unwrap();
if target != block {
// Diagnostics don't use this `Span` but debuginfo
// might. Since we don't want breakpoints to be placed
// here, especially when this is on an unwind path, we
// use `DUMMY_SP`.
let source_info =
SourceInfo { span: DUMMY_SP, ..drop_node.data.source_info };
let terminator = TerminatorKind::Goto { target };
cfg.terminate(block, source_info, terminator);
}
}
}
}
}
}
impl<'tcx> Scopes<'tcx> {
pub(crate) fn new() -> Self {
Self {
scopes: Vec::new(),
breakable_scopes: Vec::new(),
if_then_scope: None,
unwind_drops: DropTree::new(),
coroutine_drops: DropTree::new(),
}
}
fn push_scope(&mut self, region_scope: (region::Scope, SourceInfo), vis_scope: SourceScope) {
debug!("push_scope({:?})", region_scope);
self.scopes.push(Scope {
source_scope: vis_scope,
region_scope: region_scope.0,
drops: vec![],
moved_locals: vec![],
cached_unwind_block: None,
cached_coroutine_drop_block: None,
});
}
fn pop_scope(&mut self, region_scope: (region::Scope, SourceInfo)) -> Scope {
let scope = self.scopes.pop().unwrap();
assert_eq!(scope.region_scope, region_scope.0);
scope
}
fn scope_index(&self, region_scope: region::Scope, span: Span) -> usize {
self.scopes
.iter()
.rposition(|scope| scope.region_scope == region_scope)
.unwrap_or_else(|| span_bug!(span, "region_scope {:?} does not enclose", region_scope))
}
/// Returns the topmost active scope, which is known to be alive until
/// the next scope expression.
fn topmost(&self) -> region::Scope {
self.scopes.last().expect("topmost_scope: no scopes present").region_scope
}
}
impl<'a, 'tcx> Builder<'a, 'tcx> {
// Adding and removing scopes
// ==========================
/// Start a breakable scope, which tracks where `continue`, `break` and
/// `return` should branch to.
pub(crate) fn in_breakable_scope<F>(
&mut self,
loop_block: Option<BasicBlock>,
break_destination: Place<'tcx>,
span: Span,
f: F,
) -> BlockAnd<()>
where
F: FnOnce(&mut Builder<'a, 'tcx>) -> Option<BlockAnd<()>>,
{
let region_scope = self.scopes.topmost();
let scope = BreakableScope {
region_scope,
break_destination,
break_drops: DropTree::new(),
continue_drops: loop_block.map(|_| DropTree::new()),
};
self.scopes.breakable_scopes.push(scope);
let normal_exit_block = f(self);
let breakable_scope = self.scopes.breakable_scopes.pop().unwrap();
assert!(breakable_scope.region_scope == region_scope);
let break_block =
self.build_exit_tree(breakable_scope.break_drops, region_scope, span, None);
if let Some(drops) = breakable_scope.continue_drops {
self.build_exit_tree(drops, region_scope, span, loop_block);
}
match (normal_exit_block, break_block) {
(Some(block), None) | (None, Some(block)) => block,
(None, None) => self.cfg.start_new_block().unit(),
(Some(normal_block), Some(exit_block)) => {
let target = self.cfg.start_new_block();
let source_info = self.source_info(span);
self.cfg.terminate(
unpack!(normal_block),
source_info,
TerminatorKind::Goto { target },
);
self.cfg.terminate(
unpack!(exit_block),
source_info,
TerminatorKind::Goto { target },
);
target.unit()
}
}
}
/// Start an if-then scope which tracks drop for `if` expressions and `if`
/// guards.
///
/// For an if-let chain:
///
/// if let Some(x) = a && let Some(y) = b && let Some(z) = c { ... }
///
/// There are three possible ways the condition can be false and we may have
/// to drop `x`, `x` and `y`, or neither depending on which binding fails.
/// To handle this correctly we use a `DropTree` in a similar way to a
/// `loop` expression and 'break' out on all of the 'else' paths.
///
/// Notes:
/// - We don't need to keep a stack of scopes in the `Builder` because the
/// 'else' paths will only leave the innermost scope.
/// - This is also used for match guards.
pub(crate) fn in_if_then_scope<F>(
&mut self,
region_scope: region::Scope,
span: Span,
f: F,
) -> (BasicBlock, BasicBlock)
where
F: FnOnce(&mut Builder<'a, 'tcx>) -> BlockAnd<()>,
{
let scope = IfThenScope { region_scope, else_drops: DropTree::new() };
let previous_scope = mem::replace(&mut self.scopes.if_then_scope, Some(scope));
let then_block = unpack!(f(self));
let if_then_scope = mem::replace(&mut self.scopes.if_then_scope, previous_scope).unwrap();
assert!(if_then_scope.region_scope == region_scope);
let else_block = self
.build_exit_tree(if_then_scope.else_drops, region_scope, span, None)
.map_or_else(|| self.cfg.start_new_block(), |else_block_and| unpack!(else_block_and));
(then_block, else_block)
}
/// Convenience wrapper that pushes a scope and then executes `f`
/// to build its contents, popping the scope afterwards.
#[instrument(skip(self, f), level = "debug")]
pub(crate) fn in_scope<F, R>(
&mut self,
region_scope: (region::Scope, SourceInfo),
lint_level: LintLevel,
f: F,
) -> BlockAnd<R>
where
F: FnOnce(&mut Builder<'a, 'tcx>) -> BlockAnd<R>,
{
let source_scope = self.source_scope;
if let LintLevel::Explicit(current_hir_id) = lint_level {
let parent_id =
self.source_scopes[source_scope].local_data.as_ref().assert_crate_local().lint_root;
self.maybe_new_source_scope(region_scope.1.span, None, current_hir_id, parent_id);
}
self.push_scope(region_scope);
let mut block;
let rv = unpack!(block = f(self));
unpack!(block = self.pop_scope(region_scope, block));
self.source_scope = source_scope;
debug!(?block);
block.and(rv)
}
/// Push a scope onto the stack. You can then build code in this
/// scope and call `pop_scope` afterwards. Note that these two
/// calls must be paired; using `in_scope` as a convenience
/// wrapper maybe preferable.
pub(crate) fn push_scope(&mut self, region_scope: (region::Scope, SourceInfo)) {
self.scopes.push_scope(region_scope, self.source_scope);
}
/// Pops a scope, which should have region scope `region_scope`,
/// adding any drops onto the end of `block` that are needed.
/// This must match 1-to-1 with `push_scope`.
pub(crate) fn pop_scope(
&mut self,
region_scope: (region::Scope, SourceInfo),
mut block: BasicBlock,
) -> BlockAnd<()> {
debug!("pop_scope({:?}, {:?})", region_scope, block);
block = self.leave_top_scope(block);
self.scopes.pop_scope(region_scope);
block.unit()
}
/// Sets up the drops for breaking from `block` to `target`.
pub(crate) fn break_scope(
&mut self,
mut block: BasicBlock,
value: Option<ExprId>,
target: BreakableTarget,
source_info: SourceInfo,
) -> BlockAnd<()> {
let span = source_info.span;
let get_scope_index = |scope: region::Scope| {
// find the loop-scope by its `region::Scope`.
self.scopes
.breakable_scopes
.iter()
.rposition(|breakable_scope| breakable_scope.region_scope == scope)
.unwrap_or_else(|| span_bug!(span, "no enclosing breakable scope found"))
};
let (break_index, destination) = match target {
BreakableTarget::Return => {
let scope = &self.scopes.breakable_scopes[0];
if scope.break_destination != Place::return_place() {
span_bug!(span, "`return` in item with no return scope");
}
(0, Some(scope.break_destination))
}
BreakableTarget::Break(scope) => {
let break_index = get_scope_index(scope);
let scope = &self.scopes.breakable_scopes[break_index];
(break_index, Some(scope.break_destination))
}
BreakableTarget::Continue(scope) => {
let break_index = get_scope_index(scope);
(break_index, None)
}
};
match (destination, value) {
(Some(destination), Some(value)) => {
debug!("stmt_expr Break val block_context.push(SubExpr)");
self.block_context.push(BlockFrame::SubExpr);
unpack!(block = self.expr_into_dest(destination, block, value));
self.block_context.pop();
}
(Some(destination), None) => {
self.cfg.push_assign_unit(block, source_info, destination, self.tcx)
}
(None, Some(_)) => {
panic!("`return`, `become` and `break` with value and must have a destination")
}
(None, None) => {
if self.tcx.sess.instrument_coverage() {
// Normally we wouldn't build any MIR in this case, but that makes it
// harder for coverage instrumentation to extract a relevant span for
// `continue` expressions. So here we inject a dummy statement with the
// desired span.
self.cfg.push_coverage_span_marker(block, source_info);
}
}
}
let region_scope = self.scopes.breakable_scopes[break_index].region_scope;
let scope_index = self.scopes.scope_index(region_scope, span);
let drops = if destination.is_some() {
&mut self.scopes.breakable_scopes[break_index].break_drops
} else {
let Some(drops) = self.scopes.breakable_scopes[break_index].continue_drops.as_mut()
else {
self.tcx.dcx().span_delayed_bug(
source_info.span,
"unlabelled `continue` within labelled block",
);
self.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
return self.cfg.start_new_block().unit();
};
drops
};
let drop_idx = self.scopes.scopes[scope_index + 1..]
.iter()
.flat_map(|scope| &scope.drops)
.fold(ROOT_NODE, |drop_idx, &drop| drops.add_drop(drop, drop_idx));
drops.add_entry_point(block, drop_idx);
// `build_drop_trees` doesn't have access to our source_info, so we
// create a dummy terminator now. `TerminatorKind::UnwindResume` is used
// because MIR type checking will panic if it hasn't been overwritten.
// (See `<ExitScopes as DropTreeBuilder>::link_entry_point`.)
self.cfg.terminate(block, source_info, TerminatorKind::UnwindResume);
self.cfg.start_new_block().unit()
}
/// Sets up the drops for breaking from `block` due to an `if` condition
/// that turned out to be false.
///
/// Must be called in the context of [`Builder::in_if_then_scope`], so that
/// there is an if-then scope to tell us what the target scope is.
pub(crate) fn break_for_else(&mut self, block: BasicBlock, source_info: SourceInfo) {
let if_then_scope = self
.scopes
.if_then_scope
.as_ref()
.unwrap_or_else(|| span_bug!(source_info.span, "no if-then scope found"));
let target = if_then_scope.region_scope;
let scope_index = self.scopes.scope_index(target, source_info.span);
// Upgrade `if_then_scope` to `&mut`.
let if_then_scope = self.scopes.if_then_scope.as_mut().expect("upgrading & to &mut");
let mut drop_idx = ROOT_NODE;
let drops = &mut if_then_scope.else_drops;
for scope in &self.scopes.scopes[scope_index + 1..] {
for drop in &scope.drops {
drop_idx = drops.add_drop(*drop, drop_idx);
}
}
drops.add_entry_point(block, drop_idx);
// `build_drop_trees` doesn't have access to our source_info, so we
// create a dummy terminator now. `TerminatorKind::UnwindResume` is used
// because MIR type checking will panic if it hasn't been overwritten.
// (See `<ExitScopes as DropTreeBuilder>::link_entry_point`.)
self.cfg.terminate(block, source_info, TerminatorKind::UnwindResume);
}
fn leave_top_scope(&mut self, block: BasicBlock) -> BasicBlock {
// If we are emitting a `drop` statement, we need to have the cached
// diverge cleanup pads ready in case that drop panics.
let needs_cleanup = self.scopes.scopes.last().is_some_and(|scope| scope.needs_cleanup());
let is_coroutine = self.coroutine.is_some();
let unwind_to = if needs_cleanup { self.diverge_cleanup() } else { DropIdx::MAX };
let scope = self.scopes.scopes.last().expect("leave_top_scope called with no scopes");
unpack!(build_scope_drops(
&mut self.cfg,
&mut self.scopes.unwind_drops,
scope,
block,
unwind_to,
is_coroutine && needs_cleanup,
self.arg_count,
))
}
/// Possibly creates a new source scope if `current_root` and `parent_root`
/// are different, or if -Zmaximal-hir-to-mir-coverage is enabled.
pub(crate) fn maybe_new_source_scope(
&mut self,
span: Span,
safety: Option<Safety>,
current_id: HirId,
parent_id: HirId,
) {
let (current_root, parent_root) =
if self.tcx.sess.opts.unstable_opts.maximal_hir_to_mir_coverage {
// Some consumers of rustc need to map MIR locations back to HIR nodes. Currently
// the only part of rustc that tracks MIR -> HIR is the
// `SourceScopeLocalData::lint_root` field that tracks lint levels for MIR
// locations. Normally the number of source scopes is limited to the set of nodes
// with lint annotations. The -Zmaximal-hir-to-mir-coverage flag changes this
// behavior to maximize the number of source scopes, increasing the granularity of
// the MIR->HIR mapping.
(current_id, parent_id)
} else {
// Use `maybe_lint_level_root_bounded` to avoid adding Hir dependencies on our
// parents. We estimate the true lint roots here to avoid creating a lot of source
// scopes.
(
self.maybe_lint_level_root_bounded(current_id),
if parent_id == self.hir_id {
parent_id // this is very common
} else {
self.maybe_lint_level_root_bounded(parent_id)
},
)
};
if current_root != parent_root {
let lint_level = LintLevel::Explicit(current_root);
self.source_scope = self.new_source_scope(span, lint_level, safety);
}
}
/// Walks upwards from `orig_id` to find a node which might change lint levels with attributes.
/// It stops at `self.hir_id` and just returns it if reached.
fn maybe_lint_level_root_bounded(&mut self, orig_id: HirId) -> HirId {
// This assertion lets us just store `ItemLocalId` in the cache, rather
// than the full `HirId`.
assert_eq!(orig_id.owner, self.hir_id.owner);
let mut id = orig_id;
let hir = self.tcx.hir();
loop {
if id == self.hir_id {
// This is a moderately common case, mostly hit for previously unseen nodes.
break;
}
if hir.attrs(id).iter().any(|attr| Level::from_attr(attr).is_some()) {
// This is a rare case. It's for a node path that doesn't reach the root due to an
// intervening lint level attribute. This result doesn't get cached.
return id;
}
let next = self.tcx.parent_hir_id(id);
if next == id {
bug!("lint traversal reached the root of the crate");
}
id = next;
// This lookup is just an optimization; it can be removed without affecting
// functionality. It might seem strange to see this at the end of this loop, but the
// `orig_id` passed in to this function is almost always previously unseen, for which a
// lookup will be a miss. So we only do lookups for nodes up the parent chain, where
// cache lookups have a very high hit rate.
if self.lint_level_roots_cache.contains(id.local_id) {
break;
}
}
// `orig_id` traced to `self_id`; record this fact. If `orig_id` is a leaf node it will
// rarely (never?) subsequently be searched for, but it's hard to know if that is the case.
// The performance wins from the cache all come from caching non-leaf nodes.
self.lint_level_roots_cache.insert(orig_id.local_id);
self.hir_id
}
/// Creates a new source scope, nested in the current one.
pub(crate) fn new_source_scope(
&mut self,
span: Span,
lint_level: LintLevel,
safety: Option<Safety>,
) -> SourceScope {
let parent = self.source_scope;
debug!(
"new_source_scope({:?}, {:?}, {:?}) - parent({:?})={:?}",
span,
lint_level,
safety,
parent,
self.source_scopes.get(parent)
);
let scope_local_data = SourceScopeLocalData {
lint_root: if let LintLevel::Explicit(lint_root) = lint_level {
lint_root
} else {
self.source_scopes[parent].local_data.as_ref().assert_crate_local().lint_root
},
safety: safety.unwrap_or_else(|| {
self.source_scopes[parent].local_data.as_ref().assert_crate_local().safety
}),
};
self.source_scopes.push(SourceScopeData {
span,
parent_scope: Some(parent),
inlined: None,
inlined_parent_scope: None,
local_data: ClearCrossCrate::Set(scope_local_data),
})
}
/// Given a span and the current source scope, make a SourceInfo.
pub(crate) fn source_info(&self, span: Span) -> SourceInfo {
SourceInfo { span, scope: self.source_scope }
}
// Finding scopes
// ==============
/// Returns the scope that we should use as the lifetime of an
/// operand. Basically, an operand must live until it is consumed.
/// This is similar to, but not quite the same as, the temporary
/// scope (which can be larger or smaller).
///
/// Consider:
/// ```ignore (illustrative)
/// let x = foo(bar(X, Y));
/// ```
/// We wish to pop the storage for X and Y after `bar()` is
/// called, not after the whole `let` is completed.
///
/// As another example, if the second argument diverges:
/// ```ignore (illustrative)
/// foo(Box::new(2), panic!())
/// ```
/// We would allocate the box but then free it on the unwinding
/// path; we would also emit a free on the 'success' path from
/// panic, but that will turn out to be removed as dead-code.
pub(crate) fn local_scope(&self) -> region::Scope {
self.scopes.topmost()
}
// Scheduling drops
// ================
pub(crate) fn schedule_drop_storage_and_value(
&mut self,
span: Span,
region_scope: region::Scope,
local: Local,
) {
self.schedule_drop(span, region_scope, local, DropKind::Storage);
self.schedule_drop(span, region_scope, local, DropKind::Value);
}
/// Indicates that `place` should be dropped on exit from `region_scope`.
///
/// When called with `DropKind::Storage`, `place` shouldn't be the return
/// place, or a function parameter.
pub(crate) fn schedule_drop(
&mut self,
span: Span,
region_scope: region::Scope,
local: Local,
drop_kind: DropKind,
) {
let needs_drop = match drop_kind {
DropKind::Value => {
if !self.local_decls[local].ty.needs_drop(self.tcx, self.param_env) {
return;
}
true
}
DropKind::Storage => {
if local.index() <= self.arg_count {
span_bug!(
span,
"`schedule_drop` called with local {:?} and arg_count {}",
local,
self.arg_count,
)
}
false
}
};
// When building drops, we try to cache chains of drops to reduce the
// number of `DropTree::add_drop` calls. This, however, means that
// whenever we add a drop into a scope which already had some entries
// in the drop tree built (and thus, cached) for it, we must invalidate
// all caches which might branch into the scope which had a drop just
// added to it. This is necessary, because otherwise some other code
// might use the cache to branch into already built chain of drops,
// essentially ignoring the newly added drop.
//
// For example consider there’s two scopes with a drop in each. These
// are built and thus the caches are filled:
//
// +--------------------------------------------------------+
// | +---------------------------------+ |
// | | +--------+ +-------------+ | +---------------+ |
// | | | return | <-+ | drop(outer) | <-+ | drop(middle) | |
// | | +--------+ +-------------+ | +---------------+ |
// | +------------|outer_scope cache|--+ |
// +------------------------------|middle_scope cache|------+
//
// Now, a new, inner-most scope is added along with a new drop into
// both inner-most and outer-most scopes:
//
// +------------------------------------------------------------+
// | +----------------------------------+ |
// | | +--------+ +-------------+ | +---------------+ | +-------------+
// | | | return | <+ | drop(new) | <-+ | drop(middle) | <--+| drop(inner) |
// | | +--------+ | | drop(outer) | | +---------------+ | +-------------+
// | | +-+ +-------------+ | |
// | +---|invalid outer_scope cache|----+ |
// +----=----------------|invalid middle_scope cache|-----------+
//
// If, when adding `drop(new)` we do not invalidate the cached blocks for both
// outer_scope and middle_scope, then, when building drops for the inner (right-most)
// scope, the old, cached blocks, without `drop(new)` will get used, producing the
// wrong results.
//
// Note that this code iterates scopes from the inner-most to the outer-most,
// invalidating caches of each scope visited. This way bare minimum of the
// caches gets invalidated. i.e., if a new drop is added into the middle scope, the
// cache of outer scope stays intact.
//
// Since we only cache drops for the unwind path and the coroutine drop