Repository navigation
Calling Conventions 09 custom backend
Relevant source files
The following files were used as context for generating this wiki page:
The files to write, a complete LowerCall, and a checklist with tests. LowerFormalArguments and LowerReturn for Toy are on LowerFormalArguments and LowerReturn. Where this fits in a whole backend is on the bring-up wiki.
| File | Contents |
|---|---|
ToyCallingConv.td |
CC_Toy, RetCC_Toy, CSR_Toy
|
Toy.td |
include "ToyCallingConv.td" after the registers |
CMakeLists.txt |
tablegen(LLVM ToyGenCallingConv.inc -gen-callingconv) |
ToyISelLowering.cpp |
#include "ToyGenCallingConv.inc", the three hooks, CanLowerReturn
|
ToyInstrInfo.td |
ToyISD::CALL/RET nodes, CALL, RET, ADJCALLSTACKDOWN/UP pseudos |
ToyRegisterInfo.cpp |
getCalleeSavedRegs → CSR_Toy_SaveList, getCallPreservedMask → CSR_Toy_RegMask
|
ToyFrameLowering.cpp |
eliminateCallFramePseudoInstr |
def CC_Toy : CallingConv<[
CCIfByVal<CCPassByVal<4, 4>>,
CCIfType<[i1, i8, i16], CCPromoteToType<i32>>,
CCIfType<[i32], CCAssignToReg<[R0, R1, R2, R3]>>,
CCIfType<[i32], CCAssignToStack<4, 4>>
]>;
def RetCC_Toy : CallingConv<[
CCIfType<[i1, i8, i16], CCPromoteToType<i32>>,
CCIfType<[i32], CCAssignToReg<[R0, R1]>>
]>;
def CSR_Toy : CalleeSavedRegs<(add R8, R9, R10, R11, LR)>;
// Call-frame pseudos: become CALLSEQ_START / CALLSEQ_END
let Defs = [SP], Uses = [SP] in {
def ADJCALLSTACKDOWN : Pseudo<(outs), (ins i32imm:$amt1, i32imm:$amt2),
[(callseq_start timm:$amt1, timm:$amt2)]>;
def ADJCALLSTACKUP : Pseudo<(outs), (ins i32imm:$amt1, i32imm:$amt2),
[(callseq_end timm:$amt1, timm:$amt2)]>;
}
The call-frame pseudos must also be passed to the TargetInstrInfo constructor (ToyGenInstrInfo(STI, Toy::ADJCALLSTACKDOWN, Toy::ADJCALLSTACKUP)), so that generic code knows their opcodes.
SDValue ToyTargetLowering::LowerCall(CallLoweringInfo &CLI,
SmallVectorImpl<SDValue> &InVals) const {
SelectionDAG &DAG = CLI.DAG;
SDLoc DL = CLI.DL;
MachineFunction &MF = DAG.getMachineFunction();
CLI.IsTailCall = false; // no tail calls yet
SmallVector<CCValAssign, 16> ArgLocs;
CCState CCInfo(CLI.CallConv, CLI.IsVarArg, MF, ArgLocs, *DAG.getContext());
CCInfo.AnalyzeCallOperands(CLI.Outs, CC_Toy);
unsigned NumBytes = CCInfo.getStackSize();
SDValue Chain = DAG.getCALLSEQ_START(CLI.Chain, NumBytes, 0, DL);
SmallVector<std::pair<Register, SDValue>, 4> RegsToPass;
SmallVector<SDValue, 8> MemOps;
SDValue SP = DAG.getRegister(Toy::SP, MVT::i32);
for (unsigned i = 0; i != ArgLocs.size(); ++i) {
CCValAssign &VA = ArgLocs[i];
SDValue Arg = CLI.OutVals[i];
switch (VA.getLocInfo()) {
case CCValAssign::Full: break;
case CCValAssign::SExt: Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); break;
case CCValAssign::ZExt: Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); break;
case CCValAssign::AExt: Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); break;
default: llvm_unreachable("unexpected LocInfo");
}
if (VA.isRegLoc()) {
RegsToPass.push_back({VA.getLocReg(), Arg});
} else {
SDValue Addr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP,
DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
MemOps.push_back(DAG.getStore(Chain, DL, Arg, Addr, MachinePointerInfo()));
}
}
if (!MemOps.empty())
Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
SDValue Glue;
for (auto &[Reg, Val] : RegsToPass) {
Chain = DAG.getCopyToReg(Chain, DL, Reg, Val, Glue);
Glue = Chain.getValue(1);
}
SDValue Callee = CLI.Callee;
if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, MVT::i32);
else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee))
Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
SmallVector<SDValue, 8> Ops = {Chain, Callee};
for (auto &[Reg, Val] : RegsToPass)
Ops.push_back(DAG.getRegister(Reg, Val.getValueType()));
const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
Ops.push_back(DAG.getRegisterMask(TRI->getCallPreservedMask(MF, CLI.CallConv)));
if (Glue.getNode())
Ops.push_back(Glue);
Chain = DAG.getNode(ToyISD::CALL, DL, {MVT::Other, MVT::Glue}, Ops);
Glue = Chain.getValue(1);
Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, DL);
Glue = Chain.getValue(1);
SmallVector<CCValAssign, 4> RVLocs;
CCState RetInfo(CLI.CallConv, CLI.IsVarArg, MF, RVLocs, *DAG.getContext());
RetInfo.AnalyzeCallResult(CLI.Ins, RetCC_Toy);
for (CCValAssign &VA : RVLocs) {
SDValue V = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
Chain = V.getValue(1);
Glue = V.getValue(2);
if (VA.getLocVT() != VA.getValVT())
V = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), V);
InVals.push_back(V);
}
return Chain;
}This follows the same order as AArch64's version (see LowerCall): analyze, CALLSEQ_START, convert, store or queue, glued copies, call node with mask, CALLSEQ_END, results.
Sources: llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:10442-10492, llvm/lib/Target/AArch64/AArch64ISelLowering.cpp:11063-11129, llvm/include/llvm/CodeGen/CallingConvLower.h:284-304
-
CC_ToyandRetCC_Toycover every legal type (otherwiseunable to allocate function argument #N) -
CSR_Toymatches the ABI document;getCalleeSavedRegsandgetCallPreservedMaskreturn it -
LowerFormalArguments: oneInValsentry perInsentry, registers viaaddLiveIn, stack viaCreateFixedObject -
LowerReturn: glued copies, return registers as operands of the return node -
CanLowerReturnusesCheckReturn, so large returns are demoted tosret -
LowerCall: register mask on every call;CALLSEQ_START/ENDwith the right byte count -
ADJCALLSTACKDOWN/UPpseudos registered withTargetInstrInfo, removed byeliminateCallFramePseudoInstr - Extensions: arguments marked
signext/zeroextare extended by the caller (LocInfoSExt/ZExt) - Varargs and tail calls disabled until the basics pass
| Test | Expect |
|---|---|
i32 f(i32 a, i32 b) { return a + b; } |
a in r0, b in r1, result in r0
|
Six i32 arguments |
Fifth and sixth loaded from the incoming stack area |
| Call with six arguments | Two stores to [sp], [sp+4]; ADJCALLSTACKDOWN 8 in MIR |
i8 signext argument |
Caller sign-extends; callee sees AssertSext
|
| Value live across a call | Allocator uses r8–r11; prologue saves it |
i64 return on 32-bit Toy |
Split over r0/r1
|
i128 return |
Demoted to a hidden sret pointer |
Run each with llc -march=toy -verify-machineinstrs and compare with -stop-after=finalize-isel output, as in the AArch64 walkthroughs.
- 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