CodeGenerator.rst 113 KB

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