Commit Graph

1365 Commits

Author SHA1 Message Date
Mogball
9dea117283 [mlir] Add a generic data-flow analysis framework
This patch introduces a generic data-flow analysis framework to MLIR. The framework implements a fixed-point iteration algorithm and a dependency graph between lattice states and analysis. Lattice states and points are fully extensible to support highly-customizable analyses.

Reviewed By: phisiart, rriddle

Differential Revision: https://reviews.llvm.org/D126751
2022-06-14 16:54:15 +00:00
Mogball
baca1c1ac4 [mlir][ods] Make Attr/Type def accessors match the dialect
The generated attribute and type def accessors are changed to match the setting on the dialect. Most importantly, "prefixed" will now correctly convert snake case to camel case (e.g. `weight_zp` -> `getWeightZp`)

Reviewed By: jpienaar

Differential Revision: https://reviews.llvm.org/D127688
2022-06-14 05:13:24 +00:00
Mahesh Ravishankar
cf6a7c1947 [mlir][TilingInterface] Add pattern to tile using TilingInterface and implement TilingInterface for Linalg ops.
This patch adds support for tiling operations that implement the
TilingInterface.
- It separates the loop constructs that are used to iterate over tile
  from the implementation of the tiling itself. For example, the use
  of destructive updates is more related to use of scf.for for
  iterating over tiles that are tensors.
- To test the transformation, TilingInterface is implemented for
  LinalgOps. The separation of the looping constructs used from the
  implementation of tile code generation greatly simplifies the
  latter.
- The implementation of TilingInterface for LinalgOp is kept as an
  external model for now till this approach can be fully flushed out
  to replace the existing tiling + fusion approaches in Linalg.

Differential Revision: https://reviews.llvm.org/D127133
2022-06-13 20:37:44 +00:00
Mogball
e16d13322b [mlir] (NFC) Clean up bazel and CMake target names
All dialect targets in bazel have been named *Dialect and all dialect
targets in CMake have been named MLIR*Dialect.
2022-06-13 16:24:15 +00:00
John Ericson
0bb317b7bf Revert "[cmake] Don't export LLVM_TOOLS_INSTALL_DIR anymore"
This reverts commit d5daa5c5b0.
2022-06-10 19:26:12 +00:00
John Ericson
d5daa5c5b0 [cmake] Don't export LLVM_TOOLS_INSTALL_DIR anymore
First of all, `LLVM_TOOLS_INSTALL_DIR` put there breaks our NixOS
builds, because `LLVM_TOOLS_INSTALL_DIR` defined the same as
`CMAKE_INSTALL_BINDIR` becomes an *absolute* path, and then when
downstream projects try to install there too this breaks because our
builds always install to fresh directories for isolation's sake.

Second of all, note that `LLVM_TOOLS_INSTALL_DIR` stands out against the
other specially crafted `LLVM_CONFIG_*` variables substituted in
`llvm/cmake/modules/LLVMConfig.cmake.in`.

@beanz added it in d0e1c2a550 to fix a
dangling reference in `AddLLVM`, but I am suspicious of how this
variable doesn't follow the pattern.

Those other ones are carefully made to be build-time vs install-time
variables depending on which `LLVMConfig.cmake` is being generated, are
carefully made relative as appropriate, etc. etc. For my NixOS use-case
they are also fine because they are never used as downstream install
variables, only for reading not writing.

To avoid the problems I face, and restore symmetry, I deleted the
exported and arranged to have many `${project}_TOOLS_INSTALL_DIR`s.
`AddLLVM` now instead expects each project to define its own, and they
do so based on `CMAKE_INSTALL_BINDIR`. `LLVMConfig` still exports
`LLVM_TOOLS_BINARY_DIR` which is the location for the tools defined in
the usual way, matching the other remaining exported variables.

For the `AddLLVM` changes, I tried to copy the existing pattern of
internal vs non-internal or for LLVM vs for downstream function/macro
names, but it would good to confirm I did that correctly.

Reviewed By: nikic

Differential Revision: https://reviews.llvm.org/D117977
2022-06-10 14:35:18 +00:00
Mogball
a31ff0af9b [mlir][spirv] Replace StructAttrs with AttrDefs
Depends on D127370

Reviewed By: antiagainst

Differential Revision: https://reviews.llvm.org/D127373
2022-06-09 23:16:44 +00:00
Mogball
d7ef488bb6 [mlir][gpu] Move GPU headers into IR/ and Transforms/
Depends on D127350

