This is the part 2 of the CS6120 learning note. This note will introduce natural loops, loop-invariant code motion, and static single assignments.
Credit
This post uses Bril, an compiler IR for learning. Part of the code used for this post was modified from Bril.
Dominance
As we have discussed in the previous post, cycles can be formed due to the loops in the program. Because it is possible for a directed graph to have various shapes of cycles, and not all kinds of cycles happen to programs easily and are good for analysis, we define natural loops, which will be an important entity to work with in future analysis.
Before defining what a natural loop is, we need to identify a couple relations:
A
dominatesB
(simplified asA
DOMB
): if all paths leading toB
includeA
. It feels like something illustrated below. You can see the execution ofB
guarantees the execution ofA
.stateDiagram-v2 direction LR state "..." as PM state "..." as MM [*] --> P1 [*] --> PM [*] --> P3 P1 --> A PM --> A P3 --> A A --> M A --> MM M --> B MM --> B
However, the
A
andB
below do not have the DOM relation, because there is a path toB
fromM
that does not includeA
.stateDiagram-v2 direction LR state "..." as PM state "..." as MM state "..." as PPM [*] --> PM [*] --> PPM PM --> M PM --> A PPM --> A A --> MM M --> B MM --> B
Also note that, DOM is a reflexive relation, meaning
X
DOMX
for every basic blockX
.A
strictly dominatesB
(simplified asA
SDOMB
): iffA
DOMB
andA
B
. In the first diagram above,A
andM
(and many other nodes) strictly dominateB
.A
immediately dominatesB
(simplified asA
IDOMB
): iffA
SDOMB
andA
does not strictly dominate any node that strictly dominateB
. In other words,A
is a immediate ancestor ofB
.A
is post dominated byB
(simplified asA
PDOMB
): iff all paths fromB
to the exit includesA
.
We can use the same data flow framework to find the dominance easily: when visiting a basic block on CFG, add the identity of the block to combined information flowed from its predecessors, and pass all to its predecessors; when combining information, take the intersection of the information from all paths.