Section 3.14

Basic block

Definition

A basic block is a sequence of consecutive instructions that execution can enter only at the first instruction and leave only after the last one. No instruction after the first is the target of a jump, and only the last instruction can send control elsewhere. Once the first instruction runs, the others therefore run in order, unless an instruction faults. A basic block is normally as long as possible: it ends before the next jump target or at the next jump. Basic blocks are the nodes of most control-flow graphs §3.13.

Where it fits

Main entry: Control-flow graph (CFG) (§3.13).

A control-flow graph (CFG) records the possible transfers between basic blocks; the control-flow graph entry treats the graph and its edges in full. To split code into basic blocks, mark the leaders, the instructions that begin a block: the first instruction, every target of a jump, and every instruction directly after a jump or a return. Each block runs from one leader up to the next. The last instruction of a block, its terminator, decides the outgoing edges: a jump, a conditional jump, a return, or an ordinary instruction that falls through to the next block.

Blocks make analysis cheaper. An analysis treats a whole block as one step, whose effect is the effect of its instructions in sequence, and it needs to combine facts only at the start of a block, where several edges can arrive. Compilers use blocks the same way, for example to reorder instructions within a block.

Calls and faults are handled in two ways. Many compilers keep a call inside a block, because execution normally continues after it; an analysis that follows the called function, or an exception the call can raise, ends the block at the call. Instructions that can fault normally stay inside a block, with the fault treated as an extra edge out of the block. The rule that all instructions run once the first one runs therefore holds only when no fault occurs.

The leader rule assumes that the instruction boundaries are already known. For machine code, a decoder must first find where each instruction starts, and the instruction set decides which starting points are legal.

Questions answered

Can execution legally enter the middle of a decoded instruction sequence?

Execution can enter the middle of a sequence of whole instructions, but whether it can enter the middle of a single instruction depends on the instruction set and on any checker’s rules.

The instruction set decides which entry points are legal. A basic block only records them: calling something a block cannot make the inside of an instruction a legal place to start.

Related entries: Instruction encoding (§2.7), Wide immediate instruction (§2.10), eBPF verifier (§3.3).