Repository navigation
Bringup 07 instructions isel
Relevant source files
The following files were used as context for generating this wiki page:
What a target writes to get instruction selection working: instruction records, target DAG nodes, the selector class, and the TargetInstrInfo hooks that later passes need. The pattern syntax is covered by the SelectionDAG pattern language page, the matcher by the matcher interpreter page, and AArch64's hand-written selection by the AArch64 selection page.
AArch64 builds most instructions from multiclasses in AArch64InstrFormats.td, which share operand lists and encoding layouts. Integer add and subtract are one line in AArch64InstrInfo.td:
defm ADD : AddSub<0, "add", "sub", add>;
AddSub (defined in AArch64InstrFormats.td) expands into the register, immediate, shifted-register and extended-register forms for 32 and 64 bits (ADDWrr, ADDXri, ...), and the last argument, the generic add node, becomes the selection pattern. That is why the first-milestone MIR shows ADDWrr:
%1:gpr32 = COPY $w1
%0:gpr32 = COPY $w0
%2:gpr32 = ADDWrr %0, %1
$w0 = COPY %2
RET_ReallyLR implicit $w0
(llc -O2 -mtriple=aarch64-linux-gnu -stop-after=finalize-isel on the add function from the overview.)
Sources: llvm/lib/Target/AArch64/AArch64InstrInfo.td:2811, llvm/lib/Target/AArch64/AArch64InstrFormats.td:3096
Custom lowering (for calls, returns, globals) creates target-specific nodes. Each needs an SDNode record so patterns can match it:
def AArch64call : SDNode<"AArch64ISD::CALL",
...
def AArch64retglue : SDNode<"AArch64ISD::RET_GLUE", SDTNone,
The string is the C++ enum value; -gen-sd-node-info (AArch64GenSDNodeInfo.inc in AArch64's CMake file) generates the enum and the node names used in debug output.
Sources: llvm/lib/Target/AArch64/AArch64InstrInfo.td:820, llvm/lib/Target/AArch64/AArch64InstrInfo.td:895, llvm/lib/Target/AArch64/CMakeLists.txt:26
flowchart LR
N["SDNode"] --> S["ToyDAGToDAGISel::Select(N)"]
S -->|special cases| H["hand-written C++ (frame index, constants)"]
S -->|everything else| SC["SelectCode(N)<br/>(generated matcher table)"]
SC --> M["MachineSDNode"]
AArch64DAGToDAGISel derives from SelectionDAGISel, includes the generated matcher inside the class, and overrides Select. Select handles nodes that patterns cannot express and ends with a call to the generated SelectCode(Node). createAArch64ISelDag wraps it in a legacy pass for addInstSelector.
| Location | Line |
|---|---|
class AArch64DAGToDAGISel : public SelectionDAGISel |
49 |
#include "AArch64GenDAGISel.inc" (inside the class) |
460 |
void AArch64DAGToDAGISel::Select(SDNode *Node) |
5157 |
SelectCode(Node); at the end of Select
|
7820 |
createAArch64ISelDag |
7825 |
Sources: llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:49, llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:460, llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:5157, llvm/lib/Target/AArch64/AArch64ISelDAGToDAG.cpp:7820-7825
Selection alone is not enough: later generic passes ask TargetInstrInfo to create copies, spills and branches.
| Hook | Called by | AArch64 line | Needed for |
|---|---|---|---|
copyPhysReg |
Copy expansion after allocation | 6365 | Any function with a COPY that survives |
storeRegToStackSlot / loadRegFromStackSlot
|
Spiller, callee-saved spills | 6400 / 6580 | Any spill |
analyzeBranch, insertBranch, removeBranch
|
Branch folding, block placement | 523 / 839 / 772 | Correct -O2 with control flow |
expandPostRAPseudo |
postrapseudos pass |
2559 | Pseudos like RET_ReallyLR that expand late |
analyzeBranch may return true ("can't analyze") at first; passes then leave the branches alone. The regalloc wiki's TII hooks page shows the copy and spill hooks in detail.
Sources: llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:523, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:772, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:839, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:2559, llvm/lib/Target/AArch64/AArch64InstrInfo.cpp:6365-6580
Illustrative, not LLVM source.
// ToyInstrInfo.td
def SDT_ToyCall : SDTypeProfile<0, -1, [SDTCisVT<0, i32>]>;
def ToyCall : SDNode<"ToyISD::CALL", SDT_ToyCall,
[SDNPHasChain, SDNPOptInGlue, SDNPOutGlue, SDNPVariadic]>;
def ToyRet : SDNode<"ToyISD::RET", SDTNone,
[SDNPHasChain, SDNPOptInGlue, SDNPVariadic]>;
class ToyInst<dag outs, dag ins, string asm, list<dag> pat>
: Instruction {
let Namespace = "Toy";
let OutOperandList = outs;
let InOperandList = ins;
let AsmString = asm;
let Pattern = pat;
let Size = 4;
field bits<32> Inst;
}
def simm16 : Operand<i32>, ImmLeaf<i32, [{ return isInt<16>(Imm); }]>;
def ADD : ToyInst<(outs GPR:$rd), (ins GPR:$rs, GPR:$rt),
"add $rd, $rs, $rt", [(set GPR:$rd, (add GPR:$rs, GPR:$rt))]>;
def ADDI : ToyInst<(outs GPR:$rd), (ins GPR:$rs, simm16:$imm),
"addi $rd, $rs, $imm", [(set GPR:$rd, (add GPR:$rs, simm16:$imm))]>;
def LW : ToyInst<(outs GPR:$rd), (ins GPR:$base, simm16:$off),
"lw $rd, ${off}(${base})", []> { let mayLoad = 1; }
def SW : ToyInst<(outs), (ins GPR:$rs, GPR:$base, simm16:$off),
"sw $rs, ${off}(${base})", []> { let mayStore = 1; }
let isReturn = 1, isTerminator = 1, isBarrier = 1, Uses = [LR] in
def RET : ToyInst<(outs), (ins), "ret", [(ToyRet)]>;
let isCall = 1, Defs = [LR] in
def CALL : ToyInst<(outs), (ins i32imm:$target), "call $target", []>;
def : Pat<(ToyCall tglobaladdr:$dst), (CALL tglobaladdr:$dst)>;
// load/store patterns using a ComplexPattern for base+offset
def AddrFI : ComplexPattern<iPTR, 2, "SelectAddr", [frameindex], []>;
def : Pat<(load AddrFI:$addr), (LW AddrFI:$addr)>;
def : Pat<(store GPR:$v, AddrFI:$addr), (SW GPR:$v, AddrFI:$addr)>;
// ToyISelDAGToDAG.cpp (illustrative)
class ToyDAGToDAGISel : public SelectionDAGISel {
public:
explicit ToyDAGToDAGISel(ToyTargetMachine &TM, CodeGenOptLevel OL)
: SelectionDAGISel(TM, OL) {}
void Select(SDNode *N) override {
if (N->isMachineOpcode()) { N->setNodeId(-1); return; }
if (N->getOpcode() == ISD::FrameIndex) {
int FI = cast<FrameIndexSDNode>(N)->getIndex();
SDValue TFI = CurDAG->getTargetFrameIndex(FI, MVT::i32);
ReplaceNode(N, CurDAG->getMachineNode(Toy::ADDI, SDLoc(N), MVT::i32, TFI,
CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32)));
return;
}
SelectCode(N);
}
bool SelectAddr(SDValue Addr, SDValue &Base, SDValue &Off);
#include "ToyGenDAGISel.inc"
};Frame-index operands produced here are rewritten to real offsets by eliminateFrameIndex; see Frame Lowering.
- 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