CodeGenerator.rst 115 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696
  1. ==========================================
  2. The LLVM Target-Independent Code Generator
  3. ==========================================
  4. .. role:: raw-html(raw)
  5. :format: html
  6. .. raw:: html
  7. <style>
  8. .unknown { background-color: #C0C0C0; text-align: center; }
  9. .unknown:before { content: "?" }
  10. .no { background-color: #C11B17 }
  11. .no:before { content: "N" }
  12. .partial { background-color: #F88017 }
  13. .yes { background-color: #0F0; }
  14. .yes:before { content: "Y" }
  15. .na { background-color: #6666FF; }
  16. .na:before { content: "N/A" }
  17. </style>
  18. .. contents::
  19. :local:
  20. .. warning::
  21. This is a work in progress.
  22. Introduction
  23. ============
  24. The LLVM target-independent code generator is a framework that provides a suite
  25. of reusable components for translating the LLVM internal representation to the
  26. machine code for a specified target---either in assembly form (suitable for a
  27. static compiler) or in binary machine code format (usable for a JIT
  28. compiler). The LLVM target-independent code generator consists of six main
  29. components:
  30. 1. `Abstract target description`_ interfaces which capture important properties
  31. about various aspects of the machine, independently of how they will be used.
  32. These interfaces are defined in ``include/llvm/Target/``.
  33. 2. Classes used to represent the `code being generated`_ for a target. These
  34. classes are intended to be abstract enough to represent the machine code for
  35. *any* target machine. These classes are defined in
  36. ``include/llvm/CodeGen/``. At this level, concepts like "constant pool
  37. entries" and "jump tables" are explicitly exposed.
  38. 3. Classes and algorithms used to represent code at the object file level, the
  39. `MC Layer`_. These classes represent assembly level constructs like labels,
  40. sections, and instructions. At this level, concepts like "constant pool
  41. entries" and "jump tables" don't exist.
  42. 4. `Target-independent algorithms`_ used to implement various phases of native
  43. code generation (register allocation, scheduling, stack frame representation,
  44. etc). This code lives in ``lib/CodeGen/``.
  45. 5. `Implementations of the abstract target description interfaces`_ for
  46. particular targets. These machine descriptions make use of the components
  47. provided by LLVM, and can optionally provide custom target-specific passes,
  48. to build complete code generators for a specific target. Target descriptions
  49. live in ``lib/Target/``.
  50. 6. The target-independent JIT components. The LLVM JIT is completely target
  51. independent (it uses the ``TargetJITInfo`` structure to interface for
  52. target-specific issues. The code for the target-independent JIT lives in
  53. ``lib/ExecutionEngine/JIT``.
  54. Depending on which part of the code generator you are interested in working on,
  55. different pieces of this will be useful to you. In any case, you should be
  56. familiar with the `target description`_ and `machine code representation`_
  57. classes. If you want to add a backend for a new target, you will need to
  58. `implement the target description`_ classes for your new target and understand
  59. the :doc:`LLVM code representation <LangRef>`. If you are interested in
  60. implementing a new `code generation algorithm`_, it should only depend on the
  61. target-description and machine code representation classes, ensuring that it is
  62. portable.
  63. Required components in the code generator
  64. -----------------------------------------
  65. The two pieces of the LLVM code generator are the high-level interface to the
  66. code generator and the set of reusable components that can be used to build
  67. target-specific backends. The two most important interfaces (:raw-html:`<tt>`
  68. `TargetMachine`_ :raw-html:`</tt>` and :raw-html:`<tt>` `DataLayout`_
  69. :raw-html:`</tt>`) are the only ones that are required to be defined for a
  70. backend to fit into the LLVM system, but the others must be defined if the
  71. reusable code generator components are going to be used.
  72. This design has two important implications. The first is that LLVM can support
  73. completely non-traditional code generation targets. For example, the C backend
  74. does not require register allocation, instruction selection, or any of the other
  75. standard components provided by the system. As such, it only implements these
  76. two interfaces, and does its own thing. Note that C backend was removed from the
  77. trunk since LLVM 3.1 release. Another example of a code generator like this is a
  78. (purely hypothetical) backend that converts LLVM to the GCC RTL form and uses
  79. GCC to emit machine code for a target.
  80. This design also implies that it is possible to design and implement radically
  81. different code generators in the LLVM system that do not make use of any of the
  82. built-in components. Doing so is not recommended at all, but could be required
  83. for radically different targets that do not fit into the LLVM machine
  84. description model: FPGAs for example.
  85. .. _high-level design of the code generator:
  86. The high-level design of the code generator
  87. -------------------------------------------
  88. The LLVM target-independent code generator is designed to support efficient and
  89. quality code generation for standard register-based microprocessors. Code
  90. generation in this model is divided into the following stages:
  91. 1. `Instruction Selection`_ --- This phase determines an efficient way to
  92. express the input LLVM code in the target instruction set. This stage
  93. produces the initial code for the program in the target instruction set, then
  94. makes use of virtual registers in SSA form and physical registers that
  95. represent any required register assignments due to target constraints or
  96. calling conventions. This step turns the LLVM code into a DAG of target
  97. instructions.
  98. 2. `Scheduling and Formation`_ --- This phase takes the DAG of target
  99. instructions produced by the instruction selection phase, determines an
  100. ordering of the instructions, then emits the instructions as :raw-html:`<tt>`
  101. `MachineInstr`_\s :raw-html:`</tt>` with that ordering. Note that we
  102. describe this in the `instruction selection section`_ because it operates on
  103. a `SelectionDAG`_.
  104. 3. `SSA-based Machine Code Optimizations`_ --- This optional stage consists of a
  105. series of machine-code optimizations that operate on the SSA-form produced by
  106. the instruction selector. Optimizations like modulo-scheduling or peephole
  107. optimization work here.
  108. 4. `Register Allocation`_ --- The target code is transformed from an infinite
  109. virtual register file in SSA form to the concrete register file used by the
  110. target. This phase introduces spill code and eliminates all virtual register
  111. references from the program.
  112. 5. `Prolog/Epilog Code Insertion`_ --- Once the machine code has been generated
  113. for the function and the amount of stack space required is known (used for
  114. LLVM alloca's and spill slots), the prolog and epilog code for the function
  115. can be inserted and "abstract stack location references" can be eliminated.
  116. This stage is responsible for implementing optimizations like frame-pointer
  117. elimination and stack packing.
  118. 6. `Late Machine Code Optimizations`_ --- Optimizations that operate on "final"
  119. machine code can go here, such as spill code scheduling and peephole
  120. optimizations.
  121. 7. `Code Emission`_ --- The final stage actually puts out the code for the
  122. current function, either in the target assembler format or in machine
  123. code.
  124. The code generator is based on the assumption that the instruction selector will
  125. use an optimal pattern matching selector to create high-quality sequences of
  126. native instructions. Alternative code generator designs based on pattern
  127. expansion and aggressive iterative peephole optimization are much slower. This
  128. design permits efficient compilation (important for JIT environments) and
  129. aggressive optimization (used when generating code offline) by allowing
  130. components of varying levels of sophistication to be used for any step of
  131. compilation.
  132. In addition to these stages, target implementations can insert arbitrary
  133. target-specific passes into the flow. For example, the X86 target uses a
  134. special pass to handle the 80x87 floating point stack architecture. Other
  135. targets with unusual requirements can be supported with custom passes as needed.
  136. Using TableGen for target description
  137. -------------------------------------
  138. The target description classes require a detailed description of the target
  139. architecture. These target descriptions often have a large amount of common
  140. information (e.g., an ``add`` instruction is almost identical to a ``sub``
  141. instruction). In order to allow the maximum amount of commonality to be
  142. factored out, the LLVM code generator uses the
  143. :doc:`TableGen/index` tool to describe big chunks of the
  144. target machine, which allows the use of domain-specific and target-specific
  145. abstractions to reduce the amount of repetition.
  146. As LLVM continues to be developed and refined, we plan to move more and more of
  147. the target description to the ``.td`` form. Doing so gives us a number of
  148. advantages. The most important is that it makes it easier to port LLVM because
  149. it reduces the amount of C++ code that has to be written, and the surface area
  150. of the code generator that needs to be understood before someone can get
  151. something working. Second, it makes it easier to change things. In particular,
  152. if tables and other things are all emitted by ``tblgen``, we only need a change
  153. in one place (``tblgen``) to update all of the targets to a new interface.
  154. .. _Abstract target description:
  155. .. _target description:
  156. Target description classes
  157. ==========================
  158. The LLVM target description classes (located in the ``include/llvm/Target``
  159. directory) provide an abstract description of the target machine independent of
  160. any particular client. These classes are designed to capture the *abstract*
  161. properties of the target (such as the instructions and registers it has), and do
  162. not incorporate any particular pieces of code generation algorithms.
  163. All of the target description classes (except the :raw-html:`<tt>` `DataLayout`_
  164. :raw-html:`</tt>` class) are designed to be subclassed by the concrete target
  165. implementation, and have virtual methods implemented. To get to these
  166. implementations, the :raw-html:`<tt>` `TargetMachine`_ :raw-html:`</tt>` class
  167. provides accessors that should be implemented by the target.
  168. .. _TargetMachine:
  169. The ``TargetMachine`` class
  170. ---------------------------
  171. The ``TargetMachine`` class provides virtual methods that are used to access the
  172. target-specific implementations of the various target description classes via
  173. the ``get*Info`` methods (``getInstrInfo``, ``getRegisterInfo``,
  174. ``getFrameInfo``, etc.). This class is designed to be specialized by a concrete
  175. target implementation (e.g., ``X86TargetMachine``) which implements the various
  176. virtual methods. The only required target description class is the
  177. :raw-html:`<tt>` `DataLayout`_ :raw-html:`</tt>` class, but if the code
  178. generator components are to be used, the other interfaces should be implemented
  179. as well.
  180. .. _DataLayout:
  181. The ``DataLayout`` class
  182. ------------------------
  183. The ``DataLayout`` class is the only required target description class, and it
  184. is the only class that is not extensible (you cannot derive a new class from
  185. it). ``DataLayout`` specifies information about how the target lays out memory
  186. for structures, the alignment requirements for various data types, the size of
  187. pointers in the target, and whether the target is little-endian or
  188. big-endian.
  189. .. _TargetLowering:
  190. The ``TargetLowering`` class
  191. ----------------------------
  192. The ``TargetLowering`` class is used by SelectionDAG based instruction selectors
  193. primarily to describe how LLVM code should be lowered to SelectionDAG
  194. operations. Among other things, this class indicates:
  195. * an initial register class to use for various ``ValueType``\s,
  196. * which operations are natively supported by the target machine,
  197. * the return type of ``setcc`` operations,
  198. * the type to use for shift amounts, and
  199. * various high-level characteristics, like whether it is profitable to turn
  200. division by a constant into a multiplication sequence.
  201. .. _TargetRegisterInfo:
  202. The ``TargetRegisterInfo`` class
  203. --------------------------------
  204. The ``TargetRegisterInfo`` class is used to describe the register file of the
  205. target and any interactions between the registers.
  206. Registers are represented in the code generator by unsigned integers. Physical
  207. registers (those that actually exist in the target description) are unique
  208. small numbers, and virtual registers are generally large. Note that
  209. register ``#0`` is reserved as a flag value.
  210. Each register in the processor description has an associated
  211. ``TargetRegisterDesc`` entry, which provides a textual name for the register
  212. (used for assembly output and debugging dumps) and a set of aliases (used to
  213. indicate whether one register overlaps with another).
  214. In addition to the per-register description, the ``TargetRegisterInfo`` class
  215. exposes a set of processor specific register classes (instances of the
  216. ``TargetRegisterClass`` class). Each register class contains sets of registers
  217. that have the same properties (for example, they are all 32-bit integer
  218. registers). Each SSA virtual register created by the instruction selector has
  219. an associated register class. When the register allocator runs, it replaces
  220. virtual registers with a physical register in the set.
  221. The target-specific implementations of these classes is auto-generated from a
  222. :doc:`TableGen/index` description of the register file.
  223. .. _TargetInstrInfo:
  224. The ``TargetInstrInfo`` class
  225. -----------------------------
  226. The ``TargetInstrInfo`` class is used to describe the machine instructions
  227. supported by the target. Descriptions define things like the mnemonic for
  228. the opcode, the number of operands, the list of implicit register uses and defs,
  229. whether the instruction has certain target-independent properties (accesses
  230. memory, is commutable, etc), and holds any target-specific flags.
  231. The ``TargetFrameLowering`` class
  232. ---------------------------------
  233. The ``TargetFrameLowering`` class is used to provide information about the stack
  234. frame layout of the target. It holds the direction of stack growth, the known
  235. stack alignment on entry to each function, and the offset to the local area.
  236. The offset to the local area is the offset from the stack pointer on function
  237. entry to the first location where function data (local variables, spill
  238. locations) can be stored.
  239. The ``TargetSubtarget`` class
  240. -----------------------------
  241. The ``TargetSubtarget`` class is used to provide information about the specific
  242. chip set being targeted. A sub-target informs code generation of which
  243. instructions are supported, instruction latencies and instruction execution
  244. itinerary; i.e., which processing units are used, in what order, and for how
  245. long.
  246. The ``TargetJITInfo`` class
  247. ---------------------------
  248. The ``TargetJITInfo`` class exposes an abstract interface used by the
  249. Just-In-Time code generator to perform target-specific activities, such as
  250. emitting stubs. If a ``TargetMachine`` supports JIT code generation, it should
  251. provide one of these objects through the ``getJITInfo`` method.
  252. .. _code being generated:
  253. .. _machine code representation:
  254. Machine code description classes
  255. ================================
  256. At the high-level, LLVM code is translated to a machine specific representation
  257. formed out of :raw-html:`<tt>` `MachineFunction`_ :raw-html:`</tt>`,
  258. :raw-html:`<tt>` `MachineBasicBlock`_ :raw-html:`</tt>`, and :raw-html:`<tt>`
  259. `MachineInstr`_ :raw-html:`</tt>` instances (defined in
  260. ``include/llvm/CodeGen``). This representation is completely target agnostic,
  261. representing instructions in their most abstract form: an opcode and a series of
  262. operands. This representation is designed to support both an SSA representation
  263. for machine code, as well as a register allocated, non-SSA form.
  264. .. _MachineInstr:
  265. The ``MachineInstr`` class
  266. --------------------------
  267. Target machine instructions are represented as instances of the ``MachineInstr``
  268. class. This class is an extremely abstract way of representing machine
  269. instructions. In particular, it only keeps track of an opcode number and a set
  270. of operands.
  271. The opcode number is a simple unsigned integer that only has meaning to a
  272. specific backend. All of the instructions for a target should be defined in the
  273. ``*InstrInfo.td`` file for the target. The opcode enum values are auto-generated
  274. from this description. The ``MachineInstr`` class does not have any information
  275. about how to interpret the instruction (i.e., what the semantics of the
  276. instruction are); for that you must refer to the :raw-html:`<tt>`
  277. `TargetInstrInfo`_ :raw-html:`</tt>` class.
  278. The operands of a machine instruction can be of several different types: a
  279. register reference, a constant integer, a basic block reference, etc. In
  280. addition, a machine operand should be marked as a def or a use of the value
  281. (though only registers are allowed to be defs).
  282. By convention, the LLVM code generator orders instruction operands so that all
  283. register definitions come before the register uses, even on architectures that
  284. are normally printed in other orders. For example, the SPARC add instruction:
  285. "``add %i1, %i2, %i3``" adds the "%i1", and "%i2" registers and stores the
  286. result into the "%i3" register. In the LLVM code generator, the operands should
  287. be stored as "``%i3, %i1, %i2``": with the destination first.
  288. Keeping destination (definition) operands at the beginning of the operand list
  289. has several advantages. In particular, the debugging printer will print the
  290. instruction like this:
  291. .. code-block:: llvm
  292. %r3 = add %i1, %i2
  293. Also if the first operand is a def, it is easier to `create instructions`_ whose
  294. only def is the first operand.
  295. .. _create instructions:
  296. Using the ``MachineInstrBuilder.h`` functions
  297. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  298. Machine instructions are created by using the ``BuildMI`` functions, located in
  299. the ``include/llvm/CodeGen/MachineInstrBuilder.h`` file. The ``BuildMI``
  300. functions make it easy to build arbitrary machine instructions. Usage of the
  301. ``BuildMI`` functions look like this:
  302. .. code-block:: c++
  303. // Create a 'DestReg = mov 42' (rendered in X86 assembly as 'mov DestReg, 42')
  304. // instruction and insert it at the end of the given MachineBasicBlock.
  305. const TargetInstrInfo &TII = ...
  306. MachineBasicBlock &MBB = ...
  307. DebugLoc DL;
  308. MachineInstr *MI = BuildMI(MBB, DL, TII.get(X86::MOV32ri), DestReg).addImm(42);
  309. // Create the same instr, but insert it before a specified iterator point.
  310. MachineBasicBlock::iterator MBBI = ...
  311. BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), DestReg).addImm(42);
  312. // Create a 'cmp Reg, 0' instruction, no destination reg.
  313. MI = BuildMI(MBB, DL, TII.get(X86::CMP32ri8)).addReg(Reg).addImm(42);
  314. // Create an 'sahf' instruction which takes no operands and stores nothing.
  315. MI = BuildMI(MBB, DL, TII.get(X86::SAHF));
  316. // Create a self looping branch instruction.
  317. BuildMI(MBB, DL, TII.get(X86::JNE)).addMBB(&MBB);
  318. If you need to add a definition operand (other than the optional destination
  319. register), you must explicitly mark it as such:
  320. .. code-block:: c++
  321. MI.addReg(Reg, RegState::Define);
  322. Fixed (preassigned) registers
  323. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  324. One important issue that the code generator needs to be aware of is the presence
  325. of fixed registers. In particular, there are often places in the instruction
  326. stream where the register allocator *must* arrange for a particular value to be
  327. in a particular register. This can occur due to limitations of the instruction
  328. set (e.g., the X86 can only do a 32-bit divide with the ``EAX``/``EDX``
  329. registers), or external factors like calling conventions. In any case, the
  330. instruction selector should emit code that copies a virtual register into or out
  331. of a physical register when needed.
  332. For example, consider this simple LLVM example:
  333. .. code-block:: llvm
  334. define i32 @test(i32 %X, i32 %Y) {
  335. %Z = sdiv i32 %X, %Y
  336. ret i32 %Z
  337. }
  338. The X86 instruction selector might produce this machine code for the ``div`` and
  339. ``ret``:
  340. .. code-block:: text
  341. ;; Start of div
  342. %EAX = mov %reg1024 ;; Copy X (in reg1024) into EAX
  343. %reg1027 = sar %reg1024, 31
  344. %EDX = mov %reg1027 ;; Sign extend X into EDX
  345. idiv %reg1025 ;; Divide by Y (in reg1025)
  346. %reg1026 = mov %EAX ;; Read the result (Z) out of EAX
  347. ;; Start of ret
  348. %EAX = mov %reg1026 ;; 32-bit return value goes in EAX
  349. ret
  350. By the end of code generation, the register allocator would coalesce the
  351. registers and delete the resultant identity moves producing the following
  352. code:
  353. .. code-block:: text
  354. ;; X is in EAX, Y is in ECX
  355. mov %EAX, %EDX
  356. sar %EDX, 31
  357. idiv %ECX
  358. ret
  359. This approach is extremely general (if it can handle the X86 architecture, it
  360. can handle anything!) and allows all of the target specific knowledge about the
  361. instruction stream to be isolated in the instruction selector. Note that
  362. physical registers should have a short lifetime for good code generation, and
  363. all physical registers are assumed dead on entry to and exit from basic blocks
  364. (before register allocation). Thus, if you need a value to be live across basic
  365. block boundaries, it *must* live in a virtual register.
  366. Call-clobbered registers
  367. ^^^^^^^^^^^^^^^^^^^^^^^^
  368. Some machine instructions, like calls, clobber a large number of physical
  369. registers. Rather than adding ``<def,dead>`` operands for all of them, it is
  370. possible to use an ``MO_RegisterMask`` operand instead. The register mask
  371. operand holds a bit mask of preserved registers, and everything else is
  372. considered to be clobbered by the instruction.
  373. Machine code in SSA form
  374. ^^^^^^^^^^^^^^^^^^^^^^^^
  375. ``MachineInstr``'s are initially selected in SSA-form, and are maintained in
  376. SSA-form until register allocation happens. For the most part, this is
  377. trivially simple since LLVM is already in SSA form; LLVM PHI nodes become
  378. machine code PHI nodes, and virtual registers are only allowed to have a single
  379. definition.
  380. After register allocation, machine code is no longer in SSA-form because there
  381. are no virtual registers left in the code.
  382. .. _MachineBasicBlock:
  383. The ``MachineBasicBlock`` class
  384. -------------------------------
  385. The ``MachineBasicBlock`` class contains a list of machine instructions
  386. (:raw-html:`<tt>` `MachineInstr`_ :raw-html:`</tt>` instances). It roughly
  387. corresponds to the LLVM code input to the instruction selector, but there can be
  388. a one-to-many mapping (i.e. one LLVM basic block can map to multiple machine
  389. basic blocks). The ``MachineBasicBlock`` class has a "``getBasicBlock``" method,
  390. which returns the LLVM basic block that it comes from.
  391. .. _MachineFunction:
  392. The ``MachineFunction`` class
  393. -----------------------------
  394. The ``MachineFunction`` class contains a list of machine basic blocks
  395. (:raw-html:`<tt>` `MachineBasicBlock`_ :raw-html:`</tt>` instances). It
  396. corresponds one-to-one with the LLVM function input to the instruction selector.
  397. In addition to a list of basic blocks, the ``MachineFunction`` contains a a
  398. ``MachineConstantPool``, a ``MachineFrameInfo``, a ``MachineFunctionInfo``, and
  399. a ``MachineRegisterInfo``. See ``include/llvm/CodeGen/MachineFunction.h`` for
  400. more information.
  401. ``MachineInstr Bundles``
  402. ------------------------
  403. LLVM code generator can model sequences of instructions as MachineInstr
  404. bundles. A MI bundle can model a VLIW group / pack which contains an arbitrary
  405. number of parallel instructions. It can also be used to model a sequential list
  406. of instructions (potentially with data dependencies) that cannot be legally
  407. separated (e.g. ARM Thumb2 IT blocks).
  408. Conceptually a MI bundle is a MI with a number of other MIs nested within:
  409. ::
  410. --------------
  411. | Bundle | ---------
  412. -------------- \
  413. | ----------------
  414. | | MI |
  415. | ----------------
  416. | |
  417. | ----------------
  418. | | MI |
  419. | ----------------
  420. | |
  421. | ----------------
  422. | | MI |
  423. | ----------------
  424. |
  425. --------------
  426. | Bundle | --------
  427. -------------- \
  428. | ----------------
  429. | | MI |
  430. | ----------------
  431. | |
  432. | ----------------
  433. | | MI |
  434. | ----------------
  435. | |
  436. | ...
  437. |
  438. --------------
  439. | Bundle | --------
  440. -------------- \
  441. |
  442. ...
  443. MI bundle support does not change the physical representations of
  444. MachineBasicBlock and MachineInstr. All the MIs (including top level and nested
  445. ones) are stored as sequential list of MIs. The "bundled" MIs are marked with
  446. the 'InsideBundle' flag. A top level MI with the special BUNDLE opcode is used
  447. to represent the start of a bundle. It's legal to mix BUNDLE MIs with individual
  448. MIs that are not inside bundles nor represent bundles.
  449. MachineInstr passes should operate on a MI bundle as a single unit. Member
  450. methods have been taught to correctly handle bundles and MIs inside bundles.
  451. The MachineBasicBlock iterator has been modified to skip over bundled MIs to
  452. enforce the bundle-as-a-single-unit concept. An alternative iterator
  453. instr_iterator has been added to MachineBasicBlock to allow passes to iterate
  454. over all of the MIs in a MachineBasicBlock, including those which are nested
  455. inside bundles. The top level BUNDLE instruction must have the correct set of
  456. register MachineOperand's that represent the cumulative inputs and outputs of
  457. the bundled MIs.
  458. Packing / bundling of MachineInstrs for VLIW architectures should
  459. generally be done as part of the register allocation super-pass. More
  460. specifically, the pass which determines what MIs should be bundled
  461. together should be done after code generator exits SSA form
  462. (i.e. after two-address pass, PHI elimination, and copy coalescing).
  463. Such bundles should be finalized (i.e. adding BUNDLE MIs and input and
  464. output register MachineOperands) after virtual registers have been
  465. rewritten into physical registers. This eliminates the need to add
  466. virtual register operands to BUNDLE instructions which would
  467. effectively double the virtual register def and use lists. Bundles may
  468. use virtual registers and be formed in SSA form, but may not be
  469. appropriate for all use cases.
  470. .. _MC Layer:
  471. The "MC" Layer
  472. ==============
  473. The MC Layer is used to represent and process code at the raw machine code
  474. level, devoid of "high level" information like "constant pools", "jump tables",
  475. "global variables" or anything like that. At this level, LLVM handles things
  476. like label names, machine instructions, and sections in the object file. The
  477. code in this layer is used for a number of important purposes: the tail end of
  478. the code generator uses it to write a .s or .o file, and it is also used by the
  479. llvm-mc tool to implement standalone machine code assemblers and disassemblers.
  480. This section describes some of the important classes. There are also a number
  481. of important subsystems that interact at this layer, they are described later in
  482. this manual.
  483. .. _MCStreamer:
  484. The ``MCStreamer`` API
  485. ----------------------
  486. MCStreamer is best thought of as an assembler API. It is an abstract API which
  487. is *implemented* in different ways (e.g. to output a .s file, output an ELF .o
  488. file, etc) but whose API correspond directly to what you see in a .s file.
  489. MCStreamer has one method per directive, such as EmitLabel, EmitSymbolAttribute,
  490. SwitchSection, EmitValue (for .byte, .word), etc, which directly correspond to
  491. assembly level directives. It also has an EmitInstruction method, which is used
  492. to output an MCInst to the streamer.
  493. This API is most important for two clients: the llvm-mc stand-alone assembler is
  494. effectively a parser that parses a line, then invokes a method on MCStreamer. In
  495. the code generator, the `Code Emission`_ phase of the code generator lowers
  496. higher level LLVM IR and Machine* constructs down to the MC layer, emitting
  497. directives through MCStreamer.
  498. On the implementation side of MCStreamer, there are two major implementations:
  499. one for writing out a .s file (MCAsmStreamer), and one for writing out a .o
  500. file (MCObjectStreamer). MCAsmStreamer is a straightforward implementation
  501. that prints out a directive for each method (e.g. ``EmitValue -> .byte``), but
  502. MCObjectStreamer implements a full assembler.
  503. For target specific directives, the MCStreamer has a MCTargetStreamer instance.
  504. Each target that needs it defines a class that inherits from it and is a lot
  505. like MCStreamer itself: It has one method per directive and two classes that
  506. inherit from it, a target object streamer and a target asm streamer. The target
  507. asm streamer just prints it (``emitFnStart -> .fnstart``), and the object
  508. streamer implement the assembler logic for it.
  509. To make llvm use these classes, the target initialization must call
  510. TargetRegistry::RegisterAsmStreamer and TargetRegistry::RegisterMCObjectStreamer
  511. passing callbacks that allocate the corresponding target streamer and pass it
  512. to createAsmStreamer or to the appropriate object streamer constructor.
  513. The ``MCContext`` class
  514. -----------------------
  515. The MCContext class is the owner of a variety of uniqued data structures at the
  516. MC layer, including symbols, sections, etc. As such, this is the class that you
  517. interact with to create symbols and sections. This class can not be subclassed.
  518. The ``MCSymbol`` class
  519. ----------------------
  520. The MCSymbol class represents a symbol (aka label) in the assembly file. There
  521. are two interesting kinds of symbols: assembler temporary symbols, and normal
  522. symbols. Assembler temporary symbols are used and processed by the assembler
  523. but are discarded when the object file is produced. The distinction is usually
  524. represented by adding a prefix to the label, for example "L" labels are
  525. assembler temporary labels in MachO.
  526. MCSymbols are created by MCContext and uniqued there. This means that MCSymbols
  527. can be compared for pointer equivalence to find out if they are the same symbol.
  528. Note that pointer inequality does not guarantee the labels will end up at
  529. different addresses though. It's perfectly legal to output something like this
  530. to the .s file:
  531. ::
  532. foo:
  533. bar:
  534. .byte 4
  535. In this case, both the foo and bar symbols will have the same address.
  536. The ``MCSection`` class
  537. -----------------------
  538. The ``MCSection`` class represents an object-file specific section. It is
  539. subclassed by object file specific implementations (e.g. ``MCSectionMachO``,
  540. ``MCSectionCOFF``, ``MCSectionELF``) and these are created and uniqued by
  541. MCContext. The MCStreamer has a notion of the current section, which can be
  542. changed with the SwitchToSection method (which corresponds to a ".section"
  543. directive in a .s file).
  544. .. _MCInst:
  545. The ``MCInst`` class
  546. --------------------
  547. The ``MCInst`` class is a target-independent representation of an instruction.
  548. It is a simple class (much more so than `MachineInstr`_) that holds a
  549. target-specific opcode and a vector of MCOperands. MCOperand, in turn, is a
  550. simple discriminated union of three cases: 1) a simple immediate, 2) a target
  551. register ID, 3) a symbolic expression (e.g. "``Lfoo-Lbar+42``") as an MCExpr.
  552. MCInst is the common currency used to represent machine instructions at the MC
  553. layer. It is the type used by the instruction encoder, the instruction printer,
  554. and the type generated by the assembly parser and disassembler.
  555. .. _Target-independent algorithms:
  556. .. _code generation algorithm:
  557. Target-independent code generation algorithms
  558. =============================================
  559. This section documents the phases described in the `high-level design of the
  560. code generator`_. It explains how they work and some of the rationale behind
  561. their design.
  562. .. _Instruction Selection:
  563. .. _instruction selection section:
  564. Instruction Selection
  565. ---------------------
  566. Instruction Selection is the process of translating LLVM code presented to the
  567. code generator into target-specific machine instructions. There are several
  568. well-known ways to do this in the literature. LLVM uses a SelectionDAG based
  569. instruction selector.
  570. Portions of the DAG instruction selector are generated from the target
  571. description (``*.td``) files. Our goal is for the entire instruction selector
  572. to be generated from these ``.td`` files, though currently there are still
  573. things that require custom C++ code.
  574. .. _SelectionDAG:
  575. Introduction to SelectionDAGs
  576. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  577. The SelectionDAG provides an abstraction for code representation in a way that
  578. is amenable to instruction selection using automatic techniques
  579. (e.g. dynamic-programming based optimal pattern matching selectors). It is also
  580. well-suited to other phases of code generation; in particular, instruction
  581. scheduling (SelectionDAG's are very close to scheduling DAGs post-selection).
  582. Additionally, the SelectionDAG provides a host representation where a large
  583. variety of very-low-level (but target-independent) `optimizations`_ may be
  584. performed; ones which require extensive information about the instructions
  585. efficiently supported by the target.
  586. The SelectionDAG is a Directed-Acyclic-Graph whose nodes are instances of the
  587. ``SDNode`` class. The primary payload of the ``SDNode`` is its operation code
  588. (Opcode) that indicates what operation the node performs and the operands to the
  589. operation. The various operation node types are described at the top of the
  590. ``include/llvm/CodeGen/ISDOpcodes.h`` file.
  591. Although most operations define a single value, each node in the graph may
  592. define multiple values. For example, a combined div/rem operation will define
  593. both the dividend and the remainder. Many other situations require multiple
  594. values as well. Each node also has some number of operands, which are edges to
  595. the node defining the used value. Because nodes may define multiple values,
  596. edges are represented by instances of the ``SDValue`` class, which is a
  597. ``<SDNode, unsigned>`` pair, indicating the node and result value being used,
  598. respectively. Each value produced by an ``SDNode`` has an associated ``MVT``
  599. (Machine Value Type) indicating what the type of the value is.
  600. SelectionDAGs contain two different kinds of values: those that represent data
  601. flow and those that represent control flow dependencies. Data values are simple
  602. edges with an integer or floating point value type. Control edges are
  603. represented as "chain" edges which are of type ``MVT::Other``. These edges
  604. provide an ordering between nodes that have side effects (such as loads, stores,
  605. calls, returns, etc). All nodes that have side effects should take a token
  606. chain as input and produce a new one as output. By convention, token chain
  607. inputs are always operand #0, and chain results are always the last value
  608. produced by an operation. However, after instruction selection, the
  609. machine nodes have their chain after the instruction's operands, and
  610. may be followed by glue nodes.
  611. A SelectionDAG has designated "Entry" and "Root" nodes. The Entry node is
  612. always a marker node with an Opcode of ``ISD::EntryToken``. The Root node is
  613. the final side-effecting node in the token chain. For example, in a single basic
  614. block function it would be the return node.
  615. One important concept for SelectionDAGs is the notion of a "legal" vs.
  616. "illegal" DAG. A legal DAG for a target is one that only uses supported
  617. operations and supported types. On a 32-bit PowerPC, for example, a DAG with a
  618. value of type i1, i8, i16, or i64 would be illegal, as would a DAG that uses a
  619. SREM or UREM operation. The `legalize types`_ and `legalize operations`_ phases
  620. are responsible for turning an illegal DAG into a legal DAG.
  621. .. _SelectionDAG-Process:
  622. SelectionDAG Instruction Selection Process
  623. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  624. SelectionDAG-based instruction selection consists of the following steps:
  625. #. `Build initial DAG`_ --- This stage performs a simple translation from the
  626. input LLVM code to an illegal SelectionDAG.
  627. #. `Optimize SelectionDAG`_ --- This stage performs simple optimizations on the
  628. SelectionDAG to simplify it, and recognize meta instructions (like rotates
  629. and ``div``/``rem`` pairs) for targets that support these meta operations.
  630. This makes the resultant code more efficient and the `select instructions
  631. from DAG`_ phase (below) simpler.
  632. #. `Legalize SelectionDAG Types`_ --- This stage transforms SelectionDAG nodes
  633. to eliminate any types that are unsupported on the target.
  634. #. `Optimize SelectionDAG`_ --- The SelectionDAG optimizer is run to clean up
  635. redundancies exposed by type legalization.
  636. #. `Legalize SelectionDAG Ops`_ --- This stage transforms SelectionDAG nodes to
  637. eliminate any operations that are unsupported on the target.
  638. #. `Optimize SelectionDAG`_ --- The SelectionDAG optimizer is run to eliminate
  639. inefficiencies introduced by operation legalization.
  640. #. `Select instructions from DAG`_ --- Finally, the target instruction selector
  641. matches the DAG operations to target instructions. This process translates
  642. the target-independent input DAG into another DAG of target instructions.
  643. #. `SelectionDAG Scheduling and Formation`_ --- The last phase assigns a linear
  644. order to the instructions in the target-instruction DAG and emits them into
  645. the MachineFunction being compiled. This step uses traditional prepass
  646. scheduling techniques.
  647. After all of these steps are complete, the SelectionDAG is destroyed and the
  648. rest of the code generation passes are run.
  649. One great way to visualize what is going on here is to take advantage of a few
  650. LLC command line options. The following options pop up a window displaying the
  651. SelectionDAG at specific times (if you only get errors printed to the console
  652. while using this, you probably `need to configure your
  653. system <ProgrammersManual.html#viewing-graphs-while-debugging-code>`_ to add support for it).
  654. * ``-view-dag-combine1-dags`` displays the DAG after being built, before the
  655. first optimization pass.
  656. * ``-view-legalize-dags`` displays the DAG before Legalization.
  657. * ``-view-dag-combine2-dags`` displays the DAG before the second optimization
  658. pass.
  659. * ``-view-isel-dags`` displays the DAG before the Select phase.
  660. * ``-view-sched-dags`` displays the DAG before Scheduling.
  661. The ``-view-sunit-dags`` displays the Scheduler's dependency graph. This graph
  662. is based on the final SelectionDAG, with nodes that must be scheduled together
  663. bundled into a single scheduling-unit node, and with immediate operands and
  664. other nodes that aren't relevant for scheduling omitted.
  665. The option ``-filter-view-dags`` allows to select the name of the basic block
  666. that you are interested to visualize and filters all the previous
  667. ``view-*-dags`` options.
  668. .. _Build initial DAG:
  669. Initial SelectionDAG Construction
  670. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  671. The initial SelectionDAG is na\ :raw-html:`&iuml;`\ vely peephole expanded from
  672. the LLVM input by the ``SelectionDAGBuilder`` class. The intent of this pass
  673. is to expose as much low-level, target-specific details to the SelectionDAG as
  674. possible. This pass is mostly hard-coded (e.g. an LLVM ``add`` turns into an
  675. ``SDNode add`` while a ``getelementptr`` is expanded into the obvious
  676. arithmetic). This pass requires target-specific hooks to lower calls, returns,
  677. varargs, etc. For these features, the :raw-html:`<tt>` `TargetLowering`_
  678. :raw-html:`</tt>` interface is used.
  679. .. _legalize types:
  680. .. _Legalize SelectionDAG Types:
  681. .. _Legalize SelectionDAG Ops:
  682. SelectionDAG LegalizeTypes Phase
  683. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  684. The Legalize phase is in charge of converting a DAG to only use the types that
  685. are natively supported by the target.
  686. There are two main ways of converting values of unsupported scalar types to
  687. values of supported types: converting small types to larger types ("promoting"),
  688. and breaking up large integer types into smaller ones ("expanding"). For
  689. example, a target might require that all f32 values are promoted to f64 and that
  690. all i1/i8/i16 values are promoted to i32. The same target might require that
  691. all i64 values be expanded into pairs of i32 values. These changes can insert
  692. sign and zero extensions as needed to make sure that the final code has the same
  693. behavior as the input.
  694. There are two main ways of converting values of unsupported vector types to
  695. value of supported types: splitting vector types, multiple times if necessary,
  696. until a legal type is found, and extending vector types by adding elements to
  697. the end to round them out to legal types ("widening"). If a vector gets split
  698. all the way down to single-element parts with no supported vector type being
  699. found, the elements are converted to scalars ("scalarizing").
  700. A target implementation tells the legalizer which types are supported (and which
  701. register class to use for them) by calling the ``addRegisterClass`` method in
  702. its ``TargetLowering`` constructor.
  703. .. _legalize operations:
  704. .. _Legalizer:
  705. SelectionDAG Legalize Phase
  706. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  707. The Legalize phase is in charge of converting a DAG to only use the operations
  708. that are natively supported by the target.
  709. Targets often have weird constraints, such as not supporting every operation on
  710. every supported datatype (e.g. X86 does not support byte conditional moves and
  711. PowerPC does not support sign-extending loads from a 16-bit memory location).
  712. Legalize takes care of this by open-coding another sequence of operations to
  713. emulate the operation ("expansion"), by promoting one type to a larger type that
  714. supports the operation ("promotion"), or by using a target-specific hook to
  715. implement the legalization ("custom").
  716. A target implementation tells the legalizer which operations are not supported
  717. (and which of the above three actions to take) by calling the
  718. ``setOperationAction`` method in its ``TargetLowering`` constructor.
  719. If a target has legal vector types, it is expected to produce efficient machine
  720. code for common forms of the shufflevector IR instruction using those types.
  721. This may require custom legalization for SelectionDAG vector operations that
  722. are created from the shufflevector IR. The shufflevector forms that should be
  723. handled include:
  724. * Vector select --- Each element of the vector is chosen from either of the
  725. corresponding elements of the 2 input vectors. This operation may also be
  726. known as a "blend" or "bitwise select" in target assembly. This type of shuffle
  727. maps directly to the ``shuffle_vector`` SelectionDAG node.
  728. * Insert subvector --- A vector is placed into a longer vector type starting
  729. at index 0. This type of shuffle maps directly to the ``insert_subvector``
  730. SelectionDAG node with the ``index`` operand set to 0.
  731. * Extract subvector --- A vector is pulled from a longer vector type starting
  732. at index 0. This type of shuffle maps directly to the ``extract_subvector``
  733. SelectionDAG node with the ``index`` operand set to 0.
  734. * Splat --- All elements of the vector have identical scalar elements. This
  735. operation may also be known as a "broadcast" or "duplicate" in target assembly.
  736. The shufflevector IR instruction may change the vector length, so this operation
  737. may map to multiple SelectionDAG nodes including ``shuffle_vector``,
  738. ``concat_vectors``, ``insert_subvector``, and ``extract_subvector``.
  739. Prior to the existence of the Legalize passes, we required that every target
  740. `selector`_ supported and handled every operator and type even if they are not
  741. natively supported. The introduction of the Legalize phases allows all of the
  742. canonicalization patterns to be shared across targets, and makes it very easy to
  743. optimize the canonicalized code because it is still in the form of a DAG.
  744. .. _optimizations:
  745. .. _Optimize SelectionDAG:
  746. .. _selector:
  747. SelectionDAG Optimization Phase: the DAG Combiner
  748. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  749. The SelectionDAG optimization phase is run multiple times for code generation,
  750. immediately after the DAG is built and once after each legalization. The first
  751. run of the pass allows the initial code to be cleaned up (e.g. performing
  752. optimizations that depend on knowing that the operators have restricted type
  753. inputs). Subsequent runs of the pass clean up the messy code generated by the
  754. Legalize passes, which allows Legalize to be very simple (it can focus on making
  755. code legal instead of focusing on generating *good* and legal code).
  756. One important class of optimizations performed is optimizing inserted sign and
  757. zero extension instructions. We currently use ad-hoc techniques, but could move
  758. to more rigorous techniques in the future. Here are some good papers on the
  759. subject:
  760. "`Widening integer arithmetic <http://www.eecs.harvard.edu/~nr/pubs/widen-abstract.html>`_" :raw-html:`<br>`
  761. Kevin Redwine and Norman Ramsey :raw-html:`<br>`
  762. International Conference on Compiler Construction (CC) 2004
  763. "`Effective sign extension elimination <http://portal.acm.org/citation.cfm?doid=512529.512552>`_" :raw-html:`<br>`
  764. Motohiro Kawahito, Hideaki Komatsu, and Toshio Nakatani :raw-html:`<br>`
  765. Proceedings of the ACM SIGPLAN 2002 Conference on Programming Language Design
  766. and Implementation.
  767. .. _Select instructions from DAG:
  768. SelectionDAG Select Phase
  769. ^^^^^^^^^^^^^^^^^^^^^^^^^
  770. The Select phase is the bulk of the target-specific code for instruction
  771. selection. This phase takes a legal SelectionDAG as input, pattern matches the
  772. instructions supported by the target to this DAG, and produces a new DAG of
  773. target code. For example, consider the following LLVM fragment:
  774. .. code-block:: llvm
  775. %t1 = fadd float %W, %X
  776. %t2 = fmul float %t1, %Y
  777. %t3 = fadd float %t2, %Z
  778. This LLVM code corresponds to a SelectionDAG that looks basically like this:
  779. .. code-block:: text
  780. (fadd:f32 (fmul:f32 (fadd:f32 W, X), Y), Z)
  781. If a target supports floating point multiply-and-add (FMA) operations, one of
  782. the adds can be merged with the multiply. On the PowerPC, for example, the
  783. output of the instruction selector might look like this DAG:
  784. ::
  785. (FMADDS (FADDS W, X), Y, Z)
  786. The ``FMADDS`` instruction is a ternary instruction that multiplies its first
  787. two operands and adds the third (as single-precision floating-point numbers).
  788. The ``FADDS`` instruction is a simple binary single-precision add instruction.
  789. To perform this pattern match, the PowerPC backend includes the following
  790. instruction definitions:
  791. .. code-block:: text
  792. :emphasize-lines: 4-5,9
  793. def FMADDS : AForm_1<59, 29,
  794. (ops F4RC:$FRT, F4RC:$FRA, F4RC:$FRC, F4RC:$FRB),
  795. "fmadds $FRT, $FRA, $FRC, $FRB",
  796. [(set F4RC:$FRT, (fadd (fmul F4RC:$FRA, F4RC:$FRC),
  797. F4RC:$FRB))]>;
  798. def FADDS : AForm_2<59, 21,
  799. (ops F4RC:$FRT, F4RC:$FRA, F4RC:$FRB),
  800. "fadds $FRT, $FRA, $FRB",
  801. [(set F4RC:$FRT, (fadd F4RC:$FRA, F4RC:$FRB))]>;
  802. The highlighted portion of the instruction definitions indicates the pattern
  803. used to match the instructions. The DAG operators (like ``fmul``/``fadd``)
  804. are defined in the ``include/llvm/Target/TargetSelectionDAG.td`` file.
  805. "``F4RC``" is the register class of the input and result values.
  806. The TableGen DAG instruction selector generator reads the instruction patterns
  807. in the ``.td`` file and automatically builds parts of the pattern matching code
  808. for your target. It has the following strengths:
  809. * At compiler-compile time, it analyzes your instruction patterns and tells you
  810. if your patterns make sense or not.
  811. * It can handle arbitrary constraints on operands for the pattern match. In
  812. particular, it is straight-forward to say things like "match any immediate
  813. that is a 13-bit sign-extended value". For examples, see the ``immSExt16``
  814. and related ``tblgen`` classes in the PowerPC backend.
  815. * It knows several important identities for the patterns defined. For example,
  816. it knows that addition is commutative, so it allows the ``FMADDS`` pattern
  817. above to match "``(fadd X, (fmul Y, Z))``" as well as "``(fadd (fmul X, Y),
  818. Z)``", without the target author having to specially handle this case.
  819. * It has a full-featured type-inferencing system. In particular, you should
  820. rarely have to explicitly tell the system what type parts of your patterns
  821. are. In the ``FMADDS`` case above, we didn't have to tell ``tblgen`` that all
  822. of the nodes in the pattern are of type 'f32'. It was able to infer and
  823. propagate this knowledge from the fact that ``F4RC`` has type 'f32'.
  824. * Targets can define their own (and rely on built-in) "pattern fragments".
  825. Pattern fragments are chunks of reusable patterns that get inlined into your
  826. patterns during compiler-compile time. For example, the integer "``(not
  827. x)``" operation is actually defined as a pattern fragment that expands as
  828. "``(xor x, -1)``", since the SelectionDAG does not have a native '``not``'
  829. operation. Targets can define their own short-hand fragments as they see fit.
  830. See the definition of '``not``' and '``ineg``' for examples.
  831. * In addition to instructions, targets can specify arbitrary patterns that map
  832. to one or more instructions using the 'Pat' class. For example, the PowerPC
  833. has no way to load an arbitrary integer immediate into a register in one
  834. instruction. To tell tblgen how to do this, it defines:
  835. ::
  836. // Arbitrary immediate support. Implement in terms of LIS/ORI.
  837. def : Pat<(i32 imm:$imm),
  838. (ORI (LIS (HI16 imm:$imm)), (LO16 imm:$imm))>;
  839. If none of the single-instruction patterns for loading an immediate into a
  840. register match, this will be used. This rule says "match an arbitrary i32
  841. immediate, turning it into an ``ORI`` ('or a 16-bit immediate') and an ``LIS``
  842. ('load 16-bit immediate, where the immediate is shifted to the left 16 bits')
  843. instruction". To make this work, the ``LO16``/``HI16`` node transformations
  844. are used to manipulate the input immediate (in this case, take the high or low
  845. 16-bits of the immediate).
  846. * When using the 'Pat' class to map a pattern to an instruction that has one
  847. or more complex operands (like e.g. `X86 addressing mode`_), the pattern may
  848. either specify the operand as a whole using a ``ComplexPattern``, or else it
  849. may specify the components of the complex operand separately. The latter is
  850. done e.g. for pre-increment instructions by the PowerPC back end:
  851. ::
  852. def STWU : DForm_1<37, (outs ptr_rc:$ea_res), (ins GPRC:$rS, memri:$dst),
  853. "stwu $rS, $dst", LdStStoreUpd, []>,
  854. RegConstraint<"$dst.reg = $ea_res">, NoEncode<"$ea_res">;
  855. def : Pat<(pre_store GPRC:$rS, ptr_rc:$ptrreg, iaddroff:$ptroff),
  856. (STWU GPRC:$rS, iaddroff:$ptroff, ptr_rc:$ptrreg)>;
  857. Here, the pair of ``ptroff`` and ``ptrreg`` operands is matched onto the
  858. complex operand ``dst`` of class ``memri`` in the ``STWU`` instruction.
  859. * While the system does automate a lot, it still allows you to write custom C++
  860. code to match special cases if there is something that is hard to
  861. express.
  862. While it has many strengths, the system currently has some limitations,
  863. primarily because it is a work in progress and is not yet finished:
  864. * Overall, there is no way to define or match SelectionDAG nodes that define
  865. multiple values (e.g. ``SMUL_LOHI``, ``LOAD``, ``CALL``, etc). This is the
  866. biggest reason that you currently still *have to* write custom C++ code
  867. for your instruction selector.
  868. * There is no great way to support matching complex addressing modes yet. In
  869. the future, we will extend pattern fragments to allow them to define multiple
  870. values (e.g. the four operands of the `X86 addressing mode`_, which are
  871. currently matched with custom C++ code). In addition, we'll extend fragments
  872. so that a fragment can match multiple different patterns.
  873. * We don't automatically infer flags like ``isStore``/``isLoad`` yet.
  874. * We don't automatically generate the set of supported registers and operations
  875. for the `Legalizer`_ yet.
  876. * We don't have a way of tying in custom legalized nodes yet.
  877. Despite these limitations, the instruction selector generator is still quite
  878. useful for most of the binary and logical operations in typical instruction
  879. sets. If you run into any problems or can't figure out how to do something,
  880. please let Chris know!
  881. .. _Scheduling and Formation:
  882. .. _SelectionDAG Scheduling and Formation:
  883. SelectionDAG Scheduling and Formation Phase
  884. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  885. The scheduling phase takes the DAG of target instructions from the selection
  886. phase and assigns an order. The scheduler can pick an order depending on
  887. various constraints of the machines (i.e. order for minimal register pressure or
  888. try to cover instruction latencies). Once an order is established, the DAG is
  889. converted to a list of :raw-html:`<tt>` `MachineInstr`_\s :raw-html:`</tt>` and
  890. the SelectionDAG is destroyed.
  891. Note that this phase is logically separate from the instruction selection phase,
  892. but is tied to it closely in the code because it operates on SelectionDAGs.
  893. Future directions for the SelectionDAG
  894. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  895. #. Optional function-at-a-time selection.
  896. #. Auto-generate entire selector from ``.td`` file.
  897. .. _SSA-based Machine Code Optimizations:
  898. SSA-based Machine Code Optimizations
  899. ------------------------------------
  900. To Be Written
  901. Live Intervals
  902. --------------
  903. Live Intervals are the ranges (intervals) where a variable is *live*. They are
  904. used by some `register allocator`_ passes to determine if two or more virtual
  905. registers which require the same physical register are live at the same point in
  906. the program (i.e., they conflict). When this situation occurs, one virtual
  907. register must be *spilled*.
  908. Live Variable Analysis
  909. ^^^^^^^^^^^^^^^^^^^^^^
  910. The first step in determining the live intervals of variables is to calculate
  911. the set of registers that are immediately dead after the instruction (i.e., the
  912. instruction calculates the value, but it is never used) and the set of registers
  913. that are used by the instruction, but are never used after the instruction
  914. (i.e., they are killed). Live variable information is computed for
  915. each *virtual* register and *register allocatable* physical register
  916. in the function. This is done in a very efficient manner because it uses SSA to
  917. sparsely compute lifetime information for virtual registers (which are in SSA
  918. form) and only has to track physical registers within a block. Before register
  919. allocation, LLVM can assume that physical registers are only live within a
  920. single basic block. This allows it to do a single, local analysis to resolve
  921. physical register lifetimes within each basic block. If a physical register is
  922. not register allocatable (e.g., a stack pointer or condition codes), it is not
  923. tracked.
  924. Physical registers may be live in to or out of a function. Live in values are
  925. typically arguments in registers. Live out values are typically return values in
  926. registers. Live in values are marked as such, and are given a dummy "defining"
  927. instruction during live intervals analysis. If the last basic block of a
  928. function is a ``return``, then it's marked as using all live out values in the
  929. function.
  930. ``PHI`` nodes need to be handled specially, because the calculation of the live
  931. variable information from a depth first traversal of the CFG of the function
  932. won't guarantee that a virtual register used by the ``PHI`` node is defined
  933. before it's used. When a ``PHI`` node is encountered, only the definition is
  934. handled, because the uses will be handled in other basic blocks.
  935. For each ``PHI`` node of the current basic block, we simulate an assignment at
  936. the end of the current basic block and traverse the successor basic blocks. If a
  937. successor basic block has a ``PHI`` node and one of the ``PHI`` node's operands
  938. is coming from the current basic block, then the variable is marked as *alive*
  939. within the current basic block and all of its predecessor basic blocks, until
  940. the basic block with the defining instruction is encountered.
  941. Live Intervals Analysis
  942. ^^^^^^^^^^^^^^^^^^^^^^^
  943. We now have the information available to perform the live intervals analysis and
  944. build the live intervals themselves. We start off by numbering the basic blocks
  945. and machine instructions. We then handle the "live-in" values. These are in
  946. physical registers, so the physical register is assumed to be killed by the end
  947. of the basic block. Live intervals for virtual registers are computed for some
  948. ordering of the machine instructions ``[1, N]``. A live interval is an interval
  949. ``[i, j)``, where ``1 >= i >= j > N``, for which a variable is live.
  950. .. note::
  951. More to come...
  952. .. _Register Allocation:
  953. .. _register allocator:
  954. Register Allocation
  955. -------------------
  956. The *Register Allocation problem* consists in mapping a program
  957. :raw-html:`<b><tt>` P\ :sub:`v`\ :raw-html:`</tt></b>`, that can use an unbounded
  958. number of virtual registers, to a program :raw-html:`<b><tt>` P\ :sub:`p`\
  959. :raw-html:`</tt></b>` that contains a finite (possibly small) number of physical
  960. registers. Each target architecture has a different number of physical
  961. registers. If the number of physical registers is not enough to accommodate all
  962. the virtual registers, some of them will have to be mapped into memory. These
  963. virtuals are called *spilled virtuals*.
  964. How registers are represented in LLVM
  965. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  966. In LLVM, physical registers are denoted by integer numbers that normally range
  967. from 1 to 1023. To see how this numbering is defined for a particular
  968. architecture, you can read the ``GenRegisterNames.inc`` file for that
  969. architecture. For instance, by inspecting
  970. ``lib/Target/X86/X86GenRegisterInfo.inc`` we see that the 32-bit register
  971. ``EAX`` is denoted by 43, and the MMX register ``MM0`` is mapped to 65.
  972. Some architectures contain registers that share the same physical location. A
  973. notable example is the X86 platform. For instance, in the X86 architecture, the
  974. registers ``EAX``, ``AX`` and ``AL`` share the first eight bits. These physical
  975. registers are marked as *aliased* in LLVM. Given a particular architecture, you
  976. can check which registers are aliased by inspecting its ``RegisterInfo.td``
  977. file. Moreover, the class ``MCRegAliasIterator`` enumerates all the physical
  978. registers aliased to a register.
  979. Physical registers, in LLVM, are grouped in *Register Classes*. Elements in the
  980. same register class are functionally equivalent, and can be interchangeably
  981. used. Each virtual register can only be mapped to physical registers of a
  982. particular class. For instance, in the X86 architecture, some virtuals can only
  983. be allocated to 8 bit registers. A register class is described by
  984. ``TargetRegisterClass`` objects. To discover if a virtual register is
  985. compatible with a given physical, this code can be used:
  986. .. code-block:: c++
  987. bool RegMapping_Fer::compatible_class(MachineFunction &mf,
  988. unsigned v_reg,
  989. unsigned p_reg) {
  990. assert(TargetRegisterInfo::isPhysicalRegister(p_reg) &&
  991. "Target register must be physical");
  992. const TargetRegisterClass *trc = mf.getRegInfo().getRegClass(v_reg);
  993. return trc->contains(p_reg);
  994. }
  995. Sometimes, mostly for debugging purposes, it is useful to change the number of
  996. physical registers available in the target architecture. This must be done
  997. statically, inside the ``TargetRegsterInfo.td`` file. Just ``grep`` for
  998. ``RegisterClass``, the last parameter of which is a list of registers. Just
  999. commenting some out is one simple way to avoid them being used. A more polite
  1000. way is to explicitly exclude some registers from the *allocation order*. See the
  1001. definition of the ``GR8`` register class in
  1002. ``lib/Target/X86/X86RegisterInfo.td`` for an example of this.
  1003. Virtual registers are also denoted by integer numbers. Contrary to physical
  1004. registers, different virtual registers never share the same number. Whereas
  1005. physical registers are statically defined in a ``TargetRegisterInfo.td`` file
  1006. and cannot be created by the application developer, that is not the case with
  1007. virtual registers. In order to create new virtual registers, use the method
  1008. ``MachineRegisterInfo::createVirtualRegister()``. This method will return a new
  1009. virtual register. Use an ``IndexedMap<Foo, VirtReg2IndexFunctor>`` to hold
  1010. information per virtual register. If you need to enumerate all virtual
  1011. registers, use the function ``TargetRegisterInfo::index2VirtReg()`` to find the
  1012. virtual register numbers:
  1013. .. code-block:: c++
  1014. for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
  1015. unsigned VirtReg = TargetRegisterInfo::index2VirtReg(i);
  1016. stuff(VirtReg);
  1017. }
  1018. Before register allocation, the operands of an instruction are mostly virtual
  1019. registers, although physical registers may also be used. In order to check if a
  1020. given machine operand is a register, use the boolean function
  1021. ``MachineOperand::isRegister()``. To obtain the integer code of a register, use
  1022. ``MachineOperand::getReg()``. An instruction may define or use a register. For
  1023. instance, ``ADD reg:1026 := reg:1025 reg:1024`` defines the registers 1024, and
  1024. uses registers 1025 and 1026. Given a register operand, the method
  1025. ``MachineOperand::isUse()`` informs if that register is being used by the
  1026. instruction. The method ``MachineOperand::isDef()`` informs if that registers is
  1027. being defined.
  1028. We will call physical registers present in the LLVM bitcode before register
  1029. allocation *pre-colored registers*. Pre-colored registers are used in many
  1030. different situations, for instance, to pass parameters of functions calls, and
  1031. to store results of particular instructions. There are two types of pre-colored
  1032. registers: the ones *implicitly* defined, and those *explicitly*
  1033. defined. Explicitly defined registers are normal operands, and can be accessed
  1034. with ``MachineInstr::getOperand(int)::getReg()``. In order to check which
  1035. registers are implicitly defined by an instruction, use the
  1036. ``TargetInstrInfo::get(opcode)::ImplicitDefs``, where ``opcode`` is the opcode
  1037. of the target instruction. One important difference between explicit and
  1038. implicit physical registers is that the latter are defined statically for each
  1039. instruction, whereas the former may vary depending on the program being
  1040. compiled. For example, an instruction that represents a function call will
  1041. always implicitly define or use the same set of physical registers. To read the
  1042. registers implicitly used by an instruction, use
  1043. ``TargetInstrInfo::get(opcode)::ImplicitUses``. Pre-colored registers impose
  1044. constraints on any register allocation algorithm. The register allocator must
  1045. make sure that none of them are overwritten by the values of virtual registers
  1046. while still alive.
  1047. Mapping virtual registers to physical registers
  1048. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1049. There are two ways to map virtual registers to physical registers (or to memory
  1050. slots). The first way, that we will call *direct mapping*, is based on the use
  1051. of methods of the classes ``TargetRegisterInfo``, and ``MachineOperand``. The
  1052. second way, that we will call *indirect mapping*, relies on the ``VirtRegMap``
  1053. class in order to insert loads and stores sending and getting values to and from
  1054. memory.
  1055. The direct mapping provides more flexibility to the developer of the register
  1056. allocator; however, it is more error prone, and demands more implementation
  1057. work. Basically, the programmer will have to specify where load and store
  1058. instructions should be inserted in the target function being compiled in order
  1059. to get and store values in memory. To assign a physical register to a virtual
  1060. register present in a given operand, use ``MachineOperand::setReg(p_reg)``. To
  1061. insert a store instruction, use ``TargetInstrInfo::storeRegToStackSlot(...)``,
  1062. and to insert a load instruction, use ``TargetInstrInfo::loadRegFromStackSlot``.
  1063. The indirect mapping shields the application developer from the complexities of
  1064. inserting load and store instructions. In order to map a virtual register to a
  1065. physical one, use ``VirtRegMap::assignVirt2Phys(vreg, preg)``. In order to map
  1066. a certain virtual register to memory, use
  1067. ``VirtRegMap::assignVirt2StackSlot(vreg)``. This method will return the stack
  1068. slot where ``vreg``'s value will be located. If it is necessary to map another
  1069. virtual register to the same stack slot, use
  1070. ``VirtRegMap::assignVirt2StackSlot(vreg, stack_location)``. One important point
  1071. to consider when using the indirect mapping, is that even if a virtual register
  1072. is mapped to memory, it still needs to be mapped to a physical register. This
  1073. physical register is the location where the virtual register is supposed to be
  1074. found before being stored or after being reloaded.
  1075. If the indirect strategy is used, after all the virtual registers have been
  1076. mapped to physical registers or stack slots, it is necessary to use a spiller
  1077. object to place load and store instructions in the code. Every virtual that has
  1078. been mapped to a stack slot will be stored to memory after being defined and will
  1079. be loaded before being used. The implementation of the spiller tries to recycle
  1080. load/store instructions, avoiding unnecessary instructions. For an example of
  1081. how to invoke the spiller, see ``RegAllocLinearScan::runOnMachineFunction`` in
  1082. ``lib/CodeGen/RegAllocLinearScan.cpp``.
  1083. Handling two address instructions
  1084. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1085. With very rare exceptions (e.g., function calls), the LLVM machine code
  1086. instructions are three address instructions. That is, each instruction is
  1087. expected to define at most one register, and to use at most two registers.
  1088. However, some architectures use two address instructions. In this case, the
  1089. defined register is also one of the used registers. For instance, an instruction
  1090. such as ``ADD %EAX, %EBX``, in X86 is actually equivalent to ``%EAX = %EAX +
  1091. %EBX``.
  1092. In order to produce correct code, LLVM must convert three address instructions
  1093. that represent two address instructions into true two address instructions. LLVM
  1094. provides the pass ``TwoAddressInstructionPass`` for this specific purpose. It
  1095. must be run before register allocation takes place. After its execution, the
  1096. resulting code may no longer be in SSA form. This happens, for instance, in
  1097. situations where an instruction such as ``%a = ADD %b %c`` is converted to two
  1098. instructions such as:
  1099. ::
  1100. %a = MOVE %b
  1101. %a = ADD %a %c
  1102. Notice that, internally, the second instruction is represented as ``ADD
  1103. %a[def/use] %c``. I.e., the register operand ``%a`` is both used and defined by
  1104. the instruction.
  1105. The SSA deconstruction phase
  1106. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1107. An important transformation that happens during register allocation is called
  1108. the *SSA Deconstruction Phase*. The SSA form simplifies many analyses that are
  1109. performed on the control flow graph of programs. However, traditional
  1110. instruction sets do not implement PHI instructions. Thus, in order to generate
  1111. executable code, compilers must replace PHI instructions with other instructions
  1112. that preserve their semantics.
  1113. There are many ways in which PHI instructions can safely be removed from the
  1114. target code. The most traditional PHI deconstruction algorithm replaces PHI
  1115. instructions with copy instructions. That is the strategy adopted by LLVM. The
  1116. SSA deconstruction algorithm is implemented in
  1117. ``lib/CodeGen/PHIElimination.cpp``. In order to invoke this pass, the identifier
  1118. ``PHIEliminationID`` must be marked as required in the code of the register
  1119. allocator.
  1120. Instruction folding
  1121. ^^^^^^^^^^^^^^^^^^^
  1122. *Instruction folding* is an optimization performed during register allocation
  1123. that removes unnecessary copy instructions. For instance, a sequence of
  1124. instructions such as:
  1125. ::
  1126. %EBX = LOAD %mem_address
  1127. %EAX = COPY %EBX
  1128. can be safely substituted by the single instruction:
  1129. ::
  1130. %EAX = LOAD %mem_address
  1131. Instructions can be folded with the
  1132. ``TargetRegisterInfo::foldMemoryOperand(...)`` method. Care must be taken when
  1133. folding instructions; a folded instruction can be quite different from the
  1134. original instruction. See ``LiveIntervals::addIntervalsForSpills`` in
  1135. ``lib/CodeGen/LiveIntervalAnalysis.cpp`` for an example of its use.
  1136. Built in register allocators
  1137. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1138. The LLVM infrastructure provides the application developer with three different
  1139. register allocators:
  1140. * *Fast* --- This register allocator is the default for debug builds. It
  1141. allocates registers on a basic block level, attempting to keep values in
  1142. registers and reusing registers as appropriate.
  1143. * *Basic* --- This is an incremental approach to register allocation. Live
  1144. ranges are assigned to registers one at a time in an order that is driven by
  1145. heuristics. Since code can be rewritten on-the-fly during allocation, this
  1146. framework allows interesting allocators to be developed as extensions. It is
  1147. not itself a production register allocator but is a potentially useful
  1148. stand-alone mode for triaging bugs and as a performance baseline.
  1149. * *Greedy* --- *The default allocator*. This is a highly tuned implementation of
  1150. the *Basic* allocator that incorporates global live range splitting. This
  1151. allocator works hard to minimize the cost of spill code.
  1152. * *PBQP* --- A Partitioned Boolean Quadratic Programming (PBQP) based register
  1153. allocator. This allocator works by constructing a PBQP problem representing
  1154. the register allocation problem under consideration, solving this using a PBQP
  1155. solver, and mapping the solution back to a register assignment.
  1156. The type of register allocator used in ``llc`` can be chosen with the command
  1157. line option ``-regalloc=...``:
  1158. .. code-block:: bash
  1159. $ llc -regalloc=linearscan file.bc -o ln.s
  1160. $ llc -regalloc=fast file.bc -o fa.s
  1161. $ llc -regalloc=pbqp file.bc -o pbqp.s
  1162. .. _Prolog/Epilog Code Insertion:
  1163. Prolog/Epilog Code Insertion
  1164. ----------------------------
  1165. Compact Unwind
  1166. Throwing an exception requires *unwinding* out of a function. The information on
  1167. how to unwind a given function is traditionally expressed in DWARF unwind
  1168. (a.k.a. frame) info. But that format was originally developed for debuggers to
  1169. backtrace, and each Frame Description Entry (FDE) requires ~20-30 bytes per
  1170. function. There is also the cost of mapping from an address in a function to the
  1171. corresponding FDE at runtime. An alternative unwind encoding is called *compact
  1172. unwind* and requires just 4-bytes per function.
  1173. The compact unwind encoding is a 32-bit value, which is encoded in an
  1174. architecture-specific way. It specifies which registers to restore and from
  1175. where, and how to unwind out of the function. When the linker creates a final
  1176. linked image, it will create a ``__TEXT,__unwind_info`` section. This section is
  1177. a small and fast way for the runtime to access unwind info for any given
  1178. function. If we emit compact unwind info for the function, that compact unwind
  1179. info will be encoded in the ``__TEXT,__unwind_info`` section. If we emit DWARF
  1180. unwind info, the ``__TEXT,__unwind_info`` section will contain the offset of the
  1181. FDE in the ``__TEXT,__eh_frame`` section in the final linked image.
  1182. For X86, there are three modes for the compact unwind encoding:
  1183. *Function with a Frame Pointer (``EBP`` or ``RBP``)*
  1184. ``EBP/RBP``-based frame, where ``EBP/RBP`` is pushed onto the stack
  1185. immediately after the return address, then ``ESP/RSP`` is moved to
  1186. ``EBP/RBP``. Thus to unwind, ``ESP/RSP`` is restored with the current
  1187. ``EBP/RBP`` value, then ``EBP/RBP`` is restored by popping the stack, and the
  1188. return is done by popping the stack once more into the PC. All non-volatile
  1189. registers that need to be restored must have been saved in a small range on
  1190. the stack that starts ``EBP-4`` to ``EBP-1020`` (``RBP-8`` to
  1191. ``RBP-1020``). The offset (divided by 4 in 32-bit mode and 8 in 64-bit mode)
  1192. is encoded in bits 16-23 (mask: ``0x00FF0000``). The registers saved are
  1193. encoded in bits 0-14 (mask: ``0x00007FFF``) as five 3-bit entries from the
  1194. following table:
  1195. ============== ============= ===============
  1196. Compact Number i386 Register x86-64 Register
  1197. ============== ============= ===============
  1198. 1 ``EBX`` ``RBX``
  1199. 2 ``ECX`` ``R12``
  1200. 3 ``EDX`` ``R13``
  1201. 4 ``EDI`` ``R14``
  1202. 5 ``ESI`` ``R15``
  1203. 6 ``EBP`` ``RBP``
  1204. ============== ============= ===============
  1205. *Frameless with a Small Constant Stack Size (``EBP`` or ``RBP`` is not used as a frame pointer)*
  1206. To return, a constant (encoded in the compact unwind encoding) is added to the
  1207. ``ESP/RSP``. Then the return is done by popping the stack into the PC. All
  1208. non-volatile registers that need to be restored must have been saved on the
  1209. stack immediately after the return address. The stack size (divided by 4 in
  1210. 32-bit mode and 8 in 64-bit mode) is encoded in bits 16-23 (mask:
  1211. ``0x00FF0000``). There is a maximum stack size of 1024 bytes in 32-bit mode
  1212. and 2048 in 64-bit mode. The number of registers saved is encoded in bits 9-12
  1213. (mask: ``0x00001C00``). Bits 0-9 (mask: ``0x000003FF``) contain which
  1214. registers were saved and their order. (See the
  1215. ``encodeCompactUnwindRegistersWithoutFrame()`` function in
  1216. ``lib/Target/X86FrameLowering.cpp`` for the encoding algorithm.)
  1217. *Frameless with a Large Constant Stack Size (``EBP`` or ``RBP`` is not used as a frame pointer)*
  1218. This case is like the "Frameless with a Small Constant Stack Size" case, but
  1219. the stack size is too large to encode in the compact unwind encoding. Instead
  1220. it requires that the function contains "``subl $nnnnnn, %esp``" in its
  1221. prolog. The compact encoding contains the offset to the ``$nnnnnn`` value in
  1222. the function in bits 9-12 (mask: ``0x00001C00``).
  1223. .. _Late Machine Code Optimizations:
  1224. Late Machine Code Optimizations
  1225. -------------------------------
  1226. .. note::
  1227. To Be Written
  1228. .. _Code Emission:
  1229. Code Emission
  1230. -------------
  1231. The code emission step of code generation is responsible for lowering from the
  1232. code generator abstractions (like `MachineFunction`_, `MachineInstr`_, etc) down
  1233. to the abstractions used by the MC layer (`MCInst`_, `MCStreamer`_, etc). This
  1234. is done with a combination of several different classes: the (misnamed)
  1235. target-independent AsmPrinter class, target-specific subclasses of AsmPrinter
  1236. (such as SparcAsmPrinter), and the TargetLoweringObjectFile class.
  1237. Since the MC layer works at the level of abstraction of object files, it doesn't
  1238. have a notion of functions, global variables etc. Instead, it thinks about
  1239. labels, directives, and instructions. A key class used at this time is the
  1240. MCStreamer class. This is an abstract API that is implemented in different ways
  1241. (e.g. to output a .s file, output an ELF .o file, etc) that is effectively an
  1242. "assembler API". MCStreamer has one method per directive, such as EmitLabel,
  1243. EmitSymbolAttribute, SwitchSection, etc, which directly correspond to assembly
  1244. level directives.
  1245. If you are interested in implementing a code generator for a target, there are
  1246. three important things that you have to implement for your target:
  1247. #. First, you need a subclass of AsmPrinter for your target. This class
  1248. implements the general lowering process converting MachineFunction's into MC
  1249. label constructs. The AsmPrinter base class provides a number of useful
  1250. methods and routines, and also allows you to override the lowering process in
  1251. some important ways. You should get much of the lowering for free if you are
  1252. implementing an ELF, COFF, or MachO target, because the
  1253. TargetLoweringObjectFile class implements much of the common logic.
  1254. #. Second, you need to implement an instruction printer for your target. The
  1255. instruction printer takes an `MCInst`_ and renders it to a raw_ostream as
  1256. text. Most of this is automatically generated from the .td file (when you
  1257. specify something like "``add $dst, $src1, $src2``" in the instructions), but
  1258. you need to implement routines to print operands.
  1259. #. Third, you need to implement code that lowers a `MachineInstr`_ to an MCInst,
  1260. usually implemented in "<target>MCInstLower.cpp". This lowering process is
  1261. often target specific, and is responsible for turning jump table entries,
  1262. constant pool indices, global variable addresses, etc into MCLabels as
  1263. appropriate. This translation layer is also responsible for expanding pseudo
  1264. ops used by the code generator into the actual machine instructions they
  1265. correspond to. The MCInsts that are generated by this are fed into the
  1266. instruction printer or the encoder.
  1267. Finally, at your choosing, you can also implement a subclass of MCCodeEmitter
  1268. which lowers MCInst's into machine code bytes and relocations. This is
  1269. important if you want to support direct .o file emission, or would like to
  1270. implement an assembler for your target.
  1271. Emitting function stack size information
  1272. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1273. A section containing metadata on function stack sizes will be emitted when
  1274. ``TargetLoweringObjectFile::StackSizesSection`` is not null, and
  1275. ``TargetOptions::EmitStackSizeSection`` is set (-stack-size-section). The
  1276. section will contain an array of pairs of function symbol values (pointer size)
  1277. and stack sizes (unsigned LEB128). The stack size values only include the space
  1278. allocated in the function prologue. Functions with dynamic stack allocations are
  1279. not included.
  1280. VLIW Packetizer
  1281. ---------------
  1282. In a Very Long Instruction Word (VLIW) architecture, the compiler is responsible
  1283. for mapping instructions to functional-units available on the architecture. To
  1284. that end, the compiler creates groups of instructions called *packets* or
  1285. *bundles*. The VLIW packetizer in LLVM is a target-independent mechanism to
  1286. enable the packetization of machine instructions.
  1287. Mapping from instructions to functional units
  1288. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1289. Instructions in a VLIW target can typically be mapped to multiple functional
  1290. units. During the process of packetizing, the compiler must be able to reason
  1291. about whether an instruction can be added to a packet. This decision can be
  1292. complex since the compiler has to examine all possible mappings of instructions
  1293. to functional units. Therefore to alleviate compilation-time complexity, the
  1294. VLIW packetizer parses the instruction classes of a target and generates tables
  1295. at compiler build time. These tables can then be queried by the provided
  1296. machine-independent API to determine if an instruction can be accommodated in a
  1297. packet.
  1298. How the packetization tables are generated and used
  1299. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1300. The packetizer reads instruction classes from a target's itineraries and creates
  1301. a deterministic finite automaton (DFA) to represent the state of a packet. A DFA
  1302. consists of three major elements: inputs, states, and transitions. The set of
  1303. inputs for the generated DFA represents the instruction being added to a
  1304. packet. The states represent the possible consumption of functional units by
  1305. instructions in a packet. In the DFA, transitions from one state to another
  1306. occur on the addition of an instruction to an existing packet. If there is a
  1307. legal mapping of functional units to instructions, then the DFA contains a
  1308. corresponding transition. The absence of a transition indicates that a legal
  1309. mapping does not exist and that the instruction cannot be added to the packet.
  1310. To generate tables for a VLIW target, add *Target*\ GenDFAPacketizer.inc as a
  1311. target to the Makefile in the target directory. The exported API provides three
  1312. functions: ``DFAPacketizer::clearResources()``,
  1313. ``DFAPacketizer::reserveResources(MachineInstr *MI)``, and
  1314. ``DFAPacketizer::canReserveResources(MachineInstr *MI)``. These functions allow
  1315. a target packetizer to add an instruction to an existing packet and to check
  1316. whether an instruction can be added to a packet. See
  1317. ``llvm/CodeGen/DFAPacketizer.h`` for more information.
  1318. Implementing a Native Assembler
  1319. ===============================
  1320. Though you're probably reading this because you want to write or maintain a
  1321. compiler backend, LLVM also fully supports building a native assembler.
  1322. We've tried hard to automate the generation of the assembler from the .td files
  1323. (in particular the instruction syntax and encodings), which means that a large
  1324. part of the manual and repetitive data entry can be factored and shared with the
  1325. compiler.
  1326. Instruction Parsing
  1327. -------------------
  1328. .. note::
  1329. To Be Written
  1330. Instruction Alias Processing
  1331. ----------------------------
  1332. Once the instruction is parsed, it enters the MatchInstructionImpl function.
  1333. The MatchInstructionImpl function performs alias processing and then does actual
  1334. matching.
  1335. Alias processing is the phase that canonicalizes different lexical forms of the
  1336. same instructions down to one representation. There are several different kinds
  1337. of alias that are possible to implement and they are listed below in the order
  1338. that they are processed (which is in order from simplest/weakest to most
  1339. complex/powerful). Generally you want to use the first alias mechanism that
  1340. meets the needs of your instruction, because it will allow a more concise
  1341. description.
  1342. Mnemonic Aliases
  1343. ^^^^^^^^^^^^^^^^
  1344. The first phase of alias processing is simple instruction mnemonic remapping for
  1345. classes of instructions which are allowed with two different mnemonics. This
  1346. phase is a simple and unconditionally remapping from one input mnemonic to one
  1347. output mnemonic. It isn't possible for this form of alias to look at the
  1348. operands at all, so the remapping must apply for all forms of a given mnemonic.
  1349. Mnemonic aliases are defined simply, for example X86 has:
  1350. ::
  1351. def : MnemonicAlias<"cbw", "cbtw">;
  1352. def : MnemonicAlias<"smovq", "movsq">;
  1353. def : MnemonicAlias<"fldcww", "fldcw">;
  1354. def : MnemonicAlias<"fucompi", "fucomip">;
  1355. def : MnemonicAlias<"ud2a", "ud2">;
  1356. ... and many others. With a MnemonicAlias definition, the mnemonic is remapped
  1357. simply and directly. Though MnemonicAlias's can't look at any aspect of the
  1358. instruction (such as the operands) they can depend on global modes (the same
  1359. ones supported by the matcher), through a Requires clause:
  1360. ::
  1361. def : MnemonicAlias<"pushf", "pushfq">, Requires<[In64BitMode]>;
  1362. def : MnemonicAlias<"pushf", "pushfl">, Requires<[In32BitMode]>;
  1363. In this example, the mnemonic gets mapped into a different one depending on
  1364. the current instruction set.
  1365. Instruction Aliases
  1366. ^^^^^^^^^^^^^^^^^^^
  1367. The most general phase of alias processing occurs while matching is happening:
  1368. it provides new forms for the matcher to match along with a specific instruction
  1369. to generate. An instruction alias has two parts: the string to match and the
  1370. instruction to generate. For example:
  1371. ::
  1372. def : InstAlias<"movsx $src, $dst", (MOVSX16rr8W GR16:$dst, GR8 :$src)>;
  1373. def : InstAlias<"movsx $src, $dst", (MOVSX16rm8W GR16:$dst, i8mem:$src)>;
  1374. def : InstAlias<"movsx $src, $dst", (MOVSX32rr8 GR32:$dst, GR8 :$src)>;
  1375. def : InstAlias<"movsx $src, $dst", (MOVSX32rr16 GR32:$dst, GR16 :$src)>;
  1376. def : InstAlias<"movsx $src, $dst", (MOVSX64rr8 GR64:$dst, GR8 :$src)>;
  1377. def : InstAlias<"movsx $src, $dst", (MOVSX64rr16 GR64:$dst, GR16 :$src)>;
  1378. def : InstAlias<"movsx $src, $dst", (MOVSX64rr32 GR64:$dst, GR32 :$src)>;
  1379. This shows a powerful example of the instruction aliases, matching the same
  1380. mnemonic in multiple different ways depending on what operands are present in
  1381. the assembly. The result of instruction aliases can include operands in a
  1382. different order than the destination instruction, and can use an input multiple
  1383. times, for example:
  1384. ::
  1385. def : InstAlias<"clrb $reg", (XOR8rr GR8 :$reg, GR8 :$reg)>;
  1386. def : InstAlias<"clrw $reg", (XOR16rr GR16:$reg, GR16:$reg)>;
  1387. def : InstAlias<"clrl $reg", (XOR32rr GR32:$reg, GR32:$reg)>;
  1388. def : InstAlias<"clrq $reg", (XOR64rr GR64:$reg, GR64:$reg)>;
  1389. This example also shows that tied operands are only listed once. In the X86
  1390. backend, XOR8rr has two input GR8's and one output GR8 (where an input is tied
  1391. to the output). InstAliases take a flattened operand list without duplicates
  1392. for tied operands. The result of an instruction alias can also use immediates
  1393. and fixed physical registers which are added as simple immediate operands in the
  1394. result, for example:
  1395. ::
  1396. // Fixed Immediate operand.
  1397. def : InstAlias<"aad", (AAD8i8 10)>;
  1398. // Fixed register operand.
  1399. def : InstAlias<"fcomi", (COM_FIr ST1)>;
  1400. // Simple alias.
  1401. def : InstAlias<"fcomi $reg", (COM_FIr RST:$reg)>;
  1402. Instruction aliases can also have a Requires clause to make them subtarget
  1403. specific.
  1404. If the back-end supports it, the instruction printer can automatically emit the
  1405. alias rather than what's being aliased. It typically leads to better, more
  1406. readable code. If it's better to print out what's being aliased, then pass a '0'
  1407. as the third parameter to the InstAlias definition.
  1408. Instruction Matching
  1409. --------------------
  1410. .. note::
  1411. To Be Written
  1412. .. _Implementations of the abstract target description interfaces:
  1413. .. _implement the target description:
  1414. Target-specific Implementation Notes
  1415. ====================================
  1416. This section of the document explains features or design decisions that are
  1417. specific to the code generator for a particular target. First we start with a
  1418. table that summarizes what features are supported by each target.
  1419. .. _target-feature-matrix:
  1420. Target Feature Matrix
  1421. ---------------------
  1422. Note that this table does not list features that are not supported fully by any
  1423. target yet. It considers a feature to be supported if at least one subtarget
  1424. supports it. A feature being supported means that it is useful and works for
  1425. most cases, it does not indicate that there are zero known bugs in the
  1426. implementation. Here is the key:
  1427. :raw-html:`<table border="1" cellspacing="0">`
  1428. :raw-html:`<tr>`
  1429. :raw-html:`<th>Unknown</th>`
  1430. :raw-html:`<th>Not Applicable</th>`
  1431. :raw-html:`<th>No support</th>`
  1432. :raw-html:`<th>Partial Support</th>`
  1433. :raw-html:`<th>Complete Support</th>`
  1434. :raw-html:`</tr>`
  1435. :raw-html:`<tr>`
  1436. :raw-html:`<td class="unknown"></td>`
  1437. :raw-html:`<td class="na"></td>`
  1438. :raw-html:`<td class="no"></td>`
  1439. :raw-html:`<td class="partial"></td>`
  1440. :raw-html:`<td class="yes"></td>`
  1441. :raw-html:`</tr>`
  1442. :raw-html:`</table>`
  1443. Here is the table:
  1444. :raw-html:`<table width="689" border="1" cellspacing="0">`
  1445. :raw-html:`<tr><td></td>`
  1446. :raw-html:`<td colspan="13" align="center" style="background-color:#ffc">Target</td>`
  1447. :raw-html:`</tr>`
  1448. :raw-html:`<tr>`
  1449. :raw-html:`<th>Feature</th>`
  1450. :raw-html:`<th>ARM</th>`
  1451. :raw-html:`<th>Hexagon</th>`
  1452. :raw-html:`<th>MSP430</th>`
  1453. :raw-html:`<th>Mips</th>`
  1454. :raw-html:`<th>NVPTX</th>`
  1455. :raw-html:`<th>PowerPC</th>`
  1456. :raw-html:`<th>Sparc</th>`
  1457. :raw-html:`<th>SystemZ</th>`
  1458. :raw-html:`<th>X86</th>`
  1459. :raw-html:`<th>XCore</th>`
  1460. :raw-html:`<th>eBPF</th>`
  1461. :raw-html:`</tr>`
  1462. :raw-html:`<tr>`
  1463. :raw-html:`<td><a href="#feat_reliable">is generally reliable</a></td>`
  1464. :raw-html:`<td class="yes"></td> <!-- ARM -->`
  1465. :raw-html:`<td class="yes"></td> <!-- Hexagon -->`
  1466. :raw-html:`<td class="unknown"></td> <!-- MSP430 -->`
  1467. :raw-html:`<td class="yes"></td> <!-- Mips -->`
  1468. :raw-html:`<td class="yes"></td> <!-- NVPTX -->`
  1469. :raw-html:`<td class="yes"></td> <!-- PowerPC -->`
  1470. :raw-html:`<td class="yes"></td> <!-- Sparc -->`
  1471. :raw-html:`<td class="yes"></td> <!-- SystemZ -->`
  1472. :raw-html:`<td class="yes"></td> <!-- X86 -->`
  1473. :raw-html:`<td class="yes"></td> <!-- XCore -->`
  1474. :raw-html:`<td class="yes"></td> <!-- eBPF -->`
  1475. :raw-html:`</tr>`
  1476. :raw-html:`<tr>`
  1477. :raw-html:`<td><a href="#feat_asmparser">assembly parser</a></td>`
  1478. :raw-html:`<td class="no"></td> <!-- ARM -->`
  1479. :raw-html:`<td class="no"></td> <!-- Hexagon -->`
  1480. :raw-html:`<td class="no"></td> <!-- MSP430 -->`
  1481. :raw-html:`<td class="no"></td> <!-- Mips -->`
  1482. :raw-html:`<td class="no"></td> <!-- NVPTX -->`
  1483. :raw-html:`<td class="no"></td> <!-- PowerPC -->`
  1484. :raw-html:`<td class="no"></td> <!-- Sparc -->`
  1485. :raw-html:`<td class="yes"></td> <!-- SystemZ -->`
  1486. :raw-html:`<td class="yes"></td> <!-- X86 -->`
  1487. :raw-html:`<td class="no"></td> <!-- XCore -->`
  1488. :raw-html:`<td class="no"></td> <!-- eBPF -->`
  1489. :raw-html:`</tr>`
  1490. :raw-html:`<tr>`
  1491. :raw-html:`<td><a href="#feat_disassembler">disassembler</a></td>`
  1492. :raw-html:`<td class="yes"></td> <!-- ARM -->`
  1493. :raw-html:`<td class="no"></td> <!-- Hexagon -->`
  1494. :raw-html:`<td class="no"></td> <!-- MSP430 -->`
  1495. :raw-html:`<td class="no"></td> <!-- Mips -->`
  1496. :raw-html:`<td class="na"></td> <!-- NVPTX -->`
  1497. :raw-html:`<td class="no"></td> <!-- PowerPC -->`
  1498. :raw-html:`<td class="yes"></td> <!-- SystemZ -->`
  1499. :raw-html:`<td class="no"></td> <!-- Sparc -->`
  1500. :raw-html:`<td class="yes"></td> <!-- X86 -->`
  1501. :raw-html:`<td class="yes"></td> <!-- XCore -->`
  1502. :raw-html:`<td class="yes"></td> <!-- eBPF -->`
  1503. :raw-html:`</tr>`
  1504. :raw-html:`<tr>`
  1505. :raw-html:`<td><a href="#feat_inlineasm">inline asm</a></td>`
  1506. :raw-html:`<td class="yes"></td> <!-- ARM -->`
  1507. :raw-html:`<td class="yes"></td> <!-- Hexagon -->`
  1508. :raw-html:`<td class="unknown"></td> <!-- MSP430 -->`
  1509. :raw-html:`<td class="no"></td> <!-- Mips -->`
  1510. :raw-html:`<td class="yes"></td> <!-- NVPTX -->`
  1511. :raw-html:`<td class="yes"></td> <!-- PowerPC -->`
  1512. :raw-html:`<td class="unknown"></td> <!-- Sparc -->`
  1513. :raw-html:`<td class="yes"></td> <!-- SystemZ -->`
  1514. :raw-html:`<td class="yes"></td> <!-- X86 -->`
  1515. :raw-html:`<td class="yes"></td> <!-- XCore -->`
  1516. :raw-html:`<td class="no"></td> <!-- eBPF -->`
  1517. :raw-html:`</tr>`
  1518. :raw-html:`<tr>`
  1519. :raw-html:`<td><a href="#feat_jit">jit</a></td>`
  1520. :raw-html:`<td class="partial"><a href="#feat_jit_arm">*</a></td> <!-- ARM -->`
  1521. :raw-html:`<td class="no"></td> <!-- Hexagon -->`
  1522. :raw-html:`<td class="unknown"></td> <!-- MSP430 -->`
  1523. :raw-html:`<td class="yes"></td> <!-- Mips -->`
  1524. :raw-html:`<td class="na"></td> <!-- NVPTX -->`
  1525. :raw-html:`<td class="yes"></td> <!-- PowerPC -->`
  1526. :raw-html:`<td class="unknown"></td> <!-- Sparc -->`
  1527. :raw-html:`<td class="yes"></td> <!-- SystemZ -->`
  1528. :raw-html:`<td class="yes"></td> <!-- X86 -->`
  1529. :raw-html:`<td class="no"></td> <!-- XCore -->`
  1530. :raw-html:`<td class="yes"></td> <!-- eBPF -->`
  1531. :raw-html:`</tr>`
  1532. :raw-html:`<tr>`
  1533. :raw-html:`<td><a href="#feat_objectwrite">.o&nbsp;file writing</a></td>`
  1534. :raw-html:`<td class="no"></td> <!-- ARM -->`
  1535. :raw-html:`<td class="no"></td> <!-- Hexagon -->`
  1536. :raw-html:`<td class="no"></td> <!-- MSP430 -->`
  1537. :raw-html:`<td class="no"></td> <!-- Mips -->`
  1538. :raw-html:`<td class="na"></td> <!-- NVPTX -->`
  1539. :raw-html:`<td class="no"></td> <!-- PowerPC -->`
  1540. :raw-html:`<td class="no"></td> <!-- Sparc -->`
  1541. :raw-html:`<td class="yes"></td> <!-- SystemZ -->`
  1542. :raw-html:`<td class="yes"></td> <!-- X86 -->`
  1543. :raw-html:`<td class="no"></td> <!-- XCore -->`
  1544. :raw-html:`<td class="yes"></td> <!-- eBPF -->`
  1545. :raw-html:`</tr>`
  1546. :raw-html:`<tr>`
  1547. :raw-html:`<td><a hr:raw-html:`ef="#feat_tailcall">tail calls</a></td>`
  1548. :raw-html:`<td class="yes"></td> <!-- ARM -->`
  1549. :raw-html:`<td class="yes"></td> <!-- Hexagon -->`
  1550. :raw-html:`<td class="unknown"></td> <!-- MSP430 -->`
  1551. :raw-html:`<td class="no"></td> <!-- Mips -->`
  1552. :raw-html:`<td class="no"></td> <!-- NVPTX -->`
  1553. :raw-html:`<td class="yes"></td> <!-- PowerPC -->`
  1554. :raw-html:`<td class="unknown"></td> <!-- Sparc -->`
  1555. :raw-html:`<td class="no"></td> <!-- SystemZ -->`
  1556. :raw-html:`<td class="yes"></td> <!-- X86 -->`
  1557. :raw-html:`<td class="no"></td> <!-- XCore -->`
  1558. :raw-html:`<td class="no"></td> <!-- eBPF -->`
  1559. :raw-html:`</tr>`
  1560. :raw-html:`<tr>`
  1561. :raw-html:`<td><a href="#feat_segstacks">segmented stacks</a></td>`
  1562. :raw-html:`<td class="no"></td> <!-- ARM -->`
  1563. :raw-html:`<td class="no"></td> <!-- Hexagon -->`
  1564. :raw-html:`<td class="no"></td> <!-- MSP430 -->`
  1565. :raw-html:`<td class="no"></td> <!-- Mips -->`
  1566. :raw-html:`<td class="no"></td> <!-- NVPTX -->`
  1567. :raw-html:`<td class="no"></td> <!-- PowerPC -->`
  1568. :raw-html:`<td class="no"></td> <!-- Sparc -->`
  1569. :raw-html:`<td class="no"></td> <!-- SystemZ -->`
  1570. :raw-html:`<td class="partial"><a href="#feat_segstacks_x86">*</a></td> <!-- X86 -->`
  1571. :raw-html:`<td class="no"></td> <!-- XCore -->`
  1572. :raw-html:`<td class="no"></td> <!-- eBPF -->`
  1573. :raw-html:`</tr>`
  1574. :raw-html:`</table>`
  1575. .. _feat_reliable:
  1576. Is Generally Reliable
  1577. ^^^^^^^^^^^^^^^^^^^^^
  1578. This box indicates whether the target is considered to be production quality.
  1579. This indicates that the target has been used as a static compiler to compile
  1580. large amounts of code by a variety of different people and is in continuous use.
  1581. .. _feat_asmparser:
  1582. Assembly Parser
  1583. ^^^^^^^^^^^^^^^
  1584. This box indicates whether the target supports parsing target specific .s files
  1585. by implementing the MCAsmParser interface. This is required for llvm-mc to be
  1586. able to act as a native assembler and is required for inline assembly support in
  1587. the native .o file writer.
  1588. .. _feat_disassembler:
  1589. Disassembler
  1590. ^^^^^^^^^^^^
  1591. This box indicates whether the target supports the MCDisassembler API for
  1592. disassembling machine opcode bytes into MCInst's.
  1593. .. _feat_inlineasm:
  1594. Inline Asm
  1595. ^^^^^^^^^^
  1596. This box indicates whether the target supports most popular inline assembly
  1597. constraints and modifiers.
  1598. .. _feat_jit:
  1599. JIT Support
  1600. ^^^^^^^^^^^
  1601. This box indicates whether the target supports the JIT compiler through the
  1602. ExecutionEngine interface.
  1603. .. _feat_jit_arm:
  1604. The ARM backend has basic support for integer code in ARM codegen mode, but
  1605. lacks NEON and full Thumb support.
  1606. .. _feat_objectwrite:
  1607. .o File Writing
  1608. ^^^^^^^^^^^^^^^
  1609. This box indicates whether the target supports writing .o files (e.g. MachO,
  1610. ELF, and/or COFF) files directly from the target. Note that the target also
  1611. must include an assembly parser and general inline assembly support for full
  1612. inline assembly support in the .o writer.
  1613. Targets that don't support this feature can obviously still write out .o files,
  1614. they just rely on having an external assembler to translate from a .s file to a
  1615. .o file (as is the case for many C compilers).
  1616. .. _feat_tailcall:
  1617. Tail Calls
  1618. ^^^^^^^^^^
  1619. This box indicates whether the target supports guaranteed tail calls. These are
  1620. calls marked "`tail <LangRef.html#i_call>`_" and use the fastcc calling
  1621. convention. Please see the `tail call section`_ for more details.
  1622. .. _feat_segstacks:
  1623. Segmented Stacks
  1624. ^^^^^^^^^^^^^^^^
  1625. This box indicates whether the target supports segmented stacks. This replaces
  1626. the traditional large C stack with many linked segments. It is compatible with
  1627. the `gcc implementation <http://gcc.gnu.org/wiki/SplitStacks>`_ used by the Go
  1628. front end.
  1629. .. _feat_segstacks_x86:
  1630. Basic support exists on the X86 backend. Currently vararg doesn't work and the
  1631. object files are not marked the way the gold linker expects, but simple Go
  1632. programs can be built by dragonegg.
  1633. .. _tail call section:
  1634. Tail call optimization
  1635. ----------------------
  1636. Tail call optimization, callee reusing the stack of the caller, is currently
  1637. supported on x86/x86-64, PowerPC, and WebAssembly. It is performed on x86/x86-64
  1638. and PowerPC if:
  1639. * Caller and callee have the calling convention ``fastcc``, ``cc 10`` (GHC
  1640. calling convention), ``cc 11`` (HiPE calling convention), or ``tailcc``.
  1641. * The call is a tail call - in tail position (ret immediately follows call and
  1642. ret uses value of call or is void).
  1643. * Option ``-tailcallopt`` is enabled or the calling convention is ``tailcc``.
  1644. * Platform-specific constraints are met.
  1645. x86/x86-64 constraints:
  1646. * No variable argument lists are used.
  1647. * On x86-64 when generating GOT/PIC code only module-local calls (visibility =
  1648. hidden or protected) are supported.
  1649. PowerPC constraints:
  1650. * No variable argument lists are used.
  1651. * No byval parameters are used.
  1652. * On ppc32/64 GOT/PIC only module-local calls (visibility = hidden or protected)
  1653. are supported.
  1654. WebAssembly constraints:
  1655. * No variable argument lists are used
  1656. * The 'tail-call' target attribute is enabled.
  1657. * The caller and callee's return types must match. The caller cannot
  1658. be void unless the callee is, too.
  1659. Example:
  1660. Call as ``llc -tailcallopt test.ll``.
  1661. .. code-block:: llvm
  1662. declare fastcc i32 @tailcallee(i32 inreg %a1, i32 inreg %a2, i32 %a3, i32 %a4)
  1663. define fastcc i32 @tailcaller(i32 %in1, i32 %in2) {
  1664. %l1 = add i32 %in1, %in2
  1665. %tmp = tail call fastcc i32 @tailcallee(i32 %in1 inreg, i32 %in2 inreg, i32 %in1, i32 %l1)
  1666. ret i32 %tmp
  1667. }
  1668. Implications of ``-tailcallopt``:
  1669. To support tail call optimization in situations where the callee has more
  1670. arguments than the caller a 'callee pops arguments' convention is used. This
  1671. currently causes each ``fastcc`` call that is not tail call optimized (because
  1672. one or more of above constraints are not met) to be followed by a readjustment
  1673. of the stack. So performance might be worse in such cases.
  1674. Sibling call optimization
  1675. -------------------------
  1676. Sibling call optimization is a restricted form of tail call optimization.
  1677. Unlike tail call optimization described in the previous section, it can be
  1678. performed automatically on any tail calls when ``-tailcallopt`` option is not
  1679. specified.
  1680. Sibling call optimization is currently performed on x86/x86-64 when the
  1681. following constraints are met:
  1682. * Caller and callee have the same calling convention. It can be either ``c`` or
  1683. ``fastcc``.
  1684. * The call is a tail call - in tail position (ret immediately follows call and
  1685. ret uses value of call or is void).
  1686. * Caller and callee have matching return type or the callee result is not used.
  1687. * If any of the callee arguments are being passed in stack, they must be
  1688. available in caller's own incoming argument stack and the frame offsets must
  1689. be the same.
  1690. Example:
  1691. .. code-block:: llvm
  1692. declare i32 @bar(i32, i32)
  1693. define i32 @foo(i32 %a, i32 %b, i32 %c) {
  1694. entry:
  1695. %0 = tail call i32 @bar(i32 %a, i32 %b)
  1696. ret i32 %0
  1697. }
  1698. The X86 backend
  1699. ---------------
  1700. The X86 code generator lives in the ``lib/Target/X86`` directory. This code
  1701. generator is capable of targeting a variety of x86-32 and x86-64 processors, and
  1702. includes support for ISA extensions such as MMX and SSE.
  1703. X86 Target Triples supported
  1704. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1705. The following are the known target triples that are supported by the X86
  1706. backend. This is not an exhaustive list, and it would be useful to add those
  1707. that people test.
  1708. * **i686-pc-linux-gnu** --- Linux
  1709. * **i386-unknown-freebsd5.3** --- FreeBSD 5.3
  1710. * **i686-pc-cygwin** --- Cygwin on Win32
  1711. * **i686-pc-mingw32** --- MingW on Win32
  1712. * **i386-pc-mingw32msvc** --- MingW crosscompiler on Linux
  1713. * **i686-apple-darwin*** --- Apple Darwin on X86
  1714. * **x86_64-unknown-linux-gnu** --- Linux
  1715. X86 Calling Conventions supported
  1716. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1717. The following target-specific calling conventions are known to backend:
  1718. * **x86_StdCall** --- stdcall calling convention seen on Microsoft Windows
  1719. platform (CC ID = 64).
  1720. * **x86_FastCall** --- fastcall calling convention seen on Microsoft Windows
  1721. platform (CC ID = 65).
  1722. * **x86_ThisCall** --- Similar to X86_StdCall. Passes first argument in ECX,
  1723. others via stack. Callee is responsible for stack cleaning. This convention is
  1724. used by MSVC by default for methods in its ABI (CC ID = 70).
  1725. .. _X86 addressing mode:
  1726. Representing X86 addressing modes in MachineInstrs
  1727. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1728. The x86 has a very flexible way of accessing memory. It is capable of forming
  1729. memory addresses of the following expression directly in integer instructions
  1730. (which use ModR/M addressing):
  1731. ::
  1732. SegmentReg: Base + [1,2,4,8] * IndexReg + Disp32
  1733. In order to represent this, LLVM tracks no less than 5 operands for each memory
  1734. operand of this form. This means that the "load" form of '``mov``' has the
  1735. following ``MachineOperand``\s in this order:
  1736. ::
  1737. Index: 0 | 1 2 3 4 5
  1738. Meaning: DestReg, | BaseReg, Scale, IndexReg, Displacement Segment
  1739. OperandTy: VirtReg, | VirtReg, UnsImm, VirtReg, SignExtImm PhysReg
  1740. Stores, and all other instructions, treat the four memory operands in the same
  1741. way and in the same order. If the segment register is unspecified (regno = 0),
  1742. then no segment override is generated. "Lea" operations do not have a segment
  1743. register specified, so they only have 4 operands for their memory reference.
  1744. X86 address spaces supported
  1745. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1746. x86 has a feature which provides the ability to perform loads and stores to
  1747. different address spaces via the x86 segment registers. A segment override
  1748. prefix byte on an instruction causes the instruction's memory access to go to
  1749. the specified segment. LLVM address space 0 is the default address space, which
  1750. includes the stack, and any unqualified memory accesses in a program. Address
  1751. spaces 1-255 are currently reserved for user-defined code. The GS-segment is
  1752. represented by address space 256, the FS-segment is represented by address space
  1753. 257, and the SS-segment is represented by address space 258. Other x86 segments
  1754. have yet to be allocated address space numbers.
  1755. While these address spaces may seem similar to TLS via the ``thread_local``
  1756. keyword, and often use the same underlying hardware, there are some fundamental
  1757. differences.
  1758. The ``thread_local`` keyword applies to global variables and specifies that they
  1759. are to be allocated in thread-local memory. There are no type qualifiers
  1760. involved, and these variables can be pointed to with normal pointers and
  1761. accessed with normal loads and stores. The ``thread_local`` keyword is
  1762. target-independent at the LLVM IR level (though LLVM doesn't yet have
  1763. implementations of it for some configurations)
  1764. Special address spaces, in contrast, apply to static types. Every load and store
  1765. has a particular address space in its address operand type, and this is what
  1766. determines which address space is accessed. LLVM ignores these special address
  1767. space qualifiers on global variables, and does not provide a way to directly
  1768. allocate storage in them. At the LLVM IR level, the behavior of these special
  1769. address spaces depends in part on the underlying OS or runtime environment, and
  1770. they are specific to x86 (and LLVM doesn't yet handle them correctly in some
  1771. cases).
  1772. Some operating systems and runtime environments use (or may in the future use)
  1773. the FS/GS-segment registers for various low-level purposes, so care should be
  1774. taken when considering them.
  1775. Instruction naming
  1776. ^^^^^^^^^^^^^^^^^^
  1777. An instruction name consists of the base name, a default operand size, and a a
  1778. character per operand with an optional special size. For example:
  1779. ::
  1780. ADD8rr -> add, 8-bit register, 8-bit register
  1781. IMUL16rmi -> imul, 16-bit register, 16-bit memory, 16-bit immediate
  1782. IMUL16rmi8 -> imul, 16-bit register, 16-bit memory, 8-bit immediate
  1783. MOVSX32rm16 -> movsx, 32-bit register, 16-bit memory
  1784. The PowerPC backend
  1785. -------------------
  1786. The PowerPC code generator lives in the lib/Target/PowerPC directory. The code
  1787. generation is retargetable to several variations or *subtargets* of the PowerPC
  1788. ISA; including ppc32, ppc64 and altivec.
  1789. LLVM PowerPC ABI
  1790. ^^^^^^^^^^^^^^^^
  1791. LLVM follows the AIX PowerPC ABI, with two deviations. LLVM uses a PC relative
  1792. (PIC) or static addressing for accessing global values, so no TOC (r2) is
  1793. used. Second, r31 is used as a frame pointer to allow dynamic growth of a stack
  1794. frame. LLVM takes advantage of having no TOC to provide space to save the frame
  1795. pointer in the PowerPC linkage area of the caller frame. Other details of
  1796. PowerPC ABI can be found at `PowerPC ABI
  1797. <http://developer.apple.com/documentation/DeveloperTools/Conceptual/LowLevelABI/Articles/32bitPowerPC.html>`_\
  1798. . Note: This link describes the 32 bit ABI. The 64 bit ABI is similar except
  1799. space for GPRs are 8 bytes wide (not 4) and r13 is reserved for system use.
  1800. Frame Layout
  1801. ^^^^^^^^^^^^
  1802. The size of a PowerPC frame is usually fixed for the duration of a function's
  1803. invocation. Since the frame is fixed size, all references into the frame can be
  1804. accessed via fixed offsets from the stack pointer. The exception to this is
  1805. when dynamic alloca or variable sized arrays are present, then a base pointer
  1806. (r31) is used as a proxy for the stack pointer and stack pointer is free to grow
  1807. or shrink. A base pointer is also used if llvm-gcc is not passed the
  1808. -fomit-frame-pointer flag. The stack pointer is always aligned to 16 bytes, so
  1809. that space allocated for altivec vectors will be properly aligned.
  1810. An invocation frame is laid out as follows (low memory at top):
  1811. :raw-html:`<table border="1" cellspacing="0">`
  1812. :raw-html:`<tr>`
  1813. :raw-html:`<td>Linkage<br><br></td>`
  1814. :raw-html:`</tr>`
  1815. :raw-html:`<tr>`
  1816. :raw-html:`<td>Parameter area<br><br></td>`
  1817. :raw-html:`</tr>`
  1818. :raw-html:`<tr>`
  1819. :raw-html:`<td>Dynamic area<br><br></td>`
  1820. :raw-html:`</tr>`
  1821. :raw-html:`<tr>`
  1822. :raw-html:`<td>Locals area<br><br></td>`
  1823. :raw-html:`</tr>`
  1824. :raw-html:`<tr>`
  1825. :raw-html:`<td>Saved registers area<br><br></td>`
  1826. :raw-html:`</tr>`
  1827. :raw-html:`<tr style="border-style: none hidden none hidden;">`
  1828. :raw-html:`<td><br></td>`
  1829. :raw-html:`</tr>`
  1830. :raw-html:`<tr>`
  1831. :raw-html:`<td>Previous Frame<br><br></td>`
  1832. :raw-html:`</tr>`
  1833. :raw-html:`</table>`
  1834. The *linkage* area is used by a callee to save special registers prior to
  1835. allocating its own frame. Only three entries are relevant to LLVM. The first
  1836. entry is the previous stack pointer (sp), aka link. This allows probing tools
  1837. like gdb or exception handlers to quickly scan the frames in the stack. A
  1838. function epilog can also use the link to pop the frame from the stack. The
  1839. third entry in the linkage area is used to save the return address from the lr
  1840. register. Finally, as mentioned above, the last entry is used to save the
  1841. previous frame pointer (r31.) The entries in the linkage area are the size of a
  1842. GPR, thus the linkage area is 24 bytes long in 32 bit mode and 48 bytes in 64
  1843. bit mode.
  1844. 32 bit linkage area:
  1845. :raw-html:`<table border="1" cellspacing="0">`
  1846. :raw-html:`<tr>`
  1847. :raw-html:`<td>0</td>`
  1848. :raw-html:`<td>Saved SP (r1)</td>`
  1849. :raw-html:`</tr>`
  1850. :raw-html:`<tr>`
  1851. :raw-html:`<td>4</td>`
  1852. :raw-html:`<td>Saved CR</td>`
  1853. :raw-html:`</tr>`
  1854. :raw-html:`<tr>`
  1855. :raw-html:`<td>8</td>`
  1856. :raw-html:`<td>Saved LR</td>`
  1857. :raw-html:`</tr>`
  1858. :raw-html:`<tr>`
  1859. :raw-html:`<td>12</td>`
  1860. :raw-html:`<td>Reserved</td>`
  1861. :raw-html:`</tr>`
  1862. :raw-html:`<tr>`
  1863. :raw-html:`<td>16</td>`
  1864. :raw-html:`<td>Reserved</td>`
  1865. :raw-html:`</tr>`
  1866. :raw-html:`<tr>`
  1867. :raw-html:`<td>20</td>`
  1868. :raw-html:`<td>Saved FP (r31)</td>`
  1869. :raw-html:`</tr>`
  1870. :raw-html:`</table>`
  1871. 64 bit linkage area:
  1872. :raw-html:`<table border="1" cellspacing="0">`
  1873. :raw-html:`<tr>`
  1874. :raw-html:`<td>0</td>`
  1875. :raw-html:`<td>Saved SP (r1)</td>`
  1876. :raw-html:`</tr>`
  1877. :raw-html:`<tr>`
  1878. :raw-html:`<td>8</td>`
  1879. :raw-html:`<td>Saved CR</td>`
  1880. :raw-html:`</tr>`
  1881. :raw-html:`<tr>`
  1882. :raw-html:`<td>16</td>`
  1883. :raw-html:`<td>Saved LR</td>`
  1884. :raw-html:`</tr>`
  1885. :raw-html:`<tr>`
  1886. :raw-html:`<td>24</td>`
  1887. :raw-html:`<td>Reserved</td>`
  1888. :raw-html:`</tr>`
  1889. :raw-html:`<tr>`
  1890. :raw-html:`<td>32</td>`
  1891. :raw-html:`<td>Reserved</td>`
  1892. :raw-html:`</tr>`
  1893. :raw-html:`<tr>`
  1894. :raw-html:`<td>40</td>`
  1895. :raw-html:`<td>Saved FP (r31)</td>`
  1896. :raw-html:`</tr>`
  1897. :raw-html:`</table>`
  1898. The *parameter area* is used to store arguments being passed to a callee
  1899. function. Following the PowerPC ABI, the first few arguments are actually
  1900. passed in registers, with the space in the parameter area unused. However, if
  1901. there are not enough registers or the callee is a thunk or vararg function,
  1902. these register arguments can be spilled into the parameter area. Thus, the
  1903. parameter area must be large enough to store all the parameters for the largest
  1904. call sequence made by the caller. The size must also be minimally large enough
  1905. to spill registers r3-r10. This allows callees blind to the call signature,
  1906. such as thunks and vararg functions, enough space to cache the argument
  1907. registers. Therefore, the parameter area is minimally 32 bytes (64 bytes in 64
  1908. bit mode.) Also note that since the parameter area is a fixed offset from the
  1909. top of the frame, that a callee can access its spilt arguments using fixed
  1910. offsets from the stack pointer (or base pointer.)
  1911. Combining the information about the linkage, parameter areas and alignment. A
  1912. stack frame is minimally 64 bytes in 32 bit mode and 128 bytes in 64 bit mode.
  1913. The *dynamic area* starts out as size zero. If a function uses dynamic alloca
  1914. then space is added to the stack, the linkage and parameter areas are shifted to
  1915. top of stack, and the new space is available immediately below the linkage and
  1916. parameter areas. The cost of shifting the linkage and parameter areas is minor
  1917. since only the link value needs to be copied. The link value can be easily
  1918. fetched by adding the original frame size to the base pointer. Note that
  1919. allocations in the dynamic space need to observe 16 byte alignment.
  1920. The *locals area* is where the llvm compiler reserves space for local variables.
  1921. The *saved registers area* is where the llvm compiler spills callee saved
  1922. registers on entry to the callee.
  1923. Prolog/Epilog
  1924. ^^^^^^^^^^^^^
  1925. The llvm prolog and epilog are the same as described in the PowerPC ABI, with
  1926. the following exceptions. Callee saved registers are spilled after the frame is
  1927. created. This allows the llvm epilog/prolog support to be common with other
  1928. targets. The base pointer callee saved register r31 is saved in the TOC slot of
  1929. linkage area. This simplifies allocation of space for the base pointer and
  1930. makes it convenient to locate programmatically and during debugging.
  1931. Dynamic Allocation
  1932. ^^^^^^^^^^^^^^^^^^
  1933. .. note::
  1934. TODO - More to come.
  1935. The NVPTX backend
  1936. -----------------
  1937. The NVPTX code generator under lib/Target/NVPTX is an open-source version of
  1938. the NVIDIA NVPTX code generator for LLVM. It is contributed by NVIDIA and is
  1939. a port of the code generator used in the CUDA compiler (nvcc). It targets the
  1940. PTX 3.0/3.1 ISA and can target any compute capability greater than or equal to
  1941. 2.0 (Fermi).
  1942. This target is of production quality and should be completely compatible with
  1943. the official NVIDIA toolchain.
  1944. Code Generator Options:
  1945. :raw-html:`<table border="1" cellspacing="0">`
  1946. :raw-html:`<tr>`
  1947. :raw-html:`<th>Option</th>`
  1948. :raw-html:`<th>Description</th>`
  1949. :raw-html:`</tr>`
  1950. :raw-html:`<tr>`
  1951. :raw-html:`<td>sm_20</td>`
  1952. :raw-html:`<td align="left">Set shader model/compute capability to 2.0</td>`
  1953. :raw-html:`</tr>`
  1954. :raw-html:`<tr>`
  1955. :raw-html:`<td>sm_21</td>`
  1956. :raw-html:`<td align="left">Set shader model/compute capability to 2.1</td>`
  1957. :raw-html:`</tr>`
  1958. :raw-html:`<tr>`
  1959. :raw-html:`<td>sm_30</td>`
  1960. :raw-html:`<td align="left">Set shader model/compute capability to 3.0</td>`
  1961. :raw-html:`</tr>`
  1962. :raw-html:`<tr>`
  1963. :raw-html:`<td>sm_35</td>`
  1964. :raw-html:`<td align="left">Set shader model/compute capability to 3.5</td>`
  1965. :raw-html:`</tr>`
  1966. :raw-html:`<tr>`
  1967. :raw-html:`<td>ptx30</td>`
  1968. :raw-html:`<td align="left">Target PTX 3.0</td>`
  1969. :raw-html:`</tr>`
  1970. :raw-html:`<tr>`
  1971. :raw-html:`<td>ptx31</td>`
  1972. :raw-html:`<td align="left">Target PTX 3.1</td>`
  1973. :raw-html:`</tr>`
  1974. :raw-html:`</table>`
  1975. The extended Berkeley Packet Filter (eBPF) backend
  1976. --------------------------------------------------
  1977. Extended BPF (or eBPF) is similar to the original ("classic") BPF (cBPF) used
  1978. to filter network packets. The
  1979. `bpf() system call <http://man7.org/linux/man-pages/man2/bpf.2.html>`_
  1980. performs a range of operations related to eBPF. For both cBPF and eBPF
  1981. programs, the Linux kernel statically analyzes the programs before loading
  1982. them, in order to ensure that they cannot harm the running system. eBPF is
  1983. a 64-bit RISC instruction set designed for one to one mapping to 64-bit CPUs.
  1984. Opcodes are 8-bit encoded, and 87 instructions are defined. There are 10
  1985. registers, grouped by function as outlined below.
  1986. ::
  1987. R0 return value from in-kernel functions; exit value for eBPF program
  1988. R1 - R5 function call arguments to in-kernel functions
  1989. R6 - R9 callee-saved registers preserved by in-kernel functions
  1990. R10 stack frame pointer (read only)
  1991. Instruction encoding (arithmetic and jump)
  1992. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1993. eBPF is reusing most of the opcode encoding from classic to simplify conversion
  1994. of classic BPF to eBPF. For arithmetic and jump instructions the 8-bit 'code'
  1995. field is divided into three parts:
  1996. ::
  1997. +----------------+--------+--------------------+
  1998. | 4 bits | 1 bit | 3 bits |
  1999. | operation code | source | instruction class |
  2000. +----------------+--------+--------------------+
  2001. (MSB) (LSB)
  2002. Three LSB bits store instruction class which is one of:
  2003. ::
  2004. BPF_LD 0x0
  2005. BPF_LDX 0x1
  2006. BPF_ST 0x2
  2007. BPF_STX 0x3
  2008. BPF_ALU 0x4
  2009. BPF_JMP 0x5
  2010. (unused) 0x6
  2011. BPF_ALU64 0x7
  2012. When BPF_CLASS(code) == BPF_ALU or BPF_ALU64 or BPF_JMP,
  2013. 4th bit encodes source operand
  2014. ::
  2015. BPF_X 0x1 use src_reg register as source operand
  2016. BPF_K 0x0 use 32 bit immediate as source operand
  2017. and four MSB bits store operation code
  2018. ::
  2019. BPF_ADD 0x0 add
  2020. BPF_SUB 0x1 subtract
  2021. BPF_MUL 0x2 multiply
  2022. BPF_DIV 0x3 divide
  2023. BPF_OR 0x4 bitwise logical OR
  2024. BPF_AND 0x5 bitwise logical AND
  2025. BPF_LSH 0x6 left shift
  2026. BPF_RSH 0x7 right shift (zero extended)
  2027. BPF_NEG 0x8 arithmetic negation
  2028. BPF_MOD 0x9 modulo
  2029. BPF_XOR 0xa bitwise logical XOR
  2030. BPF_MOV 0xb move register to register
  2031. BPF_ARSH 0xc right shift (sign extended)
  2032. BPF_END 0xd endianness conversion
  2033. If BPF_CLASS(code) == BPF_JMP, BPF_OP(code) is one of
  2034. ::
  2035. BPF_JA 0x0 unconditional jump
  2036. BPF_JEQ 0x1 jump ==
  2037. BPF_JGT 0x2 jump >
  2038. BPF_JGE 0x3 jump >=
  2039. BPF_JSET 0x4 jump if (DST & SRC)
  2040. BPF_JNE 0x5 jump !=
  2041. BPF_JSGT 0x6 jump signed >
  2042. BPF_JSGE 0x7 jump signed >=
  2043. BPF_CALL 0x8 function call
  2044. BPF_EXIT 0x9 function return
  2045. Instruction encoding (load, store)
  2046. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  2047. For load and store instructions the 8-bit 'code' field is divided as:
  2048. ::
  2049. +--------+--------+-------------------+
  2050. | 3 bits | 2 bits | 3 bits |
  2051. | mode | size | instruction class |
  2052. +--------+--------+-------------------+
  2053. (MSB) (LSB)
  2054. Size modifier is one of
  2055. ::
  2056. BPF_W 0x0 word
  2057. BPF_H 0x1 half word
  2058. BPF_B 0x2 byte
  2059. BPF_DW 0x3 double word
  2060. Mode modifier is one of
  2061. ::
  2062. BPF_IMM 0x0 immediate
  2063. BPF_ABS 0x1 used to access packet data
  2064. BPF_IND 0x2 used to access packet data
  2065. BPF_MEM 0x3 memory
  2066. (reserved) 0x4
  2067. (reserved) 0x5
  2068. BPF_XADD 0x6 exclusive add
  2069. Packet data access (BPF_ABS, BPF_IND)
  2070. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  2071. Two non-generic instructions: (BPF_ABS | <size> | BPF_LD) and
  2072. (BPF_IND | <size> | BPF_LD) which are used to access packet data.
  2073. Register R6 is an implicit input that must contain pointer to sk_buff.
  2074. Register R0 is an implicit output which contains the data fetched
  2075. from the packet. Registers R1-R5 are scratch registers and must not
  2076. be used to store the data across BPF_ABS | BPF_LD or BPF_IND | BPF_LD
  2077. instructions. These instructions have implicit program exit condition
  2078. as well. When eBPF program is trying to access the data beyond
  2079. the packet boundary, the interpreter will abort the execution of the program.
  2080. BPF_IND | BPF_W | BPF_LD is equivalent to:
  2081. R0 = ntohl(\*(u32 \*) (((struct sk_buff \*) R6)->data + src_reg + imm32))
  2082. eBPF maps
  2083. ^^^^^^^^^
  2084. eBPF maps are provided for sharing data between kernel and user-space.
  2085. Currently implemented types are hash and array, with potential extension to
  2086. support bloom filters, radix trees, etc. A map is defined by its type,
  2087. maximum number of elements, key size and value size in bytes. eBPF syscall
  2088. supports create, update, find and delete functions on maps.
  2089. Function calls
  2090. ^^^^^^^^^^^^^^
  2091. Function call arguments are passed using up to five registers (R1 - R5).
  2092. The return value is passed in a dedicated register (R0). Four additional
  2093. registers (R6 - R9) are callee-saved, and the values in these registers
  2094. are preserved within kernel functions. R0 - R5 are scratch registers within
  2095. kernel functions, and eBPF programs must therefor store/restore values in
  2096. these registers if needed across function calls. The stack can be accessed
  2097. using the read-only frame pointer R10. eBPF registers map 1:1 to hardware
  2098. registers on x86_64 and other 64-bit architectures. For example, x86_64
  2099. in-kernel JIT maps them as
  2100. ::
  2101. R0 - rax
  2102. R1 - rdi
  2103. R2 - rsi
  2104. R3 - rdx
  2105. R4 - rcx
  2106. R5 - r8
  2107. R6 - rbx
  2108. R7 - r13
  2109. R8 - r14
  2110. R9 - r15
  2111. R10 - rbp
  2112. since x86_64 ABI mandates rdi, rsi, rdx, rcx, r8, r9 for argument passing
  2113. and rbx, r12 - r15 are callee saved.
  2114. Program start
  2115. ^^^^^^^^^^^^^
  2116. An eBPF program receives a single argument and contains
  2117. a single eBPF main routine; the program does not contain eBPF functions.
  2118. Function calls are limited to a predefined set of kernel functions. The size
  2119. of a program is limited to 4K instructions: this ensures fast termination and
  2120. a limited number of kernel function calls. Prior to running an eBPF program,
  2121. a verifier performs static analysis to prevent loops in the code and
  2122. to ensure valid register usage and operand types.
  2123. The AMDGPU backend
  2124. ------------------
  2125. The AMDGPU code generator lives in the ``lib/Target/AMDGPU``
  2126. directory. This code generator is capable of targeting a variety of
  2127. AMD GPU processors. Refer to :doc:`AMDGPUUsage` for more information.