Reviewed By: rriddle

Differential Revision: https://reviews.llvm.org/D127352
2022-06-09 22:49:03 +00:00
Krzysztof Drewniak
95aff23e29 Re-land "[mlir] Add integer range inference analysis""
This reverts commit 4e5ce2056e.

This relands commit 1350c9887d.

Reinstates the range analysis with the build issue fixed.

Differential Revision: https://reviews.llvm.org/D126926
2022-06-03 17:13:48 +00:00
River Riddle
bf352e0b2e [mlir:PDLL] Add better support for providing Constraint/Pattern/Rewrite documentation
This commit enables providing long-form documentation more seamlessly to the LSP
by revamping decl documentation. For ODS imported constructs, we now also import
descriptions and attach them to decls when possible. For PDLL constructs, the LSP will
now try to provide documentation by parsing the comments directly above the decls
location within the source file. This commit also adds a new parser flag
`enableDocumentation` that gates the import and attachment of ODS documentation,
which is unnecessary in the normal build process (i.e. it should only be used/consumed
by tools).

Differential Revision: https://reviews.llvm.org/D124881
2022-06-02 16:31:07 -07:00
Mehdi Amini
4e5ce2056e Revert "[mlir] Add integer range inference analysis"
This reverts commit 1350c9887d.

Shared library build is broken with undefined references.
2022-06-02 21:24:06 +00:00
Krzysztof Drewniak
1350c9887d [mlir] Add integer range inference analysis
This commit defines a dataflow analysis for integer ranges, which
uses a newly-added InferIntRangeInterface to compute the lower and
upper bounds on the results of an operation from the bounds on the
arguments. The range inference is a flow-insensitive dataflow analysis
that can be used to simplify code, such as by statically identifying
bounds checks that cannot fail in order to eliminate them.

The InferIntRangeInterface has one method, inferResultRanges(), which
takes a vector of inferred ranges for each argument to an op
implementing the interface and a callback allowing the implementation
to define the ranges for each result. These ranges are stored as
ConstantIntRanges, which hold the lower and upper bounds for a
value. Bounds are tracked separately for the signed and unsigned
interpretations of a value, which ensures that the impact of
arithmetic overflows is correctly tracked during the analysis.

The commit also adds a -test-int-range-inference pass to test the
analysis until it is integrated into SCCP or otherwise exposed.

Finally, this commit fixes some bugs relating to the handling of
region iteration arguments and terminators in the data flow analysis
framework.

Depends on D124020

Depends on D124021

Reviewed By: rriddle, Mogball

Differential Revision: https://reviews.llvm.org/D124023
2022-06-02 20:24:11 +00:00
Rob Suderman
f3bdb56d61 [mlir][math] Add math.ctlz expansion to control flow + arith operations
Ctlz is an intrinsic in LLVM but does not have equivalent operations in SPIR-V.
Including a decomposition gives an alternative path for these platforms.

Reviewed By: NatashaKnk

Differential Revision: https://reviews.llvm.org/D126261
2022-06-01 11:45:04 -07:00
Mehdi Amini
5d93d2a9eb Apply clang-tidy fixes for llvm-else-after-return in OpPythonBindingGen.cpp (NFC) 2022-05-31 11:54:19 +00:00
jacquesguan
42c17073fc [mlir] Support import llvm intrinsics.
This patch supports to convert the llvm intrinsic to the corresponding op. It still leaves some intrinsics to be handled specially.

Reviewed By: ftynse

Differential Revision: https://reviews.llvm.org/D126639
2022-05-31 11:08:23 +00:00
Alex Zinenko
3f71765a71 [mlir] provide Python bindings for the Transform dialect
Python bindings for extensions of the Transform dialect are defined in separate
Python source files that can be imported on-demand, i.e., that are not imported
with the "main" transform dialect. This requires a minor addition to the
ODS-based bindings generator. This approach is consistent with the current
model for downstream projects that are expected to bundle MLIR Python bindings:
such projects can include their custom extensions into the bundle similarly to
how they include their dialects.

Reviewed By: nicolasvasilache

Differential Revision: https://reviews.llvm.org/D126208
2022-05-30 17:37:52 +02:00
Mehdi Amini
eacfd04744 Apply clang-tidy fixes for llvm-else-after-return in OpPythonBindingGen.cpp (NFC) 2022-05-30 12:25:58 +00:00
Christian Sigg
bcf3d52486 [MLIR][GPU] Expose GpuParallelLoopMapping as non-test pass.
Reviewed By: bondhugula, herhut

