Code Graph Review

Guide

Control Flow Graphs: How They Work and How to Generate One

Every path a function can take, drawn as blocks of straight-line code joined by the jumps between them. Here is how a CFG is built, how to read one, and the commands that produce one from your own code.

By Code Graph Review · Updated

A control flow graph (CFG) is a directed graph of every path execution can take through a piece of code, usually one function. Its nodes are basic blocks: runs of statements with one way in and one way out, so that if the first statement runs, all the others run too, in order. Its edges are the possible transfers of control between blocks: falling through to the next block, taking or not taking a branch, jumping back to the top of a loop, returning.

The representation was set out by Frances E. Allen in the 1970 paper Control Flow Analysis, written for optimising compilers, and it is still where nearly every static analysis starts: data flow analysis, dominators, loop detection, test coverage and the code property graph all sit on top of it.

Basic blocks and edges

A CFG is built from a function's statements (or from its intermediate representation, in a compiler) in two steps.

  • Find the leaders. A statement is a leader if it is the first statement of the function, the target of any jump or branch, or the statement immediately after a jump or branch.
  • Cut the blocks. Each basic block runs from one leader up to, but not including, the next. Nothing inside a block can be jumped into or out of except at its ends.
  • Add the edges. Draw an edge from block A to block B when control can pass from the end of A to the start of B: an unconditional jump, either side of a conditional branch, or a fall-through when A does not end in a jump.

Many tools also add two synthetic nodes, ENTRY and EXIT, so the graph has exactly one start and one end even when a function has several return statements. A CFG built for one function is intraprocedural; joining the CFGs of many functions through their call and return sites gives an interprocedural CFG, which is what whole-program analyses walk.

A worked example: an if inside a loop

Take this C function, which sums the positive values in an array:

int sum_positive(const int *xs, int n) {
  int total = 0;
  int i = 0;
  while (i < n) {
    if (xs[i] > 0)
      total += xs[i];
    i++;
  }
  return total;
}

It splits into six basic blocks:

  • B0: total = 0; i = 0; (the entry block)
  • B1: the loop condition i < n
  • B2: the branch condition xs[i] > 0
  • B3: total += xs[i];
  • B4: i++;
  • B5: return total;

And seven edges:

B0 → B1             fall into the loop test
B1 → B2   (true)    i < n: enter the body
B1 → B5   (false)   i >= n: leave the loop
B2 → B3   (true)    the value is positive
B2 → B4   (false)   skip the addition
B3 → B4             fall through
B4 → B1             back edge to the loop test

Each if becomes a block with two outgoing edges that meet again further down (B2 splits, B4 joins). Each loop becomes a cycle: the edge B4 → B1 runs backwards to a block that sits above it on every path, which is how analyses recognise loops. A for loop produces the same shape as this while, with its initialiser in the block before the test and its increment in the block that jumps back. A switch gives one block with an edge per case, and break, continue, goto and early return each add an edge of their own.

Reading a CFG: paths, dominators, loops and complexity

  • Reachability. A block with no path from the entry is unreachable code. A block with no path to the exit is part of an infinite loop or ends in a call that never returns.
  • Dominators. Block D dominates block N if every path from the entry to N passes through D. Here B1 dominates B2, B3, B4 and B5: nothing in the loop or after it runs without the loop test running first. Post-dominators are the mirror image: P post-dominates N if every path from N to the exit passes through P. Dominators are how compilers decide where code can safely move, and post-dominators are how checkers ask "is this lock always released?"
  • Back edges and natural loops. An edge whose target dominates its source is a back edge, and the blocks that can reach the source without passing through the target form a natural loop. B4 → B1 is the back edge here, and {B1, B2, B3, B4} is the loop.
  • Cyclomatic complexity. Thomas McCabe's 1976 paper A Complexity Measure defined a function's complexity from its control graph as M = E − N + 2P, where E is the number of edges, N the number of nodes and P the number of connected components (1 for a single function). For sum_positive that is 7 − 6 + 2 = 3, which matches the shortcut of counting decision points (the while and the if) and adding one. M is also the number of linearly independent paths through the graph, so it is a lower bound on the tests basis-path testing asks for.
  • Coverage. Statement coverage asks that every block runs in some test; branch coverage asks that every edge is taken. The false edge out of B2, a non-positive value, is the one a quick test with only positive inputs misses.

How a CFG relates to other code graphs

  • Abstract syntax tree. The AST records how code is nested, not the order it runs in. Compilers and analysers usually build the CFG from the AST or from an intermediate representation lowered from it.
  • Call graph. A call graph says which functions call which; a CFG says how control moves inside one function. Impact analysis across a codebase, like the graph-based analysis of API changes covered here, leans on the call graph, and drops into CFGs when it needs to know whether a call happens on every path or only some.
  • Program dependence graph. Data and control dependence edges are computed from the CFG: control dependence comes from post-dominators, and data dependence from following definitions along CFG paths to their uses.
  • Code property graph. A CPG lays the AST, the CFG and the program dependence graph over the same nodes so a single query can use all three.

How to generate a control flow graph

Most toolchains can already draw one; the common output is Graphviz .dot, which dot -Tsvg file.dot -o file.svg turns into an image.

