Skip to content

SelectionDAG 03 dag construction

Mugundan edited this page Nov 27, 2026 · 1 revision

DAG Construction

Relevant source files

The following files were used as context for generating this wiki page:

`SelectionDAGBuilder` walks the instructions of one IR basic block in program order and turns each into `SDNode`s, using a per-block map from IR `Value` to `SDValue`. Values that live across blocks are exchanged through virtual registers with `CopyToReg` and `CopyFromReg`.

Purpose and Scope

This page covers phase 1: the driver loop, the translation of each IR instruction, chain handling while building, cross-block values and function arguments. PHI handling during construction is summarised here and detailed in PHI Node Resolution.

Driver Flow

flowchart TD
  A["runOnMachineFunction"] --> B["FunctionLoweringInfo::set<br/>vregs, MBBs, empty machine PHIs"]
  B --> C["SelectAllBasicBlocks"]
  C --> D["LowerArguments<br/>entry block only"]
  C --> E["for each block in reverse post-order"]
  E --> F["SelectBasicBlock"]
  F --> G["SDB visit for each instruction"]
  G --> H["CodeGenAndEmitDAG"]
  E --> I["FinishBasicBlock<br/>patch successor PHIs, switch extras"]
Loading
  1. FunctionLoweringInfo::set creates one MachineBasicBlock per IR block, assigns virtual registers to values used outside their block or by a PHI, and creates an empty machine PHI for every live IR PHI.
  2. SelectAllBasicBlocks visits blocks in reverse post-order. For the entry block it first calls LowerArguments, which calls the target's LowerFormalArguments.
  3. SelectBasicBlock(Begin, End) calls SDB->visit(*I) for each instruction, sets the DAG root to getControlRoot(), and calls CodeGenAndEmitDAG().
  4. FinishBasicBlock attaches PHI operands, handles switch-lowering extras (jump tables, bit tests, stack-protector blocks) and runs CodeGenAndEmitDAG again for any extra machine block it created.

One IR block normally yields one DAG, but it can become several machine blocks, and with FastISel only the part FastISel could not select is built as a DAG.

Sources: llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp:86-335, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1656-1971, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:884-908, llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp:1974-2227

IR Instruction to DAG Node

SelectionDAGBuilder::visit(const Instruction&) dispatches on the IR opcode. After visiting a non-terminator it calls CopyToExportRegsIfNeeded, and just before a terminator it calls HandlePHINodesInSuccessorBlocks.

LLVM IR Builder function Initial DAG node(s)
add, sub, mul, and, or, xor, shl, lshr, ashr visitBinary ISD::ADD, SUB, MUL, AND, OR, XOR, SHL, SRL, SRA; nsw/nuw/exact become node flags
sdiv, udiv, srem, urem visitBinary ISD::SDIV, UDIV, SREM, UREM
icmp visitICmp ISD::SETCC with result type i1 and a CondCodeSDNode
select visitSelect ISD::SELECT (VSELECT for vectors)
zext, sext, trunc, bitcast visitZExt ... ZERO_EXTEND, SIGN_EXTEND, TRUNCATE, BITCAST
getelementptr visitGetElementPtr ADD ptr, (MUL idx, size); constant indices fold into one offset; a power-of-two size becomes SHL
load visitLoad ISD::LOAD chain, ptr, undef, results (value, chain)
store visitStore ISD::STORE chain, value, ptr, undef, result chain
phi none No node. The PHI's virtual register is read with CopyFromReg when used
br visitCondBr, visitUncondBr ISD::BR, or ISD::BRCOND chain, cond, BasicBlock plus ISD::BR
call visitCall, LowerCallTo The target's LowerCall: CALLSEQ_START, CopyToReg per argument, AArch64ISD::CALL, CALLSEQ_END, CopyFromReg per result
ret visitRet The target's LowerReturn: CopyToReg $w0/$x0/$q0 and AArch64ISD::RET_GLUE

Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:1372-1418, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:3738-3756, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:3808-3833, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:3863-4007, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:4497-4666, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:4740-4862, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:4920-4993, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:2217-2379, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:2840-2926, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:9316-9437

Chains While Building

The builder keeps a current root chain and a few pending lists so independent memory operations do not get a false order.

  • Loads are collected in PendingLoads. A load takes the current chain as input but does not become the new root; the chains are merged with a TokenFactor only when something needs a full ordering. Two loads can therefore be reordered freely.
  • Stores, calls and ABI register copies (return values, outgoing arguments) ask for the root with getRoot() (stores use getMemoryRoot()), which first flushes PendingLoads into a TokenFactor. They chain on top of the result and become the new root.
  • Exports (CopyToReg for values leaving the block) are collected in PendingExports and joined by getControlRoot(), which becomes the DAG's Root.

Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:1206-1229

Values Across Blocks

getValue(V) checks NodeMap first, then getCopyFromRegs (is there a virtual register for V in FuncInfo.ValueMap?), then builds a constant or other leaf. A value is therefore a direct SDValue in its defining block and a CopyFromReg in any other block.

After each non-terminator, CopyToExportRegsIfNeeded emits a CopyToReg into the value's virtual register if one was assigned. FunctionLoweringInfo::set assigns registers to every value that is used outside its block or by a PHI.

sequenceDiagram
  participant FLI as FunctionLoweringInfo
  participant SDB as SelectionDAGBuilder
  participant DAG as SelectionDAG
  FLI->>FLI: InitializeRegForValue for exported values
  SDB->>DAG: visit(add) creates the ADD node
  SDB->>DAG: CopyToExportRegsIfNeeded emits CopyToReg to vreg
  Note over SDB,DAG: another block later
  SDB->>DAG: getValue finds vreg in ValueMap, emits CopyFromReg
Loading

Sources: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:1798-1815, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:2384-2395, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:11860-11884, llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp:46-55, llvm/lib/CodeGen/SelectionDAG/FunctionLoweringInfo.cpp:392-400

Function Arguments on AArch64

AArch64TargetLowering::LowerFormalArguments runs the calling-convention rules from AArch64CallingConvention.td over the IR argument types. For an argument passed in $w0 it registers a live-in (MF.addLiveIn, returning a vreg such as %0) and creates CopyFromReg Chain, Register:i32 %0. In the final MIR this appears as liveins: $w0 on the block and %0:gpr32 = COPY $w0 at its top; the copies are inserted by MachineRegisterInfo::EmitLiveInCopies after all blocks are selected (see Scheduling and MIR Emission).

Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:9059-9520, llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:12077-12441

Example: smin

define i32 @smin(i32 %a, i32 %b) {
  %c = icmp slt i32 %a, %b
  %r = select i1 %c, i32 %a, i32 %b
  ret i32 %r
}

Initial DAG (reconstructed in -debug-only=isel format; node numbers are illustrative):

t0: ch,glue = EntryToken
t2: i32,ch = CopyFromReg t0, Register:i32 %0
t4: i32,ch = CopyFromReg t0, Register:i32 %1
t5: i1 = setcc t2, t4, setlt:ch
t6: i32 = select t5, t2, t4
t8: ch,glue = CopyToReg t0, Register:i32 $w0, t6
t9: ch = AArch64ISD::RET_GLUE t8, Register:i32 $w0, t8:1

AArch64 has no 1-bit registers, so i1 is an illegal type. Here the problem disappears early, because the combiner rewrites select (setcc ...) as select_cc before type legalization starts (see DAG Combiner). A setcc whose i1 result survives is promoted by the type legalizer (see Type Legalization). The example continues on Operation and Vector Legalization.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally