2029 lines · plain
1=======================2Writing an LLVM Backend3=======================4 5.. toctree::6 :hidden:7 8 HowToUseInstrMappings9 10.. contents::11 :local:12 13Introduction14============15 16This document describes techniques for writing compiler backends that convert17the LLVM Intermediate Representation (IR) to code for a specified machine or18other languages. Code intended for a specific machine can take the form of19either assembly code or binary code (usable for a JIT compiler).20 21The backend of LLVM features a target-independent code generator that may22create output for several types of target CPUs --- including X86, PowerPC,23ARM, and SPARC. The backend may also be used to generate code targeted at SPUs24of the Cell processor or GPUs to support the execution of compute kernels.25 26The document focuses on existing examples found in subdirectories of27``llvm/lib/Target`` in a downloaded LLVM release. In particular, this document28focuses on the example of creating a static compiler (one that emits text29assembly) for a SPARC target, because SPARC has fairly standard30characteristics, such as a RISC instruction set and straightforward calling31conventions.32 33Audience34--------35 36The audience for this document is anyone who needs to write an LLVM backend to37generate code for a specific hardware or software target.38 39Prerequisite Reading40--------------------41 42These essential documents must be read before reading this document:43 44* `LLVM Language Reference Manual <LangRef.html>`_ --- a reference manual for45 the LLVM assembly language.46 47* :doc:`CodeGenerator` --- a guide to the components (classes and code48 generation algorithms) for translating the LLVM internal representation into49 machine code for a specified target. Pay particular attention to the50 descriptions of code generation stages: Instruction Selection, Scheduling and51 Formation, SSA-based Optimization, Register Allocation, Prolog/Epilog Code52 Insertion, Late Machine Code Optimizations, and Code Emission.53 54* :doc:`TableGen/index` --- a document that describes the TableGen55 (``tblgen``) application that manages domain-specific information to support56 LLVM code generation. TableGen processes input from a target description57 file (``.td`` suffix) and generates C++ code that can be used for code58 generation.59 60* :doc:`WritingAnLLVMPass` --- The assembly printer is a ``FunctionPass``, as61 are several ``SelectionDAG`` processing steps.62 63To follow the SPARC examples in this document, have a copy of `The SPARC64Architecture Manual, Version 8 <http://www.sparc.org/standards/V8.pdf>`_ for65reference. For details about the ARM instruction set, refer to the `ARM66Architecture Reference Manual <http://infocenter.arm.com/>`_. For more about67the GNU Assembler format (``GAS``), see `Using As68<http://sourceware.org/binutils/docs/as/index.html>`_, especially for the69assembly printer. "Using As" contains a list of target machine dependent70features.71 72Basic Steps73-----------74 75To write a compiler backend for LLVM that converts the LLVM IR to code for a76specified target (machine or other language), follow these steps:77 78* Create a subclass of the ``TargetMachine`` class that describes79 characteristics of your target machine. Copy existing examples of specific80 ``TargetMachine`` class and header files; for example, start with81 ``SparcTargetMachine.cpp`` and ``SparcTargetMachine.h``, but change the file82 names for your target. Similarly, change code that references "``Sparc``" to83 reference your target.84 85* Describe the register set of the target. Use TableGen to generate code for86 register definition, register aliases, and register classes from a87 target-specific ``RegisterInfo.td`` input file. You should also write88 additional code for a subclass of the ``TargetRegisterInfo`` class that89 represents the class register file data used for register allocation and also90 describes the interactions between registers.91 92* Describe the instruction set of the target. Use TableGen to generate code93 for target-specific instructions from target-specific versions of94 ``TargetInstrFormats.td`` and ``TargetInstrInfo.td``. You should write95 additional code for a subclass of the ``TargetInstrInfo`` class to represent96 machine instructions supported by the target machine.97 98* Describe the selection and conversion of the LLVM IR from a Directed Acyclic99 Graph (DAG) representation of instructions to native target-specific100 instructions. Use TableGen to generate code that matches patterns and101 selects instructions based on additional information in a target-specific102 version of ``TargetInstrInfo.td``. Write code for ``XXXISelDAGToDAG.cpp``,103 where ``XXX`` identifies the specific target, to perform pattern matching and104 DAG-to-DAG instruction selection. Also write code in ``XXXISelLowering.cpp``105 to replace or remove operations and data types that are not supported106 natively in a SelectionDAG.107 108* Write code for an assembly printer that converts LLVM IR to a GAS format for109 your target machine. You should add assembly strings to the instructions110 defined in your target-specific version of ``TargetInstrInfo.td``. You111 should also write code for a subclass of ``AsmPrinter`` that performs the112 LLVM-to-assembly conversion and a trivial subclass of ``TargetAsmInfo``.113 114* Optionally, add support for subtargets (i.e., variants with different115 capabilities). You should also write code for a subclass of the116 ``TargetSubtarget`` class, which allows you to use the ``-mcpu=`` and117 ``-mattr=`` command-line options.118 119* Optionally, add JIT support and create a machine code emitter (subclass of120 ``TargetJITInfo``) that is used to emit binary code directly into memory.121 122In the ``.cpp`` and ``.h``. files, initially stub up these methods and then123implement them later. Initially, you may not know which private members that124the class will need and which components will need to be subclassed.125 126Preliminaries127-------------128 129To actually create your compiler backend, you need to create and modify a few130files. The absolute minimum is discussed here. But to actually use the LLVM131target-independent code generator, you must perform the steps described in the132:doc:`LLVM Target-Independent Code Generator <CodeGenerator>` document.133 134First, you should create a subdirectory under ``lib/Target`` to hold all the135files related to your target. If your target is called "Dummy", create the136directory ``lib/Target/Dummy``.137 138In this new directory, create a ``CMakeLists.txt``. It is easiest to copy a139``CMakeLists.txt`` of another target and modify it. It should at least contain140the ``LLVM_TARGET_DEFINITIONS`` variable. The library can be named ``LLVMDummy``141(for example, see the MIPS target). Alternatively, you can split the library142into ``LLVMDummyCodeGen`` and ``LLVMDummyAsmPrinter``, the latter of which143should be implemented in a subdirectory below ``lib/Target/Dummy`` (for example,144see the PowerPC target).145 146Note that these two naming schemes are hardcoded into ``llvm-config``. Using147any other naming scheme will confuse ``llvm-config`` and produce a lot of148(seemingly unrelated) linker errors when linking ``llc``.149 150To make your target actually do something, you need to implement a subclass of151``TargetMachine``. This implementation should typically be in the file152``lib/Target/DummyTargetMachine.cpp``, but any file in the ``lib/Target``153directory will be built and should work. To use LLVM's target-independent code154generator, you should do what all current machine backends do: create a155subclass of ``CodeGenTargetMachineImpl``. (To create a target from scratch, create a156subclass of ``TargetMachine``.)157 158To get LLVM to actually build and link your target, you need to run ``cmake``159with ``-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=Dummy``. This will build your160target without needing to add it to the list of all the targets.161 162Once your target is stable, you can add it to the ``LLVM_ALL_TARGETS`` variable163located in the main ``CMakeLists.txt``.164 165Target Machine166==============167 168``CodeGenTargetMachineImpl`` is designed as a base class for targets implemented with169the LLVM target-independent code generator. The ``CodeGenTargetMachineImpl`` class170should be specialized by a concrete target class that implements the various171virtual methods. ``CodeGenTargetMachineImpl`` is defined as a subclass of172``TargetMachine`` in ``include/llvm/CodeGen/CodeGenTargetMachineImpl.h``. The173``TargetMachine`` class implementation (``include/llvm/Target/TargetMachine.cpp``)174also processes numerous command-line options.175 176To create a concrete target-specific subclass of ``CodeGenTargetMachineImpl``, start177by copying an existing ``TargetMachine`` class and header. You should name the178files that you create to reflect your specific target. For instance, for the179SPARC target, name the files ``SparcTargetMachine.h`` and180``SparcTargetMachine.cpp``.181 182For a target machine ``XXX``, the implementation of ``XXXTargetMachine`` must183have access methods to obtain objects that represent target components. These184methods are named ``get*Info``, and are intended to obtain the instruction set185(``getInstrInfo``), register set (``getRegisterInfo``), stack frame layout186(``getFrameInfo``), and similar information. ``XXXTargetMachine`` must also187implement the ``getDataLayout`` method to access an object with target-specific188data characteristics, such as data type size and alignment requirements.189 190For instance, for the SPARC target, the header file ``SparcTargetMachine.h``191declares prototypes for several ``get*Info`` and ``getDataLayout`` methods that192simply return a class member.193 194.. code-block:: c++195 196 namespace llvm {197 198 class Module;199 200 class SparcTargetMachine : public CodeGenTargetMachineImpl {201 const DataLayout DataLayout; // Calculates type size & alignment202 SparcSubtarget Subtarget;203 SparcInstrInfo InstrInfo;204 TargetFrameInfo FrameInfo;205 206 protected:207 virtual const TargetAsmInfo *createTargetAsmInfo() const;208 209 public:210 SparcTargetMachine(const Module &M, const std::string &FS);211 212 virtual const SparcInstrInfo *getInstrInfo() const {return &InstrInfo; }213 virtual const TargetFrameInfo *getFrameInfo() const {return &FrameInfo; }214 virtual const TargetSubtarget *getSubtargetImpl() const{return &Subtarget; }215 virtual const TargetRegisterInfo *getRegisterInfo() const {216 return &InstrInfo.getRegisterInfo();217 }218 virtual const DataLayout *getDataLayout() const { return &DataLayout; }219 220 // Pass Pipeline Configuration221 virtual bool addInstSelector(PassManagerBase &PM, bool Fast);222 virtual bool addPreEmitPass(PassManagerBase &PM, bool Fast);223 };224 225 } // end namespace llvm226 227* ``getInstrInfo()``228* ``getRegisterInfo()``229* ``getFrameInfo()``230* ``getDataLayout()``231* ``getSubtargetImpl()``232 233For some targets, you also need to support the following methods:234 235* ``getTargetLowering()``236* ``getJITInfo()``237 238Some architectures, such as GPUs, do not support jumping to an arbitrary239program location and implement branching using masked execution and loop using240special instructions around the loop body. In order to avoid CFG modifications241that introduce irreducible control flow not handled by such hardware, a target242must call `setRequiresStructuredCFG(true)` when being initialized.243 244In addition, the ``XXXTargetMachine`` constructor should specify a245``TargetDescription`` string that determines the data layout for the target246machine, including characteristics such as pointer size, alignment, and247endianness. For example, the constructor for ``SparcTargetMachine`` contains248the following:249 250.. code-block:: c++251 252 SparcTargetMachine::SparcTargetMachine(const Module &M, const std::string &FS)253 : DataLayout("E-p:32:32-f128:128:128"),254 Subtarget(M, FS), InstrInfo(Subtarget),255 FrameInfo(TargetFrameInfo::StackGrowsDown, 8, 0) {256 }257 258Hyphens separate portions of the ``TargetDescription`` string.259 260* An upper-case "``E``" in the string indicates a big-endian target data model.261 A lower-case "``e``" indicates little-endian.262 263* "``p:``" is followed by pointer information: size, ABI alignment, and264 preferred alignment. If only two figures follow "``p:``", then the first265 value is pointer size, and the second value is both ABI and preferred266 alignment.267 268* Then a letter for numeric type alignment: "``i``", "``f``", "``v``", or269 "``a``" (corresponding to integer, floating point, vector, or aggregate).270 "``i``", "``v``", or "``a``" are followed by ABI alignment and preferred271 alignment. "``f``" is followed by three values: the first indicates the size272 of a long double, then ABI alignment, and then ABI preferred alignment.273 274Target Registration275===================276 277You must also register your target with the ``TargetRegistry``, which is what278other LLVM tools use to be able to lookup and use your target at runtime. The279``TargetRegistry`` can be used directly, but for most targets there are helper280templates which should take care of the work for you.281 282All targets should declare a global ``Target`` object which is used to283represent the target during registration. Then, in the target's ``TargetInfo``284library, the target should define that object and use the ``RegisterTarget``285template to register the target. For example, the Sparc registration code286looks like this:287 288.. code-block:: c++289 290 Target llvm::getTheSparcTarget();291 292 extern "C" void LLVMInitializeSparcTargetInfo() {293 RegisterTarget<Triple::sparc, /*HasJIT=*/false>294 X(getTheSparcTarget(), "sparc", "Sparc");295 }296 297This allows the ``TargetRegistry`` to look up the target by name or by target298triple. In addition, most targets will also register additional features which299are available in separate libraries. These registration steps are separate,300because some clients may wish to only link in some parts of the target --- the301JIT code generator does not require the use of the assembler printer, for302example. Here is an example of registering the Sparc assembly printer:303 304.. code-block:: c++305 306 extern "C" void LLVMInitializeSparcAsmPrinter() {307 RegisterAsmPrinter<SparcAsmPrinter> X(getTheSparcTarget());308 }309 310For more information, see "`llvm/Target/TargetRegistry.h311</doxygen/TargetRegistry_8h-source.html>`_".312 313Register Set and Register Classes314=================================315 316You should describe a concrete target-specific class that represents the317register file of a target machine. This class is called ``XXXRegisterInfo``318(where ``XXX`` identifies the target) and represents the class register file319data that is used for register allocation. It also describes the interactions320between registers.321 322You also need to define register classes to categorize related registers. A323register class should be added for groups of registers that are all treated the324same way for some instruction. Typical examples are register classes for325integer, floating-point, or vector registers. A register allocator allows an326instruction to use any register in a specified register class to perform the327instruction in a similar manner. Register classes allocate virtual registers328to instructions from these sets, and register classes let the329target-independent register allocator automatically choose the actual330registers.331 332Much of the code for registers, including register definition, register333aliases, and register classes, is generated by TableGen from334``XXXRegisterInfo.td`` input files and placed in ``XXXGenRegisterInfo.h.inc``335and ``XXXGenRegisterInfo.inc`` output files. Some of the code in the336implementation of ``XXXRegisterInfo`` requires hand-coding.337 338Defining a Register339-------------------340 341The ``XXXRegisterInfo.td`` file typically starts with register definitions for342a target machine. The ``Register`` class (specified in ``Target.td``) is used343to define an object for each register. The specified string ``n`` becomes the344``Name`` of the register. The basic ``Register`` object does not have any345subregisters and does not specify any aliases.346 347.. code-block:: text348 349 class Register<string n> {350 string Namespace = "";351 string AsmName = n;352 string Name = n;353 int SpillSize = 0;354 int SpillAlignment = 0;355 list<Register> Aliases = [];356 list<Register> SubRegs = [];357 list<int> DwarfNumbers = [];358 }359 360For example, in the ``X86RegisterInfo.td`` file, there are register definitions361that utilize the ``Register`` class, such as:362 363.. code-block:: text364 365 def AL : Register<"AL">, DwarfRegNum<[0, 0, 0]>;366 367This defines the register ``AL`` and assigns it values (with ``DwarfRegNum``)368that are used by ``gcc``, ``gdb``, or a debug information writer to identify a369register. For register ``AL``, ``DwarfRegNum`` takes an array of 3 values370representing 3 different modes: the first element is for X86-64, the second for371exception handling (EH) on X86-32, and the third is generic. -1 is a special372Dwarf number that indicates the gcc number is undefined, and -2 indicates the373register number is invalid for this mode.374 375From the previously described line in the ``X86RegisterInfo.td`` file, TableGen376generates this code in the ``X86GenRegisterInfo.inc`` file:377 378.. code-block:: c++379 380 static const unsigned GR8[] = { X86::AL, ... };381 382 const unsigned AL_AliasSet[] = { X86::AX, X86::EAX, X86::RAX, 0 };383 384 const TargetRegisterDesc RegisterDescriptors[] = {385 ...386 { "AL", "AL", AL_AliasSet, Empty_SubRegsSet, Empty_SubRegsSet, AL_SuperRegsSet }, ...387 388From the register info file, TableGen generates a ``TargetRegisterDesc`` object389for each register. ``TargetRegisterDesc`` is defined in390``include/llvm/Target/TargetRegisterInfo.h`` with the following fields:391 392.. code-block:: c++393 394 struct TargetRegisterDesc {395 const char *AsmName; // Assembly language name for the register396 const char *Name; // Printable name for the reg (for debugging)397 const unsigned *AliasSet; // Register Alias Set398 const unsigned *SubRegs; // Sub-register set399 const unsigned *ImmSubRegs; // Immediate sub-register set400 const unsigned *SuperRegs; // Super-register set401 };402 403TableGen uses the entire target description file (``.td``) to determine text404names for the register (in the ``AsmName`` and ``Name`` fields of405``TargetRegisterDesc``) and the relationships of other registers to the defined406register (in the other ``TargetRegisterDesc`` fields). In this example, other407definitions establish the registers "``AX``", "``EAX``", and "``RAX``" as408aliases for one another, so TableGen generates a null-terminated array409(``AL_AliasSet``) for this register alias set.410 411The ``Register`` class is commonly used as a base class for more complex412classes. In ``Target.td``, the ``Register`` class is the base for the413``RegisterWithSubRegs`` class that is used to define registers that need to414specify subregisters in the ``SubRegs`` list, as shown here:415 416.. code-block:: text417 418 class RegisterWithSubRegs<string n, list<Register> subregs> : Register<n> {419 let SubRegs = subregs;420 }421 422In ``SparcRegisterInfo.td``, additional register classes are defined for SPARC:423a ``Register`` subclass, ``SparcReg``, and further subclasses: ``Ri``, ``Rf``,424and ``Rd``. SPARC registers are identified by 5-bit ID numbers, which is a425feature common to these subclasses. Note the use of "``let``" expressions to426override values that are initially defined in a superclass (such as ``SubRegs``427field in the ``Rd`` class).428 429.. code-block:: text430 431 class SparcReg<string n> : Register<n> {432 field bits<5> Num;433 let Namespace = "SP";434 }435 // Ri - 32-bit integer registers436 class Ri<bits<5> num, string n> :437 SparcReg<n> {438 let Num = num;439 }440 // Rf - 32-bit floating-point registers441 class Rf<bits<5> num, string n> :442 SparcReg<n> {443 let Num = num;444 }445 // Rd - Slots in the FP register file for 64-bit floating-point values.446 class Rd<bits<5> num, string n, list<Register> subregs> : SparcReg<n> {447 let Num = num;448 let SubRegs = subregs;449 }450 451In the ``SparcRegisterInfo.td`` file, there are register definitions that452utilize these subclasses of ``Register``, such as:453 454.. code-block:: text455 456 def G0 : Ri< 0, "G0">, DwarfRegNum<[0]>;457 def G1 : Ri< 1, "G1">, DwarfRegNum<[1]>;458 ...459 def F0 : Rf< 0, "F0">, DwarfRegNum<[32]>;460 def F1 : Rf< 1, "F1">, DwarfRegNum<[33]>;461 ...462 def D0 : Rd< 0, "F0", [F0, F1]>, DwarfRegNum<[32]>;463 def D1 : Rd< 2, "F2", [F2, F3]>, DwarfRegNum<[34]>;464 465The last two registers shown above (``D0`` and ``D1``) are double-precision466floating-point registers that are aliases for pairs of single-precision467floating-point sub-registers. In addition to aliases, the sub-register and468super-register relationships of the defined register are in fields of a469register's ``TargetRegisterDesc``.470 471Defining a Register Class472-------------------------473 474The ``RegisterClass`` class (specified in ``Target.td``) is used to define an475object that represents a group of related registers and also defines the476default allocation order of the registers. A target description file477``XXXRegisterInfo.td`` that uses ``Target.td`` can construct register classes478using the following class:479 480.. code-block:: text481 482 class RegisterClass<string namespace,483 list<ValueType> regTypes, int alignment, dag regList> {484 string Namespace = namespace;485 list<ValueType> RegTypes = regTypes;486 int Size = 0; // spill size, in bits; zero lets tblgen pick the size487 int Alignment = alignment;488 489 // CopyCost is the cost of copying a value between two registers490 // default value 1 means a single instruction491 // A negative value means copying is extremely expensive or impossible492 int CopyCost = 1;493 dag MemberList = regList;494 495 // for register classes that are subregisters of this class496 list<RegisterClass> SubRegClassList = [];497 498 code MethodProtos = [{}]; // to insert arbitrary code499 code MethodBodies = [{}];500 }501 502To define a ``RegisterClass``, use the following 4 arguments:503 504* The first argument of the definition is the name of the namespace.505 506* The second argument is a list of ``ValueType`` register type values that are507 defined in ``include/llvm/CodeGen/ValueTypes.td``. Defined values include508 integer types (such as ``i16``, ``i32``, and ``i1`` for Boolean),509 floating-point types (``f32``, ``f64``), and vector types (for example,510 ``v8i16`` for an ``8 x i16`` vector). All registers in a ``RegisterClass``511 must have the same ``ValueType``, but some registers may store vector data in512 different configurations. For example a register that can process a 128-bit513 vector may be able to handle 16 8-bit integer elements, 8 16-bit integers, 4514 32-bit integers, and so on.515 516* The third argument of the ``RegisterClass`` definition specifies the517 alignment required of the registers when they are stored or loaded to518 memory.519 520* The final argument, ``regList``, specifies which registers are in this class.521 If an alternative allocation order method is not specified, then ``regList``522 also defines the order of allocation used by the register allocator. Besides523 simply listing registers with ``(add R0, R1, ...)``, more advanced set524 operators are available. See ``include/llvm/Target/Target.td`` for more525 information.526 527In ``SparcRegisterInfo.td``, three ``RegisterClass`` objects are defined:528``FPRegs``, ``DFPRegs``, and ``IntRegs``. For all three register classes, the529first argument defines the namespace with the string "``SP``". ``FPRegs``530defines a group of 32 single-precision floating-point registers (``F0`` to531``F31``); ``DFPRegs`` defines a group of 16 double-precision registers532(``D0-D15``).533 534.. code-block:: text535 536 // F0, F1, F2, ..., F31537 def FPRegs : RegisterClass<"SP", [f32], 32, (sequence "F%u", 0, 31)>;538 539 def DFPRegs : RegisterClass<"SP", [f64], 64,540 (add D0, D1, D2, D3, D4, D5, D6, D7, D8,541 D9, D10, D11, D12, D13, D14, D15)>;542 543 def IntRegs : RegisterClass<"SP", [i32], 32,544 (add L0, L1, L2, L3, L4, L5, L6, L7,545 I0, I1, I2, I3, I4, I5,546 O0, O1, O2, O3, O4, O5, O7,547 G1,548 // Non-allocatable regs:549 G2, G3, G4,550 O6, // stack ptr551 I6, // frame ptr552 I7, // return address553 G0, // constant zero554 G5, G6, G7 // reserved for kernel555 )>;556 557Using ``SparcRegisterInfo.td`` with TableGen generates several output files558that are intended for inclusion in other source code that you write.559``SparcRegisterInfo.td`` generates ``SparcGenRegisterInfo.h.inc``, which should560be included in the header file for the implementation of the SPARC register561implementation that you write (``SparcRegisterInfo.h``). In562``SparcGenRegisterInfo.h.inc`` a new structure is defined called563``SparcGenRegisterInfo`` that uses ``TargetRegisterInfo`` as its base. It also564specifies types, based upon the defined register classes: ``DFPRegsClass``,565``FPRegsClass``, and ``IntRegsClass``.566 567``SparcRegisterInfo.td`` also generates ``SparcGenRegisterInfo.inc``, which is568included at the bottom of ``SparcRegisterInfo.cpp``, the SPARC register569implementation. The code below shows only the generated integer registers and570associated register classes. The order of registers in ``IntRegs`` reflects571the order in the definition of ``IntRegs`` in the target description file.572 573.. code-block:: c++574 575 // IntRegs Register Class...576 static const unsigned IntRegs[] = {577 SP::L0, SP::L1, SP::L2, SP::L3, SP::L4, SP::L5,578 SP::L6, SP::L7, SP::I0, SP::I1, SP::I2, SP::I3,579 SP::I4, SP::I5, SP::O0, SP::O1, SP::O2, SP::O3,580 SP::O4, SP::O5, SP::O7, SP::G1, SP::G2, SP::G3,581 SP::G4, SP::O6, SP::I6, SP::I7, SP::G0, SP::G5,582 SP::G6, SP::G7,583 };584 585 // IntRegsVTs Register Class Value Types...586 static const MVT::ValueType IntRegsVTs[] = {587 MVT::i32, MVT::Other588 };589 590 namespace SP { // Register class instances591 DFPRegsClass DFPRegsRegClass;592 FPRegsClass FPRegsRegClass;593 IntRegsClass IntRegsRegClass;594 ...595 // IntRegs Sub-register Classes...596 static const TargetRegisterClass* const IntRegsSubRegClasses [] = {597 NULL598 };599 ...600 // IntRegs Super-register Classes..601 static const TargetRegisterClass* const IntRegsSuperRegClasses [] = {602 NULL603 };604 ...605 // IntRegs Register Class sub-classes...606 static const TargetRegisterClass* const IntRegsSubclasses [] = {607 NULL608 };609 ...610 // IntRegs Register Class super-classes...611 static const TargetRegisterClass* const IntRegsSuperclasses [] = {612 NULL613 };614 615 IntRegsClass::IntRegsClass() : TargetRegisterClass(IntRegsRegClassID,616 IntRegsVTs, IntRegsSubclasses, IntRegsSuperclasses, IntRegsSubRegClasses,617 IntRegsSuperRegClasses, 4, 4, 1, IntRegs, IntRegs + 32) {}618 }619 620The register allocators will avoid using reserved registers, and callee saved621registers are not used until all the volatile registers have been used. That622is usually good enough, but in some cases it may be necessary to provide custom623allocation orders.624 625Implement a subclass of ``TargetRegisterInfo``626----------------------------------------------627 628The final step is to hand code portions of ``XXXRegisterInfo``, which629implements the interface described in ``TargetRegisterInfo.h`` (see630:ref:`TargetRegisterInfo`). These functions return ``0``, ``NULL``, or631``false``, unless overridden. Here is a list of functions that are overridden632for the SPARC implementation in ``SparcRegisterInfo.cpp``:633 634* ``getCalleeSavedRegs`` --- Returns a list of callee-saved registers in the635 order of the desired callee-save stack frame offset.636 637* ``getReservedRegs`` --- Returns a bitset indexed by physical register638 numbers, indicating if a particular register is unavailable.639 640* ``hasFP`` --- Return a Boolean indicating if a function should have a641 dedicated frame pointer register.642 643* ``eliminateCallFramePseudoInstr`` --- If call frame setup or destroy pseudo644 instructions are used, this can be called to eliminate them.645 646* ``eliminateFrameIndex`` --- Eliminate abstract frame indices from647 instructions that may use them.648 649* ``emitPrologue`` --- Insert prologue code into the function.650 651* ``emitEpilogue`` --- Insert epilogue code into the function.652 653.. _instruction-set:654 655Instruction Set656===============657 658During the early stages of code generation, the LLVM IR code is converted to a659``SelectionDAG`` with nodes that are instances of the ``SDNode`` class660containing target instructions. An ``SDNode`` has an opcode, operands, type661requirements, and operation properties. For example, is an operation662commutative, does an operation load from memory. The various operation node663types are described in the ``include/llvm/CodeGen/SelectionDAGNodes.h`` file664(values of the ``NodeType`` enum in the ``ISD`` namespace).665 666TableGen uses the following target description (``.td``) input files to667generate much of the code for instruction definition:668 669* ``Target.td`` --- Where the ``Instruction``, ``Operand``, ``InstrInfo``, and670 other fundamental classes are defined.671 672* ``TargetSelectionDAG.td`` --- Used by ``SelectionDAG`` instruction selection673 generators, contains ``SDTC*`` classes (selection DAG type constraint),674 definitions of ``SelectionDAG`` nodes (such as ``imm``, ``cond``, ``bb``,675 ``add``, ``fadd``, ``sub``), and pattern support (``Pattern``, ``Pat``,676 ``PatFrag``, ``PatLeaf``, ``ComplexPattern``.677 678* ``XXXInstrFormats.td`` --- Patterns for definitions of target-specific679 instructions.680 681* ``XXXInstrInfo.td`` --- Target-specific definitions of instruction templates,682 condition codes, and instructions of an instruction set. For architecture683 modifications, a different file name may be used. For example, for Pentium684 with SSE instruction, this file is ``X86InstrSSE.td``, and for Pentium with685 MMX, this file is ``X86InstrMMX.td``.686 687There is also a target-specific ``XXX.td`` file, where ``XXX`` is the name of688the target. The ``XXX.td`` file includes the other ``.td`` input files, but689its contents are only directly important for subtargets.690 691You should describe a concrete target-specific class ``XXXInstrInfo`` that692represents machine instructions supported by a target machine.693``XXXInstrInfo`` contains an array of ``XXXInstrDescriptor`` objects, each of694which describes one instruction. An instruction descriptor defines:695 696* Opcode mnemonic697* Number of operands698* List of implicit register definitions and uses699* Target-independent properties (such as memory access, is commutable)700* Target-specific flags701 702The Instruction class (defined in ``Target.td``) is mostly used as a base for703more complex instruction classes.704 705.. code-block:: text706 707 class Instruction {708 string Namespace = "";709 dag OutOperandList; // A dag containing the MI def operand list.710 dag InOperandList; // A dag containing the MI use operand list.711 string AsmString = ""; // The .s format to print the instruction with.712 list<dag> Pattern; // Set to the DAG pattern for this instruction.713 list<Register> Uses = [];714 list<Register> Defs = [];715 list<Predicate> Predicates = []; // predicates turned into isel match code716 ... remainder not shown for space ...717 }718 719A ``SelectionDAG`` node (``SDNode``) should contain an object representing a720target-specific instruction that is defined in ``XXXInstrInfo.td``. The721instruction objects should represent instructions from the architecture manual722of the target machine (such as the SPARC Architecture Manual for the SPARC723target).724 725A single instruction from the architecture manual is often modeled as multiple726target instructions, depending upon its operands. For example, a manual might727describe an add instruction that takes a register or an immediate operand. An728LLVM target could model this with two instructions named ``ADDri`` and729``ADDrr``.730 731You should define a class for each instruction category and define each opcode732as a subclass of the category with appropriate parameters such as the fixed733binary encoding of opcodes and extended opcodes. You should map the register734bits to the bits of the instruction in which they are encoded (for the JIT).735Also you should specify how the instruction should be printed when the736automatic assembly printer is used.737 738As is described in the SPARC Architecture Manual, Version 8, there are three739major 32-bit formats for instructions. Format 1 is only for the ``CALL``740instruction. Format 2 is for branch on condition codes and ``SETHI`` (set high741bits of a register) instructions. Format 3 is for other instructions.742 743Each of these formats has corresponding classes in ``SparcInstrFormat.td``.744``InstSP`` is a base class for other instruction classes. Additional base745classes are specified for more precise formats: for example in746``SparcInstrFormat.td``, ``F2_1`` is for ``SETHI``, and ``F2_2`` is for747branches. There are three other base classes: ``F3_1`` for register/register748operations, ``F3_2`` for register/immediate operations, and ``F3_3`` for749floating-point operations. ``SparcInstrInfo.td`` also adds the base class750``Pseudo`` for synthetic SPARC instructions.751 752``SparcInstrInfo.td`` largely consists of operand and instruction definitions753for the SPARC target. In ``SparcInstrInfo.td``, the following target754description file entry, ``LDrr``, defines the Load Integer instruction for a755Word (the ``LD`` SPARC opcode) from a memory address to a register. The first756parameter, the value 3 (``11``\ :sub:`2`), is the operation value for this757category of operation. The second parameter (``000000``\ :sub:`2`) is the758specific operation value for ``LD``/Load Word. The third parameter is the759output destination, which is a register operand and defined in the ``Register``760target description file (``IntRegs``).761 762.. code-block:: text763 764 def LDrr : F3_1 <3, 0b000000, (outs IntRegs:$rd), (ins (MEMrr $rs1, $rs2):$addr),765 "ld [$addr], $dst",766 [(set i32:$dst, (load ADDRrr:$addr))]>;767 768The fourth parameter is the input source, which uses the address operand769``MEMrr`` that is defined earlier in ``SparcInstrInfo.td``:770 771.. code-block:: text772 773 def MEMrr : Operand<i32> {774 let PrintMethod = "printMemOperand";775 let MIOperandInfo = (ops IntRegs, IntRegs);776 }777 778The fifth parameter is a string that is used by the assembly printer and can be779left as an empty string until the assembly printer interface is implemented.780The sixth and final parameter is the pattern used to match the instruction781during the SelectionDAG Select Phase described in :doc:`CodeGenerator`.782This parameter is detailed in the next section, :ref:`instruction-selector`.783 784Instruction class definitions are not overloaded for different operand types,785so separate versions of instructions are needed for register, memory, or786immediate value operands. For example, to perform a Load Integer instruction787for a Word from an immediate operand to a register, the following instruction788class is defined:789 790.. code-block:: text791 792 def LDri : F3_2 <3, 0b000000, (outs IntRegs:$rd), (ins (MEMri $rs1, $simm13):$addr),793 "ld [$addr], $dst",794 [(set i32:$rd, (load ADDRri:$addr))]>;795 796Writing these definitions for so many similar instructions can involve a lot of797cut and paste. In ``.td`` files, the ``multiclass`` directive enables the798creation of templates to define several instruction classes at once (using the799``defm`` directive). For example in ``SparcInstrInfo.td``, the ``multiclass``800pattern ``F3_12`` is defined to create 2 instruction classes each time801``F3_12`` is invoked:802 803.. code-block:: text804 805 multiclass F3_12 <string OpcStr, bits<6> Op3Val, SDNode OpNode> {806 def rr : F3_1 <2, Op3Val,807 (outs IntRegs:$rd), (ins IntRegs:$rs1, IntRegs:$rs1),808 !strconcat(OpcStr, " $rs1, $rs2, $rd"),809 [(set i32:$rd, (OpNode i32:$rs1, i32:$rs2))]>;810 def ri : F3_2 <2, Op3Val,811 (outs IntRegs:$rd), (ins IntRegs:$rs1, i32imm:$simm13),812 !strconcat(OpcStr, " $rs1, $simm13, $rd"),813 [(set i32:$rd, (OpNode i32:$rs1, simm13:$simm13))]>;814 }815 816So when the ``defm`` directive is used for the ``XOR`` and ``ADD``817instructions, as seen below, it creates four instruction objects: ``XORrr``,818``XORri``, ``ADDrr``, and ``ADDri``.819 820.. code-block:: text821 822 defm XOR : F3_12<"xor", 0b000011, xor>;823 defm ADD : F3_12<"add", 0b000000, add>;824 825``SparcInstrInfo.td`` also includes definitions for condition codes that are826referenced by branch instructions. The following definitions in827``SparcInstrInfo.td`` indicate the bit location of the SPARC condition code.828For example, the 10\ :sup:`th` bit represents the "greater than" condition for829integers, and the 22\ :sup:`nd` bit represents the "greater than" condition for830floats.831 832.. code-block:: text833 834 def ICC_NE : ICC_VAL< 9>; // Not Equal835 def ICC_E : ICC_VAL< 1>; // Equal836 def ICC_G : ICC_VAL<10>; // Greater837 ...838 def FCC_U : FCC_VAL<23>; // Unordered839 def FCC_G : FCC_VAL<22>; // Greater840 def FCC_UG : FCC_VAL<21>; // Unordered or Greater841 ...842 843(Note that ``Sparc.h`` also defines enums that correspond to the same SPARC844condition codes. Care must be taken to ensure the values in ``Sparc.h``845correspond to the values in ``SparcInstrInfo.td``. I.e., ``SPCC::ICC_NE = 9``,846``SPCC::FCC_U = 23`` and so on.)847 848Instruction Operand Mapping849---------------------------850 851The code generator backend maps instruction operands to fields in the852instruction. Whenever a bit in the instruction encoding ``Inst`` is assigned853to field without a concrete value, an operand from the ``outs`` or ``ins`` list854is expected to have a matching name. This operand then populates that undefined855field. For example, the Sparc target defines the ``XNORrr`` instruction as a856``F3_1`` format instruction having three operands: the output ``$rd``, and the857inputs ``$rs1``, and ``$rs2``.858 859.. code-block:: text860 861 def XNORrr : F3_1<2, 0b000111,862 (outs IntRegs:$rd), (ins IntRegs:$rs1, IntRegs:$rs2),863 "xnor $rs1, $rs2, $rd",864 [(set i32:$rd, (not (xor i32:$rs1, i32:$rs2)))]>;865 866The instruction templates in ``SparcInstrFormats.td`` show the base class for867``F3_1`` is ``InstSP``.868 869.. code-block:: text870 871 class InstSP<dag outs, dag ins, string asmstr, list<dag> pattern> : Instruction {872 field bits<32> Inst;873 let Namespace = "SP";874 bits<2> op;875 let Inst{31-30} = op;876 dag OutOperandList = outs;877 dag InOperandList = ins;878 let AsmString = asmstr;879 let Pattern = pattern;880 }881 882``InstSP`` defines the ``op`` field, and uses it to define bits 30 and 31 of the883instruction, but does not assign a value to it.884 885.. code-block:: text886 887 class F3<dag outs, dag ins, string asmstr, list<dag> pattern>888 : InstSP<outs, ins, asmstr, pattern> {889 bits<5> rd;890 bits<6> op3;891 bits<5> rs1;892 let op{1} = 1; // Op = 2 or 3893 let Inst{29-25} = rd;894 let Inst{24-19} = op3;895 let Inst{18-14} = rs1;896 }897 898``F3`` defines the ``rd``, ``op3``, and ``rs1`` fields, and uses them in the899instruction, and again does not assign values.900 901.. code-block:: text902 903 class F3_1<bits<2> opVal, bits<6> op3val, dag outs, dag ins,904 string asmstr, list<dag> pattern> : F3<outs, ins, asmstr, pattern> {905 bits<8> asi = 0; // asi not currently used906 bits<5> rs2;907 let op = opVal;908 let op3 = op3val;909 let Inst{13} = 0; // i field = 0910 let Inst{12-5} = asi; // address space identifier911 let Inst{4-0} = rs2;912 }913 914``F3_1`` assigns a value to ``op`` and ``op3`` fields, and defines the ``rs2``915field. Therefore, a ``F3_1`` format instruction will require a definition for916``rd``, ``rs1``, and ``rs2`` in order to fully specify the instruction encoding.917 918The ``XNORrr`` instruction then provides those three operands in its919OutOperandList and InOperandList, which bind to the corresponding fields, and920thus complete the instruction encoding.921 922For some instructions, a single operand may contain sub-operands. As shown923earlier, the instruction ``LDrr`` uses an input operand of type ``MEMrr``. This924operand type contains two register sub-operands, defined by the925``MIOperandInfo`` value to be ``(ops IntRegs, IntRegs)``.926 927.. code-block:: text928 929 def LDrr : F3_1 <3, 0b000000, (outs IntRegs:$rd), (ins (MEMrr $rs1, $rs2):$addr),930 "ld [$addr], $dst",931 [(set i32:$dst, (load ADDRrr:$addr))]>;932 933As this instruction is also the ``F3_1`` format, it will expect operands named934``rd``, ``rs1``, and ``rs2`` as well. In order to allow this, a complex operand935can optionally give names to each of its sub-operands. In this example936``MEMrr``'s first sub-operand is named ``$rs1``, the second ``$rs2``, and the937operand as a whole is also given the name ``$addr``.938 939When a particular instruction doesn't use all the operands that the instruction940format defines, a constant value may instead be bound to one or all. For941example, the ``RDASR`` instruction only takes a single register operand, so we942assign a constant zero to ``rs2``:943 944.. code-block:: text945 946 let rs2 = 0 in947 def RDASR : F3_1<2, 0b101000,948 (outs IntRegs:$rd), (ins ASRRegs:$rs1),949 "rd $rs1, $rd", []>;950 951Instruction Operand Name Mapping952^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^953 954TableGen will also generate a function called getNamedOperandIdx() which955can be used to look up an operand's index in a MachineInstr based on its956TableGen name. Setting the UseNamedOperandTable bit in an instruction's957TableGen definition will add all of its operands to an enumeration958llvm::XXX:OpName and also add an entry for it into the OperandMap959table, which can be queried using getNamedOperandIdx()960 961.. code-block:: text962 963 int DstIndex = SP::getNamedOperandIdx(SP::XNORrr, SP::OpName::dst); // => 0964 int BIndex = SP::getNamedOperandIdx(SP::XNORrr, SP::OpName::b); // => 1965 int CIndex = SP::getNamedOperandIdx(SP::XNORrr, SP::OpName::c); // => 2966 int DIndex = SP::getNamedOperandIdx(SP::XNORrr, SP::OpName::d); // => -1967 968 ...969 970The entries in the OpName enum are taken verbatim from the TableGen definitions,971so operands with lowercase names will have lower case entries in the enum.972 973To include the getNamedOperandIdx() function in your backend, you will need974to define a few preprocessor macros in XXXInstrInfo.cpp and XXXInstrInfo.h.975For example:976 977XXXInstrInfo.cpp:978 979.. code-block:: c++980 981 // For getNamedOperandIdx() function definition.982 #define GET_INSTRINFO_NAMED_OPS983 #include "XXXGenInstrInfo.inc"984 985XXXInstrInfo.h:986 987.. code-block:: c++988 989 // For OpName enum and getNamedOperandIdx declaration.990 #define GET_INSTRINFO_OPERAND_ENUM991 #include "XXXGenInstrInfo.inc"992 993Instruction Operand Types994^^^^^^^^^^^^^^^^^^^^^^^^^995 996TableGen will also generate an enumeration consisting of all named Operand997types defined in the backend, in the llvm::XXX::OpTypes namespace.998Some common immediate Operand types (for instance i8, i32, i64, f32, f64)999are defined for all targets in ``include/llvm/Target/Target.td``, and are1000available in each Target's OpTypes enum. Also, only named Operand types appear1001in the enumeration: anonymous types are ignored.1002For example, the X86 backend defines ``brtarget`` and ``brtarget8``, both1003instances of the TableGen ``Operand`` class, which represent branch target1004operands:1005 1006.. code-block:: text1007 1008 def brtarget : Operand<OtherVT>;1009 def brtarget8 : Operand<OtherVT>;1010 1011This results in:1012 1013.. code-block:: c++1014 1015 namespace X86 {1016 namespace OpTypes {1017 enum OperandType {1018 ...1019 brtarget,1020 brtarget8,1021 ...1022 i32imm,1023 i64imm,1024 ...1025 OPERAND_TYPE_LIST_END1026 } // End namespace OpTypes1027 } // End namespace X861028 1029In typical TableGen fashion, to use the enum, you will need to define a1030preprocessor macro:1031 1032.. code-block:: c++1033 1034 #define GET_INSTRINFO_OPERAND_TYPES_ENUM // For OpTypes enum1035 #include "XXXGenInstrInfo.inc"1036 1037 1038Instruction Scheduling1039----------------------1040 1041Instruction itineraries can be queried using MCDesc::getSchedClass(). The1042value can be named by an enumeration in llvm::XXX::Sched namespace generated1043by TableGen in XXXGenInstrInfo.inc. The name of the schedule classes are1044the same as provided in XXXSchedule.td plus a default NoItinerary class.1045 1046The schedule models are generated by TableGen by the SubtargetEmitter,1047using the ``CodeGenSchedModels`` class. This is distinct from the itinerary1048method of specifying machine resource use. The tool ``utils/schedcover.py``1049can be used to determine which instructions have been covered by the1050schedule model description and which haven't. The first step is to use the1051instructions below to create an output file. Then run ``schedcover.py`` on the1052output file:1053 1054.. code-block:: shell1055 1056 $ <src>/utils/schedcover.py <build>/lib/Target/AArch64/tblGenSubtarget.with1057 instruction, default, CortexA53Model, CortexA57Model, CycloneModel, ExynosM3Model, FalkorModel, KryoModel, ThunderX2T99Model, ThunderXT8XModel1058 ABSv16i8, WriteV, , , CyWriteV3, M3WriteNMISC1, FalkorWr_2VXVY_2cyc, KryoWrite_2cyc_XY_XY_150ln, ,1059 ABSv1i64, WriteV, , , CyWriteV3, M3WriteNMISC1, FalkorWr_1VXVY_2cyc, KryoWrite_2cyc_XY_noRSV_67ln, ,1060 ...1061 1062To capture the debug output from generating a schedule model, change to the1063appropriate target directory and use the following command:1064command with the ``subtarget-emitter`` debug option:1065 1066.. code-block:: shell1067 1068 $ <build>/bin/llvm-tblgen -debug-only=subtarget-emitter -gen-subtarget \1069 -I <src>/lib/Target/<target> -I <src>/include \1070 -I <src>/lib/Target <src>/lib/Target/<target>/<target>.td \1071 -o <build>/lib/Target/<target>/<target>GenSubtargetInfo.inc.tmp \1072 > tblGenSubtarget.dbg 2>&11073 1074Where ``<build>`` is the build directory, ``src`` is the source directory,1075and ``<target>`` is the name of the target.1076To double check that the above command is what is needed, one can capture the1077exact TableGen command from a build by using:1078 1079.. code-block:: shell1080 1081 $ VERBOSE=1 make ...1082 1083and search for ``llvm-tblgen`` commands in the output.1084 1085 1086Instruction Relation Mapping1087----------------------------1088 1089This TableGen feature is used to relate instructions with each other. It is1090particularly useful when you have multiple instruction formats and need to1091switch between them after instruction selection. This entire feature is driven1092by relation models which can be defined in ``XXXInstrInfo.td`` files1093according to the target-specific instruction set. Relation models are defined1094using ``InstrMapping`` class as a base. TableGen parses all the models1095and generates instruction relation maps using the specified information.1096Relation maps are emitted as tables in the ``XXXGenInstrInfo.inc`` file1097along with the functions to query them. For the detailed information on how to1098use this feature, please refer to :doc:`HowToUseInstrMappings`.1099 1100Implement a subclass of ``TargetInstrInfo``1101-------------------------------------------1102 1103The final step is to hand code portions of ``XXXInstrInfo``, which implements1104the interface described in ``TargetInstrInfo.h`` (see :ref:`TargetInstrInfo`).1105These functions return ``0`` or a Boolean or they assert, unless overridden.1106Here's a list of functions that are overridden for the SPARC implementation in1107``SparcInstrInfo.cpp``:1108 1109* ``isLoadFromStackSlot`` --- If the specified machine instruction is a direct1110 load from a stack slot, return the register number of the destination and the1111 ``FrameIndex`` of the stack slot.1112 1113* ``isStoreToStackSlot`` --- If the specified machine instruction is a direct1114 store to a stack slot, return the register number of the destination and the1115 ``FrameIndex`` of the stack slot.1116 1117* ``copyPhysReg`` --- Copy values between a pair of physical registers.1118 1119* ``storeRegToStackSlot`` --- Store a register value to a stack slot.1120 1121* ``loadRegFromStackSlot`` --- Load a register value from a stack slot.1122 1123* ``storeRegToAddr`` --- Store a register value to memory.1124 1125* ``loadRegFromAddr`` --- Load a register value from memory.1126 1127* ``foldMemoryOperand`` --- Attempt to combine instructions of any load or1128 store instruction for the specified operand(s).1129 1130Branch Folding and If Conversion1131--------------------------------1132 1133Performance can be improved by combining instructions or by eliminating1134instructions that are never reached. The ``analyzeBranch`` method in1135``XXXInstrInfo`` may be implemented to examine conditional instructions and1136remove unnecessary instructions. ``analyzeBranch`` looks at the end of a1137machine basic block (MBB) for opportunities for improvement, such as branch1138folding and if conversion. The ``BranchFolder`` and ``IfConverter`` machine1139function passes (see the source files ``BranchFolding.cpp`` and1140``IfConversion.cpp`` in the ``lib/CodeGen`` directory) call ``analyzeBranch``1141to improve the control flow graph that represents the instructions.1142 1143Several implementations of ``analyzeBranch`` (for ARM, Alpha, and X86) can be1144examined as models for your own ``analyzeBranch`` implementation. Since SPARC1145does not implement a useful ``analyzeBranch``, the ARM target implementation is1146shown below.1147 1148``analyzeBranch`` returns a Boolean value and takes four parameters:1149 1150* ``MachineBasicBlock &MBB`` --- The incoming block to be examined.1151 1152* ``MachineBasicBlock *&TBB`` --- A destination block that is returned. For a1153 conditional branch that evaluates to true, ``TBB`` is the destination.1154 1155* ``MachineBasicBlock *&FBB`` --- For a conditional branch that evaluates to1156 false, ``FBB`` is returned as the destination.1157 1158* ``std::vector<MachineOperand> &Cond`` --- List of operands to evaluate a1159 condition for a conditional branch.1160 1161In the simplest case, if a block ends without a branch, then it falls through1162to the successor block. No destination blocks are specified for either ``TBB``1163or ``FBB``, so both parameters return ``NULL``. The start of the1164``analyzeBranch`` (see code below for the ARM target) shows the function1165parameters and the code for the simplest case.1166 1167.. code-block:: c++1168 1169 bool ARMInstrInfo::analyzeBranch(MachineBasicBlock &MBB,1170 MachineBasicBlock *&TBB,1171 MachineBasicBlock *&FBB,1172 std::vector<MachineOperand> &Cond) const1173 {1174 MachineBasicBlock::iterator I = MBB.end();1175 if (I == MBB.begin() || !isUnpredicatedTerminator(--I))1176 return false;1177 1178If a block ends with a single unconditional branch instruction, then1179``analyzeBranch`` (shown below) should return the destination of that branch in1180the ``TBB`` parameter.1181 1182.. code-block:: c++1183 1184 if (LastOpc == ARM::B || LastOpc == ARM::tB) {1185 TBB = LastInst->getOperand(0).getMBB();1186 return false;1187 }1188 1189If a block ends with two unconditional branches, then the second branch is1190never reached. In that situation, as shown below, remove the last branch1191instruction and return the penultimate branch in the ``TBB`` parameter.1192 1193.. code-block:: c++1194 1195 if ((SecondLastOpc == ARM::B || SecondLastOpc == ARM::tB) &&1196 (LastOpc == ARM::B || LastOpc == ARM::tB)) {1197 TBB = SecondLastInst->getOperand(0).getMBB();1198 I = LastInst;1199 I->eraseFromParent();1200 return false;1201 }1202 1203A block may end with a single conditional branch instruction that falls through1204to successor block if the condition evaluates to false. In that case,1205``analyzeBranch`` (shown below) should return the destination of that1206conditional branch in the ``TBB`` parameter and a list of operands in the1207``Cond`` parameter to evaluate the condition.1208 1209.. code-block:: c++1210 1211 if (LastOpc == ARM::Bcc || LastOpc == ARM::tBcc) {1212 // Block ends with fall-through condbranch.1213 TBB = LastInst->getOperand(0).getMBB();1214 Cond.push_back(LastInst->getOperand(1));1215 Cond.push_back(LastInst->getOperand(2));1216 return false;1217 }1218 1219If a block ends with both a conditional branch and an ensuing unconditional1220branch, then ``analyzeBranch`` (shown below) should return the conditional1221branch destination (assuming it corresponds to a conditional evaluation of1222"``true``") in the ``TBB`` parameter and the unconditional branch destination1223in the ``FBB`` (corresponding to a conditional evaluation of "``false``"). A1224list of operands to evaluate the condition should be returned in the ``Cond``1225parameter.1226 1227.. code-block:: c++1228 1229 unsigned SecondLastOpc = SecondLastInst->getOpcode();1230 1231 if ((SecondLastOpc == ARM::Bcc && LastOpc == ARM::B) ||1232 (SecondLastOpc == ARM::tBcc && LastOpc == ARM::tB)) {1233 TBB = SecondLastInst->getOperand(0).getMBB();1234 Cond.push_back(SecondLastInst->getOperand(1));1235 Cond.push_back(SecondLastInst->getOperand(2));1236 FBB = LastInst->getOperand(0).getMBB();1237 return false;1238 }1239 1240For the last two cases (ending with a single conditional branch or ending with1241one conditional and one unconditional branch), the operands returned in the1242``Cond`` parameter can be passed to methods of other instructions to create new1243branches or perform other operations. An implementation of ``analyzeBranch``1244requires the helper methods ``removeBranch`` and ``insertBranch`` to manage1245subsequent operations.1246 1247``analyzeBranch`` should return false indicating success in most circumstances.1248``analyzeBranch`` should only return true when the method is stumped about what1249to do, for example, if a block has three terminating branches.1250``analyzeBranch`` may return true if it encounters a terminator it cannot1251handle, such as an indirect branch.1252 1253.. _instruction-selector:1254 1255Instruction Selector1256====================1257 1258LLVM uses a ``SelectionDAG`` to represent LLVM IR instructions, and nodes of1259the ``SelectionDAG`` ideally represent native target instructions. During code1260generation, instruction selection passes are performed to convert non-native1261DAG instructions into native target-specific instructions. The pass described1262in ``XXXISelDAGToDAG.cpp`` is used to match patterns and perform DAG-to-DAG1263instruction selection. Optionally, a pass may be defined (in1264``XXXBranchSelector.cpp``) to perform similar DAG-to-DAG operations for branch1265instructions. Later, the code in ``XXXISelLowering.cpp`` replaces or removes1266operations and data types not supported natively (legalizes) in a1267``SelectionDAG``.1268 1269TableGen generates code for instruction selection using the following target1270description input files:1271 1272* ``XXXInstrInfo.td`` --- Contains definitions of instructions in a1273 target-specific instruction set, generates ``XXXGenDAGISel.inc``, which is1274 included in ``XXXISelDAGToDAG.cpp``.1275 1276* ``XXXCallingConv.td`` --- Contains the calling and return value conventions1277 for the target architecture, and it generates ``XXXGenCallingConv.inc``,1278 which is included in ``XXXISelLowering.cpp``.1279 1280The implementation of an instruction selection pass must include a header that1281declares the ``FunctionPass`` class or a subclass of ``FunctionPass``. In1282``XXXTargetMachine.cpp``, a Pass Manager (PM) should add each instruction1283selection pass into the queue of passes to run.1284 1285The LLVM static compiler (``llc``) is an excellent tool for visualizing the1286contents of DAGs. To display the ``SelectionDAG`` before or after specific1287processing phases, use the command line options for ``llc``, described at1288:ref:`SelectionDAG-Process`.1289 1290To describe instruction selector behavior, you should add patterns for lowering1291LLVM code into a ``SelectionDAG`` as the last parameter of the instruction1292definitions in ``XXXInstrInfo.td``. For example, in ``SparcInstrInfo.td``,1293this entry defines a register store operation, and the last parameter describes1294a pattern with the store DAG operator.1295 1296.. code-block:: text1297 1298 def STrr : F3_1< 3, 0b000100, (outs), (ins MEMrr:$addr, IntRegs:$src),1299 "st $src, [$addr]", [(store i32:$src, ADDRrr:$addr)]>;1300 1301``ADDRrr`` is a memory mode that is also defined in ``SparcInstrInfo.td``:1302 1303.. code-block:: text1304 1305 def ADDRrr : ComplexPattern<i32, 2, "SelectADDRrr", [], []>;1306 1307The definition of ``ADDRrr`` refers to ``SelectADDRrr``, which is a function1308defined in an implementation of the Instructor Selector (such as1309``SparcISelDAGToDAG.cpp``).1310 1311In ``lib/Target/TargetSelectionDAG.td``, the DAG operator for store is defined1312below:1313 1314.. code-block:: text1315 1316 def store : PatFrag<(ops node:$val, node:$ptr),1317 (unindexedstore node:$val, node:$ptr)> {1318 let IsStore = true;1319 let IsTruncStore = false;1320 }1321 1322``XXXInstrInfo.td`` also generates (in ``XXXGenDAGISel.inc``) the1323``SelectCode`` method that is used to call the appropriate processing method1324for an instruction. In this example, ``SelectCode`` calls ``Select_ISD_STORE``1325for the ``ISD::STORE`` opcode.1326 1327.. code-block:: c++1328 1329 SDNode *SelectCode(SDValue N) {1330 ...1331 MVT::ValueType NVT = N.getNode()->getValueType(0);1332 switch (N.getOpcode()) {1333 case ISD::STORE: {1334 switch (NVT) {1335 default:1336 return Select_ISD_STORE(N);1337 break;1338 }1339 break;1340 }1341 ...1342 1343The pattern for ``STrr`` is matched, so elsewhere in ``XXXGenDAGISel.inc``,1344code for ``STrr`` is created for ``Select_ISD_STORE``. The ``Emit_22`` method1345is also generated in ``XXXGenDAGISel.inc`` to complete the processing of this1346instruction.1347 1348.. code-block:: c++1349 1350 SDNode *Select_ISD_STORE(const SDValue &N) {1351 SDValue Chain = N.getOperand(0);1352 if (Predicate_store(N.getNode())) {1353 SDValue N1 = N.getOperand(1);1354 SDValue N2 = N.getOperand(2);1355 SDValue CPTmp0;1356 SDValue CPTmp1;1357 1358 // Pattern: (st:void i32:i32:$src,1359 // ADDRrr:i32:$addr)<<P:Predicate_store>>1360 // Emits: (STrr:void ADDRrr:i32:$addr, IntRegs:i32:$src)1361 // Pattern complexity = 13 cost = 1 size = 01362 if (SelectADDRrr(N, N2, CPTmp0, CPTmp1) &&1363 N1.getNode()->getValueType(0) == MVT::i32 &&1364 N2.getNode()->getValueType(0) == MVT::i32) {1365 return Emit_22(N, SP::STrr, CPTmp0, CPTmp1);1366 }1367 ...1368 1369The SelectionDAG Legalize Phase1370-------------------------------1371 1372The Legalize phase converts a DAG to use types and operations that are natively1373supported by the target. For natively unsupported types and operations, you1374need to add code to the target-specific ``XXXTargetLowering`` implementation to1375convert unsupported types and operations to supported ones.1376 1377In the constructor for the ``XXXTargetLowering`` class, first use the1378``addRegisterClass`` method to specify which types are supported and which1379register classes are associated with them. The code for the register classes1380are generated by TableGen from ``XXXRegisterInfo.td`` and placed in1381``XXXGenRegisterInfo.h.inc``. For example, the implementation of the1382constructor for the SparcTargetLowering class (in ``SparcISelLowering.cpp``)1383starts with the following code:1384 1385.. code-block:: c++1386 1387 addRegisterClass(MVT::i32, SP::IntRegsRegisterClass);1388 addRegisterClass(MVT::f32, SP::FPRegsRegisterClass);1389 addRegisterClass(MVT::f64, SP::DFPRegsRegisterClass);1390 1391You should examine the node types in the ``ISD`` namespace1392(``include/llvm/CodeGen/SelectionDAGNodes.h``) and determine which operations1393the target natively supports. For operations that do **not** have native1394support, add a callback to the constructor for the ``XXXTargetLowering`` class,1395so the instruction selection process knows what to do. The ``TargetLowering``1396class callback methods (declared in ``llvm/Target/TargetLowering.h``) are:1397 1398* ``setOperationAction`` --- General operation.1399* ``setLoadExtAction`` --- Load with extension.1400* ``setTruncStoreAction`` --- Truncating store.1401* ``setIndexedLoadAction`` --- Indexed load.1402* ``setIndexedStoreAction`` --- Indexed store.1403* ``setConvertAction`` --- Type conversion.1404* ``setCondCodeAction`` --- Support for a given condition code.1405 1406Note: on older releases, ``setLoadXAction`` is used instead of1407``setLoadExtAction``. Also, on older releases, ``setCondCodeAction`` may not1408be supported. Examine your release to see what methods are specifically1409supported.1410 1411These callbacks are used to determine that an operation does or does not work1412with a specified type (or types). And in all cases, the third parameter is a1413``LegalAction`` type enum value: ``Promote``, ``Expand``, ``Custom``, or1414``Legal``. ``SparcISelLowering.cpp`` contains examples of all four1415``LegalAction`` values.1416 1417Promote1418^^^^^^^1419 1420For an operation without native support for a given type, the specified type1421may be promoted to a larger type that is supported. For example, SPARC does1422not support a sign-extending load for Boolean values (``i1`` type), so in1423``SparcISelLowering.cpp`` the third parameter below, ``Promote``, changes1424``i1`` type values to a large type before loading.1425 1426.. code-block:: c++1427 1428 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);1429 1430Expand1431^^^^^^1432 1433For a type without native support, a value may need to be broken down further,1434rather than promoted. For an operation without native support, a combination1435of other operations may be used to similar effect. In SPARC, the1436floating-point sine and cosine trig operations are supported by expansion to1437other operations, as indicated by the third parameter, ``Expand``, to1438``setOperationAction``:1439 1440.. code-block:: c++1441 1442 setOperationAction(ISD::FSIN, MVT::f32, Expand);1443 setOperationAction(ISD::FCOS, MVT::f32, Expand);1444 1445Custom1446^^^^^^1447 1448For some operations, simple type promotion or operation expansion may be1449insufficient. In some cases, a special intrinsic function must be implemented.1450 1451For example, a constant value may require special treatment, or an operation1452may require spilling and restoring registers in the stack and working with1453register allocators.1454 1455As seen in ``SparcISelLowering.cpp`` code below, to perform a type conversion1456from a floating point value to a signed integer, first the1457``setOperationAction`` should be called with ``Custom`` as the third parameter:1458 1459.. code-block:: c++1460 1461 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);1462 1463In the ``LowerOperation`` method, for each ``Custom`` operation, a case1464statement should be added to indicate what function to call. In the following1465code, an ``FP_TO_SINT`` opcode will call the ``LowerFP_TO_SINT`` method:1466 1467.. code-block:: c++1468 1469 SDValue SparcTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {1470 switch (Op.getOpcode()) {1471 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);1472 ...1473 }1474 }1475 1476Finally, the ``LowerFP_TO_SINT`` method is implemented, using an FP register to1477convert the floating-point value to an integer.1478 1479.. code-block:: c++1480 1481 static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {1482 assert(Op.getValueType() == MVT::i32);1483 Op = DAG.getNode(SPISD::FTOI, MVT::f32, Op.getOperand(0));1484 return DAG.getNode(ISD::BITCAST, MVT::i32, Op);1485 }1486 1487Legal1488^^^^^1489 1490The ``Legal`` ``LegalizeAction`` enum value simply indicates that an operation1491**is** natively supported. ``Legal`` represents the default condition, so it1492is rarely used. In ``SparcISelLowering.cpp``, the action for ``CTPOP`` (an1493operation to count the bits set in an integer) is natively supported only for1494SPARC v9. The following code enables the ``Expand`` conversion technique for1495non-v9 SPARC implementations.1496 1497.. code-block:: c++1498 1499 setOperationAction(ISD::CTPOP, MVT::i32, Expand);1500 ...1501 if (TM.getSubtarget<SparcSubtarget>().isV9())1502 setOperationAction(ISD::CTPOP, MVT::i32, Legal);1503 1504.. _backend-calling-convs:1505 1506Calling Conventions1507-------------------1508 1509To support target-specific calling conventions, ``XXXGenCallingConv.td`` uses1510interfaces (such as ``CCIfType`` and ``CCAssignToReg``) that are defined in1511``lib/Target/TargetCallingConv.td``. TableGen can take the target descriptor1512file ``XXXGenCallingConv.td`` and generate the header file1513``XXXGenCallingConv.inc``, which is typically included in1514``XXXISelLowering.cpp``. You can use the interfaces in1515``TargetCallingConv.td`` to specify:1516 1517* The order of parameter allocation.1518 1519* Where parameters and return values are placed (that is, on the stack or in1520 registers).1521 1522* Which registers may be used.1523 1524* Whether the caller or callee unwinds the stack.1525 1526The following example demonstrates the use of the ``CCIfType`` and1527``CCAssignToReg`` interfaces. If the ``CCIfType`` predicate is true (that is,1528if the current argument is of type ``f32`` or ``f64``), then the action is1529performed. In this case, the ``CCAssignToReg`` action assigns the argument1530value to the first available register: either ``R0`` or ``R1``.1531 1532.. code-block:: text1533 1534 CCIfType<[f32,f64], CCAssignToReg<[R0, R1]>>1535 1536``SparcCallingConv.td`` contains definitions for a target-specific return-value1537calling convention (``RetCC_Sparc32``) and a basic 32-bit C calling convention1538(``CC_Sparc32``). The definition of ``RetCC_Sparc32`` (shown below) indicates1539which registers are used for specified scalar return types. A single-precision1540float is returned to register ``F0``, and a double-precision float goes to1541register ``D0``. A 32-bit integer is returned in register ``I0`` or ``I1``.1542 1543.. code-block:: text1544 1545 def RetCC_Sparc32 : CallingConv<[1546 CCIfType<[i32], CCAssignToReg<[I0, I1]>>,1547 CCIfType<[f32], CCAssignToReg<[F0]>>,1548 CCIfType<[f64], CCAssignToReg<[D0]>>1549 ]>;1550 1551The definition of ``CC_Sparc32`` in ``SparcCallingConv.td`` introduces1552``CCAssignToStack``, which assigns the value to a stack slot with the specified1553size and alignment. In the example below, the first parameter, 4, indicates1554the size of the slot, and the second parameter, also 4, indicates the stack1555alignment along 4-byte units. (Special cases: if size is zero, then the ABI1556size is used; if alignment is zero, then the ABI alignment is used.)1557 1558.. code-block:: text1559 1560 def CC_Sparc32 : CallingConv<[1561 // All arguments get passed in integer registers if there is space.1562 CCIfType<[i32, f32, f64], CCAssignToReg<[I0, I1, I2, I3, I4, I5]>>,1563 CCAssignToStack<4, 4>1564 ]>;1565 1566``CCDelegateTo`` is another commonly used interface, which tries to find a1567specified sub-calling convention, and, if a match is found, it is invoked. In1568the following example (in ``X86CallingConv.td``), the definition of1569``RetCC_X86_32_C`` ends with ``CCDelegateTo``. After the current value is1570assigned to the register ``ST0`` or ``ST1``, the ``RetCC_X86Common`` is1571invoked.1572 1573.. code-block:: text1574 1575 def RetCC_X86_32_C : CallingConv<[1576 CCIfType<[f32], CCAssignToReg<[ST0, ST1]>>,1577 CCIfType<[f64], CCAssignToReg<[ST0, ST1]>>,1578 CCDelegateTo<RetCC_X86Common>1579 ]>;1580 1581``CCIfCC`` is an interface that attempts to match the given name to the current1582calling convention. If the name identifies the current calling convention,1583then a specified action is invoked. In the following example (in1584``X86CallingConv.td``), if the ``Fast`` calling convention is in use, then1585``RetCC_X86_32_Fast`` is invoked. If the ``SSECall`` calling convention is in1586use, then ``RetCC_X86_32_SSE`` is invoked.1587 1588.. code-block:: text1589 1590 def RetCC_X86_32 : CallingConv<[1591 CCIfCC<"CallingConv::Fast", CCDelegateTo<RetCC_X86_32_Fast>>,1592 CCIfCC<"CallingConv::X86_SSECall", CCDelegateTo<RetCC_X86_32_SSE>>,1593 CCDelegateTo<RetCC_X86_32_C>1594 ]>;1595 1596``CCAssignToRegAndStack`` is the same as ``CCAssignToReg``, but also allocates1597a stack slot, when some register is used. Basically, it works like:1598``CCIf<CCAssignToReg<regList>, CCAssignToStack<size, align>>``.1599 1600.. code-block:: text1601 1602 class CCAssignToRegAndStack<list<Register> regList, int size, int align>1603 : CCAssignToReg<regList> {1604 int Size = size;1605 int Align = align;1606 }1607 1608Other calling convention interfaces include:1609 1610* ``CCIf <predicate, action>`` --- If the predicate matches, apply the action.1611 1612* ``CCIfInReg <action>`` --- If the argument is marked with the "``inreg``"1613 attribute, then apply the action.1614 1615* ``CCIfNest <action>`` --- If the argument is marked with the "``nest``"1616 attribute, then apply the action.1617 1618* ``CCIfNotVarArg <action>`` --- If the current function does not take a1619 variable number of arguments, apply the action.1620 1621* ``CCAssignToRegWithShadow <registerList, shadowList>`` --- similar to1622 ``CCAssignToReg``, but with a shadow list of registers.1623 1624* ``CCPassByVal <size, align>`` --- Assign value to a stack slot with the1625 minimum specified size and alignment.1626 1627* ``CCPromoteToType <type>`` --- Promote the current value to the specified1628 type.1629 1630* ``CallingConv <[actions]>`` --- Define each calling convention that is1631 supported.1632 1633Assembly Printer1634================1635 1636During the code emission stage, the code generator may utilize an LLVM pass to1637produce assembly output. To do this, you want to implement the code for a1638printer that converts LLVM IR to a GAS-format assembly language for your target1639machine, using the following steps:1640 1641* Define all the assembly strings for your target, adding them to the1642 instructions defined in the ``XXXInstrInfo.td`` file. (See1643 :ref:`instruction-set`.) TableGen will produce an output file1644 (``XXXGenAsmWriter.inc``) with an implementation of the ``printInstruction``1645 method for the ``XXXAsmPrinter`` class.1646 1647* Write ``XXXTargetAsmInfo.h``, which contains the bare-bones declaration of1648 the ``XXXTargetAsmInfo`` class (a subclass of ``TargetAsmInfo``).1649 1650* Write ``XXXTargetAsmInfo.cpp``, which contains target-specific values for1651 ``TargetAsmInfo`` properties and sometimes new implementations for methods.1652 1653* Write ``XXXAsmPrinter.cpp``, which implements the ``AsmPrinter`` class that1654 performs the LLVM-to-assembly conversion.1655 1656The code in ``XXXTargetAsmInfo.h`` is usually a trivial declaration of the1657``XXXTargetAsmInfo`` class for use in ``XXXTargetAsmInfo.cpp``. Similarly,1658``XXXTargetAsmInfo.cpp`` usually has a few declarations of ``XXXTargetAsmInfo``1659replacement values that override the default values in ``TargetAsmInfo.cpp``.1660For example in ``SparcTargetAsmInfo.cpp``:1661 1662.. code-block:: c++1663 1664 SparcTargetAsmInfo::SparcTargetAsmInfo(const SparcTargetMachine &TM) {1665 Data16bitsDirective = "\t.half\t";1666 Data32bitsDirective = "\t.word\t";1667 Data64bitsDirective = 0; // .xword is only supported by V9.1668 ZeroDirective = "\t.skip\t";1669 CommentString = "!";1670 ConstantPoolSection = "\t.section \".rodata\",#alloc\n";1671 }1672 1673The X86 assembly printer implementation (``X86TargetAsmInfo``) is an example1674where the target-specific ``TargetAsmInfo`` class uses an overridden methods:1675``ExpandInlineAsm``.1676 1677A target-specific implementation of ``AsmPrinter`` is written in1678``XXXAsmPrinter.cpp``, which implements the ``AsmPrinter`` class that converts1679the LLVM to printable assembly. The implementation must include the following1680headers that have declarations for the ``AsmPrinter`` and1681``MachineFunctionPass`` classes. The ``MachineFunctionPass`` is a subclass of1682``FunctionPass``.1683 1684.. code-block:: c++1685 1686 #include "llvm/CodeGen/AsmPrinter.h"1687 #include "llvm/CodeGen/MachineFunctionPass.h"1688 1689As a ``FunctionPass``, ``AsmPrinter`` first calls ``doInitialization`` to set1690up the ``AsmPrinter``. In ``SparcAsmPrinter``, a ``Mangler`` object is1691instantiated to process variable names.1692 1693In ``XXXAsmPrinter.cpp``, the ``runOnMachineFunction`` method (declared in1694``MachineFunctionPass``) must be implemented for ``XXXAsmPrinter``. In1695``MachineFunctionPass``, the ``runOnFunction`` method invokes1696``runOnMachineFunction``. Target-specific implementations of1697``runOnMachineFunction`` differ, but generally do the following to process each1698machine function:1699 1700* Call ``SetupMachineFunction`` to perform initialization.1701 1702* Call ``EmitConstantPool`` to print out (to the output stream) constants which1703 have been spilled to memory.1704 1705* Call ``EmitJumpTableInfo`` to print out jump tables used by the current1706 function.1707 1708* Print out the label for the current function.1709 1710* Print out the code for the function, including basic block labels and the1711 assembly for the instruction (using ``printInstruction``)1712 1713The ``XXXAsmPrinter`` implementation must also include the code generated by1714TableGen that is output in the ``XXXGenAsmWriter.inc`` file. The code in1715``XXXGenAsmWriter.inc`` contains an implementation of the ``printInstruction``1716method that may call these methods:1717 1718* ``printOperand``1719* ``printMemOperand``1720* ``printCCOperand`` (for conditional statements)1721* ``printDataDirective``1722* ``printDeclare``1723* ``printImplicitDef``1724* ``printInlineAsm``1725 1726The implementations of ``printDeclare``, ``printImplicitDef``,1727``printInlineAsm``, and ``printLabel`` in ``AsmPrinter.cpp`` are generally1728adequate for printing assembly and do not need to be overridden.1729 1730The ``printOperand`` method is implemented with a long ``switch``/``case``1731statement for the type of operand: register, immediate, basic block, external1732symbol, global address, constant pool index, or jump table index. For an1733instruction with a memory address operand, the ``printMemOperand`` method1734should be implemented to generate the proper output. Similarly,1735``printCCOperand`` should be used to print a conditional operand.1736 1737``doFinalization`` should be overridden in ``XXXAsmPrinter``, and it should be1738called to shut down the assembly printer. During ``doFinalization``, global1739variables and constants are printed to output.1740 1741Subtarget Support1742=================1743 1744Subtarget support is used to inform the code generation process of instruction1745set variations for a given chip set. For example, the LLVM SPARC1746implementation provided covers three major versions of the SPARC microprocessor1747architecture: Version 8 (V8, which is a 32-bit architecture), Version 9 (V9, a174864-bit architecture), and the UltraSPARC architecture. V8 has 161749double-precision floating-point registers that are also usable as either 321750single-precision or 8 quad-precision registers. V8 is also purely big-endian.1751V9 has 32 double-precision floating-point registers that are also usable as 161752quad-precision registers, but cannot be used as single-precision registers.1753The UltraSPARC architecture combines V9 with UltraSPARC Visual Instruction Set1754extensions.1755 1756If subtarget support is needed, you should implement a target-specific1757``XXXSubtarget`` class for your architecture. This class should process the1758command-line options ``-mcpu=`` and ``-mattr=``.1759 1760TableGen uses definitions in the ``Target.td`` and ``Sparc.td`` files to1761generate code in ``SparcGenSubtarget.inc``. In ``Target.td``, shown below, the1762``SubtargetFeature`` interface is defined. The first 4 string parameters of1763the ``SubtargetFeature`` interface are a feature name, a XXXSubtarget field set1764by the feature, the value of the XXXSubtarget field, and a description of the1765feature. (The fifth parameter is a list of features whose presence is implied,1766and its default value is an empty array.)1767 1768If the value for the field is the string "true" or "false", the field1769is assumed to be a bool and only one SubtargetFeature should refer to it.1770Otherwise, it is assumed to be an integer. The integer value may be the name1771of an enum constant. If multiple features use the same integer field, the1772field will be set to the maximum value of all enabled features that share1773the field.1774 1775.. code-block:: text1776 1777 class SubtargetFeature<string n, string f, string v, string d,1778 list<SubtargetFeature> i = []> {1779 string Name = n;1780 string FieldName = f;1781 string Value = v;1782 string Desc = d;1783 list<SubtargetFeature> Implies = i;1784 }1785 1786In the ``Sparc.td`` file, the ``SubtargetFeature`` is used to define the1787following features.1788 1789.. code-block:: text1790 1791 def FeatureV9 : SubtargetFeature<"v9", "IsV9", "true",1792 "Enable SPARC-V9 instructions">;1793 def FeatureV8Deprecated : SubtargetFeature<"deprecated-v8",1794 "UseV8DeprecatedInsts", "true",1795 "Enable deprecated V8 instructions in V9 mode">;1796 def FeatureVIS : SubtargetFeature<"vis", "IsVIS", "true",1797 "Enable UltraSPARC Visual Instruction Set extensions">;1798 1799Elsewhere in ``Sparc.td``, the ``Proc`` class is defined and then is used to1800define particular SPARC processor subtypes that may have the previously1801described features.1802 1803.. code-block:: text1804 1805 class Proc<string Name, list<SubtargetFeature> Features>1806 : Processor<Name, NoItineraries, Features>;1807 1808 def : Proc<"generic", []>;1809 def : Proc<"v8", []>;1810 def : Proc<"supersparc", []>;1811 def : Proc<"sparclite", []>;1812 def : Proc<"f934", []>;1813 def : Proc<"hypersparc", []>;1814 def : Proc<"sparclite86x", []>;1815 def : Proc<"sparclet", []>;1816 def : Proc<"tsc701", []>;1817 def : Proc<"v9", [FeatureV9]>;1818 def : Proc<"ultrasparc", [FeatureV9, FeatureV8Deprecated]>;1819 def : Proc<"ultrasparc3", [FeatureV9, FeatureV8Deprecated]>;1820 def : Proc<"ultrasparc3-vis", [FeatureV9, FeatureV8Deprecated, FeatureVIS]>;1821 1822From ``Target.td`` and ``Sparc.td`` files, the resulting1823``SparcGenSubtarget.inc`` specifies enum values to identify the features,1824arrays of constants to represent the CPU features and CPU subtypes, and the1825``ParseSubtargetFeatures`` method that parses the features string that sets1826specified subtarget options. The generated ``SparcGenSubtarget.inc`` file1827should be included in the ``SparcSubtarget.cpp``. The target-specific1828implementation of the ``XXXSubtarget`` method should follow this pseudocode:1829 1830.. code-block:: c++1831 1832 XXXSubtarget::XXXSubtarget(const Module &M, const std::string &FS) {1833 // Set the default features1834 // Determine default and user specified characteristics of the CPU1835 // Call ParseSubtargetFeatures(FS, CPU) to parse the features string1836 // Perform any additional operations1837 }1838 1839JIT Support1840===========1841 1842The implementation of a target machine optionally includes a Just-In-Time (JIT)1843code generator that emits machine code and auxiliary structures as binary1844output that can be written directly to memory. To do this, implement JIT code1845generation by performing the following steps:1846 1847* Write an ``XXXCodeEmitter.cpp`` file that contains a machine function pass1848 that transforms target-machine instructions into relocatable machine1849 code.1850 1851* Write an ``XXXJITInfo.cpp`` file that implements the JIT interfaces for1852 target-specific code-generation activities, such as emitting machine code and1853 stubs.1854 1855* Modify ``XXXTargetMachine`` so that it provides a ``TargetJITInfo`` object1856 through its ``getJITInfo`` method.1857 1858There are several different approaches to writing the JIT support code. For1859instance, TableGen and target descriptor files may be used for creating a JIT1860code generator, but are not mandatory. For the Alpha and PowerPC target1861machines, TableGen is used to generate ``XXXGenCodeEmitter.inc``, which1862contains the binary coding of machine instructions and the1863``getBinaryCodeForInstr`` method to access those codes. Other JIT1864implementations do not.1865 1866Both ``XXXJITInfo.cpp`` and ``XXXCodeEmitter.cpp`` must include the1867``llvm/CodeGen/MachineCodeEmitter.h`` header file that defines the1868``MachineCodeEmitter`` class containing code for several callback functions1869that write data (in bytes, words, strings, etc.) to the output stream.1870 1871Machine Code Emitter1872--------------------1873 1874In ``XXXCodeEmitter.cpp``, a target-specific of the ``Emitter`` class is1875implemented as a function pass (subclass of ``MachineFunctionPass``). The1876target-specific implementation of ``runOnMachineFunction`` (invoked by1877``runOnFunction`` in ``MachineFunctionPass``) iterates through the1878``MachineBasicBlock`` calls ``emitInstruction`` to process each instruction and1879emit binary code. ``emitInstruction`` is largely implemented with case1880statements on the instruction types defined in ``XXXInstrInfo.h``. For1881example, in ``X86CodeEmitter.cpp``, the ``emitInstruction`` method is built1882around the following ``switch``/``case`` statements:1883 1884.. code-block:: c++1885 1886 switch (Desc->TSFlags & X86::FormMask) {1887 case X86II::Pseudo: // for not yet implemented instructions1888 ... // or pseudo-instructions1889 break;1890 case X86II::RawFrm: // for instructions with a fixed opcode value1891 ...1892 break;1893 case X86II::AddRegFrm: // for instructions that have one register operand1894 ... // added to their opcode1895 break;1896 case X86II::MRMDestReg:// for instructions that use the Mod/RM byte1897 ... // to specify a destination (register)1898 break;1899 case X86II::MRMDestMem:// for instructions that use the Mod/RM byte1900 ... // to specify a destination (memory)1901 break;1902 case X86II::MRMSrcReg: // for instructions that use the Mod/RM byte1903 ... // to specify a source (register)1904 break;1905 case X86II::MRMSrcMem: // for instructions that use the Mod/RM byte1906 ... // to specify a source (memory)1907 break;1908 case X86II::MRM0r: case X86II::MRM1r: // for instructions that operate on1909 case X86II::MRM2r: case X86II::MRM3r: // a REGISTER r/m operand and1910 case X86II::MRM4r: case X86II::MRM5r: // use the Mod/RM byte and a field1911 case X86II::MRM6r: case X86II::MRM7r: // to hold extended opcode data1912 ...1913 break;1914 case X86II::MRM0m: case X86II::MRM1m: // for instructions that operate on1915 case X86II::MRM2m: case X86II::MRM3m: // a MEMORY r/m operand and1916 case X86II::MRM4m: case X86II::MRM5m: // use the Mod/RM byte and a field1917 case X86II::MRM6m: case X86II::MRM7m: // to hold extended opcode data1918 ...1919 break;1920 case X86II::MRMInitReg: // for instructions whose source and1921 ... // destination are the same register1922 break;1923 }1924 1925The implementations of these case statements often first emit the opcode and1926then get the operand(s). Then depending upon the operand, helper methods may1927be called to process the operand(s). For example, in ``X86CodeEmitter.cpp``,1928for the ``X86II::AddRegFrm`` case, the first data emitted (by ``emitByte``) is1929the opcode added to the register operand. Then an object representing the1930machine operand, ``MO1``, is extracted. The helper methods such as1931``isImmediate``, ``isGlobalAddress``, ``isExternalSymbol``,1932``isConstantPoolIndex``, and ``isJumpTableIndex`` determine the operand type.1933(``X86CodeEmitter.cpp`` also has private methods such as ``emitConstant``,1934``emitGlobalAddress``, ``emitExternalSymbolAddress``, ``emitConstPoolAddress``,1935and ``emitJumpTableAddress`` that emit the data into the output stream.)1936 1937.. code-block:: c++1938 1939 case X86II::AddRegFrm:1940 MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++).getReg()));1941 1942 if (CurOp != NumOps) {1943 const MachineOperand &MO1 = MI.getOperand(CurOp++);1944 unsigned Size = X86InstrInfo::sizeOfImm(Desc);1945 if (MO1.isImmediate())1946 emitConstant(MO1.getImm(), Size);1947 else {1948 unsigned rt = Is64BitMode ? X86::reloc_pcrel_word1949 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);1950 if (Opcode == X86::MOV64ri)1951 rt = X86::reloc_absolute_dword; // FIXME: add X86II flag?1952 if (MO1.isGlobalAddress()) {1953 bool NeedStub = isa<Function>(MO1.getGlobal());1954 bool isLazy = gvNeedsLazyPtr(MO1.getGlobal());1955 emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,1956 NeedStub, isLazy);1957 } else if (MO1.isExternalSymbol())1958 emitExternalSymbolAddress(MO1.getSymbolName(), rt);1959 else if (MO1.isConstantPoolIndex())1960 emitConstPoolAddress(MO1.getIndex(), rt);1961 else if (MO1.isJumpTableIndex())1962 emitJumpTableAddress(MO1.getIndex(), rt);1963 }1964 }1965 break;1966 1967In the previous example, ``XXXCodeEmitter.cpp`` uses the variable ``rt``, which1968is a ``RelocationType`` enum that may be used to relocate addresses (for1969example, a global address with a PIC base offset). The ``RelocationType`` enum1970for that target is defined in the short target-specific ``XXXRelocations.h``1971file. The ``RelocationType`` is used by the ``relocate`` method defined in1972``XXXJITInfo.cpp`` to rewrite addresses for referenced global symbols.1973 1974For example, ``X86Relocations.h`` specifies the following relocation types for1975the X86 addresses. In all four cases, the relocated value is added to the1976value already in memory. For ``reloc_pcrel_word`` and ``reloc_picrel_word``,1977there is an additional initial adjustment.1978 1979.. code-block:: c++1980 1981 enum RelocationType {1982 reloc_pcrel_word = 0, // add reloc value after adjusting for the PC loc1983 reloc_picrel_word = 1, // add reloc value after adjusting for the PIC base1984 reloc_absolute_word = 2, // absolute relocation; no additional adjustment1985 reloc_absolute_dword = 3 // absolute relocation; no additional adjustment1986 };1987 1988Target JIT Info1989---------------1990 1991``XXXJITInfo.cpp`` implements the JIT interfaces for target-specific1992code-generation activities, such as emitting machine code and stubs. At1993minimum, a target-specific version of ``XXXJITInfo`` implements the following:1994 1995* ``getLazyResolverFunction`` --- Initializes the JIT, gives the target a1996 function that is used for compilation.1997 1998* ``emitFunctionStub`` --- Returns a native function with a specified address1999 for a callback function.2000 2001* ``relocate`` --- Changes the addresses of referenced globals, based on2002 relocation types.2003 2004* Callback function that are wrappers to a function stub that is used when the2005 real target is not initially known.2006 2007``getLazyResolverFunction`` is generally trivial to implement. It makes the2008incoming parameter as the global ``JITCompilerFunction`` and returns the2009callback function that will be used a function wrapper. For the Alpha target2010(in ``AlphaJITInfo.cpp``), the ``getLazyResolverFunction`` implementation is2011simply:2012 2013.. code-block:: c++2014 2015 TargetJITInfo::LazyResolverFn AlphaJITInfo::getLazyResolverFunction(2016 JITCompilerFn F) {2017 JITCompilerFunction = F;2018 return AlphaCompilationCallback;2019 }2020 2021For the X86 target, the ``getLazyResolverFunction`` implementation is a little2022more complicated, because it returns a different callback function for2023processors with SSE instructions and XMM registers.2024 2025The callback function initially saves and later restores the callee register2026values, incoming arguments, and frame and return address. The callback2027function needs low-level access to the registers or stack, so it is typically2028implemented with assembler.2029