Skip to content

SelectionDAG 05.2 op vector legalization

Mugundan edited this page Nov 27, 2026 · 1 revision

Operation and Vector Legalization

Relevant source files

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

Once every type is legal, legalization asks for every node: does the target have this operation on this type? Each answer is one of five actions, and the target supplies the Custom ones through `LowerOperation`.

Purpose and Scope

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.

Registered Actions on AArch64

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

The Scalar Legalizer Algorithm

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"]
Loading
  1. AssignTopologicalOrder() sorts AllNodes operands-first.
  2. 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".
  3. A node with no users that is not the root is deleted; otherwise, if it is not yet in the LegalizedNodes set, LegalizeOp runs.
  4. 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"]
Loading

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

The Two Target Hooks

  • 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 empty SDValue means "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 for i128 atomics, certain READ_REGISTER forms 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

Example: smin

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

Example: Global Addresses

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.

Vector Operation Legalization (VectorLegalizer)

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.

  • Run first scans the DAG and returns immediately if no node produces a vector value.
  • It then walks the nodes operands-first (topological order), calling LegalizeOp on 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, so sdiv <4 x i32> ends up as four scalar sdivs.
  • 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

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