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 to node means execution can continue at the start of directly after 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.
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.
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.
Form the blocks. Each basic block runs from one leader up to, but not including, the next leader.
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.
Indirect jumps, whose target address is computed at run time. A
switchstatement compiled into a jump table §2.39, an array §14.5 of code addresses indexed by the value being switched on, gets one edge per table entry, provided the analysis also proves that the index stays inside the table. An indirect jump without a known set of targets needs an analysis that bounds the possible targets, or an edge to a node that stands for any code.Calls. A CFG of one function usually treats a call as an ordinary instruction that continues after the call returns. An interprocedural CFG joins the graphs of several functions: an edge from each call site to the called function’s entry, and an edge from the called function’s exit back to the instruction after the call. An indirect call, through a function pointer (a variable that holds the address of a function), needs a set of possible called functions, just as an indirect jump needs a set of targets.
Faults. An instruction that can fail has a second outgoing edge. On x86 processors, an integer division by zero raises a divide-error exception, which transfers control to a fault handler §6.15 instead of the next instruction. A load from an invalid address does the same.
Exceptions of the programming language. In C++ or Java, a call that can throw an exception gets an edge to the matching
catchblock, or to the function’s exit if nocatchblock in the function matches. The C functionssetjmpandlongjmpcreate similar jumps out of the normal order.Functions that never return, such as the C function
exit. A call to such a function gets no edge to the next instruction. Marking a function as never returning when it can return removes a real edge.
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 to is a back edge when every path from the entry to passes through ; the target 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 . 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:
B1: instructions 1 and 2;
B2: instruction 3;
B3: instructions 4 to 6;
B4: instruction 7.
The edges are (fall-through), (jump taken, ), (jump not taken), (the goto) and (the return). The edge 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 . B1 sets and . In B2, is false, so execution goes to B3, which sets and . In B2, is false, so B3 sets and . In B2, 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 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 . 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 : is the set of nodes, is the set of edges, each an ordered pair of nodes, and is the node where execution starts. For the example, and .
A run of the code visits a sequence of nodes . The CFG is sound for the code, an over-approximation §19.2.5 of its control flow, when every possible run satisfies two conditions: , and every consecutive pair is in . Two consequences follow.
If a sound CFG has no path from the entry to a node, no run reaches that node.
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 and later, with unchanged, the branch for .
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 to function means may call . 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 does not depend on subsystem because includes none of the header files of 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, neither includes the declarations of nor calls a function of by name, so can be compiled without the headers of . That is a statement about the text of .
The argument misses every dependency that does not pass through an included header or a named call:
calls through function pointers or callbacks §14.22 that receives at run time, which can lead into although never names ;
calls in the other direction, from into , which the includes and calls of do not show;
transitive dependencies §10.43, where calls a function in module and that function uses , unless the call-graph check follows such chains;
shared state: a global variable of declared by hand with
externinstead of through a header of , a shared memory buffer, or a configuration value;macros (text substitutions made before compilation) and inline functions in another header that expand into code of ;
resolution by the linker §12.4, the tool that joins compiled files, of a name that uses to code that supplies;
interference without any call: one processor, one stack, interrupts, timing and locks shared with .
The two checks therefore support the claim that compiles without the headers of . It does not show that behaves the same without , or with a different .
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 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 indirect call, through a function pointer, needs an edge to every function the pointer can hold, or to a node that stands for unknown code with worst-case effects. A callback, a function handed to other code to be called later, appears twice: as an indirect call in the code that calls it, and as an extra entry into the callback itself.
An instruction that can fault, such as an integer division by zero or a load from an invalid address, needs an edge to its fault handler or to an abnormal exit.
An operation that can raise an exception needs an edge to every place that can catch it.
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).