Skip to content
Control Flow Graph
step 1/5

Reading — step 1 of 5

Read

~1 min readAST & Visitors

Control Flow Graph

A CFG decomposes a function into basic blocks (straight-line code) and edges (branches).

def f(x):
    if x > 0:    # block A: ends in branch
        y = 1     # block B
    else:
        y = -1    # block C
    return y     # block D

CFG: A → B, A → C, B → D, C → D.

Used for:

  • Unreachable code: any block not reachable from entry. Emit warning.
  • Dead store: variable assigned but never read on any path.
  • Definite assignment: every path defines y before reading. (Java/Rust enforce this.)
  • Loop analysis: detect infinite loops (no exit), bounds, etc.

Construction:

  1. Find leaders (start of each basic block: function start, branch target, statement after a branch).
  2. Collect statements between leaders → blocks.
  3. Add edges per branch / fallthrough.
python

Real implementations are involved (handle try/except/finally, break, continue, etc.). For our linter, a simple forward walk catching return; <stmt> is enough for unreachable code.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…