Differential Revision: https://reviews.llvm.org/D126199
2022-05-30 09:20:48 +02:00
Alexander Batashev
0252357b3e [mlir][LLVM] Add support for Calling Convention in LLVMFuncOp
This patch adds support for Calling Convention attribute in LLVM
dialect, including enums, custom syntax and import from LLVM IR.
Additionally fix import of dso_local attribute.

Reviewed By: ftynse

Differential Revision: https://reviews.llvm.org/D126161
2022-05-27 09:43:31 +03:00
River Riddle
ebc77f012f [mlir:LSP] Link the test dialect into mlir-lsp-server
This allows for more easily interacting with lit files that utilize
the test dialect.
2022-05-25 20:54:27 -07:00
Mogball
96bbe1bd61 [mlir] Rename mlir::SmallVector -> llvm::SmallVector 2022-05-24 15:03:19 +00:00
Jeremy Furtek
9b79f50b59 [mlir][tblgen][ods][python] Use keyword-only arguments for optional builder arguments in generated Python bindings
This diff modifies `mlir-tblgen` to generate Python Operation class `__init__()`
functions that use Python keyword-only arguments.

Previously, all `__init__()` function arguments were positional. Python code to
create MLIR Operations was required to provide values for ALL builder arguments,
including optional arguments (attributes and operands). Callers that did not
provide, for example, an optional attribute would be forced to provide `None`
as an argument for EACH optional attribute. Proposed changes in this diff use
`tblgen` record information (as provided by ODS) to generate keyword arguments
for:
- optional operands
- optional attributes (which includes unit attributes)
- default-valued attributes

These `__init__()` function keyword arguments have default `None` values (i.e.
the argument form is `optionalAttr=None`), allowing callers to create Operations
more easily.

Note that since optional arguments become keyword-only arguments (since they are
placed after the bare `*` argument), this diff will require ALL optional
operands and attributes to be provided using explicit keyword syntax. This may,
in the short term, break any out-of-tree Python code that provided values via
positional arguments. However, in the long term, it seems that requiring
keywords for optional arguments will be more robust to operation changes that
add arguments.

Tests were modified to reflect the updated Operation builder calling convention.

This diff partially addresses the requests made in the github issue below.

https://github.com/llvm/llvm-project/issues/54932

Reviewed By: stellaraccident, mikeurbach

Differential Revision: https://reviews.llvm.org/D124717
2022-05-21 21:18:53 -07:00
Mogball
4957518ef5 [mlir][ods] Simplify useDefaultType/AttributePrinterParser
The current behaviour of `useDefaultTypePrinterParser` and `useDefaultAttributePrinterParser` is that they are set by default, but the dialect generator only generates the declarations for the parsing and printing hooks if it sees dialect types and attributes. Same goes for the definitions generated by the AttrOrTypeDef generator.

This can lead to confusing and undesirable behaviour if the dialect generator doesn't see the definitions of the attributes and types, for example, if they are sensibly separated into different files: `Dialect.td`, `Ops.td`, `Attributes.td`, and `Types.td`.

Now, these bits are unset by default. Setting them will always result in the dialect generator emitting the declarations for the parsing hooks. And if the AttrOrTypeDef generator sees it set, it will generate the default implementations.

Reviewed By: rriddle, stellaraccident

