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