Writing an LLVM Backend

Introduction

This document describes techniques for writing compiler backends that convertthe LLVM Intermediate Representation (IR) to code for a specified machine orother languages. Code intended for a specific machine can take the form ofeither assembly code or binary code (usable for a JIT compiler).

The backend of LLVM features a target-independent code generator that maycreate output for several types of target CPUs — including X86, PowerPC,ARM, and SPARC. The backend may also be used to generate code targeted at SPUsof the Cell processor or GPUs to support the execution of compute kernels.

The document focuses on existing examples found in subdirectories ofllvm/lib/Target in a downloaded LLVM release. In particular, this documentfocuses on the example of creating a static compiler (one that emits textassembly) for a SPARC target, because SPARC has fairly standardcharacteristics, such as a RISC instruction set and straightforward callingconventions.

Audience

The audience for this document is anyone who needs to write an LLVM backend togenerate code for a specific hardware or software target.

Prerequisite Reading

These essential documents must be read before reading this document:

  • LLVM Language Reference Manual — a reference manual forthe LLVM assembly language.
  • The LLVM Target-Independent Code Generator — a guide to the components (classes and codegeneration algorithms) for translating the LLVM internal representation intomachine code for a specified target. Pay particular attention to thedescriptions of code generation stages: Instruction Selection, Scheduling andFormation, SSA-based Optimization, Register Allocation, Prolog/Epilog CodeInsertion, Late Machine Code Optimizations, and Code Emission.
  • TableGen — a document that describes the TableGen(tblgen) application that manages domain-specific information to supportLLVM code generation. TableGen processes input from a target descriptionfile (.td suffix) and generates C++ code that can be used for codegeneration.
  • Writing an LLVM Pass — The assembly printer is a FunctionPass, asare several SelectionDAG processing steps.

To follow the SPARC examples in this document, have a copy of The SPARCArchitecture Manual, Version 8 forreference. For details about the ARM instruction set, refer to the ARMArchitecture Reference Manual. For more aboutthe GNU Assembler format (GAS), see Using As, especially for theassembly printer. “Using As” contains a list of target machine dependentfeatures.

Basic Steps

To write a compiler backend for LLVM that converts the LLVM IR to code for aspecified target (machine or other language), follow these steps:

  • Create a subclass of the TargetMachine class that describescharacteristics of your target machine. Copy existing examples of specificTargetMachine class and header files; for example, start withSparcTargetMachine.cpp and SparcTargetMachine.h, but change the filenames for your target. Similarly, change code that references “Sparc” toreference your target.
  • Describe the register set of the target. Use TableGen to generate code forregister definition, register aliases, and register classes from atarget-specific RegisterInfo.td input file. You should also writeadditional code for a subclass of the TargetRegisterInfo class thatrepresents the class register file data used for register allocation and alsodescribes the interactions between registers.
  • Describe the instruction set of the target. Use TableGen to generate codefor target-specific instructions from target-specific versions ofTargetInstrFormats.td and TargetInstrInfo.td. You should writeadditional code for a subclass of the TargetInstrInfo class to representmachine instructions supported by the target machine.
  • Describe the selection and conversion of the LLVM IR from a Directed AcyclicGraph (DAG) representation of instructions to native target-specificinstructions. Use TableGen to generate code that matches patterns andselects instructions based on additional information in a target-specificversion of TargetInstrInfo.td. Write code for XXXISelDAGToDAG.cpp,where XXX identifies the specific target, to perform pattern matching andDAG-to-DAG instruction selection. Also write code in XXXISelLowering.cppto replace or remove operations and data types that are not supportednatively in a SelectionDAG.
  • Write code for an assembly printer that converts LLVM IR to a GAS format foryour target machine. You should add assembly strings to the instructionsdefined in your target-specific version of TargetInstrInfo.td. Youshould also write code for a subclass of AsmPrinter that performs theLLVM-to-assembly conversion and a trivial subclass of TargetAsmInfo.
  • Optionally, add support for subtargets (i.e., variants with differentcapabilities). You should also write code for a subclass of theTargetSubtarget class, which allows you to use the -mcpu= and-mattr= command-line options.
  • Optionally, add JIT support and create a machine code emitter (subclass ofTargetJITInfo) that is used to emit binary code directly into memory.

In the .cpp and .h. files, initially stub up these methods and thenimplement them later. Initially, you may not know which private members thatthe class will need and which components will need to be subclassed.

Preliminaries

To actually create your compiler backend, you need to create and modify a fewfiles. The absolute minimum is discussed here. But to actually use the LLVMtarget-independent code generator, you must perform the steps described in theLLVM Target-Independent Code Generator document.

First, you should create a subdirectory under lib/Target to hold all thefiles related to your target. If your target is called “Dummy”, create thedirectory lib/Target/Dummy.

In this new directory, create a CMakeLists.txt. It is easiest to copy aCMakeLists.txt of another target and modify it. It should at least containthe LLVM_TARGET_DEFINITIONS variable. The library can be named LLVMDummy(for example, see the MIPS target). Alternatively, you can split the libraryinto LLVMDummyCodeGen and LLVMDummyAsmPrinter, the latter of whichshould be implemented in a subdirectory below lib/Target/Dummy (for example,see the PowerPC target).

Note that these two naming schemes are hardcoded into llvm-config. Usingany other naming scheme will confuse llvm-config and produce a lot of(seemingly unrelated) linker errors when linking llc.

To make your target actually do something, you need to implement a subclass ofTargetMachine. This implementation should typically be in the filelib/Target/DummyTargetMachine.cpp, but any file in the lib/Targetdirectory will be built and should work. To use LLVM’s target independent codegenerator, you should do what all current machine backends do: create asubclass of LLVMTargetMachine. (To create a target from scratch, create asubclass of TargetMachine.)

To get LLVM to actually build and link your target, you need to run cmakewith -DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=Dummy. This will build yourtarget without needing to add it to the list of all the targets.

Once your target is stable, you can add it to the LLVM_ALL_TARGETS variablelocated in the main CMakeLists.txt.

Target Machine

LLVMTargetMachine is designed as a base class for targets implemented withthe LLVM target-independent code generator. The LLVMTargetMachine classshould be specialized by a concrete target class that implements the variousvirtual methods. LLVMTargetMachine is defined as a subclass ofTargetMachine in include/llvm/Target/TargetMachine.h. TheTargetMachine class implementation (TargetMachine.cpp) also processesnumerous command-line options.

To create a concrete target-specific subclass of LLVMTargetMachine, startby copying an existing TargetMachine class and header. You should name thefiles that you create to reflect your specific target. For instance, for theSPARC target, name the files SparcTargetMachine.h andSparcTargetMachine.cpp.

For a target machine XXX, the implementation of XXXTargetMachine musthave access methods to obtain objects that represent target components. Thesemethods are named get*Info, and are intended to obtain the instruction set(getInstrInfo), register set (getRegisterInfo), stack frame layout(getFrameInfo), and similar information. XXXTargetMachine must alsoimplement the getDataLayout method to access an object with target-specificdata characteristics, such as data type size and alignment requirements.

For instance, for the SPARC target, the header file SparcTargetMachine.hdeclares prototypes for several get*Info and getDataLayout methods thatsimply return a class member.

  1. namespace llvm {
  2.  
  3. class Module;
  4.  
  5. class SparcTargetMachine : public LLVMTargetMachine {
  6. const DataLayout DataLayout; // Calculates type size & alignment
  7. SparcSubtarget Subtarget;
  8. SparcInstrInfo InstrInfo;
  9. TargetFrameInfo FrameInfo;
  10.  
  11. protected:
  12. virtual const TargetAsmInfo *createTargetAsmInfo() const;
  13.  
  14. public:
  15. SparcTargetMachine(const Module &M, const std::string &FS);
  16.  
  17. virtual const SparcInstrInfo *getInstrInfo() const {return &InstrInfo; }
  18. virtual const TargetFrameInfo *getFrameInfo() const {return &FrameInfo; }
  19. virtual const TargetSubtarget *getSubtargetImpl() const{return &Subtarget; }
  20. virtual const TargetRegisterInfo *getRegisterInfo() const {
  21. return &InstrInfo.getRegisterInfo();
  22. }
  23. virtual const DataLayout *getDataLayout() const { return &DataLayout; }
  24. static unsigned getModuleMatchQuality(const Module &M);
  25.  
  26. // Pass Pipeline Configuration
  27. virtual bool addInstSelector(PassManagerBase &PM, bool Fast);
  28. virtual bool addPreEmitPass(PassManagerBase &PM, bool Fast);
  29. };
  30.  
  31. } // end namespace llvm
  • getInstrInfo()
  • getRegisterInfo()
  • getFrameInfo()
  • getDataLayout()
  • getSubtargetImpl()

For some targets, you also need to support the following methods:

  • getTargetLowering()
  • getJITInfo()

Some architectures, such as GPUs, do not support jumping to an arbitraryprogram location and implement branching using masked execution and loop usingspecial instructions around the loop body. In order to avoid CFG modificationsthat introduce irreducible control flow not handled by such hardware, a targetmust call setRequiresStructuredCFG(true) when being initialized.

In addition, the XXXTargetMachine constructor should specify aTargetDescription string that determines the data layout for the targetmachine, including characteristics such as pointer size, alignment, andendianness. For example, the constructor for SparcTargetMachine containsthe following:

  1. SparcTargetMachine::SparcTargetMachine(const Module &M, const std::string &FS)
  2. : DataLayout("E-p:32:32-f128:128:128"),
  3. Subtarget(M, FS), InstrInfo(Subtarget),
  4. FrameInfo(TargetFrameInfo::StackGrowsDown, 8, 0) {
  5. }

