Machine IR (MIR) Format Reference Manual

Warning

This is a work in progress.

Introduction

This document is a reference manual for the Machine IR (MIR) serializationformat. MIR is a human readable serialization format that is used to representLLVM’s machine specific intermediate representation.

The MIR serialization format is designed to be used for testing the codegeneration passes in LLVM.

Overview

The MIR serialization format uses a YAML container. YAML is a standarddata serialization language, and the full YAML language spec can be read atyaml.org.

A MIR file is split up into a series of YAML documents. The first documentcan contain an optional embedded LLVM IR module, and the rest of the documentscontain the serialized machine functions.

MIR Testing Guide

You can use the MIR format for testing in two different ways:

  • You can write MIR tests that invoke a single code generation pass using the-run-pass option in llc.
  • You can use llc’s -stop-after option with existing or new LLVM assemblytests and check the MIR output of a specific code generation pass.

Testing Individual Code Generation Passes

The -run-pass option in llc allows you to create MIR tests that invoke justa single code generation pass. When this option is used, llc will parse aninput MIR file, run the specified code generation pass(es), and output theresulting MIR code.

You can generate an input MIR file for the test by using the -stop-after or-stop-before option in llc. For example, if you would like to write a testfor the post register allocation pseudo instruction expansion pass, you canspecify the machine copy propagation pass in the -stop-after option, as itruns just before the pass that we are trying to test:

llc -stop-after=machine-cp bug-trigger.ll > test.mir

If the same pass is run multiple times, a run index can be includedafter the name with a comma.

llc -stop-after=dead-mi-elimination,1 bug-trigger.ll > test.mir

After generating the input MIR file, you’ll have to add a run line that usesthe -run-pass option to it. In order to test the post register allocationpseudo instruction expansion pass on X86-64, a run line like the one shownbelow can be used:

# RUN: llc -o - %s -mtriple=x86_64— -run-pass=postrapseudos | FileCheck %s

The MIR files are target dependent, so they have to be placed in the targetspecific test directories (lib/CodeGen/TARGETNAME). They also need tospecify a target triple or a target architecture either in the run line or inthe embedded LLVM IR module.

Simplifying MIR files

The MIR code coming out of -stop-after/-stop-before is very verbose;Tests are more accessible and future proof when simplified:

  • Use the -simplify-mir option with llc.
  • Machine function attributes often have default values or the test works justas well with default values. Typical candidates for this are: alignment:,exposesReturnsTwice, legalized, regBankSelected, selected.The whole frameInfo section is often unnecessary if there is no specialframe usage in the function. tracksRegLiveness on the other hand is oftennecessary for some passes that care about block livein lists.
  • The (global) liveins: list is typically only interesting for earlyinstruction selection passes and can be removed when testing later passes.The per-block liveins: on the other hand are necessary iftracksRegLiveness is true.
  • Branch probability data in block successors: lists can be dropped if thetest doesn’t depend on it. Example:successors: %bb.1(0x40000000), %bb.2(0x40000000) can be replaced withsuccessors: %bb.1, %bb.2.
  • MIR code contains a whole IR module. This is necessary because there areno equivalents in MIR for global variables, references to external functions,function attributes, metadata, debug info. Instead some MIR data referencesthe IR constructs. You can often remove them if the test doesn’t depend onthem.
  • Alias Analysis is performed on IR values. These are referenced by memoryoperands in MIR. Example: :: (load 8 from %ir.foobar, !alias.scope !9).If the test doesn’t depend on (good) alias analysis the references can bedropped: :: (load 8)
  • MIR blocks can reference IR blocks for debug printing, profile informationor debug locations. Example: bb.42.myblock in MIR references the IR blockmyblock. It is usually possible to drop the .myblock reference and simplyuse bb.42.
  • If there are no memory operands or blocks referencing the IR then theIR function can be replaced by a parameterless dummy function likedefine @func() { ret void }.
  • It is possible to drop the whole IR section of the MIR file if it onlycontains dummy functions (see above). The .mir loader will create theIR functions automatically in this case.

Limitations

Currently the MIR format has several limitations in terms of which state itcan serialize:

  • The target-specific state in the target-specific MachineFunctionInfosubclasses isn’t serialized at the moment.
  • The target-specific MachineConstantPoolValue subclasses (in the ARM andSystemZ backends) aren’t serialized at the moment.
  • The MCSymbol machine operands don’t support temporary or local symbols.
  • A lot of the state in MachineModuleInfo isn’t serialized - only the CFIinstructions and the variable debug information from MMI is serialized rightnow.

