Repository navigation
SelectionDAG 09.4 end to end
Relevant source files
The following files were used as context for generating this wiki page:
The IR, the final MIR and the assembly are real llc output (LLVM 23.1.4, -mtriple=aarch64 -O2). The intermediate DAGs are reconstructed from the algorithms documented on the earlier pages; node numbers and some auxiliary nodes (such as undef offsets and TokenFactors) will differ from a real dump, but the sequence of transformations is what the passes do.
define i32 @f(ptr %p, i64 %i, i32 %k) {
%g = getelementptr inbounds i32, ptr %p, i64 %i
%v = load i32, ptr %g, align 4
%m = mul i32 %v, 9
%c = icmp slt i32 %m, %k
%r = select i1 %c, i32 %m, i32 %k
ret i32 %r
}The function is one basic block with no PHIs and no values used across blocks, so FunctionLoweringInfo creates only the entry MBB.
flowchart TD
A["1 Initial DAG<br/>shl, add, load, mul, setcc i1, select"] --> B["2 Combine 1<br/>select of setcc becomes select_cc"]
B --> C["3 Type legalization<br/>nothing to do, Combine 2 skipped"]
C --> D["4 Operation legalization<br/>select_cc becomes SUBS and CSEL"]
D --> E["5 Combine 4<br/>mul by 9 becomes add of shl"]
E --> F["6 Selection<br/>LDRWroX, ADDWrs, SUBSWrr, CSELWr"]
F --> G["7 Emission<br/>MIR with virtual registers"]
Arguments arrive through LowerFormalArguments as three live-in registers ($x0, $x1, $w2) read with CopyFromReg. The GEP becomes a shift (the element size 4 is a power of two) and an add. The load takes the entry chain, and because it is the only pending load the return lowering uses its chain output directly.
t0: ch,glue = EntryToken
t2: i64,ch = CopyFromReg t0, Register:i64 %0 ; p
t4: i64,ch = CopyFromReg t0, Register:i64 %1 ; i
t6: i32,ch = CopyFromReg t0, Register:i32 %2 ; k
t8: i64 = shl t4, Constant:i64<2>
t9: i64 = add t2, t8 ; address
t10: i32,ch = load<(load (s32) from %ir.g)> t0, t9, undef:i64
t12: i32 = mul t10, Constant:i32<9>
t13: i1 = setcc t12, t6, setlt:ch ; i1 is not a legal type
t14: i32 = select t13, t12, t6
t16: ch,glue = CopyToReg t10:1, Register:i32 $w0, t14
t17: ch = AArch64ISD::RET_GLUE t16, Register:i32 $w0, t16:1
One fold applies. visitSELECT sees select (setcc t12, t6, setlt), t12, t6 and, because AArch64 registers SELECT_CC as Custom and LegalOperations is still false, rewrites it as a select_cc. The i1 setcc disappears with it. AArch64's performMulCombine still does nothing, because it returns early while DCI.isBeforeLegalizeOps() is true, so mul x, 9 is untouched for now.
t14: i32 = select_cc t12, t6, t12, t6, setlt ; replaces t13 (setcc) and the old t14 (select)
Sources: llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:13408-13415, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:21202-21215
No node has an illegal type any more: the only candidate, the i1 from setcc, vanished in Combine 1, and the shl amount is already i64, which AArch64 uses as its scalar shift-amount type. LegalizeTypes therefore reports no change, and Combine 2 (AfterLegalizeTypes) is skipped, because CodeGenAndEmitDAG only runs it if (Changed).
t14: i32 = select_cc t12, t6, t12, t6, setlt ; unchanged: every type is already legal
The vector legalizer, which runs next, will also find nothing to do.
The vector legalizer returns immediately because no node has a vector type. In operation legalization every node is visited, root first. add, shl and load are Legal. select_cc is Custom, so LowerSELECT_CC runs: it emits a flag-setting subtract and a CSEL that reads the flags with condition code 11 (LT). The old select_cc node dies.
t20: i32,i32 = AArch64ISD::SUBS t12, t6 ; result 1 = NZCV
t21: i32 = AArch64ISD::CSEL t12, t6, Constant:i32<11>, t20:1
t16: ch,glue = CopyToReg t10:1, Register:i32 $w0, t21
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:12744-13022
Now the legal-operations level is reached, so performMulCombine fires: 9 = 2^3 + 1, so mul x, 9 becomes add (shl x, 3), x, and all users of t12 (the SUBS and the CSEL) are rewired to the new add. The dead mul is deleted.
t22: i32 = shl t10, Constant:i64<3>
t23: i32 = add t10, t22
t20: i32,i32 = AArch64ISD::SUBS t23, t6
t21: i32 = AArch64ISD::CSEL t23, t6, Constant:i32<11>, t20:1
DoInstructionSelection walks the nodes from the root toward the entry. Each row is one Select decision, in order.
| Order | Node visited | What the matcher or C++ code does | Result |
|---|---|---|---|
| 1 | AArch64ISD::RET_GLUE |
Pattern AArch64retglue
|
RET_ReallyLR |
| 2 | CopyToReg $w0 |
Structural node; kept as is | stays |
| 3 | AArch64ISD::CSEL t23, t6, 11, t20:1 |
Pattern on AArch64csel with the NZCV operand |
CSELWr t23, t6, 11 |
| 4 | AArch64ISD::SUBS t23, t6 |
Pattern on AArch64sub_flag
|
SUBSWrr t23, t6 |
| 5 | add t10, t22 |
arith_shifted_reg32 sees shl t10, 3 on the second operand and absorbs it |
ADDWrs t10, t10, 3 |
| 6 | shl t10, 3 |
No users any more, skipped | removed |
| 7 | load t0, t9 |
ro_Xindexed32 (SelectAddrModeXRO) sees add t2, (shl t4, 2) with only memory users |
LDRWroX t2, t4, 0, 1 |
| 8 |
add t2, t8, shl t4, 2
|
Absorbed into the load's addressing mode, dead | removed |
| 9 |
CopyFromReg nodes, EntryToken
|
Structural | stay |
The source-order list scheduler produces the order load, add, subtract, select, copy, return. InstrEmitter creates virtual registers for each machine node's result (class from the instruction's operand constraint), turns the CopyToReg into $w0 = COPY %6, and then EmitLiveInCopies inserts the three live-in copies at the top. Real output (-stop-after=finalize-isel):
bb.0 (%ir-block.0):
liveins: $x0, $x1, $w2
%2:gpr32 = COPY $w2
%1:gpr64 = COPY $x1
%0:gpr64common = COPY $x0
%3:gpr32 = LDRWroX %0, %1, 0, 1 :: (load (s32) from %ir.g)
%4:gpr32 = ADDWrs %3, %3, 3
%5:gpr32 = SUBSWrr %4, %2, implicit-def $nzcv
%6:gpr32 = CSELWr %4, %2, 11, implicit $nzcv
$w0 = COPY %6
RET_ReallyLR implicit $w0
The base pointer is %0:gpr64common, not plain gpr64: the emitter constrained its register class because a load base cannot be xzr. The index %1 stays gpr64 because SelectAddrModeXRO produced it as the index operand.
Register allocation, the coalescer and frame lowering eliminate the COPYs. The SUBSWrr result is dead (only its flags are used), so it becomes a cmp alias. The final assembly:
f:
ldr w8, [x0, x1, lsl #2]
add w8, w8, w8, lsl #3
cmp w8, w2
csel w0, w8, w2, lt
retFive instructions for six IR instructions: the address computation and the multiply were folded away (into an addressing mode and a shifted-operand add), and the icmp plus select pair became cmp plus csel.
At -O0 on AArch64 the selector is GlobalISel, not SelectionDAG (-global-isel-abort=1 reports no fallback), and the output shows the difference: there is no combiner pass that rewrites mul x, 9.
f:
ldr w8, [x0, x1, lsl #2]
mov w9, #9
mul w8, w8, w9
subs w9, w8, w2
csel w0, w8, w2, lt
retThe load address still became a single register-offset load, but the multiply stays a mul, and the compare still writes a result register (subs) rather than being a cmp.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look