Repository navigation
SelectionDAG 05.1 type legalization
Relevant source files
The following files were used as context for generating this wiki page:
This page covers DAGTypeLegalizer: which types are legal on AArch64, the type actions, the algorithm, and worked examples of promotion, expansion, vector splitting and the setcc result type. The code is in LegalizeTypes.cpp, LegalizeIntegerTypes.cpp, LegalizeFloatTypes.cpp, LegalizeVectorTypes.cpp and LegalizeTypesGeneric.cpp, entered through CurDAG->LegalizeTypes(). See Legalization for the overall structure.
The target declares legal types with addRegisterClass(MVT, RegClass) and then calls computeRegisterProperties, which fills a table mapping each type to a type action. On AArch64 the scalar registers are i32 (GPR32all) and i64 (GPR64all); the FP registers are f16, bf16, f32, f64 and f128 whenever FP is available; NEON vectors such as v4i32 live in FPR128 and FPR64.
Action (LegalizeTypeAction) |
Meaning | AArch64 example |
|---|---|---|
TypePromoteInteger |
Make the integer wider |
i1, i8, i16 become i32
|
TypeExpandInteger |
Split into two integers of half the width |
i128 becomes two i64
|
TypeSoftenFloat |
Treat a float as an integer and use library calls | Not used for AArch64 f32/f64 (FP hardware exists) |
TypeExpandFloat |
Split a float into two halves | Rare (ppcf128) |
TypeScalarizeVector |
One-element vector becomes its element | |
TypeSplitVector |
Split into two half-width vectors |
<8 x i32> becomes two <4 x i32>
|
TypeWidenVector |
Pad to a legal vector |
<3 x i32> becomes <4 x i32>; AArch64 also widens v1i8, v1i16, v1i32
|
TypeSoftPromoteHalf |
Keep half as i16 and compute in float
|
Targets with no f16 register class (AArch64 keeps f16 legal and promotes its arithmetic to f32) |
A related query is the setcc result type: AArch64TargetLowering::getSetCCResultType returns i32 for scalar compares and an integer vector of the same shape for vector compares.
Sources: llvm/include/llvm/CodeGen/TargetLowering.h:231-242, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:471-486, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:552, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:2685-2692, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:32176-32184
DAGTypeLegalizer::run() works bottom-up in dependency order, the opposite of the combiner.
flowchart TD
I["Label nodes<br/>leaves ReadyToProcess, others count unprocessed operands"] --> W["Pop ready node N"]
W --> R{"Any result type illegal?"}
R -- yes --> RH["Result handler<br/>PromoteIntegerResult, ExpandIntegerResult, SplitVectorResult, ..."]
R -- no --> O{"Any operand type illegal?"}
O -- yes --> OH["Operand handler<br/>PromoteIntegerOperand, SplitVectorOperand, ..."]
O -- no --> OK["N is legally typed"]
RH --> DONE["Mark Processed and decrement the counts of N's users"]
OH --> DONE
OK --> DONE
DONE --> NX["Users whose count reaches zero become ready"]
NX --> W
- Leaves (no operands) are
ReadyToProcessand go on a worklist; every other node gets a count of its unprocessed operands. - Pop a ready node. Scan its result types; at the first illegal one call the matching handler, which must deal with all results of the node.
- If all result types are legal, scan operand types. An illegal operand (for example a store of an
i8) is handled by an operand handler that updates the node in place or replaces it. - When a node is done, decrement the pending count of each user; a user at zero is ready.
- Replacements are recorded in side tables (
PromotedIntegers,ExpandedIntegers,SplitVectors,WidenedVectors, ...). A user asks for the legal form of an illegal value withGetPromotedInteger,GetExpandedInteger,GetSplitVector, and so on. New nodes are re-analysed so they are legal too. - At the end dead nodes are removed.
Because operands are always done before users, a handler can rely on the legalised form of every operand.
Sources: llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp:200-487
Promoting i8 to i32 leaves the upper 24 bits unspecified (an any-extend) unless the operation cares. The handlers pick the cheapest extension that is still correct:
-
add,sub,mul,and,or,xor,shl: low bits of the result depend only on low bits of the inputs, so any-extend is fine. -
lshr,ashr,udiv,sdiv,urem,srem, comparisons,ctpop,uitofp/sitofp: high bits matter, so the operand is first fixed withzero_extend_inreg(anandwith a mask) orsign_extend_inreg. - A value that must be exactly
i8again (8-bit store, return in a register) is narrowed withtruncateor stored as a truncating store.
Example (real llc result: add8 in Arithmetic and Data Movement):
before: t3: i8 = truncate t2 ; t2 = CopyFromReg i32 (value arrives in $w0)
t5: i8 = truncate t4
t6: i8 = add t3, t5
t7: i32 = any_extend t6 ; return value convention
after: t6: i32 = add t2, t4 ; promoted; operands are the original i32 values
; t7 disappears: any_extend (truncate x) folds to x
The result is a single ADDWrr; the garbage upper bits are never observed.
Sources: llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp:1454-1494
An i128 add goes through ExpandIntegerResult, whose add handler splits the operands into low and high i64 halves with GetExpandedInteger and emits a carry chain:
before: t10: i128 = add a, b
after: t11: i64,i32 = uaddo lo_a, lo_b ; low half, produces carry
t12: i64,i32 = uaddo_carry hi_a, hi_b, t11:1
; result = (t11, t12); no i128 value remains
The real MIR is ADDSXrr %0, %2, implicit-def $nzcv followed by ADCXr %1, %3, implicit $nzcv, i.e. adds x0, x0, x2 and adc x1, x1, x3. Other i128 operations expand differently: shifts use funnel-shift sequences, multiplies use umul_lohi pieces, and division becomes a runtime call (__divti3).
Sources: llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp:3905-4046
<8 x i32> is not a register type, so SplitVectorResult splits every operation on it into two operations on <4 x i32>, with extract_subvector for the inputs and concat_vectors for the result. After the combiner cleans up the extract and concat scaffolding, the real MIR is two ADDv4i32 instructions. A <3 x i32> is widened instead (padded with undef), so one 128-bit operation runs and one lane is ignored.
Sources: llvm/lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp:1358-1685
Take ret i32 (zext (icmp slt a, b)). The setcc has an illegal i1 result and no combine removes it, because nothing uses it as a select condition. PromoteIntRes_SETCC re-creates it with the target's getSetCCResultType (i32), and the zero_extend of a value that is already 0 or 1 is dropped. AArch64 sets setBooleanContents(ZeroOrOneBooleanContent) in its constructor, which tells the legalizer that a promoted boolean holds exactly 0 or 1 in all 32 bits, so no masking is needed:
before: t5: i1 = setcc t2, t4, setlt:ch
t6: i32 = zero_extend t5
after: t6: i32 = setcc t2, t4, setlt:ch ; promoted result, the zero_extend folded away
Operation legalization then lowers the Custom setcc into a flag-setting subtract and a conditional-select-increment of the zero register (the cset idiom). The real MIR is SUBSWrr %0, %1 followed by CSINCWr $wzr, $wzr, 10 (condition 10 is GE, the inverse of lt), and the assembly is cmp w0, w1 then cset w0, lt.
Sources: llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp:1454-1494, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:460-468
- 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