WritingAnLLVMBackend.rst 81 KB

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