Hyphens separate portions of the TargetDescription string.

  • An upper-case “E” in the string indicates a big-endian target data model.A lower-case “e” indicates little-endian.
  • p:” is followed by pointer information: size, ABI alignment, andpreferred alignment. If only two figures follow “p:”, then the firstvalue is pointer size, and the second value is both ABI and preferredalignment.
  • Then a letter for numeric type alignment: “i”, “f”, “v”, or“a” (corresponding to integer, floating point, vector, or aggregate).“i”, “v”, or “a” are followed by ABI alignment and preferredalignment. “f” is followed by three values: the first indicates the sizeof a long double, then ABI alignment, and then ABI preferred alignment.

Target Registration

You must also register your target with the TargetRegistry, which is whatother LLVM tools use to be able to lookup and use your target at runtime. TheTargetRegistry can be used directly, but for most targets there are helpertemplates which should take care of the work for you.

All targets should declare a global Target object which is used torepresent the target during registration. Then, in the target’s TargetInfolibrary, the target should define that object and use the RegisterTargettemplate to register the target. For example, the Sparc registration codelooks like this:

  1. Target llvm::getTheSparcTarget();
  2.  
  3. extern "C" void LLVMInitializeSparcTargetInfo() {
  4. RegisterTarget<Triple::sparc, /*HasJIT=*/false>
  5. X(getTheSparcTarget(), "sparc", "Sparc");
  6. }

This allows the TargetRegistry to look up the target by name or by targettriple. In addition, most targets will also register additional features whichare available in separate libraries. These registration steps are separate,because some clients may wish to only link in some parts of the target — theJIT code generator does not require the use of the assembler printer, forexample. Here is an example of registering the Sparc assembly printer:

  1. extern "C" void LLVMInitializeSparcAsmPrinter() {
  2. RegisterAsmPrinter<SparcAsmPrinter> X(getTheSparcTarget());
  3. }

For more information, see “llvm/Target/TargetRegistry.h”.

Register Set and Register Classes

You should describe a concrete target-specific class that represents theregister file of a target machine. This class is called XXXRegisterInfo(where XXX identifies the target) and represents the class register filedata that is used for register allocation. It also describes the interactionsbetween registers.

You also need to define register classes to categorize related registers. Aregister class should be added for groups of registers that are all treated thesame way for some instruction. Typical examples are register classes forinteger, floating-point, or vector registers. A register allocator allows aninstruction to use any register in a specified register class to perform theinstruction in a similar manner. Register classes allocate virtual registersto instructions from these sets, and register classes let thetarget-independent register allocator automatically choose the actualregisters.

Much of the code for registers, including register definition, registeraliases, and register classes, is generated by TableGen fromXXXRegisterInfo.td input files and placed in XXXGenRegisterInfo.h.incand XXXGenRegisterInfo.inc output files. Some of the code in theimplementation of XXXRegisterInfo requires hand-coding.

Defining a Register

The XXXRegisterInfo.td file typically starts with register definitions fora target machine. The Register class (specified in Target.td) is usedto define an object for each register. The specified string n becomes theName of the register. The basic Register object does not have anysubregisters and does not specify any aliases.

  1. class Register<string n> {
  2. string Namespace = "";
  3. string AsmName = n;
  4. string Name = n;
  5. int SpillSize = 0;
  6. int SpillAlignment = 0;
  7. list<Register> Aliases = [];
  8. list<Register> SubRegs = [];
  9. list<int> DwarfNumbers = [];
  10. }

For example, in the X86RegisterInfo.td file, there are register definitionsthat utilize the Register class, such as:

  1. def AL : Register<"AL">, DwarfRegNum<[0, 0, 0]>;

This defines the register AL and assigns it values (with DwarfRegNum)that are used by gcc, gdb, or a debug information writer to identify aregister. For register AL, DwarfRegNum takes an array of 3 valuesrepresenting 3 different modes: the first element is for X86-64, the second forexception handling (EH) on X86-32, and the third is generic. -1 is a specialDwarf number that indicates the gcc number is undefined, and -2 indicates theregister number is invalid for this mode.

