]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/traversal.rs
Rollup merge of #106971 - oli-obk:tait_error, r=davidtwco
[rust.git] / compiler / rustc_middle / src / mir / traversal.rs
1 use rustc_index::bit_set::BitSet;
2
3 use super::*;
4
5 /// Preorder traversal of a graph.
6 ///
7 /// Preorder traversal is when each node is visited after at least one of its predecessors. If you
8 /// are familiar with some basic graph theory, then this performs a depth first search and returns
9 /// nodes in order of discovery time.
10 ///
11 /// ```text
12 ///
13 ///         A
14 ///        / \
15 ///       /   \
16 ///      B     C
17 ///       \   /
18 ///        \ /
19 ///         D
20 /// ```
21 ///
22 /// A preorder traversal of this graph is either `A B D C` or `A C D B`
23 #[derive(Clone)]
24 pub struct Preorder<'a, 'tcx> {
25     body: &'a Body<'tcx>,
26     visited: BitSet<BasicBlock>,
27     worklist: Vec<BasicBlock>,
28     root_is_start_block: bool,
29 }
30
31 impl<'a, 'tcx> Preorder<'a, 'tcx> {
32     pub fn new(body: &'a Body<'tcx>, root: BasicBlock) -> Preorder<'a, 'tcx> {
33         let worklist = vec![root];
34
35         Preorder {
36             body,
37             visited: BitSet::new_empty(body.basic_blocks.len()),
38             worklist,
39             root_is_start_block: root == START_BLOCK,
40         }
41     }
42 }
43
44 pub fn preorder<'a, 'tcx>(body: &'a Body<'tcx>) -> Preorder<'a, 'tcx> {
45     Preorder::new(body, START_BLOCK)
46 }
47
48 impl<'a, 'tcx> Iterator for Preorder<'a, 'tcx> {
49     type Item = (BasicBlock, &'a BasicBlockData<'tcx>);
50
51     fn next(&mut self) -> Option<(BasicBlock, &'a BasicBlockData<'tcx>)> {
52         while let Some(idx) = self.worklist.pop() {
53             if !self.visited.insert(idx) {
54                 continue;
55             }
56
57             let data = &self.body[idx];
58
59             if let Some(ref term) = data.terminator {
60                 self.worklist.extend(term.successors());
61             }
62
63             return Some((idx, data));
64         }
65
66         None
67     }
68
69     fn size_hint(&self) -> (usize, Option<usize>) {
70         // All the blocks, minus the number of blocks we've visited.
71         let upper = self.body.basic_blocks.len() - self.visited.count();
72
73         let lower = if self.root_is_start_block {
74             // We will visit all remaining blocks exactly once.
75             upper
76         } else {
77             self.worklist.len()
78         };
79
80         (lower, Some(upper))
81     }
82 }
83
84 /// Postorder traversal of a graph.
85 ///
86 /// Postorder traversal is when each node is visited after all of its successors, except when the
87 /// successor is only reachable by a back-edge. If you are familiar with some basic graph theory,
88 /// then this performs a depth first search and returns nodes in order of completion time.
89 ///
90 ///
91 /// ```text
92 ///
93 ///         A
94 ///        / \
95 ///       /   \
96 ///      B     C
97 ///       \   /
98 ///        \ /
99 ///         D
100 /// ```
101 ///
102 /// A Postorder traversal of this graph is `D B C A` or `D C B A`
103 pub struct Postorder<'a, 'tcx> {
104     basic_blocks: &'a IndexVec<BasicBlock, BasicBlockData<'tcx>>,
105     visited: BitSet<BasicBlock>,
106     visit_stack: Vec<(BasicBlock, Successors<'a>)>,
107     root_is_start_block: bool,
108 }
109
110 impl<'a, 'tcx> Postorder<'a, 'tcx> {
111     pub fn new(
112         basic_blocks: &'a IndexVec<BasicBlock, BasicBlockData<'tcx>>,
113         root: BasicBlock,
114     ) -> Postorder<'a, 'tcx> {
115         let mut po = Postorder {
116             basic_blocks,
117             visited: BitSet::new_empty(basic_blocks.len()),
118             visit_stack: Vec::new(),
119             root_is_start_block: root == START_BLOCK,
120         };
121
122         let data = &po.basic_blocks[root];
123
124         if let Some(ref term) = data.terminator {
125             po.visited.insert(root);
126             po.visit_stack.push((root, term.successors()));
127             po.traverse_successor();
128         }
129
130         po
131     }
132
133     fn traverse_successor(&mut self) {
134         // This is quite a complex loop due to 1. the borrow checker not liking it much
135         // and 2. what exactly is going on is not clear
136         //
137         // It does the actual traversal of the graph, while the `next` method on the iterator
138         // just pops off of the stack. `visit_stack` is a stack containing pairs of nodes and
139         // iterators over the successors of those nodes. Each iteration attempts to get the next
140         // node from the top of the stack, then pushes that node and an iterator over the
141         // successors to the top of the stack. This loop only grows `visit_stack`, stopping when
142         // we reach a child that has no children that we haven't already visited.
143         //
144         // For a graph that looks like this:
145         //
146         //         A
147         //        / \
148         //       /   \
149         //      B     C
150         //      |     |
151         //      |     |
152         //      D     |
153         //       \   /
154         //        \ /
155         //         E
156         //
157         // The state of the stack starts out with just the root node (`A` in this case);
158         //     [(A, [B, C])]
159         //
160         // When the first call to `traverse_successor` happens, the following happens:
161         //
162         //     [(B, [D]),  // `B` taken from the successors of `A`, pushed to the
163         //                 // top of the stack along with the successors of `B`
164         //      (A, [C])]
165         //
166         //     [(D, [E]),  // `D` taken from successors of `B`, pushed to stack
167         //      (B, []),
168         //      (A, [C])]
169         //
170         //     [(E, []),   // `E` taken from successors of `D`, pushed to stack
171         //      (D, []),
172         //      (B, []),
173         //      (A, [C])]
174         //
175         // Now that the top of the stack has no successors we can traverse, each item will
176         // be popped off during iteration until we get back to `A`. This yields [E, D, B].
177         //
178         // When we yield `B` and call `traverse_successor`, we push `C` to the stack, but
179         // since we've already visited `E`, that child isn't added to the stack. The last
180         // two iterations yield `C` and finally `A` for a final traversal of [E, D, B, C, A]
181         loop {
182             let bb = if let Some(&mut (_, ref mut iter)) = self.visit_stack.last_mut() {
183                 if let Some(bb) = iter.next() {
184                     bb
185                 } else {
186                     break;
187                 }
188             } else {
189                 break;
190             };
191
192             if self.visited.insert(bb) {
193                 if let Some(term) = &self.basic_blocks[bb].terminator {
194                     self.visit_stack.push((bb, term.successors()));
195                 }
196             }
197         }
198     }
199 }
200
201 pub fn postorder<'a, 'tcx>(body: &'a Body<'tcx>) -> Postorder<'a, 'tcx> {
202     Postorder::new(&body.basic_blocks, START_BLOCK)
203 }
204
205 impl<'a, 'tcx> Iterator for Postorder<'a, 'tcx> {
206     type Item = (BasicBlock, &'a BasicBlockData<'tcx>);
207
208     fn next(&mut self) -> Option<(BasicBlock, &'a BasicBlockData<'tcx>)> {
209         let next = self.visit_stack.pop();
210         if next.is_some() {
211             self.traverse_successor();
212         }
213
214         next.map(|(bb, _)| (bb, &self.basic_blocks[bb]))
215     }
216
217     fn size_hint(&self) -> (usize, Option<usize>) {
218         // All the blocks, minus the number of blocks we've visited.
219         let upper = self.basic_blocks.len() - self.visited.count();
220
221         let lower = if self.root_is_start_block {
222             // We will visit all remaining blocks exactly once.
223             upper
224         } else {
225             self.visit_stack.len()
226         };
227
228         (lower, Some(upper))
229     }
230 }
231
232 /// Reverse postorder traversal of a graph
233 ///
234 /// Reverse postorder is the reverse order of a postorder traversal.
235 /// This is different to a preorder traversal and represents a natural
236 /// linearization of control-flow.
237 ///
238 /// ```text
239 ///
240 ///         A
241 ///        / \
242 ///       /   \
243 ///      B     C
244 ///       \   /
245 ///        \ /
246 ///         D
247 /// ```
248 ///
249 /// A reverse postorder traversal of this graph is either `A B C D` or `A C B D`
250 /// Note that for a graph containing no loops (i.e., A DAG), this is equivalent to
251 /// a topological sort.
252 ///
253 /// Construction of a `ReversePostorder` traversal requires doing a full
254 /// postorder traversal of the graph, therefore this traversal should be
255 /// constructed as few times as possible. Use the `reset` method to be able
256 /// to re-use the traversal
257 #[derive(Clone)]
258 pub struct ReversePostorder<'a, 'tcx> {
259     body: &'a Body<'tcx>,
260     blocks: Vec<BasicBlock>,
261     idx: usize,
262 }
263
264 impl<'a, 'tcx> ReversePostorder<'a, 'tcx> {
265     pub fn new(body: &'a Body<'tcx>, root: BasicBlock) -> ReversePostorder<'a, 'tcx> {
266         let blocks: Vec<_> = Postorder::new(&body.basic_blocks, root).map(|(bb, _)| bb).collect();
267         let len = blocks.len();
268         ReversePostorder { body, blocks, idx: len }
269     }
270 }
271
272 impl<'a, 'tcx> Iterator for ReversePostorder<'a, 'tcx> {
273     type Item = (BasicBlock, &'a BasicBlockData<'tcx>);
274
275     fn next(&mut self) -> Option<(BasicBlock, &'a BasicBlockData<'tcx>)> {
276         if self.idx == 0 {
277             return None;
278         }
279         self.idx -= 1;
280
281         self.blocks.get(self.idx).map(|&bb| (bb, &self.body[bb]))
282     }
283
284     fn size_hint(&self) -> (usize, Option<usize>) {
285         (self.idx, Some(self.idx))
286     }
287 }
288
289 impl<'a, 'tcx> ExactSizeIterator for ReversePostorder<'a, 'tcx> {}
290
291 /// Returns an iterator over all basic blocks reachable from the `START_BLOCK` in no particular
292 /// order.
293 ///
294 /// This is clearer than writing `preorder` in cases where the order doesn't matter.
295 pub fn reachable<'a, 'tcx>(
296     body: &'a Body<'tcx>,
297 ) -> impl 'a + Iterator<Item = (BasicBlock, &'a BasicBlockData<'tcx>)> {
298     preorder(body)
299 }
300
301 /// Returns a `BitSet` containing all basic blocks reachable from the `START_BLOCK`.
302 pub fn reachable_as_bitset(body: &Body<'_>) -> BitSet<BasicBlock> {
303     let mut iter = preorder(body);
304     (&mut iter).for_each(drop);
305     iter.visited
306 }
307
308 #[derive(Clone)]
309 pub struct ReversePostorderIter<'a, 'tcx> {
310     body: &'a Body<'tcx>,
311     blocks: &'a [BasicBlock],
312     idx: usize,
313 }
314
315 impl<'a, 'tcx> Iterator for ReversePostorderIter<'a, 'tcx> {
316     type Item = (BasicBlock, &'a BasicBlockData<'tcx>);
317
318     fn next(&mut self) -> Option<(BasicBlock, &'a BasicBlockData<'tcx>)> {
319         if self.idx == 0 {
320             return None;
321         }
322         self.idx -= 1;
323
324         self.blocks.get(self.idx).map(|&bb| (bb, &self.body[bb]))
325     }
326
327     fn size_hint(&self) -> (usize, Option<usize>) {
328         (self.idx, Some(self.idx))
329     }
330 }
331
332 impl<'a, 'tcx> ExactSizeIterator for ReversePostorderIter<'a, 'tcx> {}
333
334 pub fn reverse_postorder<'a, 'tcx>(body: &'a Body<'tcx>) -> ReversePostorderIter<'a, 'tcx> {
335     let blocks = body.basic_blocks.postorder();
336     let len = blocks.len();
337     ReversePostorderIter { body, blocks, idx: len }
338 }