These limitations impose restrictions on what you can test with the MIR format.For now, tests that would like to test some behaviour that depends on the stateof temporary or local MCSymbol operands or the exception handling state inMMI, can’t use the MIR format. As well as that, tests that test some behaviourthat depends on the state of the target specific MachineFunctionInfo orMachineConstantPoolValue subclasses can’t use the MIR format at the moment.

High Level Structure

Embedded Module

When the first YAML document contains a YAML block literal string, the MIRparser will treat this string as an LLVM assembly language string thatrepresents an embedded LLVM IR module.Here is an example of a YAML document that contains an LLVM module:

  1. define i32 @inc(i32* %x) {
  2. entry:
  3. %0 = load i32, i32* %x
  4. %1 = add i32 %0, 1
  5. store i32 %1, i32* %x
  6. ret i32 %1
  7. }

Machine Functions

The remaining YAML documents contain the machine functions. This is an exampleof such YAML document:

  1. ---
  2. name: inc
  3. tracksRegLiveness: true
  4. liveins:
  5. - { reg: '$rdi' }
  6. callSites:
  7. - { bb: 0, offset: 3, fwdArgRegs:
  8. - { arg: 0, reg: '$edi' } }
  9. body: |
  10. bb.0.entry:
  11. liveins: $rdi
  12.  
  13. $eax = MOV32rm $rdi, 1, _, 0, _
  14. $eax = INC32r killed $eax, implicit-def dead $eflags
  15. MOV32mr killed $rdi, 1, _, 0, _, $eax
  16. CALL64pcrel32 @foo <regmask...>
  17. RETQ $eax
  18. ...

The document above consists of attributes that represent the variousproperties and data structures in a machine function.

The attribute name is required, and its value should be identical to thename of a function that this machine function is based on.

The attribute body is a YAML block literal string. Its value representsthe function’s machine basic blocks and their machine instructions.

The attribute callSites is a representation of call site information whichkeeps track of call instructions and registers used to transfer call arguments.

Machine Instructions Format Reference

The machine basic blocks and their instructions are represented using a custom,human readable serialization language. This language is used in theYAML block literal string that corresponds to the machine function’s body.

A source string that uses this language contains a list of machine basicblocks, which are described in the section below.

Machine Basic Blocks

A machine basic block is defined in a single block definition source constructthat contains the block’s ID.The example below defines two blocks that have an ID of zero and one:

  1. bb.0:
  2. <instructions>
  3. bb.1:
  4. <instructions>

A machine basic block can also have a name. It should be specified after the IDin the block’s definition:

  1. bb.0.entry: ; This block's name is "entry"
  2. <instructions>

The block’s name should be identical to the name of the IR block that thismachine block is based on.

Block References

The machine basic blocks are identified by their ID numbers. Individualblocks are referenced using the following syntax:

  1. %bb.<id>

Example:

  1. %bb.0

The following syntax is also supported, but the former syntax is preferred forblock references:

  1. %bb.<id>[.<name>]

Example:

  1. %bb.1.then

Successors

The machine basic block’s successors have to be specified before any of theinstructions:

  1. bb.0.entry:
  2. successors: %bb.1.then, %bb.2.else
  3. <instructions>
  4. bb.1.then:
  5. <instructions>
  6. bb.2.else:
  7. <instructions>

The branch weights can be specified in brackets after the successor blocks.The example below defines a block that has two successors with branch weightsof 32 and 16:

  1. bb.0.entry:
  2. successors: %bb.1.then(32), %bb.2.else(16)

Live In Registers

The machine basic block’s live in registers have to be specified before any ofthe instructions:

  1. bb.0.entry:
  2. liveins: $edi, $esi

The list of live in registers and successors can be empty. The language alsoallows multiple live in register and successor lists - they are combined intoone list by the parser.

Miscellaneous Attributes

The attributes IsAddressTaken, IsLandingPad and Alignment can bespecified in brackets after the block’s definition:

  1. bb.0.entry (address-taken):
  2. <instructions>
  3. bb.2.else (align 4):
  4. <instructions>
  5. bb.3(landing-pad, align 4):
  6. <instructions>

Alignment is specified in bytes, and must be a power of two.

Machine Instructions

A machine instruction is composed of a name,machine operands,instruction flags, and machine memory operands.