From the previously described line in the X86RegisterInfo.td file, TableGengenerates this code in the X86GenRegisterInfo.inc file:

  1. static const unsigned GR8[] = { X86::AL, ... };
  2.  
  3. const unsigned AL_AliasSet[] = { X86::AX, X86::EAX, X86::RAX, 0 };
  4.  
  5. const TargetRegisterDesc RegisterDescriptors[] = {
  6. ...
  7. { "AL", "AL", AL_AliasSet, Empty_SubRegsSet, Empty_SubRegsSet, AL_SuperRegsSet }, ...

From the register info file, TableGen generates a TargetRegisterDesc objectfor each register. TargetRegisterDesc is defined ininclude/llvm/Target/TargetRegisterInfo.h with the following fields:

  1. struct TargetRegisterDesc {
  2. const char *AsmName; // Assembly language name for the register
  3. const char *Name; // Printable name for the reg (for debugging)
  4. const unsigned *AliasSet; // Register Alias Set
  5. const unsigned *SubRegs; // Sub-register set
  6. const unsigned *ImmSubRegs; // Immediate sub-register set
  7. const unsigned *SuperRegs; // Super-register set
  8. };

TableGen uses the entire target description file (.td) to determine textnames for the register (in the AsmName and Name fields ofTargetRegisterDesc) and the relationships of other registers to the definedregister (in the other TargetRegisterDesc fields). In this example, otherdefinitions establish the registers “AX”, “EAX”, and “RAX” asaliases for one another, so TableGen generates a null-terminated array(AL_AliasSet) for this register alias set.

The Register class is commonly used as a base class for more complexclasses. In Target.td, the Register class is the base for theRegisterWithSubRegs class that is used to define registers that need tospecify subregisters in the SubRegs list, as shown here:

  1. class RegisterWithSubRegs<string n, list<Register> subregs> : Register<n> {
  2. let SubRegs = subregs;
  3. }

In SparcRegisterInfo.td, additional register classes are defined for SPARC:a Register subclass, SparcReg, and further subclasses: Ri, Rf,and Rd. SPARC registers are identified by 5-bit ID numbers, which is afeature common to these subclasses. Note the use of “let” expressions tooverride values that are initially defined in a superclass (such as SubRegsfield in the Rd class).

  1. class SparcReg<string n> : Register<n> {
  2. field bits<5> Num;
  3. let Namespace = "SP";
  4. }
  5. // Ri - 32-bit integer registers
  6. class Ri<bits<5> num, string n> :
  7. SparcReg<n> {
  8. let Num = num;
  9. }
  10. // Rf - 32-bit floating-point registers
  11. class Rf<bits<5> num, string n> :
  12. SparcReg<n> {
  13. let Num = num;
  14. }
  15. // Rd - Slots in the FP register file for 64-bit floating-point values.
  16. class Rd<bits<5> num, string n, list<Register> subregs> : SparcReg<n> {
  17. let Num = num;
  18. let SubRegs = subregs;
  19. }

In the SparcRegisterInfo.td file, there are register definitions thatutilize these subclasses of Register, such as:

  1. def G0 : Ri< 0, "G0">, DwarfRegNum<[0]>;
  2. def G1 : Ri< 1, "G1">, DwarfRegNum<[1]>;
  3. ...
  4. def F0 : Rf< 0, "F0">, DwarfRegNum<[32]>;
  5. def F1 : Rf< 1, "F1">, DwarfRegNum<[33]>;
  6. ...
  7. def D0 : Rd< 0, "F0", [F0, F1]>, DwarfRegNum<[32]>;
  8. def D1 : Rd< 2, "F2", [F2, F3]>, DwarfRegNum<[34]>;

The last two registers shown above (D0 and D1) are double-precisionfloating-point registers that are aliases for pairs of single-precisionfloating-point sub-registers. In addition to aliases, the sub-register andsuper-register relationships of the defined register are in fields of aregister’s TargetRegisterDesc.

Defining a Register Class

The RegisterClass class (specified in Target.td) is used to define anobject that represents a group of related registers and also defines thedefault allocation order of the registers. A target description fileXXXRegisterInfo.td that uses Target.td can construct register classesusing the following class:

  1. class RegisterClass<string namespace,
  2. list<ValueType> regTypes, int alignment, dag regList> {
  3. string Namespace = namespace;
  4. list<ValueType> RegTypes = regTypes;
  5. int Size = 0; // spill size, in bits; zero lets tblgen pick the size
  6. int Alignment = alignment;
  7.  
  8. // CopyCost is the cost of copying a value between two registers
  9. // default value 1 means a single instruction
  10. // A negative value means copying is extremely expensive or impossible
  11. int CopyCost = 1;
  12. dag MemberList = regList;
  13.  
  14. // for register classes that are subregisters of this class
  15. list<RegisterClass> SubRegClassList = [];
  16.  
  17. code MethodProtos = [{}]; // to insert arbitrary code
  18. code MethodBodies = [{}];
  19. }

To define a RegisterClass, use the following 4 arguments:

  • The first argument of the definition is the name of the namespace.
  • The second argument is a list of ValueType register type values that aredefined in include/llvm/CodeGen/ValueTypes.td. Defined values includeinteger types (such as i16, i32, and i1 for Boolean),floating-point types (f32, f64), and vector types (for example,v8i16 for an 8 x i16 vector). All registers in a RegisterClassmust have the same ValueType, but some registers may store vector data indifferent configurations. For example a register that can process a 128-bitvector may be able to handle 16 8-bit integer elements, 8 16-bit integers, 432-bit integers, and so on.
  • The third argument of the RegisterClass definition specifies thealignment required of the registers when they are stored or loaded tomemory.
  • The final argument, regList, specifies which registers are in this class.If an alternative allocation order method is not specified, then regListalso defines the order of allocation used by the register allocator. Besidessimply listing registers with (add R0, R1, …), more advanced setoperators are available. See include/llvm/Target/Target.td for moreinformation.

In SparcRegisterInfo.td, three RegisterClass objects are defined:FPRegs, DFPRegs, and IntRegs. For all three register classes, thefirst argument defines the namespace with the string “SP”. FPRegsdefines a group of 32 single-precision floating-point registers (F0 toF31); DFPRegs defines a group of 16 double-precision registers(D0-D15).

  1. // F0, F1, F2, ..., F31
  2. def FPRegs : RegisterClass<"SP", [f32], 32, (sequence "F%u", 0, 31)>;
  3.  
  4. def DFPRegs : RegisterClass<"SP", [f64], 64,
  5. (add D0, D1, D2, D3, D4, D5, D6, D7, D8,
  6. D9, D10, D11, D12, D13, D14, D15)>;
  7.  
  8. def IntRegs : RegisterClass<"SP", [i32], 32,
  9. (add L0, L1, L2, L3, L4, L5, L6, L7,
  10. I0, I1, I2, I3, I4, I5,
  11. O0, O1, O2, O3, O4, O5, O7,
  12. G1,
  13. // Non-allocatable regs:
  14. G2, G3, G4,
  15. O6, // stack ptr
  16. I6, // frame ptr
  17. I7, // return address
  18. G0, // constant zero
  19. G5, G6, G7 // reserved for kernel
  20. )>;

Using SparcRegisterInfo.td with TableGen generates several output filesthat are intended for inclusion in other source code that you write.SparcRegisterInfo.td generates SparcGenRegisterInfo.h.inc, which shouldbe included in the header file for the implementation of the SPARC registerimplementation that you write (SparcRegisterInfo.h). InSparcGenRegisterInfo.h.inc a new structure is defined calledSparcGenRegisterInfo that uses TargetRegisterInfo as its base. It alsospecifies types, based upon the defined register classes: DFPRegsClass,FPRegsClass, and IntRegsClass.

SparcRegisterInfo.td also generates SparcGenRegisterInfo.inc, which isincluded at the bottom of SparcRegisterInfo.cpp, the SPARC registerimplementation. The code below shows only the generated integer registers andassociated register classes. The order of registers in IntRegs reflectsthe order in the definition of IntRegs in the target description file.

  1. // IntRegs Register Class...
  2. static const unsigned IntRegs[] = {
  3. SP::L0, SP::L1, SP::L2, SP::L3, SP::L4, SP::L5,
  4. SP::L6, SP::L7, SP::I0, SP::I1, SP::I2, SP::I3,
  5. SP::I4, SP::I5, SP::O0, SP::O1, SP::O2, SP::O3,
  6. SP::O4, SP::O5, SP::O7, SP::G1, SP::G2, SP::G3,
  7. SP::G4, SP::O6, SP::I6, SP::I7, SP::G0, SP::G5,
  8. SP::G6, SP::G7,
  9. };
  10.  
  11. // IntRegsVTs Register Class Value Types...
  12. static const MVT::ValueType IntRegsVTs[] = {
  13. MVT::i32, MVT::Other
  14. };
  15.  
  16. namespace SP { // Register class instances
  17. DFPRegsClass DFPRegsRegClass;
  18. FPRegsClass FPRegsRegClass;
  19. IntRegsClass IntRegsRegClass;
  20. ...
  21. // IntRegs Sub-register Classes...
  22. static const TargetRegisterClass* const IntRegsSubRegClasses [] = {
  23. NULL
  24. };
  25. ...
  26. // IntRegs Super-register Classes..
  27. static const TargetRegisterClass* const IntRegsSuperRegClasses [] = {
  28. NULL
  29. };
  30. ...
  31. // IntRegs Register Class sub-classes...
  32. static const TargetRegisterClass* const IntRegsSubclasses [] = {
  33. NULL
  34. };
  35. ...
  36. // IntRegs Register Class super-classes...
  37. static const TargetRegisterClass* const IntRegsSuperclasses [] = {
  38. NULL
  39. };
  40.  
  41. IntRegsClass::IntRegsClass() : TargetRegisterClass(IntRegsRegClassID,
  42. IntRegsVTs, IntRegsSubclasses, IntRegsSuperclasses, IntRegsSubRegClasses,
  43. IntRegsSuperRegClasses, 4, 4, 1, IntRegs, IntRegs + 32) {}
  44. }

The register allocators will avoid using reserved registers, and callee savedregisters are not used until all the volatile registers have been used. Thatis usually good enough, but in some cases it may be necessary to provide customallocation orders.

Implement a subclass of TargetRegisterInfo

The final step is to hand code portions of XXXRegisterInfo, whichimplements the interface described in TargetRegisterInfo.h (seeThe TargetRegisterInfo class). These functions return 0, NULL, orfalse, unless overridden. Here is a list of functions that are overriddenfor the SPARC implementation in SparcRegisterInfo.cpp:

  • getCalleeSavedRegs — Returns a list of callee-saved registers in theorder of the desired callee-save stack frame offset.
  • getReservedRegs — Returns a bitset indexed by physical registernumbers, indicating if a particular register is unavailable.
  • hasFP — Return a Boolean indicating if a function should have adedicated frame pointer register.
  • eliminateCallFramePseudoInstr — If call frame setup or destroy pseudoinstructions are used, this can be called to eliminate them.
  • eliminateFrameIndex — Eliminate abstract frame indices frominstructions that may use them.
  • emitPrologue — Insert prologue code into the function.
  • emitEpilogue — Insert epilogue code into the function.

Instruction Set

During the early stages of code generation, the LLVM IR code is converted to aSelectionDAG with nodes that are instances of the SDNode classcontaining target instructions. An SDNode has an opcode, operands, typerequirements, and operation properties. For example, is an operationcommutative, does an operation load from memory. The various operation nodetypes are described in the include/llvm/CodeGen/SelectionDAGNodes.h file(values of the NodeType enum in the ISD namespace).

TableGen uses the following target description (.td) input files togenerate much of the code for instruction definition:

  • Target.td — Where the Instruction, Operand, InstrInfo, andother fundamental classes are defined.
  • TargetSelectionDAG.td — Used by SelectionDAG instruction selectiongenerators, contains SDTC* classes (selection DAG type constraint),definitions of SelectionDAG nodes (such as imm, cond, bb,add, fadd, sub), and pattern support (Pattern, Pat,PatFrag, PatLeaf, ComplexPattern.
  • XXXInstrFormats.td — Patterns for definitions of target-specificinstructions.
  • XXXInstrInfo.td — Target-specific definitions of instruction templates,condition codes, and instructions of an instruction set. For architecturemodifications, a different file name may be used. For example, for Pentiumwith SSE instruction, this file is X86InstrSSE.td, and for Pentium withMMX, this file is X86InstrMMX.td.

There is also a target-specific XXX.td file, where XXX is the name ofthe target. The XXX.td file includes the other .td input files, butits contents are only directly important for subtargets.

You should describe a concrete target-specific class XXXInstrInfo thatrepresents machine instructions supported by a target machine.XXXInstrInfo contains an array of XXXInstrDescriptor objects, each ofwhich describes one instruction. An instruction descriptor defines:

  • Opcode mnemonic
  • Number of operands
  • List of implicit register definitions and uses
  • Target-independent properties (such as memory access, is commutable)
  • Target-specific flags

The Instruction class (defined in Target.td) is mostly used as a base formore complex instruction classes.

  1. class Instruction {
  2. string Namespace = "";
  3. dag OutOperandList; // A dag containing the MI def operand list.
  4. dag InOperandList; // A dag containing the MI use operand list.
  5. string AsmString = ""; // The .s format to print the instruction with.
  6. list<dag> Pattern; // Set to the DAG pattern for this instruction.
  7. list<Register> Uses = [];
  8. list<Register> Defs = [];
  9. list<Predicate> Predicates = []; // predicates turned into isel match code
  10. ... remainder not shown for space ...
  11. }

A SelectionDAG node (SDNode) should contain an object representing atarget-specific instruction that is defined in XXXInstrInfo.td. Theinstruction objects should represent instructions from the architecture manualof the target machine (such as the SPARC Architecture Manual for the SPARCtarget).

A single instruction from the architecture manual is often modeled as multipletarget instructions, depending upon its operands. For example, a manual mightdescribe an add instruction that takes a register or an immediate operand. AnLLVM target could model this with two instructions named ADDri andADDrr.

You should define a class for each instruction category and define each opcodeas a subclass of the category with appropriate parameters such as the fixedbinary encoding of opcodes and extended opcodes. You should map the registerbits to the bits of the instruction in which they are encoded (for the JIT).Also you should specify how the instruction should be printed when theautomatic assembly printer is used.

As is described in the SPARC Architecture Manual, Version 8, there are threemajor 32-bit formats for instructions. Format 1 is only for the CALLinstruction. Format 2 is for branch on condition codes and SETHI (set highbits of a register) instructions. Format 3 is for other instructions.

Each of these formats has corresponding classes in SparcInstrFormat.td.InstSP is a base class for other instruction classes. Additional baseclasses are specified for more precise formats: for example inSparcInstrFormat.td, F2_1 is for SETHI, and F2_2 is forbranches. There are three other base classes: F3_1 for register/registeroperations, F3_2 for register/immediate operations, and F3_3 forfloating-point operations. SparcInstrInfo.td also adds the base classPseudo for synthetic SPARC instructions.

SparcInstrInfo.td largely consists of operand and instruction definitionsfor the SPARC target. In SparcInstrInfo.td, the following targetdescription file entry, LDrr, defines the Load Integer instruction for aWord (the LD SPARC opcode) from a memory address to a register. The firstparameter, the value 3 (112), is the operation value for thiscategory of operation. The second parameter (0000002) is thespecific operation value for LD/Load Word. The third parameter is theoutput destination, which is a register operand and defined in the Registertarget description file (IntRegs).

  1. def LDrr : F3_1 <3, 0b000000, (outs IntRegs:$dst), (ins MEMrr:$addr),
  2. "ld [$addr], $dst",
  3. [(set i32:$dst, (load ADDRrr:$addr))]>;

The fourth parameter is the input source, which uses the address operandMEMrr that is defined earlier in SparcInstrInfo.td:

  1. def MEMrr : Operand<i32> {
  2. let PrintMethod = "printMemOperand";
  3. let MIOperandInfo = (ops IntRegs, IntRegs);
  4. }

The fifth parameter is a string that is used by the assembly printer and can beleft as an empty string until the assembly printer interface is implemented.The sixth and final parameter is the pattern used to match the instructionduring the SelectionDAG Select Phase described in The LLVM Target-Independent Code Generator.This parameter is detailed in the next section, Instruction Selector.

Instruction class definitions are not overloaded for different operand types,so separate versions of instructions are needed for register, memory, orimmediate value operands. For example, to perform a Load Integer instructionfor a Word from an immediate operand to a register, the following instructionclass is defined:

  1. def LDri : F3_2 <3, 0b000000, (outs IntRegs:$dst), (ins MEMri:$addr),
  2. "ld [$addr], $dst",
  3. [(set i32:$dst, (load ADDRri:$addr))]>;

Writing these definitions for so many similar instructions can involve a lot ofcut and paste. In .td files, the multiclass directive enables thecreation of templates to define several instruction classes at once (using thedefm directive). For example in SparcInstrInfo.td, the multiclasspattern F3_12 is defined to create 2 instruction classes each timeF3_12 is invoked:

  1. multiclass F3_12 <string OpcStr, bits<6> Op3Val, SDNode OpNode> {
  2. def rr : F3_1 <2, Op3Val,
  3. (outs IntRegs:$dst), (ins IntRegs:$b, IntRegs:$c),
  4. !strconcat(OpcStr, " $b, $c, $dst"),
  5. [(set i32:$dst, (OpNode i32:$b, i32:$c))]>;
  6. def ri : F3_2 <2, Op3Val,
  7. (outs IntRegs:$dst), (ins IntRegs:$b, i32imm:$c),
  8. !strconcat(OpcStr, " $b, $c, $dst"),
  9. [(set i32:$dst, (OpNode i32:$b, simm13:$c))]>;
  10. }

So when the defm directive is used for the XOR and ADDinstructions, as seen below, it creates four instruction objects: XORrr,XORri, ADDrr, and ADDri.

  1. defm XOR : F3_12<"xor", 0b000011, xor>;
  2. defm ADD : F3_12<"add", 0b000000, add>;

SparcInstrInfo.td also includes definitions for condition codes that arereferenced by branch instructions. The following definitions inSparcInstrInfo.td indicate the bit location of the SPARC condition code.For example, the 10th bit represents the “greater than” condition forintegers, and the 22nd bit represents the “greater than” condition forfloats.

  1. def ICC_NE : ICC_VAL< 9>; // Not Equal
  2. def ICC_E : ICC_VAL< 1>; // Equal
  3. def ICC_G : ICC_VAL<10>; // Greater
  4. ...
  5. def FCC_U : FCC_VAL<23>; // Unordered
  6. def FCC_G : FCC_VAL<22>; // Greater
  7. def FCC_UG : FCC_VAL<21>; // Unordered or Greater
  8. ...

(Note that Sparc.h also defines enums that correspond to the same SPARCcondition codes. Care must be taken to ensure the values in Sparc.hcorrespond to the values in SparcInstrInfo.td. I.e., SPCC::ICC_NE = 9,SPCC::FCC_U = 23 and so on.)

Instruction Operand Mapping

The code generator backend maps instruction operands to fields in theinstruction. Operands are assigned to unbound fields in the instruction in theorder they are defined. Fields are bound when they are assigned a value. Forexample, the Sparc target defines the XNORrr instruction as a F3_1format instruction having three operands.

  1. def XNORrr : F3_1<2, 0b000111,
  2. (outs IntRegs:$dst), (ins IntRegs:$b, IntRegs:$c),
  3. "xnor $b, $c, $dst",
  4. [(set i32:$dst, (not (xor i32:$b, i32:$c)))]>;

The instruction templates in SparcInstrFormats.td show the base class forF3_1 is InstSP.

  1. class InstSP<dag outs, dag ins, string asmstr, list<dag> pattern> : Instruction {
  2. field bits<32> Inst;
  3. let Namespace = "SP";
  4. bits<2> op;
  5. let Inst{31-30} = op;
  6. dag OutOperandList = outs;
  7. dag InOperandList = ins;
  8. let AsmString = asmstr;
  9. let Pattern = pattern;
  10. }

InstSP leaves the op field unbound.

  1. class F3<dag outs, dag ins, string asmstr, list<dag> pattern>
  2. : InstSP<outs, ins, asmstr, pattern> {
  3. bits<5> rd;
  4. bits<6> op3;
  5. bits<5> rs1;
  6. let op{1} = 1; // Op = 2 or 3
  7. let Inst{29-25} = rd;
  8. let Inst{24-19} = op3;
  9. let Inst{18-14} = rs1;
  10. }

F3 binds the op field and defines the rd, op3, and rs1fields. F3 format instructions will bind the operands rd, op3, andrs1 fields.

  1. class F3_1<bits<2> opVal, bits<6> op3val, dag outs, dag ins,
  2. string asmstr, list<dag> pattern> : F3<outs, ins, asmstr, pattern> {
  3. bits<8> asi = 0; // asi not currently used
  4. bits<5> rs2;
  5. let op = opVal;
  6. let op3 = op3val;
  7. let Inst{13} = 0; // i field = 0
  8. let Inst{12-5} = asi; // address space identifier
  9. let Inst{4-0} = rs2;
  10. }

F3_1 binds the op3 field and defines the rs2 fields. F3_1format instructions will bind the operands to the rd, rs1, and rs2fields. This results in the XNORrr instruction binding $dst, $b,and $c operands to the rd, rs1, and rs2 fields respectively.

Instruction Operand Name Mapping

TableGen will also generate a function called getNamedOperandIdx() whichcan be used to look up an operand’s index in a MachineInstr based on itsTableGen name. Setting the UseNamedOperandTable bit in an instruction’sTableGen definition will add all of its operands to an enumeration in thellvm::XXX:OpName namespace and also add an entry for it into the OperandMaptable, which can be queried using getNamedOperandIdx()

  1. int DstIndex = SP::getNamedOperandIdx(SP::XNORrr, SP::OpName::dst); // => 0
  2. int BIndex = SP::getNamedOperandIdx(SP::XNORrr, SP::OpName::b); // => 1
  3. int CIndex = SP::getNamedOperandIdx(SP::XNORrr, SP::OpName::c); // => 2
  4. int DIndex = SP::getNamedOperandIdx(SP::XNORrr, SP::OpName::d); // => -1
  5.  
  6. ...

The entries in the OpName enum are taken verbatim from the TableGen definitions,so operands with lowercase names will have lower case entries in the enum.

To include the getNamedOperandIdx() function in your backend, you will needto define a few preprocessor macros in XXXInstrInfo.cpp and XXXInstrInfo.h.For example:

XXXInstrInfo.cpp:

  1. #define GET_INSTRINFO_NAMED_OPS // For getNamedOperandIdx() function
  2. #include "XXXGenInstrInfo.inc"

XXXInstrInfo.h:

  1. #define GET_INSTRINFO_OPERAND_ENUM // For OpName enum
  2. #include "XXXGenInstrInfo.inc"
  3.  
  4. namespace XXX {
  5. int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIndex);
  6. } // End namespace XXX

Instruction Operand Types

TableGen will also generate an enumeration consisting of all named Operandtypes defined in the backend, in the llvm::XXX::OpTypes namespace.Some common immediate Operand types (for instance i8, i32, i64, f32, f64)are defined for all targets in include/llvm/Target/Target.td, and areavailable in each Target’s OpTypes enum. Also, only named Operand types appearin the enumeration: anonymous types are ignored.For example, the X86 backend defines brtarget and brtarget8, bothinstances of the TableGen Operand class, which represent branch targetoperands:

  1. def brtarget : Operand<OtherVT>;
  2. def brtarget8 : Operand<OtherVT>;

This results in:

  1. namespace X86 {
  2. namespace OpTypes {
  3. enum OperandType {
  4. ...
  5. brtarget,
  6. brtarget8,
  7. ...
  8. i32imm,
  9. i64imm,
  10. ...
  11. OPERAND_TYPE_LIST_END
  12. } // End namespace OpTypes
  13. } // End namespace X86

In typical TableGen fashion, to use the enum, you will need to define apreprocessor macro:

  1. #define GET_INSTRINFO_OPERAND_TYPES_ENUM // For OpTypes enum
  2. #include "XXXGenInstrInfo.inc"

Instruction Scheduling

Instruction itineraries can be queried using MCDesc::getSchedClass(). Thevalue can be named by an enumeration in llvm::XXX::Sched namespace generatedby TableGen in XXXGenInstrInfo.inc. The name of the schedule classes arethe same as provided in XXXSchedule.td plus a default NoItinerary class.

The schedule models are generated by TableGen by the SubtargetEmitter,using the CodeGenSchedModels class. This is distinct from the itinerarymethod of specifying machine resource use. The tool utils/schedcover.pycan be used to determine which instructions have been covered by theschedule model description and which haven’t. The first step is to use theinstructions below to create an output file. Then run schedcover.py on theoutput file:

  1. $ <src>/utils/schedcover.py <build>/lib/Target/AArch64/tblGenSubtarget.with
  2. instruction, default, CortexA53Model, CortexA57Model, CycloneModel, ExynosM3Model, FalkorModel, KryoModel, ThunderX2T99Model, ThunderXT8XModel
  3. ABSv16i8, WriteV, , , CyWriteV3, M3WriteNMISC1, FalkorWr_2VXVY_2cyc, KryoWrite_2cyc_XY_XY_150ln, ,
  4. ABSv1i64, WriteV, , , CyWriteV3, M3WriteNMISC1, FalkorWr_1VXVY_2cyc, KryoWrite_2cyc_XY_noRSV_67ln, ,
  5. ...

To capture the debug output from generating a schedule model, change to theappropriate target directory and use the following command:command with the subtarget-emitter debug option:

  1. $ <build>/bin/llvm-tblgen -debug-only=subtarget-emitter -gen-subtarget \
  2. -I <src>/lib/Target/<target> -I <src>/include \
  3. -I <src>/lib/Target <src>/lib/Target/<target>/<target>.td \
  4. -o <build>/lib/Target/<target>/<target>GenSubtargetInfo.inc.tmp \
  5. > tblGenSubtarget.dbg 2>&1

Where <build> is the build directory, src is the source directory,and <target> is the name of the target.To double check that the above command is what is needed, one can capture theexact TableGen command from a build by using:

  1. $ VERBOSE=1 make ...

and search for llvm-tblgen commands in the output.

Instruction Relation Mapping

This TableGen feature is used to relate instructions with each other. It isparticularly useful when you have multiple instruction formats and need toswitch between them after instruction selection. This entire feature is drivenby relation models which can be defined in XXXInstrInfo.td filesaccording to the target-specific instruction set. Relation models are definedusing InstrMapping class as a base. TableGen parses all the modelsand generates instruction relation maps using the specified information.Relation maps are emitted as tables in the XXXGenInstrInfo.inc filealong with the functions to query them. For the detailed information on how touse this feature, please refer to How To Use Instruction Mappings.

Implement a subclass of TargetInstrInfo

The final step is to hand code portions of XXXInstrInfo, which implementsthe interface described in TargetInstrInfo.h (see The TargetInstrInfo class).These functions return 0 or a Boolean or they assert, unless overridden.Here’s a list of functions that are overridden for the SPARC implementation inSparcInstrInfo.cpp:

  • isLoadFromStackSlot — If the specified machine instruction is a directload from a stack slot, return the register number of the destination and theFrameIndex of the stack slot.
  • isStoreToStackSlot — If the specified machine instruction is a directstore to a stack slot, return the register number of the destination and theFrameIndex of the stack slot.
  • copyPhysReg — Copy values between a pair of physical registers.
  • storeRegToStackSlot — Store a register value to a stack slot.
  • loadRegFromStackSlot — Load a register value from a stack slot.
  • storeRegToAddr — Store a register value to memory.
  • loadRegFromAddr — Load a register value from memory.
  • foldMemoryOperand — Attempt to combine instructions of any load orstore instruction for the specified operand(s).

Branch Folding and If Conversion

Performance can be improved by combining instructions or by eliminatinginstructions that are never reached. The analyzeBranch method inXXXInstrInfo may be implemented to examine conditional instructions andremove unnecessary instructions. analyzeBranch looks at the end of amachine basic block (MBB) for opportunities for improvement, such as branchfolding and if conversion. The BranchFolder and IfConverter machinefunction passes (see the source files BranchFolding.cpp andIfConversion.cpp in the lib/CodeGen directory) call analyzeBranchto improve the control flow graph that represents the instructions.

Several implementations of analyzeBranch (for ARM, Alpha, and X86) can beexamined as models for your own analyzeBranch implementation. Since SPARCdoes not implement a useful analyzeBranch, the ARM target implementation isshown below.

analyzeBranch returns a Boolean value and takes four parameters:

  • MachineBasicBlock &MBB — The incoming block to be examined.
  • MachineBasicBlock *&TBB — A destination block that is returned. For aconditional branch that evaluates to true, TBB is the destination.
  • MachineBasicBlock *&FBB — For a conditional branch that evaluates tofalse, FBB is returned as the destination.
  • std::vector<MachineOperand> &Cond — List of operands to evaluate acondition for a conditional branch.

In the simplest case, if a block ends without a branch, then it falls throughto the successor block. No destination blocks are specified for either TBBor FBB, so both parameters return NULL. The start of theanalyzeBranch (see code below for the ARM target) shows the functionparameters and the code for the simplest case.

  1. bool ARMInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
  2. MachineBasicBlock *&TBB,
  3. MachineBasicBlock *&FBB,
  4. std::vector<MachineOperand> &Cond) const
  5. {
  6. MachineBasicBlock::iterator I = MBB.end();
  7. if (I == MBB.begin() || !isUnpredicatedTerminator(--I))
  8. return false;

If a block ends with a single unconditional branch instruction, thenanalyzeBranch (shown below) should return the destination of that branch inthe TBB parameter.

  1. if (LastOpc == ARM::B || LastOpc == ARM::tB) {
  2. TBB = LastInst->getOperand(0).getMBB();
  3. return false;
  4. }

If a block ends with two unconditional branches, then the second branch isnever reached. In that situation, as shown below, remove the last branchinstruction and return the penultimate branch in the TBB parameter.

  1. if ((SecondLastOpc == ARM::B || SecondLastOpc == ARM::tB) &&
  2. (LastOpc == ARM::B || LastOpc == ARM::tB)) {
  3. TBB = SecondLastInst->getOperand(0).getMBB();
  4. I = LastInst;
  5. I->eraseFromParent();
  6. return false;
  7. }

A block may end with a single conditional branch instruction that falls throughto successor block if the condition evaluates to false. In that case,analyzeBranch (shown below) should return the destination of thatconditional branch in the TBB parameter and a list of operands in theCond parameter to evaluate the condition.

  1. if (LastOpc == ARM::Bcc || LastOpc == ARM::tBcc) {
  2. // Block ends with fall-through condbranch.
  3. TBB = LastInst->getOperand(0).getMBB();
  4. Cond.push_back(LastInst->getOperand(1));
  5. Cond.push_back(LastInst->getOperand(2));
  6. return false;
  7. }

If a block ends with both a conditional branch and an ensuing unconditionalbranch, then analyzeBranch (shown below) should return the conditionalbranch destination (assuming it corresponds to a conditional evaluation of“true”) in the TBB parameter and the unconditional branch destinationin the FBB (corresponding to a conditional evaluation of “false”). Alist of operands to evaluate the condition should be returned in the Condparameter.

  1. unsigned SecondLastOpc = SecondLastInst->getOpcode();
  2.  
  3. if ((SecondLastOpc == ARM::Bcc && LastOpc == ARM::B) ||
  4. (SecondLastOpc == ARM::tBcc && LastOpc == ARM::tB)) {
  5. TBB = SecondLastInst->getOperand(0).getMBB();
  6. Cond.push_back(SecondLastInst->getOperand(1));
  7. Cond.push_back(SecondLastInst->getOperand(2));
  8. FBB = LastInst->getOperand(0).getMBB();
  9. return false;
  10. }

For the last two cases (ending with a single conditional branch or ending withone conditional and one unconditional branch), the operands returned in theCond parameter can be passed to methods of other instructions to create newbranches or perform other operations. An implementation of analyzeBranchrequires the helper methods removeBranch and insertBranch to managesubsequent operations.

analyzeBranch should return false indicating success in most circumstances.analyzeBranch should only return true when the method is stumped about whatto do, for example, if a block has three terminating branches.analyzeBranch may return true if it encounters a terminator it cannothandle, such as an indirect branch.

Instruction Selector

LLVM uses a SelectionDAG to represent LLVM IR instructions, and nodes ofthe SelectionDAG ideally represent native target instructions. During codegeneration, instruction selection passes are performed to convert non-nativeDAG instructions into native target-specific instructions. The pass describedin XXXISelDAGToDAG.cpp is used to match patterns and perform DAG-to-DAGinstruction selection. Optionally, a pass may be defined (inXXXBranchSelector.cpp) to perform similar DAG-to-DAG operations for branchinstructions. Later, the code in XXXISelLowering.cpp replaces or removesoperations and data types not supported natively (legalizes) in aSelectionDAG.

TableGen generates code for instruction selection using the following targetdescription input files:

  • XXXInstrInfo.td — Contains definitions of instructions in atarget-specific instruction set, generates XXXGenDAGISel.inc, which isincluded in XXXISelDAGToDAG.cpp.
  • XXXCallingConv.td — Contains the calling and return value conventionsfor the target architecture, and it generates XXXGenCallingConv.inc,which is included in XXXISelLowering.cpp.

The implementation of an instruction selection pass must include a header thatdeclares the FunctionPass class or a subclass of FunctionPass. InXXXTargetMachine.cpp, a Pass Manager (PM) should add each instructionselection pass into the queue of passes to run.

The LLVM static compiler (llc) is an excellent tool for visualizing thecontents of DAGs. To display the SelectionDAG before or after specificprocessing phases, use the command line options for llc, described atSelectionDAG Instruction Selection Process.

To describe instruction selector behavior, you should add patterns for loweringLLVM code into a SelectionDAG as the last parameter of the instructiondefinitions in XXXInstrInfo.td. For example, in SparcInstrInfo.td,this entry defines a register store operation, and the last parameter describesa pattern with the store DAG operator.

  1. def STrr : F3_1< 3, 0b000100, (outs), (ins MEMrr:$addr, IntRegs:$src),
  2. "st $src, [$addr]", [(store i32:$src, ADDRrr:$addr)]>;

ADDRrr is a memory mode that is also defined in SparcInstrInfo.td:

  1. def ADDRrr : ComplexPattern<i32, 2, "SelectADDRrr", [], []>;

The definition of ADDRrr refers to SelectADDRrr, which is a functiondefined in an implementation of the Instructor Selector (such asSparcISelDAGToDAG.cpp).

In lib/Target/TargetSelectionDAG.td, the DAG operator for store is definedbelow:

  1. def store : PatFrag<(ops node:$val, node:$ptr),
  2. (st node:$val, node:$ptr), [{
  3. if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N))
  4. return !ST->isTruncatingStore() &&
  5. ST->getAddressingMode() == ISD::UNINDEXED;
  6. return false;
  7. }]>;