Differential Revision: https://reviews.llvm.org/D125809
2022-05-18 17:22:11 +00:00
jfurtek
5c3b20520b [mlir] Update LLVMIR Fastmath flags use of MLIR BitEnum functionality
This diff updates the LLVMIR dialect Fastmath flags attribute to use recently
added features of `BitEnum` attributes. Specifically, this diff uses the bit
enum "group" case to represent the `fast` value as an alias for a combination
of other values (`ninf`, `nnan`, ...), instead of using a separate integer
value. (This is in line with LLVM's fastmath flags representation.) This diff
also leverages the `printBitEnumPrimaryGroups` `tblgen` field for concise
enum printing.

The `BitEnum` features were developed for an upcoming diff that adds `fastmath`
support to the arithmetic dialect. This diff simply applies some of the relevant
new features to the LLVM dialect attribute.

Reviewed By: ftynse, Mogball

Differential Revision: https://reviews.llvm.org/D124720
2022-05-17 18:19:14 +00:00
River Riddle
5de12bb703 [mlir][Tablegen-LSP] Add support for a basic TableGen language server
This follows the same general structure of the MLIR and PDLL language
servers. This commits adds the basic functionality for setting up the server,
and initially only supports providing diagnostics. Followon commits will
build out more comprehensive behavior.

Realistically this should eventually live in llvm/, but building in MLIR is an easier
initial step given that:
* All of the necessary LSP functionality is already here
* It allows for proving out useful language features (e.g. compilation databases)
  without affecting wider scale tablegen users
* MLIR has a vscode extension that can immediately take advantage of it

Differential Revision: https://reviews.llvm.org/D125440
2022-05-16 16:03:51 -07:00
River Riddle
e0c3b94c80 [mlir] Restrict dialect doc gen to a single dialect
In the overwhelmingly majority of cases only one dialect is generated at a time
anyways, and this restriction more easily catches user error when multiple
dialects might be generated. We hit this semi-recently with the PDL dialect,
and circt+other downstream users are also actively hitting this as well.

Differential Revision: https://reviews.llvm.org/D125651
2022-05-16 15:35:07 -07:00
Mogball
67f0e8eec3 [mlir][ods] Fix verification of attribute + colon type ambiguity
An attribute without a type builder followed by a colon in an assembly format is potentially ambiguous because the parser will read ahead to parse the colon-type and pass this as the type argument to the attribute's constructor.

However, the previous verifier that checks for this ambiguity erroneously produces an error in the case of

```
let assemblyFormat = "( `(` $attr `)` )? `:`";
```

This patch fixes the bug by implementing a checker that correctly handles all edge cases, including very strange assembly formats like:

```
let assemblyFormat = "( `(` $attr ) : (`>`)? attr-dict (`>` $a^) : (`<`)? `:`";
```

Reviewed By: rriddle

Differential Revision: https://reviews.llvm.org/D125445
2022-05-16 21:15:27 +00:00
Mogball
0533253d81 [mlir][ods] Ignore AttributeSelfTypeParameter in assembly formats
The attribute self type parameter is currently treated like any other attribute parameter in the assembly format. The self type parameter should be handled by the operation parser and printer and play no role in the generated parsers and printers of attributes.

Reviewed By: rriddle

Differential Revision: https://reviews.llvm.org/D125724
2022-05-16 20:23:54 +00:00
Mogball
70b69c54fa [mlir] Rename Zero* traits to Zero*s
Rename
ZeroResult -> ZeroResults
ZeroSuccessor -> ZeroSuccessors
ZeroRegion -> ZeroRegions

to be in line with ZeroOperands and grammatically correct.
2022-05-14 00:20:28 +00:00
Mogball
0ffef0c23b [mlir][ods] (NFC) don't use std::function for map_range 2022-05-12 05:15:03 +00:00
Sam McCall
e571e1a6c3 Reland "[FuzzMutate] Split out FuzzerCLI library that doesn't depend on IR."
This reverts commit a1bb952e83.

I'd somehow missed updating llvm-yaml-parser-fuzzer, now fixed.
2022-05-07 13:49:54 +02:00
Aaron Ballman
a1bb952e83 Revert "[FuzzMutate] Split out FuzzerCLI library that doesn't depend on IR."
This reverts commit 1c5e85b3da.

It broke a lot of bots with a link error:
https://lab.llvm.org/buildbot/#/builders/171/builds/14222
https://lab.llvm.org/buildbot/#/builders/188/builds/13748
https://lab.llvm.org/buildbot/#/builders/109/builds/38127
2022-05-07 07:29:57 -04:00
Sam McCall
1c5e85b3da [FuzzMutate] Split out FuzzerCLI library that doesn't depend on IR.
All llvm-project fuzzers use this library to parse command-line arguments.
Many of them don't deal with LLVM IR or modules in any way. Bundling those
functions in one library forces build dependencies that don't need to be there.

Among other things, this means check-clang-pseudo no longer depends on most of
LLVM.

Differential Revision: https://reviews.llvm.org/D125081
2022-05-07 12:11:51 +02:00
Nikita Popov
686bd6dd2b [MLIR] Fix build with make
https://reviews.llvm.org/D124075 causes MLIR to no longer build
when using make rather than ninja, due to a tablegen-generated
header being used before it is created.

It seems that this is related to the use of LLVM_ENABLE_OBJLIB when
using add_tablgen with a non-Ninja/Xcode generator. In that case an
intermediate objlib target is generated.

This patch fixes the issue by a) declaring dependencies in
add_tablegen for mlir-pdll and b) making sure those dependencies
are added to the objlib target.

