Section 3.13

Control-flow graph (CFG)

Definition

A control-flow graph (CFG) is a directed graph, a set of nodes joined by one-way edges, that records every way execution can move through a piece of code, usually one function. Each node is normally a basic block §3.14: a run of instructions that execution enters only at the first and leaves only after the last. An edge from node uu to node vv means execution can continue at the start of vv directly after uu ends. A CFG shows which transfers are possible, not which one a particular run takes.

The idea

A checker that proves something about a program must consider every order in which the instructions can run. Straight-line code is easy: each instruction is followed by the next. A conditional jump makes two continuations possible, a loop makes the same instructions run again, and a call or a fault sends execution somewhere else entirely. Without a map of these possibilities, the checker cannot tell which facts flow to which instruction.

The CFG is that map. A road map is a fair picture: the nodes are stretches of road without junctions, and the edges are the one-way connections between them. An analysis travels the map and carries its facts along every road. The picture stops in two places. A map shows the roads that exist, not the route a particular driver takes, and the CFG can contain a path that no run follows because the branch conditions along it contradict each other. And a road missing from the map is a road the analysis never checks: if a run can take it, the conclusions of the analysis are wrong.

How it works

A CFG is built in four steps. Some CFGs use single instructions as nodes; the steps below build the usual kind, whose nodes are basic blocks.

  1. Find the instructions. For source code or an intermediate representation §3.37 (the simplified form of a program that a compiler works on), the instructions are given. For machine code, a decoder reads the bytes and determines where each instruction starts and how long it is. A wrong boundary produces a wrong graph.

  2. Find the leaders, the instructions that start a basic block: the first instruction of the code, every target of a jump, and every instruction that directly follows a jump or a return.

  3. Form the blocks. Each basic block runs from one leader up to, but not including, the next leader.

  4. Add the edges. The last instruction of each block, called its terminator, decides them:

    • an ordinary instruction falls through: one edge to the next block;

    • an unconditional jump: one edge to its target;

    • a conditional jump: two edges, one to its target (jump taken) and one to the next block (not taken);

    • a return: one edge to a single exit node that stands for leaving the function.

Some transfers need more than reading one instruction.

Interrupts §6.11 are usually not drawn as edges. An interrupt, a hardware signal that suspends the running code to run a handler, can arrive between almost any two instructions. Analyses model the handler as code that can run concurrently with the function, not as an edge from every node.

Once built, the graph answers structural questions. A node with no path from the entry is unreachable code. A cycle in the graph is a loop. An edge from uu to vv is a back edge when every path from the entry to uu passes through vv; the target vv is then the head of a loop. Data-flow analysis §3.15 propagates facts about values along the edges.

Worked example

The following function adds the whole numbers from 0 to n−1n - 1. The number before each instruction is its position.

1: i = 0
2: s = 0
3: if i >= n goto 7
4: s = s + i
5: i = i + 1
6: goto 3
7: return s

The leaders are instruction 1 (the first instruction), instruction 3 (the target of goto 3), instruction 4 (it follows the conditional jump at 3) and instruction 7 (the target of the jump at 3, and it follows the goto at 6). The blocks are:

The edges are B1→B2\mathrm{B1} \to \mathrm{B2} (fall-through), B2→B4\mathrm{B2} \to \mathrm{B4} (jump taken, i≥ni \ge n), B2→B3\mathrm{B2} \to \mathrm{B3} (jump not taken), B3→B2\mathrm{B3} \to \mathrm{B2} (the goto) and B4→exit\mathrm{B4} \to \mathrm{exit} (the return). The edge B3→B2\mathrm{B3} \to \mathrm{B2} is a back edge, because every path from the entry to B3 passes through B2. So B2 is the head of the loop formed by B2 and B3.

Run the function with n=2n = 2. B1 sets i=0i = 0 and s=0s = 0. In B2, 0≥20 \ge 2 is false, so execution goes to B3, which sets s=0+0=0s = 0 + 0 = 0 and i=0+1=1i = 0 + 1 = 1. In B2, 1≥21 \ge 2 is false, so B3 sets s=0+1=1s = 0 + 1 = 1 and i=1+1=2i = 1 + 1 = 2. In B2, 2≥22 \ge 2 is true, so execution goes to B4, which returns 1. The run follows the path B1, B2, B3, B2, B3, B2, B4, and every step of that path is an edge of the graph. With n=0n = 0 the run is B1, B2, B4, and the function returns 0, also along edges of the graph.

Now suppose a faulty builder treated instruction 3 as an ordinary instruction and drew only the edge B2→B3\mathrm{B2} \to \mathrm{B3}. Block B4 then has no incoming edge, so it looks unreachable, and an analysis concludes that the function loops forever and never returns. Nothing the analysis says about B4 has been checked, although every real run ends in B4. A missing edge does not produce a false alarm §1.22; it hides real behavior.

Stated precisely

