Repository navigation
SelectionDAG 05.2 op vector legalization
Relevant source files
The following files were used as context for generating this wiki page:
This page covers the scalar operation legalizer (SelectionDAG::Legalize, SelectionDAGLegalize), the vector operation legalizer (VectorLegalizer), the two target hooks LowerOperation and ReplaceNodeResults, and AArch64 examples. See Legalization for how the three legalizers connect.
setOperationAction(ISD::OPCODE, MVT, Action) in the AArch64TargetLowering constructor fills a table indexed by opcode and simple value type. Anything left unset defaults to Legal for opcodes every target supports and Expand for the rest.
| Action | Registered for | Why on AArch64 |
|---|---|---|
| Custom |
SETCC, SELECT, SELECT_CC, BR_CC on i32/i64/f16/f32/f64; BRCOND; also GlobalAddress, ConstantPool, JumpTable, VASTART, UADDO_CARRY, BITCAST
|
The generic node is not an instruction; the target builds the real sequence |
| Expand |
ROTL on i32/i64
|
AArch64 has rotate-right only, so rotl x, n is rewritten as rotr x, (size - n)
|
| Expand |
SDIVREM, UDIVREM, UMUL_LOHI, SMUL_LOHI, MULHU, MULHS (i32) |
No combined divide-and-remainder or widening-multiply-pair instruction |
| Expand |
EXTLOAD from f16/f32/f64 to wider FP types |
Handled by an explicit fpext after a plain load |
| Legal | Indexed (pre/post-increment) LOAD/STORE for i8 to i64, f64
|
The hardware has ldr x, [base], #imm forms, so the combiner may form them |
| Legal or Custom |
CTPOP on i32/i64
|
Legal with the CSSC extension; otherwise Custom (move to a vector register, cnt, addv, move back) |
| Legal or default |
SMIN/SMAX/UMIN/UMAX/ABS on i32/i64
|
Legal with CSSC; without it SMIN/SMAX expand to compare and select and ABS is Custom |
| LibCall |
FADD and friends on f128
|
No quad-precision hardware; becomes a call such as __addtf3
|
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:574-593, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:621, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:716-731, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:733-773, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:1138-1142, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:1164-1168
flowchart TD
A["AssignTopologicalOrder"] --> B["Sweep AllNodes from the end to the start"]
B --> C{"Node dead and not the root?"}
C -- yes --> D["DeleteNode"]
C -- no --> E{"Already in LegalizedNodes?"}
E -- yes --> B
E -- no --> F["LegalizeOp of N"]
F --> B
B --> G{"Whole sweep legalized nothing new?"}
G -- no --> B
G -- yes --> H["RemoveDeadNodes"]
-
AssignTopologicalOrder()sortsAllNodesoperands-first. - The sweep goes from the end toward the beginning, so users are visited before their operands. The source comment explains it: nodes are seen "with their original operands intact".
- A node with no users that is not the root is deleted; otherwise, if it is not yet in the
LegalizedNodesset,LegalizeOpruns. - Legalization can create new nodes that themselves need legalizing, so the sweep repeats until a whole pass legalizes nothing new.
Inside LegalizeOp the action comes from TLI.getOperationAction. The type used for the lookup depends on the opcode: usually the result type, but for SINT_TO_FP and EXTRACT_VECTOR_ELT it is the operand type, for SIGN_EXTEND_INREG the inner type, for atomics the memory type, and for SETCC/SELECT_CC/BR_CC the condition code is consulted too. Then:
flowchart TD
A["getOperationAction"] --> L{"Action"}
L -- Legal --> N["Nothing to do"]
L -- Custom --> CU["TLI.LowerOperation"]
CU --> CR{"Returned a value?"}
CR -- yes --> RN["ReplaceNode with the result"]
CR -- no --> EX
L -- Expand --> EX["ExpandNode"]
EX --> ER{"Expanded?"}
ER -- yes --> DONE["Done"]
ER -- no --> LC["ConvertNodeToLibcall"]
L -- LibCall --> LC
L -- Promote --> PR["PromoteNode<br/>extend operands, operate wide, truncate"]
Sources: llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp:6328-6375, llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp:985-1426, llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp:1357-1406
-
LowerOperation(SDValue Op, SelectionDAG &DAG)is called for a node whose action is Custom and whose result types are all legal. It returns the replacement, whose result types must match the original; an emptySDValuemeans "I could not", and the generic code falls through to Expand. In AArch64 it is one switch:LowerSETCC,LowerSELECT_CC,LowerBR_CC,LowerGlobalAddress,lowerADDSUBO_CARRY, and so on. -
ReplaceNodeResults(SDNode *N, Results, DAG)is called when a node has a result of an illegal type and the operation is marked Custom for it, which happens during type legalization. The target pushes legal-typed replacement values, one per result of N, or nothing to decline. AArch64 uses it fori128atomics, certainREAD_REGISTERforms and a few vector conversions.
Sources: llvm/include/llvm/CodeGen/TargetLowering.h:5273-5284, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:8432-8850, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:31808-32145
For select (setcc a, b, setlt), a, b, DAGCombiner::visitSELECT has already rewritten the node in Combine 1 as select_cc a, b, a, b, setlt, because AArch64 registers SELECT_CC as Custom and operations do not have to be legal yet at that level. If a plain select survives instead, LowerSELECT forwards to the same logic; its source comment says it "lowers it the same way as we would lower a SELECT_CC node". LowerSELECT_CC emits a flag-setting subtract and a conditional select that reads its flag result:
before: t6: i32 = select_cc t2, t4, t2, t4, setlt
after: t10: i32,i32 = AArch64ISD::SUBS t2, t4 ; result 1 is the NZCV flags
t11: i32 = AArch64ISD::CSEL t2, t4, Constant:i32<11>, t10:1 ; 11 = condition code LT
The two new nodes are AArch64ISD:: opcodes, not machine instructions yet. The real post-selection MIR confirms the shape: %2:gpr32 = SUBSWrr %0, %1, implicit-def $nzcv then %3:gpr32 = CSELWr %0, %1, 11, implicit $nzcv.
LowerSELECT_CC also checks whether both arms are constants that differ by one, in which case it builds AArch64ISD::CSINC (or CSINV / CSNEG for related constants) directly.
Sources: llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp:13408-13415, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:12744-13022, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:13078-13156, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:12868-12912
ISD::GlobalAddress is Custom. For a dso_local global in the small code model, LowerGlobalAddress builds a two-part address: AArch64ISD::ADRP (the 4 KiB page of the symbol) plus AArch64ISD::ADDlow (the low 12 bits). The real MIR for load i32, ptr @g shows selection folding the low part into the load:
%0:gpr64common = ADRP target-flags(aarch64-page) @g
%1:gpr32 = LDRWui killed %0, target-flags(aarch64-pageoff, aarch64-nc) @g :: (dereferenceable load (s32) from @g)
If only the pointer is needed (ret ptr @g) the pair is the pseudo MOVaddr, expanded into adrp and add :lo12: after register allocation. For a preemptible global in a position-independent build, LOADgot becomes adrp plus an ldr from the GOT slot.
Type legalization made vector types legal; the VectorLegalizer makes vector operations legal. It runs on its own because many rewrites only make sense once types are legal.
-
Runfirst scans the DAG and returns immediately if no node produces a vector value. - It then walks the nodes operands-first (topological order), calling
LegalizeOpon each. - The same action switch applies: Legal, Promote, Custom (
LowerOperationWrapper) and Expand. - Expansion tries an equivalent sequence of other vector operations and, as the last resort,
UnrollVectorOp, which extracts each lane, applies the scalar operation and rebuilds the vector. NEON has no integer vector divide, sosdiv <4 x i32>ends up as four scalarsdivs. - If it changed anything, type legalization runs a second time (the expansion may have created illegal scalar types), followed by Combine 3.
Sources: llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp:207-247, llvm/lib/CodeGen/SelectionDAG/LegalizeVectorOps.cpp:559-609
- 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