Clang and LLVM (C, C++ and other LLVM languages). Emit LLVM IR, then run the dot-cfg printer pass with opt. It writes one .dot file per function into the current directory; the file names start with a dot, so list them with ls -a. The -cfg-func-name= option limits the output to functions whose names contain a given string, and dot-cfg-only draws the blocks without their instructions.

clang -S -emit-llvm sum.c -o sum.ll
opt -passes=dot-cfg -disable-output sum.ll
dot -Tsvg .sum_positive.dot -o sum_positive.svg

The graph is of LLVM IR rather than your source lines, so expect extra blocks for things the source writes on one line, and a different shape again once optimisations have run.

GCC. Add the graph option to a tree dump. GCC writes a Graphviz file for the dumped pass, with every function in the file as a subgraph; the pass number in the file name depends on the GCC version, so look for the file ending in .cfg.dot. Adding -lineno (-fdump-tree-cfg-graph-lineno) labels statements with source line numbers. The options are listed under GCC Developer Options.

gcc -c -fdump-tree-cfg-graph sum.c

Joern (source code in several languages, and binaries). Joern builds a CFG as part of its code property graph, and can export it from the shell or the command line:

joern> importCode("./src")
joern> cpg.method("sum_positive").dotCfg.l     // the CFG as dot text
joern> cpg.method("sum_positive").plotDotCfg   // render and open it

# or, from the system shell, for every method:
joern-parse ./src
joern-export --repr cfg --out cfg-out

Binaries. Disassemblers recover CFGs from machine code. Ghidra, for example, shows a function's basic blocks and branches in its Function Graph view; see the documentation of your disassembler for how to export the graph.

Option names and output formats change between releases; if a command here does not match your version, check opt -print-passes, gcc --help=common or joern-export --help.

Using control flow graphs in code review

Reviewers rarely draw a CFG, but many of the questions they ask of a diff are questions about one, and tools that hold the graph can answer them before a person has to trace the paths by hand:

  • Does every path still clean up? A new early return or continue adds an edge that can skip an unlock, a close or a rollback. The check is post-dominance: does the cleanup block lie on every path from the acquisition to the exit?
  • Is a check really on the path? A validation that sits in one branch protects only that branch. Following CFG paths from where a value enters to where it is used shows whether the check dominates the use.
  • Did the change add paths without tests? New branches are new edges. Comparing the edges in the changed function with the edges your branch coverage report marks as taken shows which ones no test exercises.
  • Did the function get harder to follow? Cyclomatic complexity before and after the change is a quick signal that a function has grown more paths than it can comfortably be reviewed in one sitting. Treat it as a prompt to look, not a rule.
  • Is anything now unreachable? A condition that can no longer be true leaves blocks with no incoming path; compilers and linters often report these as dead code.

Limits to plan for

  • Exceptions add hidden edges. Any call that can throw is, in principle, a branch to a handler or out of the function. Tools differ on whether, and how precisely, they draw those edges.
  • Indirect jumps and calls. Function pointers, virtual dispatch, computed goto and jump tables in binaries leave the target of an edge unknown until other analyses narrow it down.
  • Source graph or compiled graph. A CFG of source code, of compiler IR and of machine code for the same function can look quite different. Pick the level that matches your question: source for review, IR or machine code for what actually runs.
  • Paths are not runs. A CFG over-approximates: it includes paths no input can drive, such as both sides of two branches on the same condition. Path counts grow quickly, which is why analyses summarise per block rather than enumerating paths.

Frequently asked questions

What is a control flow graph in simple terms?
A diagram of every route execution can take through a function: boxes are basic blocks of statements that always run together, and arrows show where control can go next, such as either side of an if or the jump back to the top of a loop.
What is a basic block?
A sequence of statements with a single entry at the top and a single exit at the bottom, so that if the first statement runs, every statement in the block runs in order. A new block starts at the first statement of a function, at every jump target and right after every jump.
How do you calculate cyclomatic complexity from a control flow graph?
Use McCabe's formula M = E − N + 2P: edges minus nodes plus twice the number of connected components, which is 1 for a single function. For a function with a single loop containing a single if, 7 edges and 6 blocks give 7 − 6 + 2 = 3, the same as counting its two decision points and adding one.
How do I generate a control flow graph from C code?
With Clang, emit LLVM IR (clang -S -emit-llvm file.c -o file.ll) and run opt -passes=dot-cfg -disable-output file.ll to get a Graphviz .dot file per function. With GCC, compile with -fdump-tree-cfg-graph. Joern can also export a function's CFG with dotCfg or joern-export --repr cfg. Render any .dot file with Graphviz's dot command.
What is the difference between a control flow graph and a call graph?
A call graph shows which functions call which other functions across a program. A control flow graph shows how execution moves between blocks of statements inside a function. Interprocedural analyses join the two by linking call sites in one function's CFG to the entry of the function they call.

Sources

  1. Control Flow Analysis, Frances E. Allen (ACM SIGPLAN Notices, 1970)
  2. A Complexity Measure, T. J. McCabe (IEEE Transactions on Software Engineering, 1976)
  3. LLVM's Analysis and Transform Passes (dot-cfg, dot-cfg-only)
  4. GCC Developer Options (-fdump-tree and the graph option)
  5. Exporting Graphs, Joern documentation