XXXInstrInfo.td also generates (in XXXGenDAGISel.inc) theSelectCode method that is used to call the appropriate processing methodfor an instruction. In this example, SelectCode calls Select_ISD_STOREfor the ISD::STORE opcode.

  1. SDNode *SelectCode(SDValue N) {
  2. ...
  3. MVT::ValueType NVT = N.getNode()->getValueType(0);
  4. switch (N.getOpcode()) {
  5. case ISD::STORE: {
  6. switch (NVT) {
  7. default:
  8. return Select_ISD_STORE(N);
  9. break;
  10. }
  11. break;
  12. }
  13. ...

The pattern for STrr is matched, so elsewhere in XXXGenDAGISel.inc,code for STrr is created for Select_ISD_STORE. The Emit_22 methodis also generated in XXXGenDAGISel.inc to complete the processing of thisinstruction.

  1. SDNode *Select_ISD_STORE(const SDValue &N) {
  2. SDValue Chain = N.getOperand(0);
  3. if (Predicate_store(N.getNode())) {
  4. SDValue N1 = N.getOperand(1);
  5. SDValue N2 = N.getOperand(2);
  6. SDValue CPTmp0;
  7. SDValue CPTmp1;
  8.  
  9. // Pattern: (st:void i32:i32:$src,
  10. // ADDRrr:i32:$addr)<<P:Predicate_store>>
  11. // Emits: (STrr:void ADDRrr:i32:$addr, IntRegs:i32:$src)
  12. // Pattern complexity = 13 cost = 1 size = 0
  13. if (SelectADDRrr(N, N2, CPTmp0, CPTmp1) &&
  14. N1.getNode()->getValueType(0) == MVT::i32 &&
  15. N2.getNode()->getValueType(0) == MVT::i32) {
  16. return Emit_22(N, SP::STrr, CPTmp0, CPTmp1);
  17. }
  18. ...

The SelectionDAG Legalize Phase

The Legalize phase converts a DAG to use types and operations that are nativelysupported by the target. For natively unsupported types and operations, youneed to add code to the target-specific XXXTargetLowering implementation toconvert unsupported types and operations to supported ones.

In the constructor for the XXXTargetLowering class, first use theaddRegisterClass method to specify which types are supported and whichregister classes are associated with them. The code for the register classesare generated by TableGen from XXXRegisterInfo.td and placed inXXXGenRegisterInfo.h.inc. For example, the implementation of theconstructor for the SparcTargetLowering class (in SparcISelLowering.cpp)starts with the following code:

  1. addRegisterClass(MVT::i32, SP::IntRegsRegisterClass);
  2. addRegisterClass(MVT::f32, SP::FPRegsRegisterClass);
  3. addRegisterClass(MVT::f64, SP::DFPRegsRegisterClass);

You should examine the node types in the ISD namespace(include/llvm/CodeGen/SelectionDAGNodes.h) and determine which operationsthe target natively supports. For operations that do not have nativesupport, add a callback to the constructor for the XXXTargetLowering class,so the instruction selection process knows what to do. The TargetLoweringclass callback methods (declared in llvm/Target/TargetLowering.h) are:

  • setOperationAction — General operation.
  • setLoadExtAction — Load with extension.
  • setTruncStoreAction — Truncating store.
  • setIndexedLoadAction — Indexed load.
  • setIndexedStoreAction — Indexed store.
  • setConvertAction — Type conversion.
  • setCondCodeAction — Support for a given condition code.

Note: on older releases, setLoadXAction is used instead ofsetLoadExtAction. Also, on older releases, setCondCodeAction may notbe supported. Examine your release to see what methods are specificallysupported.

These callbacks are used to determine that an operation does or does not workwith a specified type (or types). And in all cases, the third parameter is aLegalAction type enum value: Promote, Expand, Custom, orLegal. SparcISelLowering.cpp contains examples of all fourLegalAction values.

Promote

For an operation without native support for a given type, the specified typemay be promoted to a larger type that is supported. For example, SPARC doesnot support a sign-extending load for Boolean values (i1 type), so inSparcISelLowering.cpp the third parameter below, Promote, changesi1 type values to a large type before loading.

  1. setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);

Expand

For a type without native support, a value may need to be broken down further,rather than promoted. For an operation without native support, a combinationof other operations may be used to similar effect. In SPARC, thefloating-point sine and cosine trig operations are supported by expansion toother operations, as indicated by the third parameter, Expand, tosetOperationAction:

  1. setOperationAction(ISD::FSIN, MVT::f32, Expand);
  2. setOperationAction(ISD::FCOS, MVT::f32, Expand);

Custom

For some operations, simple type promotion or operation expansion may beinsufficient. In some cases, a special intrinsic function must be implemented.

For example, a constant value may require special treatment, or an operationmay require spilling and restoring registers in the stack and working withregister allocators.

As seen in SparcISelLowering.cpp code below, to perform a type conversionfrom a floating point value to a signed integer, first thesetOperationAction should be called with Custom as the third parameter:

  1. setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);

In the LowerOperation method, for each Custom operation, a casestatement should be added to indicate what function to call. In the followingcode, an FP_TO_SINT opcode will call the LowerFP_TO_SINT method:

  1. SDValue SparcTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
  2. switch (Op.getOpcode()) {
  3. case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
  4. ...
  5. }
  6. }

Finally, the LowerFP_TO_SINT method is implemented, using an FP register toconvert the floating-point value to an integer.

  1. static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
  2. assert(Op.getValueType() == MVT::i32);
  3. Op = DAG.getNode(SPISD::FTOI, MVT::f32, Op.getOperand(0));
  4. return DAG.getNode(ISD::BITCAST, MVT::i32, Op);
  5. }