Differential Revision: https://reviews.llvm.org/D125010
2022-05-06 14:52:35 +02:00
Marius Brehler
63aaf9a6e7 [mlir] Add missing CMake deps to mlir-pdll
Reviewed By: rriddle

Differential Revision: https://reviews.llvm.org/D124851
2022-05-04 06:17:13 +00:00
River Riddle
1bd1edaf40 [mlir:ODS] Support using attributes in AllTypesMatch to automatically add InferTypeOpInterface
This allows for using attribute types in result type inference for use with
InferTypeOpInterface. This was a TODO before, but it isn't much
additional work to properly support this. After this commit,
arith::ConstantOp can now have its InferTypeOpInterface implementation automatically
generated.

Differential Revision: https://reviews.llvm.org/D124580
2022-04-28 12:57:59 -07:00
Mathieu Fehr
9e0b553359 [mlir] Add extensible dialects
Depends on D104534
Add support for extensible dialects, which are dialects that can be
extended at runtime with new operations and types.

These operations and types cannot at the moment implement traits
or interfaces.

Reviewed By: rriddle

Differential Revision: https://reviews.llvm.org/D104554
2022-04-26 19:48:22 -07:00
River Riddle
597fde54a8 [mlir][PDLL] Add support for generating PDL patterns from PDLL at build time
This essentially sets up mlir-pdll to function in a similar manner to mlir-tblgen. Aside
from the boilerplate of configuring CMake and setting up a basic initial test, two new
options are added to mlir-pdll to mirror options provided by tblgen:

* -d
 This option generates a dependency file (i.e. a set of build time dependencies) while
 processing the input file.

* --write-if-changed
 This option only writes to the output file if the data would have changed, which for
 the build system prevents unnecesarry rebuilds if the file was touched but not actually
 changed.

Differential Revision: https://reviews.llvm.org/D124075
2022-04-26 18:33:16 -07:00
Krzysztof Drewniak
d35f7f254f [mlir] Allow data flow analysis of non-control flow branch arguments
This commit adds the visitNonControlFlowArguments method to
DataFlowAnalysis, allowing analyses to provide lattice values for the
arguments to a RegionSuccessor block that aren't directly tied to an
op's inputs. For example, integer range interface can use this method
to infer bounds for the step values in loops.

This method has a default implementation that keeps the old behavior
of assigning a pessimistic fixedpoint state to all such arguments.

Reviewed By: Mogball, rriddle

Differential Revision: https://reviews.llvm.org/D124021
2022-04-25 20:19:34 +00:00
jfurtek
c4caa90b15 [mlir][tblgen] Generate builders with inferred return types and unwrapped attributes
This diff causes mlir-tblgen to generate code for an additional builder for an
operation argument with a return type that can be inferred *AND* an attribute in
the argument list can be "unwrapped." (Previously, the unwrapped build function
was only generated for builders with explicit return types in separate or
aggregate form.) As an example, this builder might be used by code that creates
operations that implement the `SameOperandsAndResultType` interface. A test case
was created.

Reviewed By: jpienaar

Differential Revision: https://reviews.llvm.org/D124043
2022-04-25 19:00:44 +00:00
jfurtek
4e5dee2f30 [mlir][ods] Add tablegen field for concise printing of BitEnum attributes
This diff introduces a tablegen field for bit enum attributes
(`printBitEnumPrimaryGroups`) to control printing when the enum uses "group"
cases. An example would be an implementation that uses a `fastmath` enum value
as an alias for individual fastmath flags. The proposed field would allow
printing of simply `fast` for the enum value, instead of the more verbose list
that would include `fast` as well as the individual flags (e.g. `reassoc,nnan,
ninf,nsz,arcp,contract,afn,fast`).

Reviewed By: rriddle

Differential Revision: https://reviews.llvm.org/D123871
2022-04-25 18:48:35 +00:00
River Riddle
f3ebf828dc [mlir] Generate Dialect constructors in .cpp instead of .h
By generating in the .h file, we were forcing dialects to include
a lot of additional header files because:

* Fields of the dialect, e.g. std::unique_ptr<>, were unable to use
  forward declarations.
* Dependent dialects are loaded in the constructor, requiring the
  full definition of each dependent dialect (which, depending on
  the file structure of the dialect, may include the operations).

