Data-flow Analysis on a Control-flow Graph
This semester, I took a Compilers course where the problem sets involved incrementally implementing compiler features in OCaml. In this series, Iâll briefly summarize each piece. Taken together, I hope these posts provide a good foundation for understanding how compilers work.
The problem sets were fairly open-ended as long as the compiler produced correct results. My approaches wonât always match what a production compiler would do, but Iâve attempted to preserve the core ideas. Code is available in this repo.
Although the articles closely follow the problem sets, some also cover topics that werenât directly tied to a specific problem set.
- Assembly, Lexer + Parser, Compiling Function Calls
- Closures and Type Inference
- Data-flow Analysis on a Control-flow Graph
- Graph-Coloring Register Allocation
So far, weâve focused on making sure our compiler generates RISC-V code that behaves as intended. Now weâll also start thinking about how well that code performs.
A compiler typically processes a program in multiple passes. Some passes translate the program into an intermediate representation that makes it easier to analyze and optimize. In this post, weâll look at one such representation, the control-flow graph (CFG).
Control-flow Graphs
Section titled âControl-flow GraphsâAs its name suggests, a Control-Flow Graph represents the program as a graph dictated by control-flows. In a CFG, nodes are basic blocks. Each block is a sequence of instructions associated with a label, and ends with a control-flow instruction such as a jump or a branch. Within a block, the sequence of instructions is uninterrupted by control-flow. So we can think of control-flow as traversing an edge to the block whose label is the jump target.
CFG is built at a later stage, after the compiler has lowered the program to assembly-like instructions. Hereâs an example of what those instructions look like.
v := w;v := *(w+i);*(w+i) := v;...Here, v is a temp, which the compilerâs lower-level intermediate representation uses to refer to a location that holds a value. Some temps refer to physical registers such as $x10. I find it easier to think of the compiler-generated temps as virtual registers.
At this point, the compiler is already working with loads and stores, but it can use more virtual registers than the available physical registers. Later, during register allocation, the compiler can map virtual registers to physical registers.
In this form, we can overwrite values in registers. In higher-level representations, we could keep variables effectively immutable by creating a fresh variable for each intermediate result in a chain of operations. As we move to assembly-like instructions, we start thinking about which values we still need and whether we have to save them before overwriting a register.
v := 7;B;u := v+3; // can we propagate 7? What if B modifies v?Data-flow Analysis
Section titled âData-flow AnalysisâOnce we have constructed a CFG, we can analyze the graph to answer questions like: âDo u and v interfere?â This is where data-flow analysis comes in. While there are different kinds of data-flow analysis, we will focus on liveness analysis.
For each block in the CFG, we want to determine which temps are alive when entering and exiting the block. This information is useful because if two variables are alive at the same time, they interfere, which means we might not want to assign them to the same physical register.
Our rule for liveness is that âa use of x generates liveness (Gen), while a definition of x kills it (Kill)â. This can feel a bit counterintuitive, but it makes sense when we look backwards.
If x is used at some point, then x must have been alive (defined) before. On the other hand, if x is defined now, then that definition provides a new value for x, so any earlier value of x is no longer needed.
For example, consider an instruction like x := y. Since liveness flows backward, this instruction generates y and kills x. It generates y because y must already have been alive before this point in order for its value to be read. It kills x because this instruction assigns a new value to x, so any older value of x is no longer needed before this assignment.
If we formally define liveness, then for a block L whose successors are succ[L] = {L1, ..., Ln}, we have:
LiveIn[L] = Gen[L] âȘ (LiveOut[L] - Kill[L])LiveOut[L] = LiveIn[L1] âȘ ... âȘ LiveIn[Ln]In English, a variable is alive on entry to a block if either:
- It is used within the block, or
- It is live on exit from the block and is not redefined within the block.
A variable is live on exit from a block if it is live on entry to at least one of that blockâs successors.
If the CFG is acyclic, we can compute LiveIn and LiveOut for each block in a single backward pass. We begin with LiveOut, derive LiveIn, and then propagate that information to the preceding blocks. If the graph is cyclic, we may need to iterate until LiveIn and LiveOut saturate and no longer change.
Pseudocode for Liveness Analysis
initialize LiveIn[L] = Gen[L]initialize LiveOut[L] = {}
repeat until no set changes: for each block L: LiveOut[L] = â {LiveIn[S] | S â succ[L]} LiveIn[L] = Gen[L] âȘ (LiveOut[L] - Kill[L])ps7: Interference Graphs
Section titled âps7: Interference GraphsâThe goal of ps7 was to run a liveness analysis on a CFG, then use the computed LiveIn and LiveOut to build an interference graph. Instead of blocks, we compute LiveIn and LiveOut for each instruction.
In an interference graph, nodes represent temps. If two nodes âinterfere,â we add an edge between them. For this implementation, we follow Appelâs definition of interference: x and y interfere if y is live when x is defined.
For each instruction i: For each node d in kill[i]: For each node y in live_out[i]: Add edge d -- yLetâs take a look at a simple example.
main() { return 12 + 4;}
main:t0 := 12+4$x10 := t0jump .L0
.L1:jump .L0
.L0:returnGiven simple code like this, we can compute the live_in and live_out for each instruction. Then, we can use this information to determine whether there is any interference. In this case, t0 and $x10 do not interfere.
| Instruction | live_in | live_out |
|---|---|---|
0: t0 := 12+4 | {} | {t0} |
1: $x10 := t0 | {t0} | {$x10} |
2: jump .L0 | {$x10} | {$x10} |
3: .L0: | {$x10} | {$x10} |
4: return | {$x10} | {} |
The starter code for ps7 provided code that converts a source program into a CFG. It also provided helper functions for constructing an interference graph, such as creating new nodes or adding new edges. I will not discuss the details, but my implementation faithfully followed the above explanation.
let build_interfere_graph (f : func) : interfere_graph = (* function here is a list of blocks, which is a list of inst *) let insts = flatten_func f in let successors = build_successors insts in let (live_in, live_out) = solve_liveness insts successors in build_appel_graph insts live_in live_outThe next problem set, the mini project, uses the interference graph constructed here to implement register allocation.