Legal

The Legal LegalizeAction enum value simply indicates that an operationis natively supported. Legal represents the default condition, so itis rarely used. In SparcISelLowering.cpp, the action for CTPOP (anoperation to count the bits set in an integer) is natively supported only forSPARC v9. The following code enables the Expand conversion technique fornon-v9 SPARC implementations.

  1. setOperationAction(ISD::CTPOP, MVT::i32, Expand);
  2. ...
  3. if (TM.getSubtarget<SparcSubtarget>().isV9())
  4. setOperationAction(ISD::CTPOP, MVT::i32, Legal);

Calling Conventions

To support target-specific calling conventions, XXXGenCallingConv.td usesinterfaces (such as CCIfType and CCAssignToReg) that are defined inlib/Target/TargetCallingConv.td. TableGen can take the target descriptorfile XXXGenCallingConv.td and generate the header fileXXXGenCallingConv.inc, which is typically included inXXXISelLowering.cpp. You can use the interfaces inTargetCallingConv.td to specify:

  • The order of parameter allocation.
  • Where parameters and return values are placed (that is, on the stack or inregisters).
  • Which registers may be used.
  • Whether the caller or callee unwinds the stack.

The following example demonstrates the use of the CCIfType andCCAssignToReg interfaces. If the CCIfType predicate is true (that is,if the current argument is of type f32 or f64), then the action isperformed. In this case, the CCAssignToReg action assigns the argumentvalue to the first available register: either R0 or R1.

  1. CCIfType<[f32,f64], CCAssignToReg<[R0, R1]>>