The instruction’s name is usually specified before the operands. The examplebelow shows an instance of the X86 RETQ instruction with a single machineoperand:

  1. RETQ $eax

However, if the machine instruction has one or more explicitly defined registeroperands, the instruction’s name has to be specified after them. The examplebelow shows an instance of the AArch64 LDPXpost instruction with threedefined register operands:

  1. $sp, $fp, $lr = LDPXpost $sp, 2

The instruction names are serialized using the exact definitions from thetarget’s *InstrInfo.td files, and they are case sensitive. This means thatsimilar instruction names like TSTri and tSTRi represent differentmachine instructions.

Instruction Flags

The flag frame-setup or frame-destroy can be specified before theinstruction’s name:

  1. $fp = frame-setup ADDXri $sp, 0, 0
  1. $x21, $x20 = frame-destroy LDPXi $sp

Bundled Instructions

The syntax for bundled instructions is the following:

  1. BUNDLE implicit-def $r0, implicit-def $r1, implicit $r2 {
  2. $r0 = SOME_OP $r2
  3. $r1 = ANOTHER_OP internal $r0
  4. }

The first instruction is often a bundle header. The instructions between {and } are bundled with the first instruction.

Registers

Registers are one of the key primitives in the machine instructionsserialization language. They are primarily used in theregister machine operands,but they can also be used in a number of other places, like thebasic block’s live in list.

The physical registers are identified by their name and by the ‘$’ prefix sigil.They use the following syntax:

  1. $<name>

The example below shows three X86 physical registers:

  1. $eax
  2. $r15
  3. $eflags

The virtual registers are identified by their ID number and by the ‘%’ sigil.They use the following syntax:

  1. %<id>

Example:

  1. %0

The null registers are represented using an underscore (‘_’). They can also berepresented using a ‘$noreg’ named register, although the former syntaxis preferred.

Machine Operands

There are seventeen different kinds of machine operands, and all of them can beserialized.

Immediate Operands

The immediate machine operands are untyped, 64-bit signed integers. Theexample below shows an instance of the X86 MOV32ri instruction that has animmediate machine operand -42:

  1. $eax = MOV32ri -42

An immediate operand is also used to represent a subregister index when themachine instruction has one of the following opcodes:

  • EXTRACT_SUBREG
  • INSERT_SUBREG
  • REG_SEQUENCE
  • SUBREG_TO_REG

In case this is true, the Machine Operand is printed according to the target.

For example:

In AArch64RegisterInfo.td:

  1. def sub_32 : SubRegIndex<32>;

If the third operand is an immediate with the value 15 (target-dependentvalue), based on the instruction’s opcode and the operand’s index the operandwill be printed as %subreg.sub_32:

  1. %1:gpr64 = SUBREG_TO_REG 0, %0, %subreg.sub_32

For integers > 64bit, we use a special machine operand, MO_CImmediate,which stores the immediate in a ConstantInt using an APInt (LLVM’sarbitrary precision integers).

Register Operands

The register primitive is used to represent the registermachine operands. The register operands can also have optionalregister flags,a subregister index,and a reference to the tied register operand.The full syntax of a register operand is shown below:

  1. [<flags>] <register> [ :<subregister-idx-name> ] [ (tied-def <tied-op>) ]

This example shows an instance of the X86 XOR32rr instruction that has5 register operands with different register flags:

  1. dead $eax = XOR32rr undef $eax, undef $eax, implicit-def dead $eflags, implicit-def $al
Register Flags

The table below shows all of the possible register flags along with thecorresponding internal llvm::RegState representation:

FlagInternal Value
implicitRegState::Implicit
implicit-defRegState::ImplicitDefine
defRegState::Define
deadRegState::Dead
killedRegState::Kill
undefRegState::Undef
internalRegState::InternalRead
early-clobberRegState::EarlyClobber
debug-useRegState::Debug
renamableRegState::Renamable
Subregister Indices

The register machine operands can reference a portion of a register by usingthe subregister indices. The example below shows an instance of the COPYpseudo instruction that uses the X86 sub_8bit subregister index to copy 8lower bits from the 32-bit virtual register 0 to the 8-bit virtual register 1:

  1. %1 = COPY %0:sub_8bit

The names of the subregister indices are target specific, and are typicallydefined in the target’s *RegisterInfo.td file.

Constant Pool Indices

A constant pool index (CPI) operand is printed using its index in thefunction’s MachineConstantPool and an offset.

