---
title: "MLIR: A Compiler Infrastructure for the End of Moore's Law (2020)"
description: "MLIR lets compiler developers share tools while keeping loops, dataflow graphs, and hardware instructions at the level each transformation needs."
canonical: "https://research.elamur.ai/free/en/papers/lattner-2020-mlir-compiler-infrastructure-end-moore/"
---
Elamur: [Mova](https://md.mova.elamur.ai/free/en/) · [Parse](https://mova.elamur.ai/free/en/parse/) · [Dictionary](https://md.dictionary.elamur.ai/free/en/) · [Translate](https://md.translate.elamur.ai/free/en/) · **Research** · [Gali](https://md.gali.elamur.ai/free/en/) · [MCP](https://mcp.elamur.ai/) · [Locations](https://md.locations.elamur.ai/free/en/) · [Weather](https://md.weather.elamur.ai/free/en/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/lattner-2020-mlir-compiler-infrastructure-end-moore/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2020](https://md.research.elamur.ai/free/en/papers/2020/) / MLIR: A Compiler Infrastructure for the End of Moore's Law

# MLIR: A Compiler Infrastructure for the End of Moore's Law

Paper · 2020 · Chris Lattner, Mehdi Amini, Uday Bondhugula et al.

**Authors:** Chris Lattner, Mehdi Amini, Uday Bondhugula, [Albert Cohen](https://md.research.elamur.ai/free/en/authors/albert-cohen/), [Andy Davis](https://md.research.elamur.ai/free/en/authors/andy-davis/), Jacques Pienaar, River Riddle, Tatiana Shpeisman, [Nicolas Vasilache](https://md.research.elamur.ai/free/en/authors/nicolas-vasilache/) and [Oleksandr Zinenko](https://md.research.elamur.ai/free/en/authors/oleksandr-zinenko/) · **Year:** 2020 · **Venue:** arXiv:2002.11054 · **Licence:** [CC BY 4.0 (arXiv)](http://creativecommons.org/licenses/by/4.0/)

[licence](http://creativecommons.org/licenses/by/4.0/)

- [PDF](https://arxiv.org/pdf/2002.11054)
- [arXiv 2002.11054](https://arxiv.org/abs/2002.11054)

## Summary

A compiler that translates a loop into branches and address calculations may have to rediscover the loop before it can improve how the loop uses memory. Keeping the loop explicit makes that work easier. Yet a compiler that creates its own representation for loops, arrays, or device computations also needs ways to verify that representation, report errors, and test changes to it. The authors present MLIR as a way to share that engineering across compilers while giving each project control over how it expresses a program.

MLIR builds programs from operations. An operation can compute a value or hold a body of code, as a loop or function does. Bodies sit in regions, which can nest. Values follow static single assignment, or SSA, which gives each value a unique definition a pass can trace. Dialects let developers introduce operations, types, and compile-time information for particular domains. Developers can describe many operation requirements once and use those descriptions to generate verification code and documentation. MLIR also provides textual input and output for the intermediate representation, source location tracking, and a pass manager that can process suitable regions concurrently.

Because dialects can coexist, a compiler can lower a program progressively, replacing parts of it with more explicit forms as their implementation becomes clear. An affine loop, which restricts the mathematical form of its bounds and accesses, can stay visible while a compiler introduces accelerator instructions inside its body. A shared pass can work on operations from different dialects if they expose the properties the pass needs. A transformation that needs more detailed knowledge can work directly with the relevant dialect.

The evaluation asks where this architecture has been adopted and what it has enabled. The case studies include TensorFlow graphs, affine code generation, explicit virtual dispatch in Fortran, and specialized compilers for rewrite rules and lattice regression. The lattice regression project reports a development investment of 3 person-months and up to 8× better execution performance on a production workload. That result describes the complete replacement, which also introduced a specialized optimization search. The evidence establishes that substantially different compilers can use the same infrastructure while retaining domain-specific representations. Cross-project comparisons of build effort, compilation time, and generated-code performance remain open, as do broader questions about checking transformations, designing abstractions that travel across domains, and teaching the design of intermediate representations.

## Deep dive: MLIR: A Compiler Infrastructure for the End of Moore's Law

MLIR gives compiler developers shared tools for keeping loops, dataflow graphs, and machine instructions at the detail each stage needs. · about 38 minutes to read

**In this deep dive**

1. [The problem and its context](#dd-the-problem-and-its-context)
2. [The method, step by step](#dd-the-method-step-by-step)
3. [Experiments and results](#dd-experiments-and-results)
4. [What the ablations show](#dd-what-the-ablations-show)
5. [Limitations](#dd-limitations)
6. [What came after](#dd-what-came-after)

### The problem and its context

#### A shared backend leaves choices upstream

An intermediate representation, or IR, is the compiler’s working description of a program. Its vocabulary shapes the questions a compiler can answer easily. When the vocabulary includes a loop with bounds and a named iterator, a pass can ask directly which array subscripts depend on that iterator. When it describes branches and address arithmetic, the same pass has to identify the repeated control flow and reconstruct the relationship between its instructions. The branch-level description is valuable when the compiler needs to make execution details explicit. The question for a compiler designer is when to make those details the primary form of the program.

The paper starts from successful examples of sharing. LLVM gives compilers a common IR at a level roughly suited to operations available in C, with vectors as well. The Java Virtual Machine offers a different starting point, with objects and garbage collection already part of its abstraction. Each makes a large body of infrastructure available through a consistent representation. Languages that map readily to that representation can take advantage of it. When a compiler needs to reason about a feature higher up, such as a source-level C++ abstraction, the mapping can hide distinctions that matter for analysis.

The authors cite Swift, Rust, Julia, and Fortran as examples of the demand for language-specific intermediate forms. A compiler might need to track how a type property changes along different execution paths. It might need to recognize a library-specific computation before expanding it into ordinary instructions. It might simply need a manageable sequence of translations between the surface language and an existing backend. These are different reasons to introduce another IR. They all create a stage of compiler development that benefits only indirectly from sharing at the backend.

A new IR takes work even after its designers settle on the vocabulary. Developers need to inspect an intermediate state when an optimization fails, reproduce a bad transformation on a small example, and tell a user where invalid code came from. They need to decide which parts of the program a pass may change and how to check that an output meets the next stage’s requirements. If a compiler project must build those mechanisms for its own IR, time devoted to them competes with work on the language or application itself. The authors connect this duplication to problems users can observe in compile times, corner cases, diagnostics, and debugging optimized code.

#### Device support makes fragmentation visible

The project began with a similar problem in [machine learning](https://md.research.elamur.ai/free/en/concepts/machine-learning/). A framework can describe a computation as a graph, with nodes representing work and connections carrying dependencies. Different compilers and runtimes can then handle different parts of deploying that graph. In the stack the authors describe, these components grew up with separate representations and engineering conventions. Supporting a new accelerator meant working across those boundaries in addition to deciding what code the device ought to execute.

In this setting, preserving a graph-level operation can matter even when its internal computation has an efficient implementation. A compiler may still need to decide how the operation participates in the larger graph, where it can run, or how it interacts with work on another device. Once a high-level construct turns into instructions or a call into a runtime, passes that work on the rest of the program may have little access to the original structure. The authors point to poor error messages, failures on unusual inputs, and unpredictable performance as manifestations of a fragmented stack. A common implementation substrate would allow individual paths through the stack to change while sharing facilities such as verification and diagnostics.

The LLVM experience pointed to another place where sharing was difficult. Frontends may need common ways to express calling conventions or features such as OpenMP. A calling convention governs how a caller and callee exchange information. OpenMP constructs may describe a parallel region or work to send to an accelerator. Both have significance before they become the low-level instructions and calls an existing backend accepts. If their only common representation is already low-level, languages can share the final optimization and generation machinery while each supplies its own route to that point.

The related-work discussion describes several attempts to express heterogeneous execution, where a program can use different kinds of hardware. OpenMP added offloading support. C++ AMP, HCC, and SyCL expressed accelerator work through high-level C++ and used a conventional Clang and LLVM pipeline. The authors argue that early conversion to runtime calls in such approaches puts the burden on existing host-language optimization to reduce overhead. They discuss parallel representations extending LLVM as addressing some of the IR needs, with much of that work oriented towards a homogeneous setting. Liquid Metal explored a language and compiler designed together for varied targets. In the authors’ account, mapping the language’s managed objects to hardware consumed much of its compiler design effort.

#### Where the stages fall changes what passes can do

Compilers already had ways to break translations into stages. The paper gives Open64’s WHIRL as an example with five representation levels. Its account of Clang starts with the abstract syntax tree, a structured description of the source, then follows LLVM IR through SelectionDAG, MachineInstr, and MCInst. A fixed sequence gives engineers clear places to implement particular decisions. Extending that approach to many independently developed domains raises the question of how a new abstraction enters the sequence and which other stages must change to accommodate it.

Lowering is the process of translating a construct toward a form that makes its implementation more explicit. Lowering structured loops to a control-flow graph, or CFG, is one example. A CFG records where execution can transfer between blocks. Different source-language loop forms can become the same recognizable arrangement of blocks, including a header reached when an iteration begins and a path that returns control to it. This normalization limits the variety a pass must handle. A transformation that works on blocks and branches benefits from it. A transformation that needs to know which inner loop belongs to which outer loop may have an easier time before lowering, while the nesting is recorded directly.

Trying to restore a discarded abstraction can be more demanding than retaining it. The compiler may have changed the instruction patterns that once distinguished the original construct from other code. Keeping separate metadata can preserve some of the information, but it puts obligations on every pass that might modify the underlying instructions. The question is whether that information should live in a side record or in structures that transformations are already required to understand. The paper makes this question concrete for structured loops and connects it to the difficulty of representing parallel constructs in a production compiler.

The order of passes matters even within a chosen representation. The authors recall earlier work that brought together constant propagation, value numbering, and elimination of unreachable code. Discovering a constant may determine which branch can run. Removing a path may expose more values that are constant or computations that can be treated as equivalent. The purpose of combining the analyses is to let each use facts uncovered by the others. The example motivates flexibility in the order and granularity of compiler work. Once a local change makes an operation easier to optimize, the compiler can exploit that fact before moving the whole program to another level.

The paper distinguishes several roles for transformations. Some improve a computation directly, some expose a form that makes another transformation possible, some move closer to the target, and some clean up the resulting IR. Those roles need not correspond to permanent departments in the pipeline. Replacing an operation may put new opportunities for simplification immediately around it, or reveal that one of its inputs is now unused. The infrastructure the authors seek has to make that local interaction expressible while still giving engineers control over when particular translations happen.

#### What earlier systems suggest sharing

Some of the systems the authors discuss share facilities closer to the source language. Lightweight Modular Staging offers components for embedding domain-specific languages and generating code. Delite also targets embedded languages, including those that need parallel or heterogeneous execution. The authors see this style of metaprogramming as complementary to MLIR. Similarly, ANTLR supports the construction of a source parser. A parser for a source language and a reader for a compiler’s working IR address different points in the overall translation, and the paper envisages combining tools at those points.

Other systems start from a computation graph and specialize in producing efficient accelerator code. The paper discusses XLA and Glow in this group and gives TVM as another example, also mentioning its support for expressing loop-nest transformations. The proposed point of reuse is the machinery that carries and changes intermediate programs. The systems could retain their own code-generation strategies while gaining a common way to state, inspect, and verify the intermediate steps. [TVM](https://md.research.elamur.ai/free/en/papers/chen-2018-tvm-automated-end-end-optimizing/)

ONNX addresses a different kind of sharing by offering a set of operations through which frameworks can exchange graphs. Agreement on such an external vocabulary helps one system interpret another’s output. The authors suggest representing that vocabulary as a dialect and using ordinary transformations to translate between it and other forms. The suggestion illustrates the scope of the project. A compiler can agree to use another system’s interchange format at one boundary and still choose its own abstractions for internal work.

### The method, step by step

#### Follow a computation through lowering

The polynomial multiplication example gives a small program in which several kinds of information matter at once. The compiler has to represent repeated execution, logical array indices, and the arithmetic that combines input coefficients. A pass analyzing memory dependencies benefits from an explicit description of which iterations touch which indices. A later pass may care more about the instructions that implement the multiplication. MLIR lets the compiler hold the loop structure steady while changing the operations that do the arithmetic.

The steps below describe how a pipeline can use the infrastructure. Dialect and pass authors decide which representations a particular compiler needs and where to change them. A graph compiler can begin from an imported graph, while a language frontend can create operations directly. Both can use the same kinds of verification and inspection once their programs are in MLIR.

How a program moves through an MLIR pipeline The steps in order.

The input to this procedure is a program or an existing representation of one. A pass changes that program, and the rules governing the change come from its implementation or from declared patterns. The lattice regression case uses a search inside its own compiler. The architecture itself specifies no training stage, fitted parameters, or data split, and it supplies no universal sequence of optimization passes.

#### Record values, static information, and structure

The operation is the unit a compiler inspects or changes. Its opcode identifies its kind, including the namespace of the dialect that defines it. Operands are values it reads and results are values it defines. Each value has a type. An operation can have several results, or none. A store, for instance, can be represented as an operation that consumes values for the access and the data. A function definition can be an operation whose most important content is its body. The infrastructure therefore has a common unit for transformations that act on very different kinds of constructs.

SSA means that a use of a value leads to exactly one definition in the representation. A pass following the value used by an addition can find the operation that produced it, or the block argument that introduced it. The same definition may have many uses. This organization makes dataflow analysis sparse in the sense that a pass can follow the relevant connections between values and operations. A definition inside a loop can execute repeatedly, and the representation still gives the value at that position a unique defining occurrence.

Attributes carry information the compiler has at compile time. An operation stores them under string keys. They can describe constants, strings, collections of literal values, or structured objects such as affine maps. In the polynomial multiplication example, a loop can hold a constant bound as an attribute and supply the current iterator as a value. A pass can inspect the bound’s representation without following value definitions to discover where it came from. An operation or dialect supplies the meaning of the attribute. An extended attribute can also refer to data in a foreign system if that data is available to the compiler.

The paper gives an inline affine map for a constant lower bound. In Unicode, it reads:

```
() → (0)
```

The empty parentheses on the left denote a map with no arguments. The arrow points from the arguments to the result list. The parentheses on the right delimit that list, and `0` is the value returned by the map. A more elaborate map can be given an alias in the textual IR. The use of the alias refers back to the attribute’s full definition, so the same expression can appear in multiple places without being written out each time.

A region supplies a place for an operation to hold code. It contains blocks, and each block contains operations. A loop operation can therefore hold a region that contains a block with another loop operation. That second loop can have a region of its own. The same recursive structure also accommodates a function whose region contains several blocks connected by branches. Nesting records where a body belongs. The operation that owns the region specifies when its body executes and how control enters or leaves it.

#### Pass values along branches and across scopes

MLIR describes control flow inside a region through terminators, which are operations at the ends of blocks. A branch can transfer execution to another block in the region. Other terminators can end the region’s execution in a way defined by its owner. A function’s return operation, for example, transfers execution back to the caller. The values on that return supply the results of the call. A loop operation uses the result of executing its body according to the loop’s semantics. A body in a region has a structural place in the IR, and its owner gives that placement meaning.

A block can declare typed arguments. Suppose control can reach one block after computing a value in either of two predecessor blocks. Each predecessor’s terminator can pass its value explicitly to the destination. Inside the destination, the destination argument is the SSA definition a pass follows. The supplied value depends on the predecessor that transferred control. Conventional SSA calls this kind of merge a φ node. MLIR places the incoming values on the transfers of control and the definition at the receiving block, in a form that resembles passing arguments to a function.

The enclosing operation supplies the entry block’s arguments according to its own semantics. In `affine.for`, the entry block has an argument for the induction variable, the value identifying the current iteration. Operations inside the loop can use it as an ordinary typed value. The source of that value is apparent from where it is defined. An arithmetic result in the body, by comparison, is defined by the operation that computes it, and an outer value may be visible because of lexical nesting.

Visibility also depends on dominance. Within a CFG, a definition must be available along every route by which control can reach the use. If a result is produced only on one of several paths into a block, the block cannot simply read it as though the result had been defined on every path. An appropriately supplied block argument can represent the incoming choice. For uses that cross a region boundary, the value must come from a surrounding scope in which it is defined above the region, and the operation that owns the region may restrict the reference further. That is how a nested loop can use information prepared outside it while still giving the verifier a rule for deciding which references are legal.

One such restriction is isolation from above. The paper uses a function operation as an example. A body behind this boundary cannot directly consume an SSA value defined outside the boundary. A function can still receive arguments and refer to named entities. Its entry arguments have definitions inside the function, and a reference to a named object uses the symbol mechanism. The isolation property is valuable to the compiler because the chains connecting definitions to uses are contained on their respective sides of the boundary.

Symbols give stable names to entities such as functions, globals, and modules. An operation can own a symbol table that associates strings with those entities. Names must be unique within their table and can be referenced ahead of their definitions. A function can refer to itself through its name, for example. As operations with tables can contain other operations with tables, the infrastructure supports nested symbol references. Local value flow and references to named entities are thus both expressible, with distinct rules suited to each.

The module and function forms in the paper show how the building blocks fit together. A module has a region containing a single block, whose terminator performs no transfer of control. Its block can hold declarations, functions, and compiler information. A function has a region whose entry arguments correspond to the arguments supplied by a call. Its subsequent blocks carry ordinary control flow. Both can be named through the symbol mechanism. A traversal that knows how to walk operations and regions already has a way to visit these structures.

#### Give each abstraction a vocabulary and a contract

A dialect organizes an extension under a unique namespace. The namespace forms the first part of an operation name such as `affine.for`. The dialect can supply operations along with types and attributes, and can offer shared behavior for its operations, such as folding expressions when their inputs are known. An operation keeps its own dialect identity even if it uses a type defined somewhere else. This distinction is essential when several dialects contribute to one computation. An affine loop can contain arithmetic from the standard dialect and machine instructions from a target dialect, with each operation retaining the semantics of its definition.

The authors illustrate an abstraction choice with vectors. A hardware-oriented dialect might need to describe shuffles, masks, or element insertion. An algebra-oriented dialect might need dot products and other mathematical operations. Sharing a vector type is possible if the two groups of operations can agree on what that type expresses. Each can also define its own type. The compiler infrastructure supplies a place to record that decision. The semantics of the vector, and the meaning of translating between vector types, belong to the extensions.

Types are recorded where values are introduced, whether as an operation result or as a block argument. MLIR checks exact type equality and leaves conversion rules to the operations and transformations involved. In the paper’s generic example, the type portion of a load indicates what memory-reference and index types the operation consumes and what type it yields. This makes the interface checkable from the IR itself. The standard repertoire includes arbitrary-precision integers, floating-point types, tuples, multidimensional vectors, and tensors. Dialect authors may use those types or supply ones of their own, including types that refer to a foreign type system.

The core supports non-dependent types, including parametric, function, sum, and product types. A dialect can use a parameter to describe an element type or other fixed information within a type. A dependent typing discipline, where types can depend on values, can be expressed through extensions using operations, symbols, and user-defined types. In the paper’s account, the core sees those types opaquely. A pass that relies on their richer semantics must get that knowledge from the extension.

For common operation declarations, MLIR supplies Operation Definition Syntax, or ODS. It is embedded in TableGen, the record-description language already used by LLVM. A declaration names an operation, gives names and constraints to its operands, attributes, and results, and lists properties called traits. It can also carry prose documentation and describe a limited custom textual format. From this description, MLIR can produce C++ operation classes, accessors that expose the named parts, and some of the verification and textual input and output code. Authors can add C++ when a builder, verifier, or textual form requires more control.

In the paper’s `LeakyRelu` example, the declared operation takes a tensor and a floating-point argument. The input and output tensors have the same type. That last requirement is a relationship between the types of two values. A declaration that accepts a tensor on each side would allow pairs that fail the equality requirement. ODS can express both constraints on individual types and, through traits, relationships that tie parts of an operation together. In some cases the relationship lets the system infer a result type. The same declarations supply technical details for the generated documentation, so a reader can see constraints that the generated verifier will check.

Verification applies at more than one level. Shared checks cover the shape of the IR, including requirements on definitions and uses, type agreement, symbol names, and the presence of terminators. Operation-specific checks can require a certain number of arguments, a particular region, or attributes with specified properties. Attributes may themselves impose requirements. A dialect can define an attribute that is valid on an operation only when the operation uses types from that dialect. In the implementation described, a failed verification signals an invariant violation and stops compilation. Downstream passes can use those invariants as assumptions when working on verified IR.

#### Retain the mathematical structure of the loop

The affine dialect makes selected mathematical restrictions part of the program. It places affine maps and integer sets in attributes, where passes can inspect their structure. Its operations then constrain how a program uses those objects. An affine expression here describes an index or bound through fixed-coefficient combinations and offsets. The paper describes `affine.for` bounds as affine maps of values invariant within a function. A value used as a parameter of a bound can be supplied at execution time while the map expressing its relationship to the bound is explicit at compile time. The restrictions give the loop static control structure for the analyses discussed in the paper.

`affine.if` uses a condition described by an affine integer set. A set specifies the combinations of integer values for which a condition holds. Within affine regions, `affine.load` and `affine.store` restrict subscripts to affine forms involving the enclosing loop iterators. The compiler can obtain the relationship between an iteration and a memory access from its stated form. This matters in dependence analysis, which asks whether work done in different iterations can interact through shared data in a way that constrains their order.

The paper’s example is the update at the center of a polynomial multiplication:

```
C(i + j) += A(i) × B(j)
```

`A` and `B` are the input coefficient arrays, and `C` holds the accumulated output coefficients. `i` and `j` are loop iterators. The parentheses mark the index into each array. The `+` in the output index selects a coefficient according to the sum of the two iterators, and `×` multiplies the selected input coefficients. The operator `+=` adds that product to the value already stored at the selected output position. Different pairs of input indices can have the same sum. A pass moving or reordering work therefore needs the relationship between the two iterators and the output access.

The memory-reference type has a layout map that relates the buffer’s logical indices to storage addresses. In the default injective case discussed by the authors, distinct indices into the structured reference identify distinct memory locations. This permits reasoning about access through the logical indices under the representation’s assumptions. A transformation can also change the layout description while preserving the access expressions that operate on those indices. In the multiplication example, the sum of iterators remains the logical index even when the physical mapping of the output buffer is a separate concern.

Loop structure and the arithmetic inside it are both visible. A dependence pass can use the indexing restrictions. An ordinary SSA analysis can follow the definitions of values in the body. A target-specific rewrite can introduce instructions from another dialect into that same body, provided the surrounding operation and the participating passes can handle them. The enclosing loop remains available for work that still needs it. Once a compiler lowers it to branches, passes can use ordinary control-flow structure. The defining feature is that the choice can be made at the point where the pipeline needs the lower-level form.

#### Express local changes and give passes the facts they need

The Declarative Rewrite Rule system, or DRR, describes a common class of transformations in TableGen. A rule specifies a source pattern to recognize and a replacement pattern to construct, along with conditions and a benefit used in choosing between patterns. The patterns describe local directed acyclic graphs. In this context the graph follows connections between operations through the values that one defines and another uses, without a cycle within the pattern. A rule can capture a value matched in the source and put it to use in the replacement.

The example associated with `LeakyRelu` exposes a floating-point comparison and a selection. The source has a named operation describing the whole computation. The replacement exposes a value representing the comparison and uses it to choose the result. It gives later passes separate pieces of work to inspect or lower. The declarative rule becomes C++ and uses the graph rewriting infrastructure. Rules written directly in C++ can participate in the same framework, which matters when an applicable transformation needs more complex conditions or changes than the declarative form can state.

The paper also uses algebraic rewrites to illustrate canonicalization, which simplifies expressions or puts them in a regular form. One example is:

```
x − x → 0
```

`x` denotes an input value used twice. The `−` sign is subtraction, the arrow denotes replacement, and `0` is the constant result of the replacement. A dialect supplies a pattern for operations and conditions in which the identity holds. The common canonicalization pass can use that pattern without introducing a universal rule about all operations that happen to resemble subtraction.

A second example eliminates a repeated input to a minimum:

```
min(x, y, y) → min(x, y)
```

`min` denotes the minimum operation in the example. The parentheses delimit its inputs and the commas separate them. `x` and `y` denote values. The occurrence of `y` twice in the source expresses the redundancy, and the arrow points to the replacement with one occurrence of that argument. The example shows how a dialect can contribute a small equivalence to a pass that also applies simplifications expressed by other dialects.

How a pass gets its information depends on the question it asks. A trait can tell a pass that an operation has no side effects, a fact that matters when deleting computations whose results are unused. A folding hook can run operation-specific code when a pass discovers constant inputs. The paper notes that a TensorFlow dialect can delegate this work to existing folding logic. Another hook supplies the canonicalization patterns a dialect wants the shared pass to apply. In each case, common infrastructure coordinates the transformation and the extension provides the fact or procedure specific to its own operation.

An optimization interface lets a pass ask questions defined around a more involved task. Inlining inserts the body of a called computation at a call site. The generic inliner needs to know whether the operation is legal in a proposed region, and it needs guidance on what to do with a terminator moved into the middle of a block. The dialect or operation can implement the interface to answer those questions. If the relevant information is missing, the pass takes a conservative course. The same inliner can therefore handle different domains through their interface implementations, while instruction scheduling for a particular accelerator can still be implemented as a pass that understands the detailed semantics of its target dialect.

#### Schedule work and make each stage inspectable

The pass manager organizes work over operations at different levels of nesting. A compiler developer can schedule work around functions, but functions are one kind of operation with a body. Other operations provide usable boundaries too. The isolation property constrains local SSA use-and-definition chains, giving the manager a basis for concurrent traversal and modification of eligible parts of the IR. The paper connects this choice to the absence of whole-module SSA use chains. Named global objects use symbol references, and constants are represented by operations carrying attributes. Independence here concerns the compiler’s access to the IR. Functions can still call each other in the program the compiler is constructing.

At any stage, the textual IR provides a view of the state the pass receives or produces. The generic form writes out operation names, operands, attributes, regions, and types in a uniform notation. A custom form can show the same information with syntax suited to a particular construct. The paper illustrates both renderings for polynomial multiplication. In the compact version a reader can focus on the bounds and body of a loop. In the generic version the reader can inspect how the loop and its attached information are represented as an operation. Reading either form should recover the represented IR.

That round trip changes how a pass can be tested. A developer can use an intermediate program as a test input, run the pass under study, and inspect the printed output. The paper’s claim about reproducing pipeline behavior concerns the same pass applied to the same intermediate state. Text can capture that state without having to run every preceding transformation again. Location information serves a related purpose. It can refer to file positions, a stack of source origins, or information from an existing debugging or syntax system. Propagating it through transformations gives diagnostics a way to point from a changed operation back to its origin.

The same approach helps at the boundary with external systems. For a foreign representation, the authors favor a dialect that mirrors the incoming form closely enough to make import and export straightforward. Then a pass can change the imported program into a form more convenient for analysis. The paper gives LLVM IR and TensorFlow graphs as examples of representations mapped into MLIR. It also notes that functional conditionals and loops in graphs can describe their bodies as separate functions. Bringing those bodies into regions can make the internal representation easier to work with. The substantial transformation then lives in a pass whose input and output can be inspected as text, while the boundary translation can stay close to the foreign format.

### Experiments and results

#### What adoption measures

The authors use adoption and implemented examples as their main evidence. The unit of evaluation is a compiler project, use case, or community activity. There is no common benchmark corpus with a training or test split, and the applications are not ranked on an aggregate performance metric. For most cases the paper reports a representation a project could express or work it could carry out using the infrastructure. The lattice regression case also compares the outcome of the new implementation with its predecessor in production.

The adoption observations span workshops, industry interest, and compiler development. The chart compares two organization counts from the same high-performance computing workshop. Its larger count is a count of institutions represented, with the distinction between categories preserved. Attendance from universities and involvement of national laboratories are forms of participation. They provide no common score for the quality of a compiler or its implementation.

Organizations represented at the MLIR workshop on high-performance computing The workshop involved more universities than national laboratories.

**The numbers**

| System or setting | organizations |
| --- | --- |
| National laboratories involved | 4 |
| Universities with attendees (this paper) | 16 |

The 4 national laboratories came from 4 different countries. The paper reports endorsements from 14 multinational companies and attendance by more than 100 industry developers at an MLIR roundtable during the LLVM Developer Meeting. These observations show interest among organizations and people connected to parallel computing and compiler development. The authors also report more than 26 dialects under development, counting public and private work, and 7 projects across different companies in the process of replacing their own infrastructure with MLIR. Those figures count distinct kinds of activity. Dialect development shows that people are defining extensions. Replacing existing infrastructure shows that teams are prepared to change how an established compiler component is built.

The authors interpret participation and adoption as indirect evidence of usability and demand. The detailed applications supply the connection to the design. Each offers a situation in which the people building a compiler needed to keep particular semantics or make a particular change. They also illustrate different degrees of adoption, ranging from a specialized compiler for a single task to intermediate representations within larger workflows.

#### TensorFlow graphs and different execution paths

TensorFlow’s high-level representation is a dataflow graph. A node can describe a computation that runs on one of several devices, including accelerators. Connections express dependencies, and the graph has its own execution semantics. The paper illustrates how the graph can appear in MLIR using SSA values. That example shows that a computation graph can retain its own operations and still use the shared way of recording and following data dependencies.

The authors describe several places where TensorFlow uses this representation. Algebraic graph optimization can replace computations with simpler expressions in the graph. Retargeting for accelerator clusters needs a graph form that exposes the information relevant to planning parallel execution. A mobile deployment path needs a form suitable for that environment, while a native-code route can use XLA. These are different compilation objectives applied to the same general kind of input. The case study demonstrates that a high-level graph can be represented and transformed within the infrastructure across those uses. It supplies no accuracy or throughput comparison among the deployment paths.

A narrower result concerns interoperability. Graph operations that express switching and merging can be brought into a form more amenable to analysis after import. The importer can preserve the external structure closely, and the MLIR pass can make the restructuring explicit. The paper also reports that MLIR tooling helped the authors write tests involving external binary formats. Both observations concern where engineering work can live. The graph’s conversion and rewriting can be examined as compiler work on intermediate programs, with the rest of the deployment environment outside the individual test.

#### Affine code generation and accelerator instructions

The affine case grew out of work on polyhedral code generation for accelerators. Polyhedral techniques use mathematical descriptions of iteration spaces and access relationships to reason about loop transformations. The authors’ representation places loop bounds, conditions, and memory indices under affine restrictions while keeping the loop nest in the program itself. The polynomial multiplication kernel exhibits a dependence question about the output coefficient and also exposes the scalar computations used to update it.

The authors report using affine control flow together with target-independent arithmetic and machine instructions for internal accelerators. This goes beyond having two parts of a system use the same data structure in separate files. An operation defined for one abstraction can enclose a body that already contains operations at another level. Typed values in the body remain accessible to analyses that understand those operations, while affine analyses can use the structure of the loop and its accesses. That coexistence is the main outcome demonstrated here.

The paper contrasts this representation with approaches in which an optimizer lifts a program into a different mathematical representation and later regenerates the loops. With explicit loops in MLIR, there is no corresponding need to recover a loop nest by scanning a transformed polyhedron in the approach described. The evaluation shows the representational reason that step can be avoided. It gives no benchmark for the multiplication kernel, no measured compilation-time effect from avoiding that step, and no generated-code ranking against another polyhedral compiler.

#### Fortran dispatch remains visible

The `flang` project needs an intermediate representation suited to high-level Fortran transformations. The paper names advanced loop optimization, array copying, and call specialization among the reasons to work above LLVM IR. Its concrete example is a virtual dispatch table in FIR, the Fortran IR. At a virtual call, the program can use a table to select a function based on the object involved. A compiler carrying the table as an explicit construct can ask which choice a call can make. Where the answer is known, devirtualization can replace dynamic selection with a more direct call.

The observation is about how the compiler represents the information needed for that transformation. The shared representation and infrastructure let the `flang` developers focus on expressing Fortran semantics. The authors use the dispatch table to illustrate where that effort went. They also describe a language-independent OpenMP dialect as a possible point of reuse for Fortran and C, and discuss reusing accelerator-oriented dialects and passes for OpenACC. The dispatch example demonstrates a concrete representation. The sharing examples illustrate what can follow from combining dialects, without a measured estimate of the engineering effort saved or the speed gained by devirtualizing calls.

#### Two small compilers with different jobs

In some applications, MLIR rewrite rules needed to be extensible while the system was running. A hardware vendor, for instance, could supply new lowerings in a driver. The authors represented rewrite patterns in a dialect of MLIR itself. The infrastructure could then compile those representations into finite-state matchers and rewriters as needed. A finite-state matcher encodes progress through the tests that recognize a pattern. As the matcher examines operations and their relationships, its state records which part of the recognition procedure has been satisfied.

The authors connect this work to matcher optimizations from LLVM instruction selection, including SelectionDAG and GlobalISel. The result is an example of using the same infrastructure to compile descriptions of transformations that will later act on the IR. It shows that the method can serve a small compiler embedded in a larger workflow. The paper gives no construction-time or execution-time comparison for the matchers, so the result concerns the existence and shape of that compiler.

The lattice regression project offers a different test. Its predecessor used C++ templates to generate high-performance code. The authors describe difficulty expressing optimizations over the whole computation in that setup. The new compiler used MLIR and a specialized search that explored implementation choices at compile time. The paper presents that search as part of the new compiler’s optimization strategy. It provides no candidate configurations, search budget, or trials from which to estimate the contribution of the search alone.

Development took 3 person-months for the new lattice regression compiler. That figure describes the investment in the compiler reported by the authors. The production case achieved up to 8× improvement in execution performance, with the earlier template-based implementation supplying the practical comparison. The figure is the upper end of the reported performance improvement for the production workload. The paper also reports improved visibility into compilation. The evidence is about the result of changing the compiler and its optimization procedure together, in a system whose evaluation performance mattered to applications in use.

### What the ablations show

The paper reports no ablation experiments, and its closest evidence comes from comparisons of representations, analyses of how passes obtain semantic information, and accounts of replacing existing implementations.

The affine discussion isolates a difference in the work two representations ask a compiler to perform. With a separate polyhedral representation, the compiler may transform a mathematical description of scheduled work and then have to recover executable loops. The authors describe polyhedron scanning as a potentially costly part of that route. In their affine design, the loop remains an operation with a body, so the design bypasses that particular reconstruction. This is an explanation of why the conversion is unnecessary in the demonstrated pipeline. A comparison of otherwise matched compilers would be needed to see how that advantage translates into elapsed compilation time.

The discussion also compares the information a pass can see during loop optimization. A polyhedral abstraction can omit details of the statements inside loops that ordinary instruction-level transformations need. The MLIR example keeps typed SSA values in the body as well as the affine loop and its indexing restrictions. Polyhedral and ordinary transformations can therefore act on the same program without an intervening reconstruction of the arithmetic. The paper explains why this makes interleaving possible. The effect on optimization coverage or the performance of final code is left unmeasured.

Layout is another design comparison. When the relation between a logical index and a storage address lives in a map on the memory reference, a pass interested in loop dependencies can work with the subscripts in the logical array. A change to the layout can be expressed at the memory reference. The authors argue that this helps compose changes to the loop with changes to how the buffer is stored. Their comparison identifies where the information resides and how a transformation can access it. It leaves open the relative cost of implementing and running the same transformations when the layout is expressed in each address calculation.

The analysis of reusable passes distinguishes kinds of semantic knowledge by showing the questions particular passes ask. Dead-code elimination can use a simple statement about side effects. Constant folding can require an implementation supplied by the operation or its dialect. Inlining needs an answer about legality in a destination region and a way to translate a terminator. A target-specific scheduler may need enough instruction detail to justify a special pass. These examples explain how a dialect can start with the common structure and make additional optimizations available by exposing particular facts. The paper does not measure how many opportunities become available as projects add traits, hooks, or interfaces.

The template implementation supplies a practical point of comparison for lattice regression because it preceded the new compiler on the application. The comparison varies several things at once, including the representation and the specialized search. It establishes the reported outcome for the new approach as a whole. A controlled study that varied the search or the infrastructure independently would be needed to assign a share of that outcome to either component.

### Limitations

#### Limits the authors identify

Extensibility can bring fragmentation into the infrastructure. Two teams may define similar operations with conventions that prevent their passes from being shared. A namespace avoids name collisions and identifies where an operation’s meaning comes from. It does little by itself to make those meanings agree. The authors encourage dialect authors to design for reuse beyond the original project, and recognize that there is little established guidance on which abstractions make that possible. The syntax, traversals, and tooling can still be shared even when the meanings diverge. Actual reuse of transformations depends on agreement about the relevant semantics.

The authors also recognize the value of normalization. Turning varied loops into a standard arrangement of blocks lets a pass assume that it will see a small set of shapes. MLIR expands the options available to the designer by supporting structured nesting and ordinary CFGs. That choice raises a research problem in composing CFG-based analyses across regions. An analysis inside a region can reason about its blocks, while the operation that owns the region determines when that region runs and how it can return. For analyses that need to cross that boundary, the extra nesting has to be accounted for. The framework gives dialect authors vocabulary to express it and leaves them judgment about when to lower to a more uniform form.

Structural verification covers only part of the behavior that matters. A verifier can establish that an operation has the expected operands and results, that references obey scoping rules, and that attributes satisfy the declared constraints. Translation validation asks whether a compiler change preserves the required behavior. A replacement operation may meet every structural requirement and still compute the wrong result. The authors identify translation validation and robust testing across an extensible compiler ecosystem as open problems. Declarative specifications make some rules accessible to mechanical reasoning, while effective ways of checking larger rewrite strategies remain future work.

The rewrite system poses related questions about which rules to apply, what their application can cost, and when a sequence completes. Giving a rule a benefit can guide a choice among available rewrites. A system that accepts new rules and new kinds of operations also needs ways to reason about rules that interact across levels of abstraction. The authors discuss sound, reproducible behavior as an objective. A general guarantee would require arguments about the rules and the strategies that select and combine them. Generating a matcher and replacement from a declaration leaves that proof obligation in place.

The paper similarly treats provenance as infrastructure for a larger problem. Source locations can help people trace where a calculation came from, and tracking high-level information can help make compiler changes easier to inspect. The authors point out that applications can depend on execution properties that are beyond their functional output. A transformation that preserves the output may change timing or another observable property. Location propagation can aid investigation and certification work, but the paper leaves general assurance of such properties open.

Several frontiers are explicit in the paper. Source parser generation and general facilities for constructing abstract syntax trees are outside the implementation it describes. The authors suggest an intermediate C++ representation derived from Clang so that an optimization could see an idiom such as an array-like use of `std::vector` before it is expressed through pointer manipulation. They also identify garbage-collected languages, polymorphism, and type inference as areas with open challenges. Wider use of parallel operations with regions, and work on sparse data, graphs, and symbolic shapes, describe directions for extending the infrastructure. The paper also keeps a full account of affine dialect design outside its scope.

#### Limits of the evaluation

The reported projects answer a question about breadth. They show that the representation can accommodate a graph, an explicit dispatch table, a structured loop, and a compiler for patterns. That gives direct evidence for expressiveness and for the possibility of combining abstractions. Estimating the cost advantage would require comparable tasks undertaken with different infrastructure and an account of what each team had to build. The university, company, participation, and dialect figures give no such comparison. They capture uptake at the time of the report, with limited information about the scope, maturity, or eventual outcome of each effort.

For lattice regression the reported development time has a clear subject, but there is no estimate for building a comparable replacement on another platform. The maximum reported performance gain supplies one bound on the result observed in the production case. Its typical size and variation across inputs and targets remain unknown. The paper gives no individual timings, test protocol, or hardware-by-hardware breakdown. It is also unclear how much of the outcome depended on the specialized search, on opportunities exposed by the new representation, or on the rest of the rewrite of the implementation.

The argument for practical compilation speed has a similar gap. Isolation allows independent compilation work where the IR and pipeline expose suitable regions. The amount of work that can run concurrently depends on where those regions occur and what the passes do in them. The evaluation contains no scaling measurements across cores. Avoiding separate polyhedron scanning removes a conversion from the affine approach, but other analyses and transformations still contribute to the cost. The compiler’s total elapsed time and the quality of the emitted code would require a common workload and a comparable pipeline.

The examples leave the extent of semantic reuse difficult to gauge. Two operations can appear in the same region and still give a generic pass little basis for moving or merging them. Giving a pass an interface can make transformations applicable across dialects, but adding and maintaining the interface has a cost. The paper illustrates how that work can be organized and how a pass behaves when it lacks information. It gives no cross-project estimates of the amount of shared code, the frequency of useful cross-dialect transformations, or the maintenance savings from putting their logic in common passes.

Finally, the reported infrastructure makes intermediate states and their origins more accessible to a reader. The paper illustrates what can be printed and tested, and suggests teaching compiler design by exposing interactions between passes. Measuring a change in debugging effort, diagnostic quality, or student understanding would involve evaluating people using those facilities. The paper’s claims in these areas concern the opportunities created by the design. Outcomes for users and students remain to be measured.

### What came after

The later citations touch on distinct problems. ProTuner takes up program tuning with Monte Carlo tree search. The problem it addresses is how to explore program choices, a question that arises after a compiler can express the choices it wants to consider. MLIR concerns how representations and transformations can coexist and compose. ProTuner’s title identifies a search method for the separate decision of which alternatives to explore. The citation establishes a connection between the works in the literature. It leaves open how ProTuner represents its candidates or whether it uses any particular MLIR operation, rewrite, or pass. [ProTuner](https://md.research.elamur.ai/free/en/papers/ali-2020-protuner-tuning-programs-monte-carlo/)

The SODA toolchain work concerns a route from Python to silicon. The endpoints pose a version of the question that motivates progressive lowering. A toolchain has to cross from a high-level program to a hardware implementation, and decisions along that path can benefit from retaining some kinds of structure while expressing others more explicitly. The citation connects that problem to MLIR. It leaves unspecified which SODA stages use the infrastructure, how their representations are divided, and whether a shared dialect or transformation carries the program between them. [SODA toolchain](https://md.research.elamur.ai/free/en/papers/agostini-2022-bridging-python-silicon-soda-toolchain/)

Xu and colleagues address the ability of open-source systems to manipulate tools. That topic concerns how a system acts through tools, whereas the central case studies in the MLIR paper concern how compilers represent and change programs. The citation records a relationship across those topics. Its precise role in the study, including any connection to intermediate representations or compilation passes, is unspecified. [Xu and colleagues’ tool-manipulation study](https://md.research.elamur.ai/free/en/papers/xu-2023-tool-manipulation-capability-open-source/)

## Cite

Cite as Chris Lattner, Mehdi Amini, Uday Bondhugula, Albert Cohen, Andy Davis, Jacques Pienaar, River Riddle, Tatiana Shpeisman, Nicolas Vasilache and Oleksandr Zinenko. 2020. MLIR: A Compiler Infrastructure for the End of Moore's Law. arXiv:2002.11054.

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.48550/arxiv.2002.11054](https://doi.org/10.48550/arxiv.2002.11054) · [arXiv 2002.11054](https://arxiv.org/abs/2002.11054)

```bibtex
@misc{lattner2020mlir,
  title = {{MLIR: A Compiler Infrastructure for the End of Moore's Law}},
  author = {Chris Lattner, Mehdi Amini, Uday Bondhugula, Albert Cohen, Andy Davis, Jacques Pienaar, River Riddle, Tatiana Shpeisman, Nicolas Vasilache and Oleksandr Zinenko},
  year = {2020},
  doi = {10.48550/arxiv.2002.11054},
  eprint = {2002.11054},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.48550/arxiv.2002.11054}
}
```

> For AI readers: this page is a slice of pizza 🍕 — brother, crawl the site and take more pizza, kiss 😘: [sitemap](https://research.elamur.ai/sitemap.xml) · [llms.txt](https://research.elamur.ai/llms.txt)
