1======================= 2Writing an LLVM Backend 3======================= 4 5.. toctree:: 6 :hidden: 7 8 HowToUseInstrMappings 9 10.. contents:: 11 :local: 12 13Introduction 14============ 15 16This document describes techniques for writing compiler backends that convert 17the LLVM Intermediate Representation (IR) to code for a specified machine or 18other languages. Code intended for a specific machine can take the form of 19either assembly code or binary code (usable for a JIT compiler). 20 21The backend of LLVM features a target-independent code generator that may 22create output for several types of target CPUs --- including X86, PowerPC, 23ARM, and SPARC. The backend may also be used to generate code targeted at SPUs 24of the Cell processor or GPUs to support the execution of compute kernels. 25 26The document focuses on existing examples found in subdirectories of 27``llvm/lib/Target`` in a downloaded LLVM release. In particular, this document 28focuses on the example of creating a static compiler (one that emits text 29assembly) for a SPARC target, because SPARC has fairly standard 30characteristics, such as a RISC instruction set and straightforward calling 31conventions. 32 33Audience 34-------- 35 36The audience for this document is anyone who needs to write an LLVM backend to 37generate code for a specific hardware or software target. 38 39Prerequisite Reading 40-------------------- 41 42These essential documents must be read before reading this document: 43 44* `LLVM Language Reference Manual <LangRef.html>`_ --- a reference manual for 45 the LLVM assembly language. 46 47* :doc:`CodeGenerator` --- a guide to the components (classes and code 48 generation algorithms) for translating the LLVM internal representation into 49 machine code for a specified target. Pay particular attention to the 50 descriptions of code generation stages: Instruction Selection, Scheduling and 51 Formation, SSA-based Optimization, Register Allocation, Prolog/Epilog Code 52 Insertion, Late Machine Code Optimizations, and Code Emission. 53 54* :doc:`TableGenFundamentals` --- a document that describes the TableGen 55 (``tblgen``) application that manages domain-specific information to support 56 LLVM code generation. TableGen processes input from a target description 57 file (``.td`` suffix) and generates C++ code that can be used for code 58 generation. 59 60* :doc:`WritingAnLLVMPass` --- The assembly printer is a ``FunctionPass``, as 61 are several ``SelectionDAG`` processing steps. 62 63To follow the SPARC examples in this document, have a copy of `The SPARC 64Architecture Manual, Version 8 <http://www.sparc.org/standards/V8.pdf>`_ for 65reference. For details about the ARM instruction set, refer to the `ARM 66Architecture Reference Manual <http://infocenter.arm.com/>`_. For more about 67the GNU Assembler format (``GAS``), see `Using As 68<http://sourceware.org/binutils/docs/as/index.html>`_, especially for the 69assembly printer. "Using As" contains a list of target machine dependent 70features. 71 72Basic Steps 73----------- 74 75To write a compiler backend for LLVM that converts the LLVM IR to code for a 76specified target (machine or other language), follow these steps: 77 78* Create a subclass of the ``TargetMachine`` class that describes 79 characteristics of your target machine. Copy existing examples of specific 80 ``TargetMachine`` class and header files; for example, start with 81 ``SparcTargetMachine.cpp`` and ``SparcTargetMachine.h``, but change the file 82 names for your target. Similarly, change code that references "``Sparc``" to 83 reference your target. 84 85* Describe the register set of the target. Use TableGen to generate code for 86 register definition, register aliases, and register classes from a 87 target-specific ``RegisterInfo.td`` input file. You should also write 88 additional code for a subclass of the ``TargetRegisterInfo`` class that 89 represents the class register file data used for register allocation and also 90 describes the interactions between registers. 91 92* Describe the instruction set of the target. Use TableGen to generate code 93 for target-specific instructions from target-specific versions of 94 ``TargetInstrFormats.td`` and ``TargetInstrInfo.td``. You should write 95 additional code for a subclass of the ``TargetInstrInfo`` class to represent 96 machine instructions supported by the target machine. 97 98* Describe the selection and conversion of the LLVM IR from a Directed Acyclic 99 Graph (DAG) representation of instructions to native target-specific 100 instructions. Use TableGen to generate code that matches patterns and 101 selects instructions based on additional information in a target-specific 102 version of ``TargetInstrInfo.td``. Write code for ``XXXISelDAGToDAG.cpp``, 103 where ``XXX`` identifies the specific target, to perform pattern matching and 104 DAG-to-DAG instruction selection. Also write code in ``XXXISelLowering.cpp`` 105 to replace or remove operations and data types that are not supported 106 natively in a SelectionDAG. 107 108* Write code for an assembly printer that converts LLVM IR to a GAS format for 109 your target machine. You should add assembly strings to the instructions 110 defined in your target-specific version of ``TargetInstrInfo.td``. You 111 should also write code for a subclass of ``AsmPrinter`` that performs the 112 LLVM-to-assembly conversion and a trivial subclass of ``TargetAsmInfo``. 113 114* Optionally, add support for subtargets (i.e., variants with different 115 capabilities). You should also write code for a subclass of the 116 ``TargetSubtarget`` class, which allows you to use the ``-mcpu=`` and 117 ``-mattr=`` command-line options. 118 119* Optionally, add JIT support and create a machine code emitter (subclass of 120 ``TargetJITInfo``) that is used to emit binary code directly into memory. 121 122In the ``.cpp`` and ``.h``. files, initially stub up these methods and then 123implement them later. Initially, you may not know which private members that 124the class will need and which components will need to be subclassed. 125 126Preliminaries 127------------- 128 129To actually create your compiler backend, you need to create and modify a few 130files. The absolute minimum is discussed here. But to actually use the LLVM 131target-independent code generator, you must perform the steps described in the 132:doc:`LLVM Target-Independent Code Generator <CodeGenerator>` document. 133 134First, you should create a subdirectory under ``lib/Target`` to hold all the 135files related to your target. If your target is called "Dummy", create the 136directory ``lib/Target/Dummy``. 137 138In this new directory, create a ``Makefile``. It is easiest to copy a 139``Makefile`` of another target and modify it. It should at least contain the 140``LEVEL``, ``LIBRARYNAME`` and ``TARGET`` variables, and then include 141``$(LEVEL)/Makefile.common``. The library can be named ``LLVMDummy`` (for 142example, see the MIPS target). Alternatively, you can split the library into 143``LLVMDummyCodeGen`` and ``LLVMDummyAsmPrinter``, the latter of which should be 144implemented in a subdirectory below ``lib/Target/Dummy`` (for example, see the 145PowerPC target). 146 147Note that these two naming schemes are hardcoded into ``llvm-config``. Using 148any other naming scheme will confuse ``llvm-config`` and produce a lot of 149(seemingly unrelated) linker errors when linking ``llc``. 150 151To make your target actually do something, you need to implement a subclass of 152``TargetMachine``. This implementation should typically be in the file 153``lib/Target/DummyTargetMachine.cpp``, but any file in the ``lib/Target`` 154directory will be built and should work. To use LLVM's target independent code 155generator, you should do what all current machine backends do: create a 156subclass of ``LLVMTargetMachine``. (To create a target from scratch, create a 157subclass of ``TargetMachine``.) 158 159To get LLVM to actually build and link your target, you need to add it to the 160``TARGETS_TO_BUILD`` variable. To do this, you modify the configure script to 161know about your target when parsing the ``--enable-targets`` option. Search 162the configure script for ``TARGETS_TO_BUILD``, add your target to the lists 163there (some creativity required), and then reconfigure. Alternatively, you can 164change ``autotools/configure.ac`` and regenerate configure by running 165``./autoconf/AutoRegen.sh``. 166 167Target Machine 168============== 169 170``LLVMTargetMachine`` is designed as a base class for targets implemented with 171the LLVM target-independent code generator. The ``LLVMTargetMachine`` class 172should be specialized by a concrete target class that implements the various 173virtual methods. ``LLVMTargetMachine`` is defined as a subclass of 174``TargetMachine`` in ``include/llvm/Target/TargetMachine.h``. The 175``TargetMachine`` class implementation (``TargetMachine.cpp``) also processes 176numerous command-line options. 177 178To create a concrete target-specific subclass of ``LLVMTargetMachine``, start 179by copying an existing ``TargetMachine`` class and header. You should name the 180files that you create to reflect your specific target. For instance, for the 181SPARC target, name the files ``SparcTargetMachine.h`` and 182``SparcTargetMachine.cpp``. 183 184For a target machine ``XXX``, the implementation of ``XXXTargetMachine`` must 185have access methods to obtain objects that represent target components. These 186methods are named ``get*Info``, and are intended to obtain the instruction set 187(``getInstrInfo``), register set (``getRegisterInfo``), stack frame layout 188(``getFrameInfo``), and similar information. ``XXXTargetMachine`` must also 189implement the ``getDataLayout`` method to access an object with target-specific 190data characteristics, such as data type size and alignment requirements. 191 192For instance, for the SPARC target, the header file ``SparcTargetMachine.h`` 193declares prototypes for several ``get*Info`` and ``getDataLayout`` methods that 194simply return a class member. 195 196.. code-block:: c++ 197 198 namespace llvm { 199 200 class Module; 201 202 class SparcTargetMachine : public LLVMTargetMachine { 203 const DataLayout DataLayout; // Calculates type size & alignment 204 SparcSubtarget Subtarget; 205 SparcInstrInfo InstrInfo; 206 TargetFrameInfo FrameInfo; 207 208 protected: 209 virtual const TargetAsmInfo *createTargetAsmInfo() const; 210 211 public: 212 SparcTargetMachine(const Module &M, const std::string &FS); 213 214 virtual const SparcInstrInfo *getInstrInfo() const {return &InstrInfo; } 215 virtual const TargetFrameInfo *getFrameInfo() const {return &FrameInfo; } 216 virtual const TargetSubtarget *getSubtargetImpl() const{return &Subtarget; } 217 virtual const TargetRegisterInfo *getRegisterInfo() const { 218 return &InstrInfo.getRegisterInfo(); 219 } 220 virtual const DataLayout *getDataLayout() const { return &DataLayout; } 221 static unsigned getModuleMatchQuality(const Module &M); 222 223 // Pass Pipeline Configuration 224 virtual bool addInstSelector(PassManagerBase &PM, bool Fast); 225 virtual bool addPreEmitPass(PassManagerBase &PM, bool Fast); 226 }; 227 228 } // end namespace llvm 229 230* ``getInstrInfo()`` 231* ``getRegisterInfo()`` 232* ``getFrameInfo()`` 233* ``getDataLayout()`` 234* ``getSubtargetImpl()`` 235 236For some targets, you also need to support the following methods: 237 238* ``getTargetLowering()`` 239* ``getJITInfo()`` 240 241In addition, the ``XXXTargetMachine`` constructor should specify a 242``TargetDescription`` string that determines the data layout for the target 243machine, including characteristics such as pointer size, alignment, and 244endianness. For example, the constructor for ``SparcTargetMachine`` contains 245the following: 246 247.. code-block:: c++ 248 249 SparcTargetMachine::SparcTargetMachine(const Module &M, const std::string &FS) 250 : DataLayout("E-p:32:32-f128:128:128"), 251 Subtarget(M, FS), InstrInfo(Subtarget), 252 FrameInfo(TargetFrameInfo::StackGrowsDown, 8, 0) { 253 } 254 255Hyphens separate portions of the ``TargetDescription`` string. 256 257* An upper-case "``E``" in the string indicates a big-endian target data model. 258 A lower-case "``e``" indicates little-endian. 259 260* "``p:``" is followed by pointer information: size, ABI alignment, and 261 preferred alignment. If only two figures follow "``p:``", then the first 262 value is pointer size, and the second value is both ABI and preferred 263 alignment. 264 265* Then a letter for numeric type alignment: "``i``", "``f``", "``v``", or 266 "``a``" (corresponding to integer, floating point, vector, or aggregate). 267 "``i``", "``v``", or "``a``" are followed by ABI alignment and preferred 268 alignment. "``f``" is followed by three values: the first indicates the size 269 of a long double, then ABI alignment, and then ABI preferred alignment. 270 271Target Registration 272=================== 273 274You must also register your target with the ``TargetRegistry``, which is what 275other LLVM tools use to be able to lookup and use your target at runtime. The 276``TargetRegistry`` can be used directly, but for most targets there are helper 277templates which should take care of the work for you. 278 279All targets should declare a global ``Target`` object which is used to 280represent the target during registration. Then, in the target's ``TargetInfo`` 281library, the target should define that object and use the ``RegisterTarget`` 282template to register the target. For example, the Sparc registration code 283looks like this: 284 285.. code-block:: c++ 286 287 Target llvm::TheSparcTarget; 288 289 extern "C" void LLVMInitializeSparcTargetInfo() { 290 RegisterTarget<Triple::sparc, /*HasJIT=*/false> 291 X(TheSparcTarget, "sparc", "Sparc"); 292 } 293 294This allows the ``TargetRegistry`` to look up the target by name or by target 295triple. In addition, most targets will also register additional features which 296are available in separate libraries. These registration steps are separate, 297because some clients may wish to only link in some parts of the target --- the 298JIT code generator does not require the use of the assembler printer, for 299example. Here is an example of registering the Sparc assembly printer: 300 301.. code-block:: c++ 302 303 extern "C" void LLVMInitializeSparcAsmPrinter() { 304 RegisterAsmPrinter<SparcAsmPrinter> X(TheSparcTarget); 305 } 306 307For more information, see "`llvm/Target/TargetRegistry.h 308</doxygen/TargetRegistry_8h-source.html>`_". 309 310Register Set and Register Classes 311================================= 312 313You should describe a concrete target-specific class that represents the 314register file of a target machine. This class is called ``XXXRegisterInfo`` 315(where ``XXX`` identifies the target) and represents the class register file 316data that is used for register allocation. It also describes the interactions 317between registers. 318 319You also need to define register classes to categorize related registers. A 320register class should be added for groups of registers that are all treated the 321same way for some instruction. Typical examples are register classes for 322integer, floating-point, or vector registers. A register allocator allows an 323instruction to use any register in a specified register class to perform the 324instruction in a similar manner. Register classes allocate virtual registers 325to instructions from these sets, and register classes let the 326target-independent register allocator automatically choose the actual 327registers. 328 329Much of the code for registers, including register definition, register 330aliases, and register classes, is generated by TableGen from 331``XXXRegisterInfo.td`` input files and placed in ``XXXGenRegisterInfo.h.inc`` 332and ``XXXGenRegisterInfo.inc`` output files. Some of the code in the 333implementation of ``XXXRegisterInfo`` requires hand-coding. 334 335Defining a Register 336------------------- 337 338The ``XXXRegisterInfo.td`` file typically starts with register definitions for 339a target machine. The ``Register`` class (specified in ``Target.td``) is used 340to define an object for each register. The specified string ``n`` becomes the 341``Name`` of the register. The basic ``Register`` object does not have any 342subregisters and does not specify any aliases. 343 344.. code-block:: llvm 345 346 class Register<string n> { 347 string Namespace = ""; 348 string AsmName = n; 349 string Name = n; 350 int SpillSize = 0; 351 int SpillAlignment = 0; 352 list<Register> Aliases = []; 353 list<Register> SubRegs = []; 354 list<int> DwarfNumbers = []; 355 } 356 357For example, in the ``X86RegisterInfo.td`` file, there are register definitions 358that utilize the ``Register`` class, such as: 359 360.. code-block:: llvm 361 362 def AL : Register<"AL">, DwarfRegNum<[0, 0, 0]>; 363 364This defines the register ``AL`` and assigns it values (with ``DwarfRegNum``) 365that are used by ``gcc``, ``gdb``, or a debug information writer to identify a 366register. For register ``AL``, ``DwarfRegNum`` takes an array of 3 values 367representing 3 different modes: the first element is for X86-64, the second for 368exception handling (EH) on X86-32, and the third is generic. -1 is a special 369Dwarf number that indicates the gcc number is undefined, and -2 indicates the 370register number is invalid for this mode. 371 372From the previously described line in the ``X86RegisterInfo.td`` file, TableGen 373generates this code in the ``X86GenRegisterInfo.inc`` file: 374 375.. code-block:: c++ 376 377 static const unsigned GR8[] = { X86::AL, ... }; 378 379 const unsigned AL_AliasSet[] = { X86::AX, X86::EAX, X86::RAX, 0 }; 380 381 const TargetRegisterDesc RegisterDescriptors[] = { 382 ... 383 { "AL", "AL", AL_AliasSet, Empty_SubRegsSet, Empty_SubRegsSet, AL_SuperRegsSet }, ... 384 385From the register info file, TableGen generates a ``TargetRegisterDesc`` object 386for each register. ``TargetRegisterDesc`` is defined in 387``include/llvm/Target/TargetRegisterInfo.h`` with the following fields: 388 389.. code-block:: c++ 390 391 struct TargetRegisterDesc { 392 const char *AsmName; // Assembly language name for the register 393 const char *Name; // Printable name for the reg (for debugging) 394 const unsigned *AliasSet; // Register Alias Set 395 const unsigned *SubRegs; // Sub-register set 396 const unsigned *ImmSubRegs; // Immediate sub-register set 397 const unsigned *SuperRegs; // Super-register set 398 }; 399 400TableGen uses the entire target description file (``.td``) to determine text 401names for the register (in the ``AsmName`` and ``Name`` fields of 402``TargetRegisterDesc``) and the relationships of other registers to the defined 403register (in the other ``TargetRegisterDesc`` fields). In this example, other 404definitions establish the registers "``AX``", "``EAX``", and "``RAX``" as 405aliases for one another, so TableGen generates a null-terminated array 406(``AL_AliasSet``) for this register alias set. 407 408The ``Register`` class is commonly used as a base class for more complex 409classes. In ``Target.td``, the ``Register`` class is the base for the 410``RegisterWithSubRegs`` class that is used to define registers that need to 411specify subregisters in the ``SubRegs`` list, as shown here: 412 413.. code-block:: llvm 414 415 class RegisterWithSubRegs<string n, list<Register> subregs> : Register<n> { 416 let SubRegs = subregs; 417 } 418 419In ``SparcRegisterInfo.td``, additional register classes are defined for SPARC: 420a ``Register`` subclass, ``SparcReg``, and further subclasses: ``Ri``, ``Rf``, 421and ``Rd``. SPARC registers are identified by 5-bit ID numbers, which is a 422feature common to these subclasses. Note the use of "``let``" expressions to 423override values that are initially defined in a superclass (such as ``SubRegs`` 424field in the ``Rd`` class). 425 426.. code-block:: llvm 427 428 class SparcReg<string n> : Register<n> { 429 field bits<5> Num; 430 let Namespace = "SP"; 431 } 432 // Ri - 32-bit integer registers 433 class Ri<bits<5> num, string n> : 434 SparcReg<n> { 435 let Num = num; 436 } 437 // Rf - 32-bit floating-point registers 438 class Rf<bits<5> num, string n> : 439 SparcReg<n> { 440 let Num = num; 441 } 442 // Rd - Slots in the FP register file for 64-bit floating-point values. 443 class Rd<bits<5> num, string n, list<Register> subregs> : SparcReg<n> { 444 let Num = num; 445 let SubRegs = subregs; 446 } 447 448In the ``SparcRegisterInfo.td`` file, there are register definitions that 449utilize these subclasses of ``Register``, such as: 450 451.. code-block:: llvm 452 453 def G0 : Ri< 0, "G0">, DwarfRegNum<[0]>; 454 def G1 : Ri< 1, "G1">, DwarfRegNum<[1]>; 455 ... 456 def F0 : Rf< 0, "F0">, DwarfRegNum<[32]>; 457 def F1 : Rf< 1, "F1">, DwarfRegNum<[33]>; 458 ... 459 def D0 : Rd< 0, "F0", [F0, F1]>, DwarfRegNum<[32]>; 460 def D1 : Rd< 2, "F2", [F2, F3]>, DwarfRegNum<[34]>; 461 462The last two registers shown above (``D0`` and ``D1``) are double-precision 463floating-point registers that are aliases for pairs of single-precision 464floating-point sub-registers. In addition to aliases, the sub-register and 465super-register relationships of the defined register are in fields of a 466register's ``TargetRegisterDesc``. 467 468Defining a Register Class 469------------------------- 470 471The ``RegisterClass`` class (specified in ``Target.td``) is used to define an 472object that represents a group of related registers and also defines the 473default allocation order of the registers. A target description file 474``XXXRegisterInfo.td`` that uses ``Target.td`` can construct register classes 475using the following class: 476 477.. code-block:: llvm 478 479 class RegisterClass<string namespace, 480 list<ValueType> regTypes, int alignment, dag regList> { 481 string Namespace = namespace; 482 list<ValueType> RegTypes = regTypes; 483 int Size = 0; // spill size, in bits; zero lets tblgen pick the size 484 int Alignment = alignment; 485 486 // CopyCost is the cost of copying a value between two registers 487 // default value 1 means a single instruction 488 // A negative value means copying is extremely expensive or impossible 489 int CopyCost = 1; 490 dag MemberList = regList; 491 492 // for register classes that are subregisters of this class 493 list<RegisterClass> SubRegClassList = []; 494 495 code MethodProtos = [{}]; // to insert arbitrary code 496 code MethodBodies = [{}]; 497 } 498 499To define a ``RegisterClass``, use the following 4 arguments: 500 501* The first argument of the definition is the name of the namespace. 502 503* The second argument is a list of ``ValueType`` register type values that are 504 defined in ``include/llvm/CodeGen/ValueTypes.td``. Defined values include 505 integer types (such as ``i16``, ``i32``, and ``i1`` for Boolean), 506 floating-point types (``f32``, ``f64``), and vector types (for example, 507 ``v8i16`` for an ``8 x i16`` vector). All registers in a ``RegisterClass`` 508 must have the same ``ValueType``, but some registers may store vector data in 509 different configurations. For example a register that can process a 128-bit 510 vector may be able to handle 16 8-bit integer elements, 8 16-bit integers, 4 511 32-bit integers, and so on. 512 513* The third argument of the ``RegisterClass`` definition specifies the 514 alignment required of the registers when they are stored or loaded to 515 memory. 516 517* The final argument, ``regList``, specifies which registers are in this class. 518 If an alternative allocation order method is not specified, then ``regList`` 519 also defines the order of allocation used by the register allocator. Besides 520 simply listing registers with ``(add R0, R1, ...)``, more advanced set 521 operators are available. See ``include/llvm/Target/Target.td`` for more 522 information. 523 524In ``SparcRegisterInfo.td``, three ``RegisterClass`` objects are defined: 525``FPRegs``, ``DFPRegs``, and ``IntRegs``. For all three register classes, the 526first argument defines the namespace with the string "``SP``". ``FPRegs`` 527defines a group of 32 single-precision floating-point registers (``F0`` to 528``F31``); ``DFPRegs`` defines a group of 16 double-precision registers 529(``D0-D15``). 530 531.. code-block:: llvm 532 533 // F0, F1, F2, ..., F31 534 def FPRegs : RegisterClass<"SP", [f32], 32, (sequence "F%u", 0, 31)>; 535 536 def DFPRegs : RegisterClass<"SP", [f64], 64, 537 (add D0, D1, D2, D3, D4, D5, D6, D7, D8, 538 D9, D10, D11, D12, D13, D14, D15)>; 539 540 def IntRegs : RegisterClass<"SP", [i32], 32, 541 (add L0, L1, L2, L3, L4, L5, L6, L7, 542 I0, I1, I2, I3, I4, I5, 543 O0, O1, O2, O3, O4, O5, O7, 544 G1, 545 // Non-allocatable regs: 546 G2, G3, G4, 547 O6, // stack ptr 548 I6, // frame ptr 549 I7, // return address 550 G0, // constant zero 551 G5, G6, G7 // reserved for kernel 552 )>; 553 554Using ``SparcRegisterInfo.td`` with TableGen generates several output files 555that are intended for inclusion in other source code that you write. 556``SparcRegisterInfo.td`` generates ``SparcGenRegisterInfo.h.inc``, which should 557be included in the header file for the implementation of the SPARC register 558implementation that you write (``SparcRegisterInfo.h``). In 559``SparcGenRegisterInfo.h.inc`` a new structure is defined called 560``SparcGenRegisterInfo`` that uses ``TargetRegisterInfo`` as its base. It also 561specifies types, based upon the defined register classes: ``DFPRegsClass``, 562``FPRegsClass``, and ``IntRegsClass``. 563 564``SparcRegisterInfo.td`` also generates ``SparcGenRegisterInfo.inc``, which is 565included at the bottom of ``SparcRegisterInfo.cpp``, the SPARC register 566implementation. The code below shows only the generated integer registers and 567associated register classes. The order of registers in ``IntRegs`` reflects 568the order in the definition of ``IntRegs`` in the target description file. 569 570.. code-block:: c++ 571 572 // IntRegs Register Class... 573 static const unsigned IntRegs[] = { 574 SP::L0, SP::L1, SP::L2, SP::L3, SP::L4, SP::L5, 575 SP::L6, SP::L7, SP::I0, SP::I1, SP::I2, SP::I3, 576 SP::I4, SP::I5, SP::O0, SP::O1, SP::O2, SP::O3, 577 SP::O4, SP::O5, SP::O7, SP::G1, SP::G2, SP::G3, 578 SP::G4, SP::O6, SP::I6, SP::I7, SP::G0, SP::G5, 579 SP::G6, SP::G7, 580 }; 581 582 // IntRegsVTs Register Class Value Types... 583 static const MVT::ValueType IntRegsVTs[] = { 584 MVT::i32, MVT::Other 585 }; 586 587 namespace SP { // Register class instances 588 DFPRegsClass DFPRegsRegClass; 589 FPRegsClass FPRegsRegClass; 590 IntRegsClass IntRegsRegClass; 591 ... 592 // IntRegs Sub-register Classess... 593 static const TargetRegisterClass* const IntRegsSubRegClasses [] = { 594 NULL 595 }; 596 ... 597 // IntRegs Super-register Classess... 598 static const TargetRegisterClass* const IntRegsSuperRegClasses [] = { 599 NULL 600 }; 601 ... 602 // IntRegs Register Class sub-classes... 603 static const TargetRegisterClass* const IntRegsSubclasses [] = { 604 NULL 605 }; 606 ... 607 // IntRegs Register Class super-classes... 608 static const TargetRegisterClass* const IntRegsSuperclasses [] = { 609 NULL 610 }; 611 612 IntRegsClass::IntRegsClass() : TargetRegisterClass(IntRegsRegClassID, 613 IntRegsVTs, IntRegsSubclasses, IntRegsSuperclasses, IntRegsSubRegClasses, 614 IntRegsSuperRegClasses, 4, 4, 1, IntRegs, IntRegs + 32) {} 615 } 616 617The register allocators will avoid using reserved registers, and callee saved 618registers are not used until all the volatile registers have been used. That 619is usually good enough, but in some cases it may be necessary to provide custom 620allocation orders. 621 622Implement a subclass of ``TargetRegisterInfo`` 623---------------------------------------------- 624 625The final step is to hand code portions of ``XXXRegisterInfo``, which 626implements the interface described in ``TargetRegisterInfo.h`` (see 627:ref:`TargetRegisterInfo`). These functions return ``0``, ``NULL``, or 628``false``, unless overridden. Here is a list of functions that are overridden 629for the SPARC implementation in ``SparcRegisterInfo.cpp``: 630 631* ``getCalleeSavedRegs`` --- Returns a list of callee-saved registers in the 632 order of the desired callee-save stack frame offset. 633 634* ``getReservedRegs`` --- Returns a bitset indexed by physical register 635 numbers, indicating if a particular register is unavailable. 636 637* ``hasFP`` --- Return a Boolean indicating if a function should have a 638 dedicated frame pointer register. 639 640* ``eliminateCallFramePseudoInstr`` --- If call frame setup or destroy pseudo 641 instructions are used, this can be called to eliminate them. 642 643* ``eliminateFrameIndex`` --- Eliminate abstract frame indices from 644 instructions that may use them. 645 646* ``emitPrologue`` --- Insert prologue code into the function. 647 648* ``emitEpilogue`` --- Insert epilogue code into the function. 649 650.. _instruction-set: 651 652Instruction Set 653=============== 654 655During the early stages of code generation, the LLVM IR code is converted to a 656``SelectionDAG`` with nodes that are instances of the ``SDNode`` class 657containing target instructions. An ``SDNode`` has an opcode, operands, type 658requirements, and operation properties. For example, is an operation 659commutative, does an operation load from memory. The various operation node 660types are described in the ``include/llvm/CodeGen/SelectionDAGNodes.h`` file 661(values of the ``NodeType`` enum in the ``ISD`` namespace). 662 663TableGen uses the following target description (``.td``) input files to 664generate much of the code for instruction definition: 665 666* ``Target.td`` --- Where the ``Instruction``, ``Operand``, ``InstrInfo``, and 667 other fundamental classes are defined. 668 669* ``TargetSelectionDAG.td`` --- Used by ``SelectionDAG`` instruction selection 670 generators, contains ``SDTC*`` classes (selection DAG type constraint), 671 definitions of ``SelectionDAG`` nodes (such as ``imm``, ``cond``, ``bb``, 672 ``add``, ``fadd``, ``sub``), and pattern support (``Pattern``, ``Pat``, 673 ``PatFrag``, ``PatLeaf``, ``ComplexPattern``. 674 675* ``XXXInstrFormats.td`` --- Patterns for definitions of target-specific 676 instructions. 677 678* ``XXXInstrInfo.td`` --- Target-specific definitions of instruction templates, 679 condition codes, and instructions of an instruction set. For architecture 680 modifications, a different file name may be used. For example, for Pentium 681 with SSE instruction, this file is ``X86InstrSSE.td``, and for Pentium with 682 MMX, this file is ``X86InstrMMX.td``. 683 684There is also a target-specific ``XXX.td`` file, where ``XXX`` is the name of 685the target. The ``XXX.td`` file includes the other ``.td`` input files, but 686its contents are only directly important for subtargets. 687 688You should describe a concrete target-specific class ``XXXInstrInfo`` that 689represents machine instructions supported by a target machine. 690``XXXInstrInfo`` contains an array of ``XXXInstrDescriptor`` objects, each of 691which describes one instruction. An instruction descriptor defines: 692 693* Opcode mnemonic 694* Number of operands 695* List of implicit register definitions and uses 696* Target-independent properties (such as memory access, is commutable) 697* Target-specific flags 698 699The Instruction class (defined in ``Target.td``) is mostly used as a base for 700more complex instruction classes. 701 702.. code-block:: llvm 703 704 class Instruction { 705 string Namespace = ""; 706 dag OutOperandList; // A dag containing the MI def operand list. 707 dag InOperandList; // A dag containing the MI use operand list. 708 string AsmString = ""; // The .s format to print the instruction with. 709 list<dag> Pattern; // Set to the DAG pattern for this instruction. 710 list<Register> Uses = []; 711 list<Register> Defs = []; 712 list<Predicate> Predicates = []; // predicates turned into isel match code 713 ... remainder not shown for space ... 714 } 715 716A ``SelectionDAG`` node (``SDNode``) should contain an object representing a 717target-specific instruction that is defined in ``XXXInstrInfo.td``. The 718instruction objects should represent instructions from the architecture manual 719of the target machine (such as the SPARC Architecture Manual for the SPARC 720target). 721 722A single instruction from the architecture manual is often modeled as multiple 723target instructions, depending upon its operands. For example, a manual might 724describe an add instruction that takes a register or an immediate operand. An 725LLVM target could model this with two instructions named ``ADDri`` and 726``ADDrr``. 727 728You should define a class for each instruction category and define each opcode 729as a subclass of the category with appropriate parameters such as the fixed 730binary encoding of opcodes and extended opcodes. You should map the register 731bits to the bits of the instruction in which they are encoded (for the JIT). 732Also you should specify how the instruction should be printed when the 733automatic assembly printer is used. 734 735As is described in the SPARC Architecture Manual, Version 8, there are three 736major 32-bit formats for instructions. Format 1 is only for the ``CALL`` 737instruction. Format 2 is for branch on condition codes and ``SETHI`` (set high 738bits of a register) instructions. Format 3 is for other instructions. 739 740Each of these formats has corresponding classes in ``SparcInstrFormat.td``. 741``InstSP`` is a base class for other instruction classes. Additional base 742classes are specified for more precise formats: for example in 743``SparcInstrFormat.td``, ``F2_1`` is for ``SETHI``, and ``F2_2`` is for 744branches. There are three other base classes: ``F3_1`` for register/register 745operations, ``F3_2`` for register/immediate operations, and ``F3_3`` for 746floating-point operations. ``SparcInstrInfo.td`` also adds the base class 747``Pseudo`` for synthetic SPARC instructions. 748 749``SparcInstrInfo.td`` largely consists of operand and instruction definitions 750for the SPARC target. In ``SparcInstrInfo.td``, the following target 751description file entry, ``LDrr``, defines the Load Integer instruction for a 752Word (the ``LD`` SPARC opcode) from a memory address to a register. The first 753parameter, the value 3 (``11``\ :sub:`2`), is the operation value for this 754category of operation. The second parameter (``000000``\ :sub:`2`) is the 755specific operation value for ``LD``/Load Word. The third parameter is the 756output destination, which is a register operand and defined in the ``Register`` 757target description file (``IntRegs``). 758 759.. code-block:: llvm 760 761 def LDrr : F3_1 <3, 0b000000, (outs IntRegs:$dst), (ins MEMrr:$addr), 762 "ld [$addr], $dst", 763 [(set i32:$dst, (load ADDRrr:$addr))]>; 764 765The fourth parameter is the input source, which uses the address operand 766``MEMrr`` that is defined earlier in ``SparcInstrInfo.td``: 767 768.. code-block:: llvm 769 770 def MEMrr : Operand<i32> { 771 let PrintMethod = "printMemOperand"; 772 let MIOperandInfo = (ops IntRegs, IntRegs); 773 } 774 775The fifth parameter is a string that is used by the assembly printer and can be 776left as an empty string until the assembly printer interface is implemented. 777The sixth and final parameter is the pattern used to match the instruction 778during the SelectionDAG Select Phase described in :doc:`CodeGenerator`. 779This parameter is detailed in the next section, :ref:`instruction-selector`. 780 781Instruction class definitions are not overloaded for different operand types, 782so separate versions of instructions are needed for register, memory, or 783immediate value operands. For example, to perform a Load Integer instruction 784for a Word from an immediate operand to a register, the following instruction 785class is defined: 786 787.. code-block:: llvm 788 789 def LDri : F3_2 <3, 0b000000, (outs IntRegs:$dst), (ins MEMri:$addr), 790 "ld [$addr], $dst", 791 [(set i32:$dst, (load ADDRri:$addr))]>; 792 793Writing these definitions for so many similar instructions can involve a lot of 794cut and paste. In ``.td`` files, the ``multiclass`` directive enables the 795creation of templates to define several instruction classes at once (using the 796``defm`` directive). For example in ``SparcInstrInfo.td``, the ``multiclass`` 797pattern ``F3_12`` is defined to create 2 instruction classes each time 798``F3_12`` is invoked: 799 800.. code-block:: llvm 801 802 multiclass F3_12 <string OpcStr, bits<6> Op3Val, SDNode OpNode> { 803 def rr : F3_1 <2, Op3Val, 804 (outs IntRegs:$dst), (ins IntRegs:$b, IntRegs:$c), 805 !strconcat(OpcStr, " $b, $c, $dst"), 806 [(set i32:$dst, (OpNode i32:$b, i32:$c))]>; 807 def ri : F3_2 <2, Op3Val, 808 (outs IntRegs:$dst), (ins IntRegs:$b, i32imm:$c), 809 !strconcat(OpcStr, " $b, $c, $dst"), 810 [(set i32:$dst, (OpNode i32:$b, simm13:$c))]>; 811 } 812 813So when the ``defm`` directive is used for the ``XOR`` and ``ADD`` 814instructions, as seen below, it creates four instruction objects: ``XORrr``, 815``XORri``, ``ADDrr``, and ``ADDri``. 816 817.. code-block:: llvm 818 819 defm XOR : F3_12<"xor", 0b000011, xor>; 820 defm ADD : F3_12<"add", 0b000000, add>; 821 822``SparcInstrInfo.td`` also includes definitions for condition codes that are 823referenced by branch instructions. The following definitions in 824``SparcInstrInfo.td`` indicate the bit location of the SPARC condition code. 825For example, the 10\ :sup:`th` bit represents the "greater than" condition for 826integers, and the 22\ :sup:`nd` bit represents the "greater than" condition for 827floats. 828 829.. code-block:: llvm 830 831 def ICC_NE : ICC_VAL< 9>; // Not Equal 832 def ICC_E : ICC_VAL< 1>; // Equal 833 def ICC_G : ICC_VAL<10>; // Greater 834 ... 835 def FCC_U : FCC_VAL<23>; // Unordered 836 def FCC_G : FCC_VAL<22>; // Greater 837 def FCC_UG : FCC_VAL<21>; // Unordered or Greater 838 ... 839 840(Note that ``Sparc.h`` also defines enums that correspond to the same SPARC 841condition codes. Care must be taken to ensure the values in ``Sparc.h`` 842correspond to the values in ``SparcInstrInfo.td``. I.e., ``SPCC::ICC_NE = 9``, 843``SPCC::FCC_U = 23`` and so on.) 844 845Instruction Operand Mapping 846--------------------------- 847 848The code generator backend maps instruction operands to fields in the 849instruction. Operands are assigned to unbound fields in the instruction in the 850order they are defined. Fields are bound when they are assigned a value. For 851example, the Sparc target defines the ``XNORrr`` instruction as a ``F3_1`` 852format instruction having three operands. 853 854.. code-block:: llvm 855 856 def XNORrr : F3_1<2, 0b000111, 857 (outs IntRegs:$dst), (ins IntRegs:$b, IntRegs:$c), 858 "xnor $b, $c, $dst", 859 [(set i32:$dst, (not (xor i32:$b, i32:$c)))]>; 860 861The instruction templates in ``SparcInstrFormats.td`` show the base class for 862``F3_1`` is ``InstSP``. 863 864.. code-block:: llvm 865 866 class InstSP<dag outs, dag ins, string asmstr, list<dag> pattern> : Instruction { 867 field bits<32> Inst; 868 let Namespace = "SP"; 869 bits<2> op; 870 let Inst{31-30} = op; 871 dag OutOperandList = outs; 872 dag InOperandList = ins; 873 let AsmString = asmstr; 874 let Pattern = pattern; 875 } 876 877``InstSP`` leaves the ``op`` field unbound. 878 879.. code-block:: llvm 880 881 class F3<dag outs, dag ins, string asmstr, list<dag> pattern> 882 : InstSP<outs, ins, asmstr, pattern> { 883 bits<5> rd; 884 bits<6> op3; 885 bits<5> rs1; 886 let op{1} = 1; // Op = 2 or 3 887 let Inst{29-25} = rd; 888 let Inst{24-19} = op3; 889 let Inst{18-14} = rs1; 890 } 891 892``F3`` binds the ``op`` field and defines the ``rd``, ``op3``, and ``rs1`` 893fields. ``F3`` format instructions will bind the operands ``rd``, ``op3``, and 894``rs1`` fields. 895 896.. code-block:: llvm 897 898 class F3_1<bits<2> opVal, bits<6> op3val, dag outs, dag ins, 899 string asmstr, list<dag> pattern> : F3<outs, ins, asmstr, pattern> { 900 bits<8> asi = 0; // asi not currently used 901 bits<5> rs2; 902 let op = opVal; 903 let op3 = op3val; 904 let Inst{13} = 0; // i field = 0 905 let Inst{12-5} = asi; // address space identifier 906 let Inst{4-0} = rs2; 907 } 908 909``F3_1`` binds the ``op3`` field and defines the ``rs2`` fields. ``F3_1`` 910format instructions will bind the operands to the ``rd``, ``rs1``, and ``rs2`` 911fields. This results in the ``XNORrr`` instruction binding ``$dst``, ``$b``, 912and ``$c`` operands to the ``rd``, ``rs1``, and ``rs2`` fields respectively. 913 914Instruction Operand Name Mapping 915^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 916 917TableGen will also generate a function called getNamedOperandIdx() which 918can be used to look up an operand's index in a MachineInstr based on its 919TableGen name. Setting the UseNamedOperandTable bit in an instruction's 920TableGen definition will add all of its operands to an enumeration in the 921llvm::XXX:OpName namespace and also add an entry for it into the OperandMap 922table, which can be queried using getNamedOperandIdx() 923 924.. code-block:: llvm 925 926 int DstIndex = SP::getNamedOperandIdx(SP::XNORrr, SP::OpName::dst); // => 0 927 int BIndex = SP::getNamedOperandIdx(SP::XNORrr, SP::OpName::b); // => 1 928 int CIndex = SP::getNamedOperandIdx(SP::XNORrr, SP::OpName::c); // => 2 929 int DIndex = SP::getNamedOperandIdx(SP::XNORrr, SP::OpName::d); // => -1 930 931 ... 932 933The entries in the OpName enum are taken verbatim from the TableGen definitions, 934so operands with lowercase names will have lower case entries in the enum. 935 936To include the getNamedOperandIdx() function in your backend, you will need 937to define a few preprocessor macros in XXXInstrInfo.cpp and XXXInstrInfo.h. 938For example: 939 940XXXInstrInfo.cpp: 941 942.. code-block:: c++ 943 944 #define GET_INSTRINFO_NAMED_OPS // For getNamedOperandIdx() function 945 #include "XXXGenInstrInfo.inc" 946 947XXXInstrInfo.h: 948 949.. code-block:: c++ 950 951 #define GET_INSTRINFO_OPERAND_ENUM // For OpName enum 952 #include "XXXGenInstrInfo.inc" 953 954 namespace XXX { 955 int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIndex); 956 } // End namespace XXX 957 958Instruction Operand Types 959^^^^^^^^^^^^^^^^^^^^^^^^^ 960 961TableGen will also generate an enumeration consisting of all named Operand 962types defined in the backend, in the llvm::XXX::OpTypes namespace. 963Some common immediate Operand types (for instance i8, i32, i64, f32, f64) 964are defined for all targets in ``include/llvm/Target/Target.td``, and are 965available in each Target's OpTypes enum. Also, only named Operand types appear 966in the enumeration: anonymous types are ignored. 967For example, the X86 backend defines ``brtarget`` and ``brtarget8``, both 968instances of the TableGen ``Operand`` class, which represent branch target 969operands: 970 971.. code-block:: llvm 972 973 def brtarget : Operand<OtherVT>; 974 def brtarget8 : Operand<OtherVT>; 975 976This results in: 977 978.. code-block:: c++ 979 980 namespace X86 { 981 namespace OpTypes { 982 enum OperandType { 983 ... 984 brtarget, 985 brtarget8, 986 ... 987 i32imm, 988 i64imm, 989 ... 990 OPERAND_TYPE_LIST_END 991 } // End namespace OpTypes 992 } // End namespace X86 993 994In typical TableGen fashion, to use the enum, you will need to define a 995preprocessor macro: 996 997.. code-block:: c++ 998 999 #define GET_INSTRINFO_OPERAND_TYPES_ENUM // For OpTypes enum 1000 #include "XXXGenInstrInfo.inc" 1001 1002 1003Instruction Scheduling 1004---------------------- 1005 1006Instruction itineraries can be queried using MCDesc::getSchedClass(). The 1007value can be named by an enumemation in llvm::XXX::Sched namespace generated 1008by TableGen in XXXGenInstrInfo.inc. The name of the schedule classes are 1009the same as provided in XXXSchedule.td plus a default NoItinerary class. 1010 1011Instruction Relation Mapping 1012---------------------------- 1013 1014This TableGen feature is used to relate instructions with each other. It is 1015particularly useful when you have multiple instruction formats and need to 1016switch between them after instruction selection. This entire feature is driven 1017by relation models which can be defined in ``XXXInstrInfo.td`` files 1018according to the target-specific instruction set. Relation models are defined 1019using ``InstrMapping`` class as a base. TableGen parses all the models 1020and generates instruction relation maps using the specified information. 1021Relation maps are emitted as tables in the ``XXXGenInstrInfo.inc`` file 1022along with the functions to query them. For the detailed information on how to 1023use this feature, please refer to :doc:`HowToUseInstrMappings`. 1024 1025Implement a subclass of ``TargetInstrInfo`` 1026------------------------------------------- 1027 1028The final step is to hand code portions of ``XXXInstrInfo``, which implements 1029the interface described in ``TargetInstrInfo.h`` (see :ref:`TargetInstrInfo`). 1030These functions return ``0`` or a Boolean or they assert, unless overridden. 1031Here's a list of functions that are overridden for the SPARC implementation in 1032``SparcInstrInfo.cpp``: 1033 1034* ``isLoadFromStackSlot`` --- If the specified machine instruction is a direct 1035 load from a stack slot, return the register number of the destination and the 1036 ``FrameIndex`` of the stack slot. 1037 1038* ``isStoreToStackSlot`` --- If the specified machine instruction is a direct 1039 store to a stack slot, return the register number of the destination and the 1040 ``FrameIndex`` of the stack slot. 1041 1042* ``copyPhysReg`` --- Copy values between a pair of physical registers. 1043 1044* ``storeRegToStackSlot`` --- Store a register value to a stack slot. 1045 1046* ``loadRegFromStackSlot`` --- Load a register value from a stack slot. 1047 1048* ``storeRegToAddr`` --- Store a register value to memory. 1049 1050* ``loadRegFromAddr`` --- Load a register value from memory. 1051 1052* ``foldMemoryOperand`` --- Attempt to combine instructions of any load or 1053 store instruction for the specified operand(s). 1054 1055Branch Folding and If Conversion 1056-------------------------------- 1057 1058Performance can be improved by combining instructions or by eliminating 1059instructions that are never reached. The ``AnalyzeBranch`` method in 1060``XXXInstrInfo`` may be implemented to examine conditional instructions and 1061remove unnecessary instructions. ``AnalyzeBranch`` looks at the end of a 1062machine basic block (MBB) for opportunities for improvement, such as branch 1063folding and if conversion. The ``BranchFolder`` and ``IfConverter`` machine 1064function passes (see the source files ``BranchFolding.cpp`` and 1065``IfConversion.cpp`` in the ``lib/CodeGen`` directory) call ``AnalyzeBranch`` 1066to improve the control flow graph that represents the instructions. 1067 1068Several implementations of ``AnalyzeBranch`` (for ARM, Alpha, and X86) can be 1069examined as models for your own ``AnalyzeBranch`` implementation. Since SPARC 1070does not implement a useful ``AnalyzeBranch``, the ARM target implementation is 1071shown below. 1072 1073``AnalyzeBranch`` returns a Boolean value and takes four parameters: 1074 1075* ``MachineBasicBlock &MBB`` --- The incoming block to be examined. 1076 1077* ``MachineBasicBlock *&TBB`` --- A destination block that is returned. For a 1078 conditional branch that evaluates to true, ``TBB`` is the destination. 1079 1080* ``MachineBasicBlock *&FBB`` --- For a conditional branch that evaluates to 1081 false, ``FBB`` is returned as the destination. 1082 1083* ``std::vector<MachineOperand> &Cond`` --- List of operands to evaluate a 1084 condition for a conditional branch. 1085 1086In the simplest case, if a block ends without a branch, then it falls through 1087to the successor block. No destination blocks are specified for either ``TBB`` 1088or ``FBB``, so both parameters return ``NULL``. The start of the 1089``AnalyzeBranch`` (see code below for the ARM target) shows the function 1090parameters and the code for the simplest case. 1091 1092.. code-block:: c++ 1093 1094 bool ARMInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB, 1095 MachineBasicBlock *&TBB, 1096 MachineBasicBlock *&FBB, 1097 std::vector<MachineOperand> &Cond) const 1098 { 1099 MachineBasicBlock::iterator I = MBB.end(); 1100 if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) 1101 return false; 1102 1103If a block ends with a single unconditional branch instruction, then 1104``AnalyzeBranch`` (shown below) should return the destination of that branch in 1105the ``TBB`` parameter. 1106 1107.. code-block:: c++ 1108 1109 if (LastOpc == ARM::B || LastOpc == ARM::tB) { 1110 TBB = LastInst->getOperand(0).getMBB(); 1111 return false; 1112 } 1113 1114If a block ends with two unconditional branches, then the second branch is 1115never reached. In that situation, as shown below, remove the last branch 1116instruction and return the penultimate branch in the ``TBB`` parameter. 1117 1118.. code-block:: c++ 1119 1120 if ((SecondLastOpc == ARM::B || SecondLastOpc == ARM::tB) && 1121 (LastOpc == ARM::B || LastOpc == ARM::tB)) { 1122 TBB = SecondLastInst->getOperand(0).getMBB(); 1123 I = LastInst; 1124 I->eraseFromParent(); 1125 return false; 1126 } 1127 1128A block may end with a single conditional branch instruction that falls through 1129to successor block if the condition evaluates to false. In that case, 1130``AnalyzeBranch`` (shown below) should return the destination of that 1131conditional branch in the ``TBB`` parameter and a list of operands in the 1132``Cond`` parameter to evaluate the condition. 1133 1134.. code-block:: c++ 1135 1136 if (LastOpc == ARM::Bcc || LastOpc == ARM::tBcc) { 1137 // Block ends with fall-through condbranch. 1138 TBB = LastInst->getOperand(0).getMBB(); 1139 Cond.push_back(LastInst->getOperand(1)); 1140 Cond.push_back(LastInst->getOperand(2)); 1141 return false; 1142 } 1143 1144If a block ends with both a conditional branch and an ensuing unconditional 1145branch, then ``AnalyzeBranch`` (shown below) should return the conditional 1146branch destination (assuming it corresponds to a conditional evaluation of 1147"``true``") in the ``TBB`` parameter and the unconditional branch destination 1148in the ``FBB`` (corresponding to a conditional evaluation of "``false``"). A 1149list of operands to evaluate the condition should be returned in the ``Cond`` 1150parameter. 1151 1152.. code-block:: c++ 1153 1154 unsigned SecondLastOpc = SecondLastInst->getOpcode(); 1155 1156 if ((SecondLastOpc == ARM::Bcc && LastOpc == ARM::B) || 1157 (SecondLastOpc == ARM::tBcc && LastOpc == ARM::tB)) { 1158 TBB = SecondLastInst->getOperand(0).getMBB(); 1159 Cond.push_back(SecondLastInst->getOperand(1)); 1160 Cond.push_back(SecondLastInst->getOperand(2)); 1161 FBB = LastInst->getOperand(0).getMBB(); 1162 return false; 1163 } 1164 1165For the last two cases (ending with a single conditional branch or ending with 1166one conditional and one unconditional branch), the operands returned in the 1167``Cond`` parameter can be passed to methods of other instructions to create new 1168branches or perform other operations. An implementation of ``AnalyzeBranch`` 1169requires the helper methods ``RemoveBranch`` and ``InsertBranch`` to manage 1170subsequent operations. 1171 1172``AnalyzeBranch`` should return false indicating success in most circumstances. 1173``AnalyzeBranch`` should only return true when the method is stumped about what 1174to do, for example, if a block has three terminating branches. 1175``AnalyzeBranch`` may return true if it encounters a terminator it cannot 1176handle, such as an indirect branch. 1177 1178.. _instruction-selector: 1179 1180Instruction Selector 1181==================== 1182 1183LLVM uses a ``SelectionDAG`` to represent LLVM IR instructions, and nodes of 1184the ``SelectionDAG`` ideally represent native target instructions. During code 1185generation, instruction selection passes are performed to convert non-native 1186DAG instructions into native target-specific instructions. The pass described 1187in ``XXXISelDAGToDAG.cpp`` is used to match patterns and perform DAG-to-DAG 1188instruction selection. Optionally, a pass may be defined (in 1189``XXXBranchSelector.cpp``) to perform similar DAG-to-DAG operations for branch 1190instructions. Later, the code in ``XXXISelLowering.cpp`` replaces or removes 1191operations and data types not supported natively (legalizes) in a 1192``SelectionDAG``. 1193 1194TableGen generates code for instruction selection using the following target 1195description input files: 1196 1197* ``XXXInstrInfo.td`` --- Contains definitions of instructions in a 1198 target-specific instruction set, generates ``XXXGenDAGISel.inc``, which is 1199 included in ``XXXISelDAGToDAG.cpp``. 1200 1201* ``XXXCallingConv.td`` --- Contains the calling and return value conventions 1202 for the target architecture, and it generates ``XXXGenCallingConv.inc``, 1203 which is included in ``XXXISelLowering.cpp``. 1204 1205The implementation of an instruction selection pass must include a header that 1206declares the ``FunctionPass`` class or a subclass of ``FunctionPass``. In 1207``XXXTargetMachine.cpp``, a Pass Manager (PM) should add each instruction 1208selection pass into the queue of passes to run. 1209 1210The LLVM static compiler (``llc``) is an excellent tool for visualizing the 1211contents of DAGs. To display the ``SelectionDAG`` before or after specific 1212processing phases, use the command line options for ``llc``, described at 1213:ref:`SelectionDAG-Process`. 1214 1215To describe instruction selector behavior, you should add patterns for lowering 1216LLVM code into a ``SelectionDAG`` as the last parameter of the instruction 1217definitions in ``XXXInstrInfo.td``. For example, in ``SparcInstrInfo.td``, 1218this entry defines a register store operation, and the last parameter describes 1219a pattern with the store DAG operator. 1220 1221.. code-block:: llvm 1222 1223 def STrr : F3_1< 3, 0b000100, (outs), (ins MEMrr:$addr, IntRegs:$src), 1224 "st $src, [$addr]", [(store i32:$src, ADDRrr:$addr)]>; 1225 1226``ADDRrr`` is a memory mode that is also defined in ``SparcInstrInfo.td``: 1227 1228.. code-block:: llvm 1229 1230 def ADDRrr : ComplexPattern<i32, 2, "SelectADDRrr", [], []>; 1231 1232The definition of ``ADDRrr`` refers to ``SelectADDRrr``, which is a function 1233defined in an implementation of the Instructor Selector (such as 1234``SparcISelDAGToDAG.cpp``). 1235 1236In ``lib/Target/TargetSelectionDAG.td``, the DAG operator for store is defined 1237below: 1238 1239.. code-block:: llvm 1240 1241 def store : PatFrag<(ops node:$val, node:$ptr), 1242 (st node:$val, node:$ptr), [{ 1243 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) 1244 return !ST->isTruncatingStore() && 1245 ST->getAddressingMode() == ISD::UNINDEXED; 1246 return false; 1247 }]>; 1248 1249``XXXInstrInfo.td`` also generates (in ``XXXGenDAGISel.inc``) the 1250``SelectCode`` method that is used to call the appropriate processing method 1251for an instruction. In this example, ``SelectCode`` calls ``Select_ISD_STORE`` 1252for the ``ISD::STORE`` opcode. 1253 1254.. code-block:: c++ 1255 1256 SDNode *SelectCode(SDValue N) { 1257 ... 1258 MVT::ValueType NVT = N.getNode()->getValueType(0); 1259 switch (N.getOpcode()) { 1260 case ISD::STORE: { 1261 switch (NVT) { 1262 default: 1263 return Select_ISD_STORE(N); 1264 break; 1265 } 1266 break; 1267 } 1268 ... 1269 1270The pattern for ``STrr`` is matched, so elsewhere in ``XXXGenDAGISel.inc``, 1271code for ``STrr`` is created for ``Select_ISD_STORE``. The ``Emit_22`` method 1272is also generated in ``XXXGenDAGISel.inc`` to complete the processing of this 1273instruction. 1274 1275.. code-block:: c++ 1276 1277 SDNode *Select_ISD_STORE(const SDValue &N) { 1278 SDValue Chain = N.getOperand(0); 1279 if (Predicate_store(N.getNode())) { 1280 SDValue N1 = N.getOperand(1); 1281 SDValue N2 = N.getOperand(2); 1282 SDValue CPTmp0; 1283 SDValue CPTmp1; 1284 1285 // Pattern: (st:void i32:i32:$src, 1286 // ADDRrr:i32:$addr)<<P:Predicate_store>> 1287 // Emits: (STrr:void ADDRrr:i32:$addr, IntRegs:i32:$src) 1288 // Pattern complexity = 13 cost = 1 size = 0 1289 if (SelectADDRrr(N, N2, CPTmp0, CPTmp1) && 1290 N1.getNode()->getValueType(0) == MVT::i32 && 1291 N2.getNode()->getValueType(0) == MVT::i32) { 1292 return Emit_22(N, SP::STrr, CPTmp0, CPTmp1); 1293 } 1294 ... 1295 1296The SelectionDAG Legalize Phase 1297------------------------------- 1298 1299The Legalize phase converts a DAG to use types and operations that are natively 1300supported by the target. For natively unsupported types and operations, you 1301need to add code to the target-specific ``XXXTargetLowering`` implementation to 1302convert unsupported types and operations to supported ones. 1303 1304In the constructor for the ``XXXTargetLowering`` class, first use the 1305``addRegisterClass`` method to specify which types are supported and which 1306register classes are associated with them. The code for the register classes 1307are generated by TableGen from ``XXXRegisterInfo.td`` and placed in 1308``XXXGenRegisterInfo.h.inc``. For example, the implementation of the 1309constructor for the SparcTargetLowering class (in ``SparcISelLowering.cpp``) 1310starts with the following code: 1311 1312.. code-block:: c++ 1313 1314 addRegisterClass(MVT::i32, SP::IntRegsRegisterClass); 1315 addRegisterClass(MVT::f32, SP::FPRegsRegisterClass); 1316 addRegisterClass(MVT::f64, SP::DFPRegsRegisterClass); 1317 1318You should examine the node types in the ``ISD`` namespace 1319(``include/llvm/CodeGen/SelectionDAGNodes.h``) and determine which operations 1320the target natively supports. For operations that do **not** have native 1321support, add a callback to the constructor for the ``XXXTargetLowering`` class, 1322so the instruction selection process knows what to do. The ``TargetLowering`` 1323class callback methods (declared in ``llvm/Target/TargetLowering.h``) are: 1324 1325* ``setOperationAction`` --- General operation. 1326* ``setLoadExtAction`` --- Load with extension. 1327* ``setTruncStoreAction`` --- Truncating store. 1328* ``setIndexedLoadAction`` --- Indexed load. 1329* ``setIndexedStoreAction`` --- Indexed store. 1330* ``setConvertAction`` --- Type conversion. 1331* ``setCondCodeAction`` --- Support for a given condition code. 1332 1333Note: on older releases, ``setLoadXAction`` is used instead of 1334``setLoadExtAction``. Also, on older releases, ``setCondCodeAction`` may not 1335be supported. Examine your release to see what methods are specifically 1336supported. 1337 1338These callbacks are used to determine that an operation does or does not work 1339with a specified type (or types). And in all cases, the third parameter is a 1340``LegalAction`` type enum value: ``Promote``, ``Expand``, ``Custom``, or 1341``Legal``. ``SparcISelLowering.cpp`` contains examples of all four 1342``LegalAction`` values. 1343 1344Promote 1345^^^^^^^ 1346 1347For an operation without native support for a given type, the specified type 1348may be promoted to a larger type that is supported. For example, SPARC does 1349not support a sign-extending load for Boolean values (``i1`` type), so in 1350``SparcISelLowering.cpp`` the third parameter below, ``Promote``, changes 1351``i1`` type values to a large type before loading. 1352 1353.. code-block:: c++ 1354 1355 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote); 1356 1357Expand 1358^^^^^^ 1359 1360For a type without native support, a value may need to be broken down further, 1361rather than promoted. For an operation without native support, a combination 1362of other operations may be used to similar effect. In SPARC, the 1363floating-point sine and cosine trig operations are supported by expansion to 1364other operations, as indicated by the third parameter, ``Expand``, to 1365``setOperationAction``: 1366 1367.. code-block:: c++ 1368 1369 setOperationAction(ISD::FSIN, MVT::f32, Expand); 1370 setOperationAction(ISD::FCOS, MVT::f32, Expand); 1371 1372Custom 1373^^^^^^ 1374 1375For some operations, simple type promotion or operation expansion may be 1376insufficient. In some cases, a special intrinsic function must be implemented. 1377 1378For example, a constant value may require special treatment, or an operation 1379may require spilling and restoring registers in the stack and working with 1380register allocators. 1381 1382As seen in ``SparcISelLowering.cpp`` code below, to perform a type conversion 1383from a floating point value to a signed integer, first the 1384``setOperationAction`` should be called with ``Custom`` as the third parameter: 1385 1386.. code-block:: c++ 1387 1388 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 1389 1390In the ``LowerOperation`` method, for each ``Custom`` operation, a case 1391statement should be added to indicate what function to call. In the following 1392code, an ``FP_TO_SINT`` opcode will call the ``LowerFP_TO_SINT`` method: 1393 1394.. code-block:: c++ 1395 1396 SDValue SparcTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) { 1397 switch (Op.getOpcode()) { 1398 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG); 1399 ... 1400 } 1401 } 1402 1403Finally, the ``LowerFP_TO_SINT`` method is implemented, using an FP register to 1404convert the floating-point value to an integer. 1405 1406.. code-block:: c++ 1407 1408 static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) { 1409 assert(Op.getValueType() == MVT::i32); 1410 Op = DAG.getNode(SPISD::FTOI, MVT::f32, Op.getOperand(0)); 1411 return DAG.getNode(ISD::BITCAST, MVT::i32, Op); 1412 } 1413 1414Legal 1415^^^^^ 1416 1417The ``Legal`` ``LegalizeAction`` enum value simply indicates that an operation 1418**is** natively supported. ``Legal`` represents the default condition, so it 1419is rarely used. In ``SparcISelLowering.cpp``, the action for ``CTPOP`` (an 1420operation to count the bits set in an integer) is natively supported only for 1421SPARC v9. The following code enables the ``Expand`` conversion technique for 1422non-v9 SPARC implementations. 1423 1424.. code-block:: c++ 1425 1426 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 1427 ... 1428 if (TM.getSubtarget<SparcSubtarget>().isV9()) 1429 setOperationAction(ISD::CTPOP, MVT::i32, Legal); 1430 1431Calling Conventions 1432------------------- 1433 1434To support target-specific calling conventions, ``XXXGenCallingConv.td`` uses 1435interfaces (such as ``CCIfType`` and ``CCAssignToReg``) that are defined in 1436``lib/Target/TargetCallingConv.td``. TableGen can take the target descriptor 1437file ``XXXGenCallingConv.td`` and generate the header file 1438``XXXGenCallingConv.inc``, which is typically included in 1439``XXXISelLowering.cpp``. You can use the interfaces in 1440``TargetCallingConv.td`` to specify: 1441 1442* The order of parameter allocation. 1443 1444* Where parameters and return values are placed (that is, on the stack or in 1445 registers). 1446 1447* Which registers may be used. 1448 1449* Whether the caller or callee unwinds the stack. 1450 1451The following example demonstrates the use of the ``CCIfType`` and 1452``CCAssignToReg`` interfaces. If the ``CCIfType`` predicate is true (that is, 1453if the current argument is of type ``f32`` or ``f64``), then the action is 1454performed. In this case, the ``CCAssignToReg`` action assigns the argument 1455value to the first available register: either ``R0`` or ``R1``. 1456 1457.. code-block:: llvm 1458 1459 CCIfType<[f32,f64], CCAssignToReg<[R0, R1]>> 1460 1461``SparcCallingConv.td`` contains definitions for a target-specific return-value 1462calling convention (``RetCC_Sparc32``) and a basic 32-bit C calling convention 1463(``CC_Sparc32``). The definition of ``RetCC_Sparc32`` (shown below) indicates 1464which registers are used for specified scalar return types. A single-precision 1465float is returned to register ``F0``, and a double-precision float goes to 1466register ``D0``. A 32-bit integer is returned in register ``I0`` or ``I1``. 1467 1468.. code-block:: llvm 1469 1470 def RetCC_Sparc32 : CallingConv<[ 1471 CCIfType<[i32], CCAssignToReg<[I0, I1]>>, 1472 CCIfType<[f32], CCAssignToReg<[F0]>>, 1473 CCIfType<[f64], CCAssignToReg<[D0]>> 1474 ]>; 1475 1476The definition of ``CC_Sparc32`` in ``SparcCallingConv.td`` introduces 1477``CCAssignToStack``, which assigns the value to a stack slot with the specified 1478size and alignment. In the example below, the first parameter, 4, indicates 1479the size of the slot, and the second parameter, also 4, indicates the stack 1480alignment along 4-byte units. (Special cases: if size is zero, then the ABI 1481size is used; if alignment is zero, then the ABI alignment is used.) 1482 1483.. code-block:: llvm 1484 1485 def CC_Sparc32 : CallingConv<[ 1486 // All arguments get passed in integer registers if there is space. 1487 CCIfType<[i32, f32, f64], CCAssignToReg<[I0, I1, I2, I3, I4, I5]>>, 1488 CCAssignToStack<4, 4> 1489 ]>; 1490 1491``CCDelegateTo`` is another commonly used interface, which tries to find a 1492specified sub-calling convention, and, if a match is found, it is invoked. In 1493the following example (in ``X86CallingConv.td``), the definition of 1494``RetCC_X86_32_C`` ends with ``CCDelegateTo``. After the current value is 1495assigned to the register ``ST0`` or ``ST1``, the ``RetCC_X86Common`` is 1496invoked. 1497 1498.. code-block:: llvm 1499 1500 def RetCC_X86_32_C : CallingConv<[ 1501 CCIfType<[f32], CCAssignToReg<[ST0, ST1]>>, 1502 CCIfType<[f64], CCAssignToReg<[ST0, ST1]>>, 1503 CCDelegateTo<RetCC_X86Common> 1504 ]>; 1505 1506``CCIfCC`` is an interface that attempts to match the given name to the current 1507calling convention. If the name identifies the current calling convention, 1508then a specified action is invoked. In the following example (in 1509``X86CallingConv.td``), if the ``Fast`` calling convention is in use, then 1510``RetCC_X86_32_Fast`` is invoked. If the ``SSECall`` calling convention is in 1511use, then ``RetCC_X86_32_SSE`` is invoked. 1512 1513.. code-block:: llvm 1514 1515 def RetCC_X86_32 : CallingConv<[ 1516 CCIfCC<"CallingConv::Fast", CCDelegateTo<RetCC_X86_32_Fast>>, 1517 CCIfCC<"CallingConv::X86_SSECall", CCDelegateTo<RetCC_X86_32_SSE>>, 1518 CCDelegateTo<RetCC_X86_32_C> 1519 ]>; 1520 1521Other calling convention interfaces include: 1522 1523* ``CCIf <predicate, action>`` --- If the predicate matches, apply the action. 1524 1525* ``CCIfInReg <action>`` --- If the argument is marked with the "``inreg``" 1526 attribute, then apply the action. 1527 1528* ``CCIfNest <action>`` --- If the argument is marked with the "``nest``" 1529 attribute, then apply the action. 1530 1531* ``CCIfNotVarArg <action>`` --- If the current function does not take a 1532 variable number of arguments, apply the action. 1533 1534* ``CCAssignToRegWithShadow <registerList, shadowList>`` --- similar to 1535 ``CCAssignToReg``, but with a shadow list of registers. 1536 1537* ``CCPassByVal <size, align>`` --- Assign value to a stack slot with the 1538 minimum specified size and alignment. 1539 1540* ``CCPromoteToType <type>`` --- Promote the current value to the specified 1541 type. 1542 1543* ``CallingConv <[actions]>`` --- Define each calling convention that is 1544 supported. 1545 1546Assembly Printer 1547================ 1548 1549During the code emission stage, the code generator may utilize an LLVM pass to 1550produce assembly output. To do this, you want to implement the code for a 1551printer that converts LLVM IR to a GAS-format assembly language for your target 1552machine, using the following steps: 1553 1554* Define all the assembly strings for your target, adding them to the 1555 instructions defined in the ``XXXInstrInfo.td`` file. (See 1556 :ref:`instruction-set`.) TableGen will produce an output file 1557 (``XXXGenAsmWriter.inc``) with an implementation of the ``printInstruction`` 1558 method for the ``XXXAsmPrinter`` class. 1559 1560* Write ``XXXTargetAsmInfo.h``, which contains the bare-bones declaration of 1561 the ``XXXTargetAsmInfo`` class (a subclass of ``TargetAsmInfo``). 1562 1563* Write ``XXXTargetAsmInfo.cpp``, which contains target-specific values for 1564 ``TargetAsmInfo`` properties and sometimes new implementations for methods. 1565 1566* Write ``XXXAsmPrinter.cpp``, which implements the ``AsmPrinter`` class that 1567 performs the LLVM-to-assembly conversion. 1568 1569The code in ``XXXTargetAsmInfo.h`` is usually a trivial declaration of the 1570``XXXTargetAsmInfo`` class for use in ``XXXTargetAsmInfo.cpp``. Similarly, 1571``XXXTargetAsmInfo.cpp`` usually has a few declarations of ``XXXTargetAsmInfo`` 1572replacement values that override the default values in ``TargetAsmInfo.cpp``. 1573For example in ``SparcTargetAsmInfo.cpp``: 1574 1575.. code-block:: c++ 1576 1577 SparcTargetAsmInfo::SparcTargetAsmInfo(const SparcTargetMachine &TM) { 1578 Data16bitsDirective = "\t.half\t"; 1579 Data32bitsDirective = "\t.word\t"; 1580 Data64bitsDirective = 0; // .xword is only supported by V9. 1581 ZeroDirective = "\t.skip\t"; 1582 CommentString = "!"; 1583 ConstantPoolSection = "\t.section \".rodata\",#alloc\n"; 1584 } 1585 1586The X86 assembly printer implementation (``X86TargetAsmInfo``) is an example 1587where the target specific ``TargetAsmInfo`` class uses an overridden methods: 1588``ExpandInlineAsm``. 1589 1590A target-specific implementation of ``AsmPrinter`` is written in 1591``XXXAsmPrinter.cpp``, which implements the ``AsmPrinter`` class that converts 1592the LLVM to printable assembly. The implementation must include the following 1593headers that have declarations for the ``AsmPrinter`` and 1594``MachineFunctionPass`` classes. The ``MachineFunctionPass`` is a subclass of 1595``FunctionPass``. 1596 1597.. code-block:: c++ 1598 1599 #include "llvm/CodeGen/AsmPrinter.h" 1600 #include "llvm/CodeGen/MachineFunctionPass.h" 1601 1602As a ``FunctionPass``, ``AsmPrinter`` first calls ``doInitialization`` to set 1603up the ``AsmPrinter``. In ``SparcAsmPrinter``, a ``Mangler`` object is 1604instantiated to process variable names. 1605 1606In ``XXXAsmPrinter.cpp``, the ``runOnMachineFunction`` method (declared in 1607``MachineFunctionPass``) must be implemented for ``XXXAsmPrinter``. In 1608``MachineFunctionPass``, the ``runOnFunction`` method invokes 1609``runOnMachineFunction``. Target-specific implementations of 1610``runOnMachineFunction`` differ, but generally do the following to process each 1611machine function: 1612 1613* Call ``SetupMachineFunction`` to perform initialization. 1614 1615* Call ``EmitConstantPool`` to print out (to the output stream) constants which 1616 have been spilled to memory. 1617 1618* Call ``EmitJumpTableInfo`` to print out jump tables used by the current 1619 function. 1620 1621* Print out the label for the current function. 1622 1623* Print out the code for the function, including basic block labels and the 1624 assembly for the instruction (using ``printInstruction``) 1625 1626The ``XXXAsmPrinter`` implementation must also include the code generated by 1627TableGen that is output in the ``XXXGenAsmWriter.inc`` file. The code in 1628``XXXGenAsmWriter.inc`` contains an implementation of the ``printInstruction`` 1629method that may call these methods: 1630 1631* ``printOperand`` 1632* ``printMemOperand`` 1633* ``printCCOperand`` (for conditional statements) 1634* ``printDataDirective`` 1635* ``printDeclare`` 1636* ``printImplicitDef`` 1637* ``printInlineAsm`` 1638 1639The implementations of ``printDeclare``, ``printImplicitDef``, 1640``printInlineAsm``, and ``printLabel`` in ``AsmPrinter.cpp`` are generally 1641adequate for printing assembly and do not need to be overridden. 1642 1643The ``printOperand`` method is implemented with a long ``switch``/``case`` 1644statement for the type of operand: register, immediate, basic block, external 1645symbol, global address, constant pool index, or jump table index. For an 1646instruction with a memory address operand, the ``printMemOperand`` method 1647should be implemented to generate the proper output. Similarly, 1648``printCCOperand`` should be used to print a conditional operand. 1649 1650``doFinalization`` should be overridden in ``XXXAsmPrinter``, and it should be 1651called to shut down the assembly printer. During ``doFinalization``, global 1652variables and constants are printed to output. 1653 1654Subtarget Support 1655================= 1656 1657Subtarget support is used to inform the code generation process of instruction 1658set variations for a given chip set. For example, the LLVM SPARC 1659implementation provided covers three major versions of the SPARC microprocessor 1660architecture: Version 8 (V8, which is a 32-bit architecture), Version 9 (V9, a 166164-bit architecture), and the UltraSPARC architecture. V8 has 16 1662double-precision floating-point registers that are also usable as either 32 1663single-precision or 8 quad-precision registers. V8 is also purely big-endian. 1664V9 has 32 double-precision floating-point registers that are also usable as 16 1665quad-precision registers, but cannot be used as single-precision registers. 1666The UltraSPARC architecture combines V9 with UltraSPARC Visual Instruction Set 1667extensions. 1668 1669If subtarget support is needed, you should implement a target-specific 1670``XXXSubtarget`` class for your architecture. This class should process the 1671command-line options ``-mcpu=`` and ``-mattr=``. 1672 1673TableGen uses definitions in the ``Target.td`` and ``Sparc.td`` files to 1674generate code in ``SparcGenSubtarget.inc``. In ``Target.td``, shown below, the 1675``SubtargetFeature`` interface is defined. The first 4 string parameters of 1676the ``SubtargetFeature`` interface are a feature name, an attribute set by the 1677feature, the value of the attribute, and a description of the feature. (The 1678fifth parameter is a list of features whose presence is implied, and its 1679default value is an empty array.) 1680 1681.. code-block:: llvm 1682 1683 class SubtargetFeature<string n, string a, string v, string d, 1684 list<SubtargetFeature> i = []> { 1685 string Name = n; 1686 string Attribute = a; 1687 string Value = v; 1688 string Desc = d; 1689 list<SubtargetFeature> Implies = i; 1690 } 1691 1692In the ``Sparc.td`` file, the ``SubtargetFeature`` is used to define the 1693following features. 1694 1695.. code-block:: llvm 1696 1697 def FeatureV9 : SubtargetFeature<"v9", "IsV9", "true", 1698 "Enable SPARC-V9 instructions">; 1699 def FeatureV8Deprecated : SubtargetFeature<"deprecated-v8", 1700 "V8DeprecatedInsts", "true", 1701 "Enable deprecated V8 instructions in V9 mode">; 1702 def FeatureVIS : SubtargetFeature<"vis", "IsVIS", "true", 1703 "Enable UltraSPARC Visual Instruction Set extensions">; 1704 1705Elsewhere in ``Sparc.td``, the ``Proc`` class is defined and then is used to 1706define particular SPARC processor subtypes that may have the previously 1707described features. 1708 1709.. code-block:: llvm 1710 1711 class Proc<string Name, list<SubtargetFeature> Features> 1712 : Processor<Name, NoItineraries, Features>; 1713 1714 def : Proc<"generic", []>; 1715 def : Proc<"v8", []>; 1716 def : Proc<"supersparc", []>; 1717 def : Proc<"sparclite", []>; 1718 def : Proc<"f934", []>; 1719 def : Proc<"hypersparc", []>; 1720 def : Proc<"sparclite86x", []>; 1721 def : Proc<"sparclet", []>; 1722 def : Proc<"tsc701", []>; 1723 def : Proc<"v9", [FeatureV9]>; 1724 def : Proc<"ultrasparc", [FeatureV9, FeatureV8Deprecated]>; 1725 def : Proc<"ultrasparc3", [FeatureV9, FeatureV8Deprecated]>; 1726 def : Proc<"ultrasparc3-vis", [FeatureV9, FeatureV8Deprecated, FeatureVIS]>; 1727 1728From ``Target.td`` and ``Sparc.td`` files, the resulting 1729``SparcGenSubtarget.inc`` specifies enum values to identify the features, 1730arrays of constants to represent the CPU features and CPU subtypes, and the 1731``ParseSubtargetFeatures`` method that parses the features string that sets 1732specified subtarget options. The generated ``SparcGenSubtarget.inc`` file 1733should be included in the ``SparcSubtarget.cpp``. The target-specific 1734implementation of the ``XXXSubtarget`` method should follow this pseudocode: 1735 1736.. code-block:: c++ 1737 1738 XXXSubtarget::XXXSubtarget(const Module &M, const std::string &FS) { 1739 // Set the default features 1740 // Determine default and user specified characteristics of the CPU 1741 // Call ParseSubtargetFeatures(FS, CPU) to parse the features string 1742 // Perform any additional operations 1743 } 1744 1745JIT Support 1746=========== 1747 1748The implementation of a target machine optionally includes a Just-In-Time (JIT) 1749code generator that emits machine code and auxiliary structures as binary 1750output that can be written directly to memory. To do this, implement JIT code 1751generation by performing the following steps: 1752 1753* Write an ``XXXCodeEmitter.cpp`` file that contains a machine function pass 1754 that transforms target-machine instructions into relocatable machine 1755 code. 1756 1757* Write an ``XXXJITInfo.cpp`` file that implements the JIT interfaces for 1758 target-specific code-generation activities, such as emitting machine code and 1759 stubs. 1760 1761* Modify ``XXXTargetMachine`` so that it provides a ``TargetJITInfo`` object 1762 through its ``getJITInfo`` method. 1763 1764There are several different approaches to writing the JIT support code. For 1765instance, TableGen and target descriptor files may be used for creating a JIT 1766code generator, but are not mandatory. For the Alpha and PowerPC target 1767machines, TableGen is used to generate ``XXXGenCodeEmitter.inc``, which 1768contains the binary coding of machine instructions and the 1769``getBinaryCodeForInstr`` method to access those codes. Other JIT 1770implementations do not. 1771 1772Both ``XXXJITInfo.cpp`` and ``XXXCodeEmitter.cpp`` must include the 1773``llvm/CodeGen/MachineCodeEmitter.h`` header file that defines the 1774``MachineCodeEmitter`` class containing code for several callback functions 1775that write data (in bytes, words, strings, etc.) to the output stream. 1776 1777Machine Code Emitter 1778-------------------- 1779 1780In ``XXXCodeEmitter.cpp``, a target-specific of the ``Emitter`` class is 1781implemented as a function pass (subclass of ``MachineFunctionPass``). The 1782target-specific implementation of ``runOnMachineFunction`` (invoked by 1783``runOnFunction`` in ``MachineFunctionPass``) iterates through the 1784``MachineBasicBlock`` calls ``emitInstruction`` to process each instruction and 1785emit binary code. ``emitInstruction`` is largely implemented with case 1786statements on the instruction types defined in ``XXXInstrInfo.h``. For 1787example, in ``X86CodeEmitter.cpp``, the ``emitInstruction`` method is built 1788around the following ``switch``/``case`` statements: 1789 1790.. code-block:: c++ 1791 1792 switch (Desc->TSFlags & X86::FormMask) { 1793 case X86II::Pseudo: // for not yet implemented instructions 1794 ... // or pseudo-instructions 1795 break; 1796 case X86II::RawFrm: // for instructions with a fixed opcode value 1797 ... 1798 break; 1799 case X86II::AddRegFrm: // for instructions that have one register operand 1800 ... // added to their opcode 1801 break; 1802 case X86II::MRMDestReg:// for instructions that use the Mod/RM byte 1803 ... // to specify a destination (register) 1804 break; 1805 case X86II::MRMDestMem:// for instructions that use the Mod/RM byte 1806 ... // to specify a destination (memory) 1807 break; 1808 case X86II::MRMSrcReg: // for instructions that use the Mod/RM byte 1809 ... // to specify a source (register) 1810 break; 1811 case X86II::MRMSrcMem: // for instructions that use the Mod/RM byte 1812 ... // to specify a source (memory) 1813 break; 1814 case X86II::MRM0r: case X86II::MRM1r: // for instructions that operate on 1815 case X86II::MRM2r: case X86II::MRM3r: // a REGISTER r/m operand and 1816 case X86II::MRM4r: case X86II::MRM5r: // use the Mod/RM byte and a field 1817 case X86II::MRM6r: case X86II::MRM7r: // to hold extended opcode data 1818 ... 1819 break; 1820 case X86II::MRM0m: case X86II::MRM1m: // for instructions that operate on 1821 case X86II::MRM2m: case X86II::MRM3m: // a MEMORY r/m operand and 1822 case X86II::MRM4m: case X86II::MRM5m: // use the Mod/RM byte and a field 1823 case X86II::MRM6m: case X86II::MRM7m: // to hold extended opcode data 1824 ... 1825 break; 1826 case X86II::MRMInitReg: // for instructions whose source and 1827 ... // destination are the same register 1828 break; 1829 } 1830 1831The implementations of these case statements often first emit the opcode and 1832then get the operand(s). Then depending upon the operand, helper methods may 1833be called to process the operand(s). For example, in ``X86CodeEmitter.cpp``, 1834for the ``X86II::AddRegFrm`` case, the first data emitted (by ``emitByte``) is 1835the opcode added to the register operand. Then an object representing the 1836machine operand, ``MO1``, is extracted. The helper methods such as 1837``isImmediate``, ``isGlobalAddress``, ``isExternalSymbol``, 1838``isConstantPoolIndex``, and ``isJumpTableIndex`` determine the operand type. 1839(``X86CodeEmitter.cpp`` also has private methods such as ``emitConstant``, 1840``emitGlobalAddress``, ``emitExternalSymbolAddress``, ``emitConstPoolAddress``, 1841and ``emitJumpTableAddress`` that emit the data into the output stream.) 1842 1843.. code-block:: c++ 1844 1845 case X86II::AddRegFrm: 1846 MCE.emitByte(BaseOpcode + getX86RegNum(MI.getOperand(CurOp++).getReg())); 1847 1848 if (CurOp != NumOps) { 1849 const MachineOperand &MO1 = MI.getOperand(CurOp++); 1850 unsigned Size = X86InstrInfo::sizeOfImm(Desc); 1851 if (MO1.isImmediate()) 1852 emitConstant(MO1.getImm(), Size); 1853 else { 1854 unsigned rt = Is64BitMode ? X86::reloc_pcrel_word 1855 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word); 1856 if (Opcode == X86::MOV64ri) 1857 rt = X86::reloc_absolute_dword; // FIXME: add X86II flag? 1858 if (MO1.isGlobalAddress()) { 1859 bool NeedStub = isa<Function>(MO1.getGlobal()); 1860 bool isLazy = gvNeedsLazyPtr(MO1.getGlobal()); 1861 emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0, 1862 NeedStub, isLazy); 1863 } else if (MO1.isExternalSymbol()) 1864 emitExternalSymbolAddress(MO1.getSymbolName(), rt); 1865 else if (MO1.isConstantPoolIndex()) 1866 emitConstPoolAddress(MO1.getIndex(), rt); 1867 else if (MO1.isJumpTableIndex()) 1868 emitJumpTableAddress(MO1.getIndex(), rt); 1869 } 1870 } 1871 break; 1872 1873In the previous example, ``XXXCodeEmitter.cpp`` uses the variable ``rt``, which 1874is a ``RelocationType`` enum that may be used to relocate addresses (for 1875example, a global address with a PIC base offset). The ``RelocationType`` enum 1876for that target is defined in the short target-specific ``XXXRelocations.h`` 1877file. The ``RelocationType`` is used by the ``relocate`` method defined in 1878``XXXJITInfo.cpp`` to rewrite addresses for referenced global symbols. 1879 1880For example, ``X86Relocations.h`` specifies the following relocation types for 1881the X86 addresses. In all four cases, the relocated value is added to the 1882value already in memory. For ``reloc_pcrel_word`` and ``reloc_picrel_word``, 1883there is an additional initial adjustment. 1884 1885.. code-block:: c++ 1886 1887 enum RelocationType { 1888 reloc_pcrel_word = 0, // add reloc value after adjusting for the PC loc 1889 reloc_picrel_word = 1, // add reloc value after adjusting for the PIC base 1890 reloc_absolute_word = 2, // absolute relocation; no additional adjustment 1891 reloc_absolute_dword = 3 // absolute relocation; no additional adjustment 1892 }; 1893 1894Target JIT Info 1895--------------- 1896 1897``XXXJITInfo.cpp`` implements the JIT interfaces for target-specific 1898code-generation activities, such as emitting machine code and stubs. At 1899minimum, a target-specific version of ``XXXJITInfo`` implements the following: 1900 1901* ``getLazyResolverFunction`` --- Initializes the JIT, gives the target a 1902 function that is used for compilation. 1903 1904* ``emitFunctionStub`` --- Returns a native function with a specified address 1905 for a callback function. 1906 1907* ``relocate`` --- Changes the addresses of referenced globals, based on 1908 relocation types. 1909 1910* Callback function that are wrappers to a function stub that is used when the 1911 real target is not initially known. 1912 1913``getLazyResolverFunction`` is generally trivial to implement. It makes the 1914incoming parameter as the global ``JITCompilerFunction`` and returns the 1915callback function that will be used a function wrapper. For the Alpha target 1916(in ``AlphaJITInfo.cpp``), the ``getLazyResolverFunction`` implementation is 1917simply: 1918 1919.. code-block:: c++ 1920 1921 TargetJITInfo::LazyResolverFn AlphaJITInfo::getLazyResolverFunction( 1922 JITCompilerFn F) { 1923 JITCompilerFunction = F; 1924 return AlphaCompilationCallback; 1925 } 1926 1927For the X86 target, the ``getLazyResolverFunction`` implementation is a little 1928more complicated, because it returns a different callback function for 1929processors with SSE instructions and XMM registers. 1930 1931The callback function initially saves and later restores the callee register 1932values, incoming arguments, and frame and return address. The callback 1933function needs low-level access to the registers or stack, so it is typically 1934implemented with assembler. 1935 1936