By generating in the .cpp we get much faster builds, and also
better align with the rest of the code base.

Fixes #55044

Differential Revision: https://reviews.llvm.org/D124297
2022-04-23 00:44:54 -07:00
Markus Böck
850b2c6b3c [mlir] Fix Regions takeBody method if the region is not empty
The current implementation of takeBody first clears the Region, before then taking ownership of the blocks of the other regions. The issue here however, is that when clearing the region, it does not take into account references of operations to each other. In particular, blocks are deleted from front to back, and operations within a block are very likely to be deleted despite still having uses, causing an assertion to trigger [0].

This patch fixes that issue by simply calling dropAllReferences()before clearing the blocks.

[0] 9a8bb4bc63/mlir/lib/IR/Operation.cpp (L154)

Differential Revision: https://reviews.llvm.org/D123913
2022-04-21 15:32:59 +02:00
gysit
407b351da2 [mlir][linalg] Add ods-gen helper to simplify the build methods.
Add a helper used to implement the build methods generated by ods-gen. The change reduces code size and compilation time since all structured op builders use the same build method. The change reduces the LinalgOps.cpp compilation time from 10.2s to 9.8s (debug build).

Depends On D123987

Reviewed By: nicolasvasilache

Differential Revision: https://reviews.llvm.org/D124003
2022-04-20 13:14:38 +00:00
gysit
17721b6915 [mlir][linalg] Avoid template methods for parsing and printing.
The revision avoids template methods for parsing and printing that are replicated for every named operation. Instead, the new methods take a regionBuilder argument. The revision reduces the compile time of LinalgOps.cpp from 11.2 to 10.2 seconds (debug build).

Reviewed By: nicolasvasilache

Differential Revision: https://reviews.llvm.org/D123987
2022-04-20 13:06:31 +00:00
Mehdi Amini
709868707c Apply clang-tidy fixes for readability-identifier-naming in OpFormatGen.cpp (NFC) 2022-04-16 06:36:12 +00:00
Mehdi Amini
cdbd9c9bab Apply clang-tidy fixes for llvm-qualified-auto in OpFormatGen.cpp (NFC) 2022-04-16 06:36:11 +00:00
Mehdi Amini
94244bda9d Apply clang-tidy fixes for readability-identifier-naming in mlir-parser-fuzzer.cpp (NFC) 2022-04-16 00:44:51 +00:00
Mehdi Amini
fc9e440942 Apply clang-tidy fixes for readability-identifier-naming in DummyParserFuzzer.cpp (NFC) 2022-04-16 00:44:51 +00:00
William S. Moses
ed499ddcda [MLIR] Fix operation clone
Operation clone is currently faulty.

Suppose you have a block like as follows:

```
(%x0 : i32) {
   %x1 = f(%x0)
   return %x1
}
```

The test case we have is that we want to "unroll" this, in which we want to change this to compute `f(f(x0))` instead of just `f(x0)`. We do so by making a copy of the body at the end of the block and set the uses of the argument in the copy operations with the value returned from the original block.
This is implemented as follows:
1) map to the block arguments to the returned value (`map[x0] = x1`).
2) clone the body

Now for this small example, this works as intended and we get the following.

```
(%x0 : i32) {
   %x1 = f(%x0)
   %x2 = f(%x1)
   return %x2
}
```

This is because the current logic to clone `x1 = f(x0)` first looks up the arguments in the map (which finds `x0` maps to `x1` from the initialization), and then sets the map of the result to the cloned result (`map[x1] = x2`).

However, this fails if `x0` is not an argument to the op, but instead used inside the region, like below.

```
(%x0 : i32) {
   %x1 = f() {
      yield %x0
   }
   return %x1
}
```

This is because cloning an op currently first looks up the args (none), sets the map of the result (`map[%x1] = %x2`), and then clones the regions. This results in the following, which is clearly illegal:

```
(%x0 : i32) {
   %x1 = f() {
      yield %x0
   }
   %x2 = f() {
      yield %x2
   }
   return %x2
}
```

Diving deeper, this is partially due to the ordering (how this PR fixes it), as well as how region cloning works. Namely it will first clone with the mapping, and then it will remap all operands. Since the ordering above now has a map of `x0 -> x1` and `x1 -> x2`, we end up with the incorrect behavior here.

Reviewed By: ftynse

Differential Revision: https://reviews.llvm.org/D122531
2022-04-15 13:09:13 -04:00