For example, a CPI with the index 1 and offset 8:

  1. %1:gr64 = MOV64ri %const.1 + 8

For a CPI with the index 0 and offset -12:

  1. %1:gr64 = MOV64ri %const.0 - 12

A constant pool entry is bound to a LLVM IR Constant or a target-specificMachineConstantPoolValue. When serializing all the function’s constants thefollowing format is used:

  1. constants:
  2. - id: <index>
  3. value: <value>
  4. alignment: <alignment>
  5. isTargetSpecific: <target-specific>
  • where:
    • <index> is a 32-bit unsigned integer;
    • <value> is a LLVM IR Constant;
    • <alignment> is a 32-bit unsigned integer specified in bytes, and must bepower of two;
    • <target-specific> is either true or false.

Example:

  1. constants:
  2. - id: 0
  3. value: 'double 3.250000e+00'
  4. alignment: 8
  5. - id: 1
  6. value: 'g-(LPC0+8)'
  7. alignment: 4
  8. isTargetSpecific: true

Global Value Operands

The global value machine operands reference the global values from theembedded LLVM IR module.The example below shows an instance of the X86 MOV64rm instruction that hasa global value operand named G:

  1. $rax = MOV64rm $rip, 1, _, @G, _

The named global values are represented using an identifier with the ‘@’ prefix.If the identifier doesn’t match the regular expression[-a-zA-Z$.][-a-zA-Z$.0-9]*, then this identifier must be quoted.

The unnamed global values are represented using an unsigned numeric value withthe ‘@’ prefix, like in the following examples: @0, @989.

Target-dependent Index Operands

A target index operand is a target-specific index and an offset. Thetarget-specific index is printed using target-specific names and a positive ornegative offset.

For example, the amdgpu-constdata-start is associated with the index 0in the AMDGPU backend. So if we have a target index operand with the index 0and the offset 8:

  1. $sgpr2 = S_ADD_U32 _, target-index(amdgpu-constdata-start) + 8, implicit-def _, implicit-def _

Jump-table Index Operands

A jump-table index operand with the index 0 is printed as following:

  1. tBR_JTr killed $r0, %jump-table.0

A machine jump-table entry contains a list of MachineBasicBlocks. When serializing all the function’s jump-table entries, the following format is used:

  1. jumpTable:
  2. kind: <kind>
  3. entries:
  4. - id: <index>
  5. blocks: [ <bbreference>, <bbreference>, ... ]

where <kind> is describing how the jump table is represented and emitted (plain address, relocations, PIC, etc.), and each <index> is a 32-bit unsigned integer and blocks contains a list of machine basic block references.

Example:

  1. jumpTable:
  2. kind: inline
  3. entries:
  4. - id: 0
  5. blocks: [ '%bb.3', '%bb.9', '%bb.4.d3' ]
  6. - id: 1
  7. blocks: [ '%bb.7', '%bb.7', '%bb.4.d3', '%bb.5' ]

External Symbol Operands

An external symbol operand is represented using an identifier with the &prefix. The identifier is surrounded with ““‘s and escaped if it has anyspecial non-printable characters in it.

Example:

  1. CALL64pcrel32 &__stack_chk_fail, csr_64, implicit $rsp, implicit-def $rsp

MCSymbol Operands

A MCSymbol operand is holding a pointer to a MCSymbol. For the limitationsof this operand in MIR, see limitations.

The syntax is:

  1. EH_LABEL <mcsymbol Ltmp1>

CFIIndex Operands

A CFI Index operand is holding an index into a per-function side-table,MachineFunction::getFrameInstructions(), which references all the frameinstructions in a MachineFunction. A CFI_INSTRUCTION may look like itcontains multiple operands, but the only operand it contains is the CFI Index.The other operands are tracked by the MCCFIInstruction object.

The syntax is:

  1. CFI_INSTRUCTION offset $w30, -16

which may be emitted later in the MC layer as:

  1. .cfi_offset w30, -16

IntrinsicID Operands

An Intrinsic ID operand contains a generic intrinsic ID or a target-specific ID.

The syntax for the returnaddress intrinsic is:

  1. $x0 = COPY intrinsic(@llvm.returnaddress)

Predicate Operands

A Predicate operand contains an IR predicate from CmpInst::Predicate, likeICMP_EQ, etc.

For an int eq predicate ICMP_EQ, the syntax is:

  1. %2:gpr(s32) = G_ICMP intpred(eq), %0, %1