From 0f81dd187f0b4b1159d367fe9499136bd645094f Mon Sep 17 00:00:00 2001 From: Faith Ekstrand Date: Wed, 30 Jul 2025 09:57:22 -0400 Subject: [PATCH] compiler/rust: Add a CFG::loop_depth() method Part-of: --- src/compiler/rust/cfg.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/compiler/rust/cfg.rs b/src/compiler/rust/cfg.rs index 109e7850e8a..59576f54bd0 100644 --- a/src/compiler/rust/cfg.rs +++ b/src/compiler/rust/cfg.rs @@ -341,6 +341,26 @@ impl CFG { } } + /// Returns the loop depth of the given node. Nodes not in any loops have + /// a loop depth of zero. For nodes inside a loop, this is the count of + /// number of loop headers above them in the dominance tree. + pub fn loop_depth(&self, idx: usize) -> usize { + let mut idx = idx; + let mut depth = 0; + loop { + let lph = self.nodes[idx].lph; + if lph == usize::MAX { + return depth; + } + + depth += 1; + + // Loop headers have themselves as the lph so we need to skip to + // the dominator of the loop header for the next iteration. + idx = self.nodes[lph].dom; + } + } + /// Returns the indices of the successors of this node in the CFG. pub fn succ_indices(&self, idx: usize) -> &[usize] { &self.nodes[idx].succ[..]