SparcCallingConv.td contains definitions for a target-specific return-valuecalling convention (RetCC_Sparc32) and a basic 32-bit C calling convention(CC_Sparc32). The definition of RetCC_Sparc32 (shown below) indicateswhich registers are used for specified scalar return types. A single-precisionfloat is returned to register F0, and a double-precision float goes toregister D0. A 32-bit integer is returned in register I0 or I1.

  1. def RetCC_Sparc32 : CallingConv<[
  2. CCIfType<[i32], CCAssignToReg<[I0, I1]>>,
  3. CCIfType<[f32], CCAssignToReg<[F0]>>,
  4. CCIfType<[f64], CCAssignToReg<[D0]>>
  5. ]>;

The definition of CC_Sparc32 in SparcCallingConv.td introducesCCAssignToStack, which assigns the value to a stack slot with the specifiedsize and alignment. In the example below, the first parameter, 4, indicatesthe size of the slot, and the second parameter, also 4, indicates the stackalignment along 4-byte units. (Special cases: if size is zero, then the ABIsize is used; if alignment is zero, then the ABI alignment is used.)

  1. def CC_Sparc32 : CallingConv<[
  2. // All arguments get passed in integer registers if there is space.
  3. CCIfType<[i32, f32, f64], CCAssignToReg<[I0, I1, I2, I3, I4, I5]>>,
  4. CCAssignToStack<4, 4>
  5. ]>;

