Repository navigation
SelectionDAG 04 dag combiner
Relevant source files
The following files were used as context for generating this wiki page:
This page describes the DAGCombiner::Run algorithm, the four combine levels, the categories of folds, the AArch64 target hooks, and three worked examples. It is not a single top-to-bottom pass, and not a fixed-point loop over the whole graph either: only nodes touched by a change are revisited.
flowchart TD
S["Seed worklist with every node in AllNodes order"] --> P["Pop node N from the back"]
P --> D{"N has no users?"}
D -- yes --> DEL["Delete N and re-queue its operands"]
DEL --> P
D -- no --> LG{"Level is AfterLegalizeDAG?"}
LG -- yes --> RL["Re-legalize N"]
RL --> Q
LG -- no --> Q["Queue N's operands that were not combined before"]
Q --> C["combine of N"]
C --> R{"Replacement found?"}
R -- no --> P
R -- yes --> REP["ReplaceAllUsesWith, queue the new node and all its users"]
REP --> P
-
Seed. Every node in
DAG.allnodes()is pushed on a worklist. With-combiner-topological-sorting(or when the target'suseTopologicalSorting()says so) the DAG is first sorted and pushed in reverse. Each node stores its worklist index in the node itself;-2means already combined once. - Pop from the back. The worklist is a vector used as a stack, so the node created last (normally the root) is processed first.
- Dead node? A popped node with no users is deleted and its operands are queued again.
-
After legalization only: at
AfterLegalizeDAGthe node is first re-legalized withDAG.LegalizeOp, so combines never see an illegal node. - Queue the operands that have not been combined yet. Because the list is last-in-first-out, the operands are visited next: the walk descends from users toward operands.
-
combine(N), stopping at the first success:- the generic
visit(N), onevisitXxxper opcode; - the target hook
TLI.PerformDAGCombine(N, DCI), called only if the target registered the opcode withsetTargetDAGCombine(or N is a target opcode); - operation promotion (
PromoteIntBinOpand friends); - for commutative operations, reuse of an existing operand-swapped node.
- the generic
-
Replace. If a replacement
RVcame back,ReplaceAllUsesWith(N, RV)rewires every user, and the new node and all its users go on the worklist. A dead N is deleted.
Two consequences follow. A pattern rooted at a user sees its operands in their original shape, and when an operand later simplifies the user is re-queued for a second look. And termination relies on every fold making the DAG better by some measure: two folds that undo each other make llc hang.
Uniquing (see Core Data Structures) makes common-subexpression elimination implicit.
Sources: llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:1846-1963, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:235-252, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:274-294, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:2152-2222
The CombineLevel enum is in DAGCombine.h. Run derives LegalTypes, LegalOperations and LegalDAG from it (see the table on Pipeline, Phases and Traversal Orders).
| Run | Level | Runs | Illegal types allowed? | Illegal operations allowed? |
|---|---|---|---|---|
| 1 | BeforeLegalizeTypes |
always | yes | yes |
| 2 | AfterLegalizeTypes |
only if type legalization changed the DAG | no | yes |
| 3 | AfterLegalizeVectorOps |
only if vector legalization changed the DAG | no | no |
| 4 | AfterLegalizeDAG |
always | no | no |
Combines guard themselves with the flags, for example if (!LegalOperations || TLI.isOperationLegal(ISD::ROTL, VT)), so a fold never introduces something the target cannot select. TargetLowering::DAGCombinerInfo exposes isBeforeLegalize(), isBeforeLegalizeOps() (true for levels 1 and 2) and isAfterLegalizeDAG() to target code.
Sources: llvm/include/llvm/CodeGen/DAGCombine.h:15-20, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:1846-1851, llvm/include/llvm/CodeGen/TargetLowering.h:4574-4587
| Category | Example fold | Where |
|---|---|---|
| Constant folding |
add 3, 4 becomes 7
|
getNode folds on creation |
| Identities |
x + 0, x * 1, x & -1, x ^ x
|
visitADD, visitMUL, ... |
| Reassociation |
(x + c1) + c2 becomes x + (c1 + c2)
|
reassociateOps |
| Strength reduction |
mul x, 8 becomes shl x, 3; udiv x, c becomes multiply-high and shifts |
visitMUL, visitUDIV
|
| Extension folding |
zext (load i8) becomes a ZEXTLOAD; trunc (zext x) becomes x
|
visitZERO_EXTEND, visitTRUNCATE
|
| Demanded bits | Remove masks or extensions whose bits no user reads | SimplifyDemandedBits |
| Compare and select |
select (setcc a, b, cc), x, y becomes select_cc a, b, x, y, cc when SELECT_CC is legal or Custom; brcond (setcc ...) becomes br_cc
|
visitSELECT, visitBRCOND
|
| Memory | Store-to-load forwarding, store merging, load narrowing, forming pre/post-indexed loads and stores |
visitLOAD, visitSTORE, CombineToPreIndexedLoadStore, CombineToPostIndexedLoadStore
|
| Vectors | Fold extract_vector_elt (build_vector ...), merge shuffles, detect splats |
visitEXTRACT_VECTOR_ELT, visitVECTOR_SHUFFLE
|
Sources: llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:13243-13440, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:376-377, llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:4868
AArch64TargetLowering registers the opcodes it wants with setTargetDAGCombine in its constructor, and PerformDAGCombine is a switch over N->getOpcode() that dispatches to specialised functions: performAddSubCombine, performMulCombine, performANDCombine, performORCombine, performSelectCombine, performSETCCCombine, performLOADCombine, performSTORECombine, performExtendCombine, performBRCONDCombine, performTBZCombine and more. They match target-aware shapes the generic combiner cannot know, such as turning mul x, (2^n + 1) into add (shl x, n), x.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:1188-1205, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:30803-31168
performMulCombine returns early while DCI.isBeforeLegalizeOps() is true, so the fold fires in the later runs. It sees that 9 is 2^3 + 1 and rewrites:
before: t5: i32 = mul t2, Constant:i32<9>
after: t6: i32 = shl t2, Constant:i64<3>
t7: i32 = add t2, t6 ; replaces t5 for all users
Instruction Selection then matches the add plus shl to a single ADDWrs. Real llc output confirms it: the MIR contains only ADDWrs %0, %0, 3 and the assembly is add w0, w0, w0, lsl #3.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:21202-21213, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:21266-21306
The generic visitUDIV replaces division by a constant with multiplication by a magic reciprocal (TargetLowering::BuildUDIV). AArch64 has a fast 32 by 32 to 64 multiply, so the result is a widening multiply and a shift:
t3: i32 = udiv t2, Constant:i32<10>
==>
t7: i64 = zero_extend t2
t9: i64 = mul t7, Constant:i64<3435973837> ; 0xCCCCCCCD
t10: i64 = srl t9, Constant:i64<35>
t11: i32 = truncate t10
The real post-selection MIR matches: MOVi32imm -858993459 (the same constant as a signed 32-bit value), UMADDLrrr %0, killed %1, $xzr, UBFMXri killed %2, 35, 63, then a sub_32 copy for the truncate.
In the loop of PHI Node Resolution the IR is a load i32, ptr %p followed in the same iteration by getelementptr i8, ptr %p, i64 4. CombineToPostIndexedLoadStore asks the target getPostIndexedAddressParts; AArch64 answers yes for a small constant offset, so the load and the pointer add merge into one indexed load node that produces both the loaded value and the incremented pointer. AArch64 Instruction Selection shows it selected as LDRWpost.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:31289-31350
-combiner-disabled turns the generic combiner off (a quick check for whether a miscompile comes from a combine), -combiner-topological-sorting changes the visit order, -combiner-global-alias-analysis lets store and load combines use IR alias analysis, and -combiner-store-merging=false disables store merging. -debug-counter=dagcombine-skip=N,dagcombine-count=M bisects combines in assertion builds. See Tooling, Debugging and Extending.
- 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