Write the CFG as G=(V,E,entry)G = (V, E, \mathrm{entry}): VV is the set of nodes, E⊆V×VE \subseteq V \times V is the set of edges, each an ordered pair of nodes, and entry∈V\mathrm{entry} \in V is the node where execution starts. For the example, V={B1,B2,B3,B4,exit}V = \{\mathrm{B1}, \mathrm{B2}, \mathrm{B3}, \mathrm{B4}, \mathrm{exit}\} and E={(B1,B2),(B2,B3),(B2,B4),(B3,B2),(B4,exit)}E = \{(\mathrm{B1}, \mathrm{B2}), (\mathrm{B2}, \mathrm{B3}), (\mathrm{B2}, \mathrm{B4}), (\mathrm{B3}, \mathrm{B2}), (\mathrm{B4}, \mathrm{exit})\}.

A run of the code visits a sequence of nodes b0,b1,…,bmb_0, b_1, \dots, b_m. The CFG is sound for the code, an over-approximation §19.2.5 of its control flow, when every possible run satisfies two conditions: b0=entryb_0 = \mathrm{entry}, and every consecutive pair (bi,bi+1)(b_i, b_{i+1}) is in EE. Two consequences follow.

  1. If a sound CFG has no path from the entry to a node, no run reaches that node.

  2. The converse fails: a path in the graph need not be taken by any run. A path whose branch conditions contradict each other is called infeasible; an example is a path that takes the branch for x>0x > 0 and later, with xx unchanged, the branch for x≤0x \le 0.

The soundness §3.7 of a CFG rests on four assumptions about its builder: the decoder found the true instruction boundaries; the target set of every indirect jump and indirect call contains every target a run can use; every fault and exception that can occur has its edge, or has been proved impossible; and the code is not changed while it runs.

Call graphs and dependency arguments

A call graph is a different graph over the same program. Its nodes are functions, and an edge from function ff to function gg means ff may call gg. A CFG describes the possible orders of the instructions inside a function; a call graph records which functions may call which. An interprocedural CFG combines the two. Building a call graph meets the same difficulty as building a CFG. A direct call names the called function, but a call through a function pointer does not, so a sound call graph needs a set of possible targets for every indirect call. A common choice is every function whose address the program takes and whose type matches the call.

Programs are also split into modules, and a common argument says that module MM does not depend on subsystem SS because MM includes none of the header files of SS and calls none of its functions. In C, a header file is the file of declarations that other files include in order to use a module’s functions and data. The argument checks two graphs. The include graph records which file includes which; it must be followed through chains, because one header can include another. The call graph records the calls. If both checks pass, MM neither includes the declarations of SS nor calls a function of SS by name, so MM can be compiled without the headers of SS. That is a statement about the text of MM.

The argument misses every dependency that does not pass through an included header or a named call:

The two checks therefore support the claim that MM compiles without the headers of SS. It does not show that MM behaves the same without SS, or with a different SS.

Limits and common mistakes

A CFG carries no values. It says that B2 can go to B3 or to B4, not which of the two a run with n=2n = 2 takes. Branch conditions and the values they test come from the meaning of the instructions, which an analysis such as data-flow analysis tracks separately.

Infeasible paths cost precision. An analysis that follows every path of the graph also follows the infeasible ones and can raise a false alarm on them. Path sensitivity §3.11 reduces this.

Missing edges cost soundness. The usual causes are unresolved indirect jumps and calls, faults, exceptions, longjmp, functions wrongly assumed never to return, and code generated or changed at run time.

Machine code is harder than source code. On processors whose instructions vary in length, such as x86, a jump can land inside what a decoder read as one instruction, and the bytes from that point decode as different instructions. Data such as jump tables can also sit between instructions. A decoder that reads the bytes in order from the start, called a linear sweep, can misread data as code. A decoder that follows only known jump targets, called recursive traversal, can miss code reached by indirect jumps.

The level of the code matters. The CFGs of source code, of an intermediate representation and of machine code differ, because a compiler adds, removes and reorders branches. A proof about the code that runs needs the CFG of that code, or a proven link between the levels.

Questions answered

Are indirect calls, faults, and exceptional edges included?

Indirect calls, faults and exceptional edges are in a control-flow graph (CFG) only if its builder puts them in, and a CFG used to prove that every run is safe must include all three. A textbook CFG of one function contains only the ordinary branch edges. It treats a call as one instruction that continues after the call, and it often leaves out exceptions. That is acceptable for some compiler optimizations §3.39, but not for a safety proof.

For a safety proof, every transfer a run can make needs an edge.

An edge may be left out only with a proof that the transfer is impossible, for example a check before the division that guarantees a nonzero divisor. A missing real edge makes the analysis unsound: an unsafe path can look unreachable. An extra edge that no run takes keeps the analysis sound but can cause false alarms.

Related entries: Instruction encoding (§2.7), Program counter (PC) (§2.9), Data-flow analysis (§3.15), Basic block (§3.14), Reachability (§3.21).