CCDelegateTo is another commonly used interface, which tries to find aspecified sub-calling convention, and, if a match is found, it is invoked. Inthe following example (in X86CallingConv.td), the definition ofRetCC_X86_32_C ends with CCDelegateTo. After the current value isassigned to the register ST0 or ST1, the RetCC_X86Common isinvoked.

  1. def RetCC_X86_32_C : CallingConv<[
  2. CCIfType<[f32], CCAssignToReg<[ST0, ST1]>>,
  3. CCIfType<[f64], CCAssignToReg<[ST0, ST1]>>,
  4. CCDelegateTo<RetCC_X86Common>
  5. ]>;

CCIfCC is an interface that attempts to match the given name to the currentcalling convention. If the name identifies the current calling convention,then a specified action is invoked. In the following example (inX86CallingConv.td), if the Fast calling convention is in use, thenRetCC_X86_32_Fast is invoked. If the SSECall calling convention is inuse, then RetCC_X86_32_SSE is invoked.

  1. def RetCC_X86_32 : CallingConv<[
  2. CCIfCC<"CallingConv::Fast", CCDelegateTo<RetCC_X86_32_Fast>>,
  3. CCIfCC<"CallingConv::X86_SSECall", CCDelegateTo<RetCC_X86_32_SSE>>,
  4. CCDelegateTo<RetCC_X86_32_C>
  5. ]>;

Other calling convention interfaces include:

  • CCIf <predicate, action> — If the predicate matches, apply the action.
  • CCIfInReg <action> — If the argument is marked with the “inreg”attribute, then apply the action.
  • CCIfNest <action> — If the argument is marked with the “nest”attribute, then apply the action.
  • CCIfNotVarArg <action> — If the current function does not take avariable number of arguments, apply the action.
  • CCAssignToRegWithShadow <registerList, shadowList> — similar toCCAssignToReg, but with a shadow list of registers.
  • CCPassByVal <size, align> — Assign value to a stack slot with theminimum specified size and alignment.
  • CCPromoteToType <type> — Promote the current value to the specifiedtype.
  • CallingConv <[actions]> — Define each calling convention that issupported.

Assembly Printer

During the code emission stage, the code generator may utilize an LLVM pass toproduce assembly output. To do this, you want to implement the code for aprinter that converts LLVM IR to a GAS-format assembly language for your targetmachine, using the following steps:

  • Define all the assembly strings for your target, adding them to theinstructions defined in the XXXInstrInfo.td file. (SeeInstruction Set.) TableGen will produce an output file(XXXGenAsmWriter.inc) with an implementation of the printInstructionmethod for the XXXAsmPrinter class.
  • Write XXXTargetAsmInfo.h, which contains the bare-bones declaration ofthe XXXTargetAsmInfo class (a subclass of TargetAsmInfo).
  • Write XXXTargetAsmInfo.cpp, which contains target-specific values forTargetAsmInfo properties and sometimes new implementations for methods.
  • Write XXXAsmPrinter.cpp, which implements the AsmPrinter class thatperforms the LLVM-to-assembly conversion.

The code in XXXTargetAsmInfo.h is usually a trivial declaration of theXXXTargetAsmInfo class for use in XXXTargetAsmInfo.cpp. Similarly,XXXTargetAsmInfo.cpp usually has a few declarations of XXXTargetAsmInforeplacement values that override the default values in TargetAsmInfo.cpp.For example in SparcTargetAsmInfo.cpp:

  1. SparcTargetAsmInfo::SparcTargetAsmInfo(const SparcTargetMachine &TM) {
  2. Data16bitsDirective = "\t.half\t";
  3. Data32bitsDirective = "\t.word\t";
  4. Data64bitsDirective = 0; // .xword is only supported by V9.
  5. ZeroDirective = "\t.skip\t";
  6. CommentString = "!";
  7. ConstantPoolSection = "\t.section \".rodata\",#alloc\n";
  8. }

The X86 assembly printer implementation (X86TargetAsmInfo) is an examplewhere the target specific TargetAsmInfo class uses an overridden methods:ExpandInlineAsm.

A target-specific implementation of AsmPrinter is written inXXXAsmPrinter.cpp, which implements the AsmPrinter class that convertsthe LLVM to printable assembly. The implementation must include the followingheaders that have declarations for the AsmPrinter andMachineFunctionPass classes. The MachineFunctionPass is a subclass ofFunctionPass.

  1. #include "llvm/CodeGen/AsmPrinter.h"
  2. #include "llvm/CodeGen/MachineFunctionPass.h"

As a FunctionPass, AsmPrinter first calls doInitialization to setup the AsmPrinter. In SparcAsmPrinter, a Mangler object isinstantiated to process variable names.

In XXXAsmPrinter.cpp, the runOnMachineFunction method (declared inMachineFunctionPass) must be implemented for XXXAsmPrinter. InMachineFunctionPass, the runOnFunction method invokesrunOnMachineFunction. Target-specific implementations ofrunOnMachineFunction differ, but generally do the following to process eachmachine function:

  • Call SetupMachineFunction to perform initialization.
  • Call EmitConstantPool to print out (to the output stream) constants whichhave been spilled to memory.
  • Call EmitJumpTableInfo to print out jump tables used by the currentfunction.
  • Print out the label for the current function.
  • Print out the code for the function, including basic block labels and theassembly for the instruction (using printInstruction)

The XXXAsmPrinter implementation must also include the code generated byTableGen that is output in the XXXGenAsmWriter.inc file. The code inXXXGenAsmWriter.inc contains an implementation of the printInstructionmethod that may call these methods:

  • printOperand
  • printMemOperand
  • printCCOperand (for conditional statements)
  • printDataDirective
  • printDeclare
  • printImplicitDef
  • printInlineAsm

The implementations of printDeclare, printImplicitDef,printInlineAsm, and printLabel in AsmPrinter.cpp are generallyadequate for printing assembly and do not need to be overridden.

The printOperand method is implemented with a long switch/casestatement for the type of operand: register, immediate, basic block, externalsymbol, global address, constant pool index, or jump table index. For aninstruction with a memory address operand, the printMemOperand methodshould be implemented to generate the proper output. Similarly,printCCOperand should be used to print a conditional operand.

doFinalization should be overridden in XXXAsmPrinter, and it should becalled to shut down the assembly printer. During doFinalization, globalvariables and constants are printed to output.

Subtarget Support

Subtarget support is used to inform the code generation process of instructionset variations for a given chip set. For example, the LLVM SPARCimplementation provided covers three major versions of the SPARC microprocessorarchitecture: Version 8 (V8, which is a 32-bit architecture), Version 9 (V9, a64-bit architecture), and the UltraSPARC architecture. V8 has 16double-precision floating-point registers that are also usable as either 32single-precision or 8 quad-precision registers. V8 is also purely big-endian.V9 has 32 double-precision floating-point registers that are also usable as 16quad-precision registers, but cannot be used as single-precision registers.The UltraSPARC architecture combines V9 with UltraSPARC Visual Instruction Setextensions.

If subtarget support is needed, you should implement a target-specificXXXSubtarget class for your architecture. This class should process thecommand-line options -mcpu= and -mattr=.

TableGen uses definitions in the Target.td and Sparc.td files togenerate code in SparcGenSubtarget.inc. In Target.td, shown below, theSubtargetFeature interface is defined. The first 4 string parameters ofthe SubtargetFeature interface are a feature name, an attribute set by thefeature, the value of the attribute, and a description of the feature. (Thefifth parameter is a list of features whose presence is implied, and itsdefault value is an empty array.)

  1. class SubtargetFeature<string n, string a, string v, string d,
  2. list<SubtargetFeature> i = []> {
  3. string Name = n;
  4. string Attribute = a;
  5. string Value = v;
  6. string Desc = d;
  7. list<SubtargetFeature> Implies = i;
  8. }

In the Sparc.td file, the SubtargetFeature is used to define thefollowing features.

  1. def FeatureV9 : SubtargetFeature<"v9", "IsV9", "true",
  2. "Enable SPARC-V9 instructions">;
  3. def FeatureV8Deprecated : SubtargetFeature<"deprecated-v8",
  4. "V8DeprecatedInsts", "true",
  5. "Enable deprecated V8 instructions in V9 mode">;
  6. def FeatureVIS : SubtargetFeature<"vis", "IsVIS", "true",
  7. "Enable UltraSPARC Visual Instruction Set extensions">;

Elsewhere in Sparc.td, the Proc class is defined and then is used todefine particular SPARC processor subtypes that may have the previouslydescribed features.

  1. class Proc<string Name, list<SubtargetFeature> Features>
  2. : Processor<Name, NoItineraries, Features>;
  3.  
  4. def : Proc<"generic", []>;
  5. def : Proc<"v8", []>;
  6. def : Proc<"supersparc", []>;
  7. def : Proc<"sparclite", []>;
  8. def : Proc<"f934", []>;
  9. def : Proc<"hypersparc", []>;
  10. def : Proc<"sparclite86x", []>;
  11. def : Proc<"sparclet", []>;
  12. def : Proc<"tsc701", []>;
  13. def : Proc<"v9", [FeatureV9]>;
  14. def : Proc<"ultrasparc", [FeatureV9, FeatureV8Deprecated]>;
  15. def : Proc<"ultrasparc3", [FeatureV9, FeatureV8Deprecated]>;
  16. def : Proc<"ultrasparc3-vis", [FeatureV9, FeatureV8Deprecated, FeatureVIS]>;

From Target.td and Sparc.td files, the resultingSparcGenSubtarget.inc specifies enum values to identify the features,arrays of constants to represent the CPU features and CPU subtypes, and theParseSubtargetFeatures method that parses the features string that setsspecified subtarget options. The generated SparcGenSubtarget.inc fileshould be included in the SparcSubtarget.cpp. The target-specificimplementation of the XXXSubtarget method should follow this pseudocode:

  1. XXXSubtarget::XXXSubtarget(const Module &M, const std::string &FS) {
  2. // Set the default features
  3. // Determine default and user specified characteristics of the CPU
  4. // Call ParseSubtargetFeatures(FS, CPU) to parse the features string
  5. // Perform any additional operations
  6. }

JIT Support

The implementation of a target machine optionally includes a Just-In-Time (JIT)code generator that emits machine code and auxiliary structures as binaryoutput that can be written directly to memory. To do this, implement JIT codegeneration by performing the following steps:

  • Write an XXXCodeEmitter.cpp file that contains a machine function passthat transforms target-machine instructions into relocatable machinecode.
  • Write an XXXJITInfo.cpp file that implements the JIT interfaces fortarget-specific code-generation activities, such as emitting machine code andstubs.
  • Modify XXXTargetMachine so that it provides a TargetJITInfo objectthrough its getJITInfo method.

There are several different approaches to writing the JIT support code. Forinstance, TableGen and target descriptor files may be used for creating a JITcode generator, but are not mandatory. For the Alpha and PowerPC targetmachines, TableGen is used to generate XXXGenCodeEmitter.inc, whichcontains the binary coding of machine instructions and thegetBinaryCodeForInstr method to access those codes. Other JITimplementations do not.

Both XXXJITInfo.cpp and XXXCodeEmitter.cpp must include thellvm/CodeGen/MachineCodeEmitter.h header file that defines theMachineCodeEmitter class containing code for several callback functionsthat write data (in bytes, words, strings, etc.) to the output stream.

Machine Code Emitter

In XXXCodeEmitter.cpp, a target-specific of the Emitter class isimplemented as a function pass (subclass of MachineFunctionPass). Thetarget-specific implementation of runOnMachineFunction (invoked byrunOnFunction in MachineFunctionPass) iterates through theMachineBasicBlock calls emitInstruction to process each instruction andemit binary code. emitInstruction is largely implemented with casestatements on the instruction types defined in XXXInstrInfo.h. Forexample, in X86CodeEmitter.cpp, the emitInstruction method is builtaround the following switch/case statements:

  1. switch (Desc->TSFlags & X86::FormMask) {
  2. case X86II::Pseudo: // for not yet implemented instructions
  3. ... // or pseudo-instructions
  4. break;
  5. case X86II::RawFrm: // for instructions with a fixed opcode value
  6. ...
  7. break;
  8. case X86II::AddRegFrm: // for instructions that have one register operand
  9. ... // added to their opcode
  10. break;
  11. case X86II::MRMDestReg:// for instructions that use the Mod/RM byte
  12. ... // to specify a destination (register)
  13. break;
  14. case X86II::MRMDestMem:// for instructions that use the Mod/RM byte
  15. ... // to specify a destination (memory)
  16. break;
  17. case X86II::MRMSrcReg: // for instructions that use the Mod/RM byte
  18. ... // to specify a source (register)
  19. break;
  20. case X86II::MRMSrcMem: // for instructions that use the Mod/RM byte
  21. ... // to specify a source (memory)
  22. break;
  23. case X86II::MRM0r: case X86II::MRM1r: // for instructions that operate on
  24. case X86II::MRM2r: case X86II::MRM3r: // a REGISTER r/m operand and
  25. case X86II::MRM4r: case X86II::MRM5r: // use the Mod/RM byte and a field
  26. case X86II::MRM6r: case X86II::MRM7r: // to hold extended opcode data
  27. ...
  28. break;
  29. case X86II::MRM0m: case X86II::MRM1m: // for instructions that operate on
  30. case X86II::MRM2m: case X86II::MRM3m: // a MEMORY r/m operand and
  31. case X86II::MRM4m: case X86II::MRM5m: // use the Mod/RM byte and a field
  32. case X86II::MRM6m: case X86II::MRM7m: // to hold extended opcode data
  33. ...
  34. break;
  35. case X86II::MRMInitReg: // for instructions whose source and
  36. ... // destination are the same register
  37. break;
  38. }

The implementations of these case statements often first emit the opcode andthen get the operand(s). Then depending upon the operand, helper methods maybe called to process the operand(s). For example, in X86CodeEmitter.cpp,for the X86II::AddRegFrm case, the first data emitted (by emitByte) isthe opcode added to the register operand. Then an object representing themachine operand, MO1, is extracted. The helper methods such asisImmediate, isGlobalAddress, isExternalSymbol,isConstantPoolIndex, and isJumpTableIndex determine the operand type.(X86CodeEmitter.cpp also has private methods such as emitConstant,emitGlobalAddress, emitExternalSymbolAddress, emitConstPoolAddress,and emitJumpTableAddress that emit the data into the output stream.)

  1. case X86II::AddRegFrm:
  2. MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++).getReg()));
  3.  
  4. if (CurOp != NumOps) {
  5. const MachineOperand &MO1 = MI.getOperand(CurOp++);
  6. unsigned Size = X86InstrInfo::sizeOfImm(Desc);
  7. if (MO1.isImmediate())
  8. emitConstant(MO1.getImm(), Size);
  9. else {
  10. unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
  11. : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
  12. if (Opcode == X86::MOV64ri)
  13. rt = X86::reloc_absolute_dword; // FIXME: add X86II flag?
  14. if (MO1.isGlobalAddress()) {
  15. bool NeedStub = isa<Function>(MO1.getGlobal());
  16. bool isLazy = gvNeedsLazyPtr(MO1.getGlobal());
  17. emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
  18. NeedStub, isLazy);
  19. } else if (MO1.isExternalSymbol())
  20. emitExternalSymbolAddress(MO1.getSymbolName(), rt);
  21. else if (MO1.isConstantPoolIndex())
  22. emitConstPoolAddress(MO1.getIndex(), rt);
  23. else if (MO1.isJumpTableIndex())
  24. emitJumpTableAddress(MO1.getIndex(), rt);
  25. }
  26. }
  27. break;

In the previous example, XXXCodeEmitter.cpp uses the variable rt, whichis a RelocationType enum that may be used to relocate addresses (forexample, a global address with a PIC base offset). The RelocationType enumfor that target is defined in the short target-specific XXXRelocations.hfile. The RelocationType is used by the relocate method defined inXXXJITInfo.cpp to rewrite addresses for referenced global symbols.

For example, X86Relocations.h specifies the following relocation types forthe X86 addresses. In all four cases, the relocated value is added to thevalue already in memory. For reloc_pcrel_word and reloc_picrel_word,there is an additional initial adjustment.

  1. enum RelocationType {
  2. reloc_pcrel_word = 0, // add reloc value after adjusting for the PC loc
  3. reloc_picrel_word = 1, // add reloc value after adjusting for the PIC base
  4. reloc_absolute_word = 2, // absolute relocation; no additional adjustment
  5. reloc_absolute_dword = 3 // absolute relocation; no additional adjustment
  6. };

Target JIT Info

XXXJITInfo.cpp implements the JIT interfaces for target-specificcode-generation activities, such as emitting machine code and stubs. Atminimum, a target-specific version of XXXJITInfo implements the following:

  • getLazyResolverFunction — Initializes the JIT, gives the target afunction that is used for compilation.
  • emitFunctionStub — Returns a native function with a specified addressfor a callback function.
  • relocate — Changes the addresses of referenced globals, based onrelocation types.
  • Callback function that are wrappers to a function stub that is used when thereal target is not initially known.

getLazyResolverFunction is generally trivial to implement. It makes theincoming parameter as the global JITCompilerFunction and returns thecallback function that will be used a function wrapper. For the Alpha target(in AlphaJITInfo.cpp), the getLazyResolverFunction implementation issimply:

  1. TargetJITInfo::LazyResolverFn AlphaJITInfo::getLazyResolverFunction(
  2. JITCompilerFn F) {
  3. JITCompilerFunction = F;
  4. return AlphaCompilationCallback;
  5. }

For the X86 target, the getLazyResolverFunction implementation is a littlemore complicated, because it returns a different callback function forprocessors with SSE instructions and XMM registers.

The callback function initially saves and later restores the callee registervalues, incoming arguments, and frame and return address. The callbackfunction needs low-level access to the registers or stack, so it is typicallyimplemented with assembler.