Commit Graph

4398 Commits

Author SHA1 Message Date
Uday Bondhugula 04b5274ede [MLIR] Introduce applyOpPatternsAndFold for op local rewrites
Introduce mlir::applyOpPatternsAndFold which applies patterns as well as
any folding only on a specified op (in contrast to
applyPatternsAndFoldGreedily which applies patterns only on the regions
of an op isolated from above).  The caller is made aware of the op being
folded away or erased.

Depends on D77485.

Differential Revision: https://reviews.llvm.org/D77487
2020-04-15 14:10:01 +05:30
River Riddle 229e392b4e [llvm][StringExtras] Merge StringExtras from MLIR into LLVM
Summary:
This revision adds two utilities currently present in MLIR to LLVM StringExtras:

* convertToSnakeFromCamelCase
Convert a string from a camel case naming scheme, to a snake case scheme

* convertToCamelFromSnakeCase
Convert a string from a snake case naming scheme, to a camel case scheme

Differential Revision: https://reviews.llvm.org/D78167
2020-04-14 18:57:22 -07:00
Adam Straw 2f8b4545f4 [mlir] Fix assert on signed integer type in EDSC
Integer type in Std dialect is signless so we should be checking
for signless integer type instead of signed integer type in EDSC.

Differential Revision: https://reviews.llvm.org/D78144
2020-04-15 02:04:49 +03:00
River Riddle 92f1562f3d [mlir][NFC] Remove the STLExtras.h header file now that it has been merged into LLVM.
Now that no more utilities exist within, this file can be deleted.

Differential Revision: https://reviews.llvm.org/D78079
2020-04-14 15:14:41 -07:00
River Riddle ebf190fcda [llvm][ADT] Move TypeSwitch class from MLIR to LLVM
This class implements a switch-like dispatch statement for a value of 'T' using dyn_cast functionality. Each `Case<T>` takes a callable to be invoked if the root value isa<T>, the callable is invoked with the result of dyn_cast<T>() as a parameter.

Differential Revision: https://reviews.llvm.org/D78070
2020-04-14 15:14:41 -07:00
River Riddle 2f21a57966 [llvm][STLExtras] Move the algorithm `interleave*` methods from MLIR to LLVM
These have proved incredibly useful for interleaving values between a range w.r.t to streams. After this revision, the mlir/Support/STLExtras.h is empty. A followup revision will remove it from the tree.

Differential Revision: https://reviews.llvm.org/D78067
2020-04-14 15:14:40 -07:00
River Riddle 204c3b5516 [llvm][STLExtras] Move various iterator/range utilities from MLIR to LLVM
This revision moves the various range utilities present in MLIR to LLVM to enable greater reuse. This revision moves the following utilities:

* indexed_accessor_*
This is set of utility iterator/range base classes that allow for building a range class where the iterators are represented by an object+index pair.

* make_second_range
Given a range of pairs, returns a range iterating over the `second` elements.

* hasSingleElement
Returns if the given range has 1 element. size() == 1 checks end up being very common, but size() is not always O(1) (e.g., ilist). This method provides O(1) checks for those cases.

Differential Revision: https://reviews.llvm.org/D78064
2020-04-14 15:14:40 -07:00
River Riddle 8cbe371c28 [llvm][STLExtras] Add various type_trait utilities currently present in MLIR
This revision moves several type_trait utilities from MLIR into LLVM. Namely, this revision adds:
is_detected - This matches the experimental std::is_detected
is_invocable - This matches the c++17 std::is_invocable
function_traits - A utility traits class for getting the argument and result types of a callable type

Differential Revision: https://reviews.llvm.org/D78059
2020-04-14 15:14:40 -07:00
River Riddle f52ec5d5c0 [llvm][DenseMapInfo] Add an info specialization for std::tuple
This revision adds a DenseMapInfo overload for std::tuples whose elements all have a DenseMapInfo. The implementation is similar to that of std::pair, and has been used within MLIR for over a year.

Differential Revision: https://reviews.llvm.org/D78057
2020-04-14 15:14:40 -07:00
Sean Silva 483f2783ae Use index for shape.to_extent_tensor
Summary:
Also,
- add IndexTensor to OpBase.td
- fix typo in the op name. It was mistakenly `to_tensor` instead of
  `to_extent_tensor`.

Differential Revision: https://reviews.llvm.org/D78149
2020-04-14 15:09:18 -07:00
MaheshRavishankar 37b520763f [mlir][Linalg] Handle null affine map returns from inversePermutation.
The inversePermutation method returns a null map on failure. Update
uses of this method within Linalg to handle this. In LinalgToLoops the
null return value was used to emit scalar code. Modify that to return
failure, and emit scalar implementation when affine map is "empty",
i.e. 1 dims, 0 symbols and no result exprs.

Differential Revision: https://reviews.llvm.org/D77964
2020-04-14 14:41:20 -07:00
MaheshRavishankar 4d9fac6da5 [mlir][Linalg] NFC: Add missing comments from earlier commit (D77965)
Differential Revision: https://reviews.llvm.org/D78140
2020-04-14 12:15:42 -07:00
Alina Sbirlea d5fcb7966e [STLExtras] Make const the * operator for mapped_iterator.
Summary:
The current non-const * operator shadows the const operator in
iterator_adaptor_base.

Reviewers: mehdi_amini, rriddle!, dblaikie, timshen

Subscribers: dexonsmith, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, grosul1, frgossen, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D78073
2020-04-14 11:04:20 -07:00
Tres Popp 58516718fc [MLIR] Constant fold multiplies in deriveStaticUpperBound.
Summary:
This operation occurs during collapseParallelLoops, so we constant fold
them also to allow more situations of determining a loop invariant upper
bound when lowering to the GPU dialect from the Loop dialect.

Differential Revision: https://reviews.llvm.org/D77723
2020-04-14 13:04:16 +02:00
Chris Lattner 1beffb92d1 Fix the MLIR integer attribute parser to be correct in the face of large integer attributes, it was previously artificially limited to 64 bits.
Reviewers: rriddle!

Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, grosul1, frgossen, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D78065
2020-04-13 21:50:36 -07:00
Uday Bondhugula 0a54887dac Fix MLIR test case failure caused by 89e0662dee
Fix MLIR test case failure introduced by
89e0662dee. LLVM's IR builder
now automatically sets the alignment on alloca.
2020-04-14 09:54:22 +05:30
Uday Bondhugula ac047d9fce [MLIR] Remove dead affine.applys while generating pointwise copies
This makes no impact on the test cases because affine-data-copy-generate
runs whole function canonicalization at its end; however, the latter
will be removed in a pending revision. It is thus useful to clean up
these affine.applys right here, and eventually, not even generate
these (when the right API to compose by construction is in place).

Differential Revision: https://reviews.llvm.org/D78055
2020-04-14 09:47:14 +05:30
Christopher Tetreault eab73dfed9 [SVE] Change return type of getNumElements to unsigned
Reviewers: efriedma, sdesmalen, craig.topper, dexonsmith

Reviewed By: efriedma, sdesmalen

Subscribers: tschuett, hiraditya, rkruppe, psnobl, mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, aartbik, liufengdb, Joonsoo, grosul1, frgossen, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D77763
2020-04-13 16:24:18 -07:00
Jean-Luc Brouillet 9b1a0d300e Fix a typo in the error message for an incorrect prototype.
Summary: Cut & paste error had the error message mentionning "}" rather than ")".

Differential Revision: https://reviews.llvm.org/D77625
2020-04-13 15:43:51 -07:00
River Riddle d3588d0814 [mlir][NFC] Replace mlir/Support/Functional.h with llvm equivalents.
Summary: Functional.h contains many different methods that have a direct, and more efficient, equivalent in LLVM. This revision replaces all usages with the LLVM equivalent, and removes the header. This is part of larger cleanup, pr45513, merging MLIR support facilities into LLVM.

Differential Revision: https://reviews.llvm.org/D78053
2020-04-13 14:22:12 -07:00
MaheshRavishankar 2a99e700e0 [mlir][Linalg] NFC: Add utility function to tile, fuse and set marker to use loop.parallel.
This change is NFC since the facility to tile and generate
loop.parallel loops already exists in Linalg.

Differential Revision: https://reviews.llvm.org/D77965
2020-04-13 13:23:06 -07:00
MaheshRavishankar 3b2f26ab05 [mlir][Linalg] NFC : Fix check for scalar case handling in LinalgToLoops
The invertPermutation method does not return a nullptr anymore, but
rather returns an empty map for the scalar case. Update the check in
LinalgToLoops to reflect this.
Also add test case for generating scalar code.
2020-04-13 13:23:01 -07:00
MaheshRavishankar 03391df90e [mlir][Linalg] Add loop.parallel lowering for all Linalg Ops.
The outer parallel loops of a linalg operation is lowered to
loop.parallel, with the other loops lowered to loop.for. This gets the
lowering to loop.parallel on par with the loop.for lowering. In future
the reduction loop could also be lowered to loop.parallel.
Also add a utility function that returns the loops that are
created.

Differential Revision: https://reviews.llvm.org/D77678
2020-04-13 13:19:12 -07:00
Denis Khalikov ec99d6e62f [mlir][spirv] Add a `spirv::InterfaceVarABIAttr`.
Summary:
Add a proper dialect-specific attribute for interface variable ABI.

Differential Revision: https://reviews.llvm.org/D77941
2020-04-13 22:47:47 +03:00
Lei Zhang a9cb529a84 [mlir][spirv] NFC: use Optional to replace SPV_Optional
Differential Revision: https://reviews.llvm.org/D78046
2020-04-13 15:44:06 -04:00
Chris Lattner 359541ed4f Remove the Identifier::is() method, it is now equivalent to operator==. NFC.
Summary: Depends on D78042.

Reviewers: rriddle!

Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, grosul1, frgossen, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D78043
2020-04-13 12:37:37 -07:00
Chris Lattner 74e6a5b2a3 Eliminate all uses of Identifier::is() in the source tree, this doesn't remove the definition of it (yet). NFC.
Reviewers: mravishankar, antiagainst, herhut, rriddle!

Subscribers: jholewinski, mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, csigg, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, bader, grosul1, frgossen, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D78042
2020-04-13 11:49:31 -07:00
Uday Bondhugula 42ada5fee9 [MLIR] NFC cleanup/modernize memref-dataflow-opt / getNestingDepth
Bring code to date with recent changes to the core infrastructure /
coding style.

Differential Revision: https://reviews.llvm.org/D77998
2020-04-14 00:03:06 +05:30
Uday Bondhugula 500e03881b [MLIR] NFC clean up simplify-affine-structures test case
NFC clean up for simplify-affine-structures test cases. Rename sets
better; avoid suffix numbers;  move outlined definitions close to use.
This is in preparation for other functionality updates.

Differential Revision: https://reviews.llvm.org/D78017
2020-04-13 23:59:21 +05:30
River Riddle 8a49ed2133 [mlir][Transforms][docs] Add a description blurb for various passes
Summary: This revision adds blurbs of documentation to various different passes, namely: Canonicalizer, CSE, LocationSnapshot, StripDebugInfo, and SymbolDCE.

Differential Revision: https://reviews.llvm.org/D78007
2020-04-13 11:28:03 -07:00
Lei Zhang a290c3af9d [mlir][spirv] Improve stride support in array types
This commit added stride support in runtime array types. It also
adjusted the assembly form for the stride from `[N]` to `stride=N`.
This makes the IR more readable, especially for the cases where
one mix array types and struct types.

Differential Revision: https://reviews.llvm.org/D78034
2020-04-13 14:08:17 -04:00
Chris Lattner d63036c0ef Reimplement mlir::Identifier to be a wrapper around 'StringMapEntry*' instead of a wrapper around a 'const char*'. This makes it so strref() can be computed without calling strlen, which is more efficient and less error-prone. While here...
Summary:
..., reimplement DenseMapInfo<mlir::Identifier>::getHashValue in terms of mlir::hash_value(Identifier).

Both of these improvements were suggested by River, thanks!

Reviewers: rriddle!

Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, aartbik, liufengdb, Joonsoo, grosul1, frgossen, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D77999
2020-04-13 10:47:04 -07:00
Lei Zhang 32e6cbe203 [mlir][spirv] Add missing interface storage classes in serializer
Differential Revision: https://reviews.llvm.org/D78037
2020-04-13 13:34:58 -04:00
River Riddle 2e8188ff48 [mlir][NFC] Mark a debug only variable as (void) to avoid unused warning 2020-04-13 00:48:17 -07:00
River Riddle 43cf489cf5 [mlir][SymbolDCE][NFC] Fix the visibility of the symbols within the test and
move it to test/Transforms/
2020-04-13 00:33:11 -07:00
River Riddle decac2d9ea [mlir][EnumGen] Generate utility symbolizeEnum and stringifyEnum methods during EnumGen
Summary:
This revision adds generation of two utility methods during EnumGen:
```
llvm::Optional<EnumType> symbolizeEnum<EnumType>(llvm::StringRef)
<stringifyResult> stringifyEnum(EnumType);
```

This provides a generic interface for stringifying/symbolizing any enum that can be used in a template environment.

Differential Revision: https://reviews.llvm.org/D77937
2020-04-12 19:08:08 -07:00
Ehud Katz 3e8de2ed74 [MLIR] Fix MLIR_MAIN_[SRC|INCLUDE]_DIR variables
Define MLIR_MAIN_INCLUDE_DIR, as it was not set anywhere.

Set MLIR_MAIN_SRC_DIR to the actual "source directory", and not the
"include directory" (as currently set).

Differential Revision: https://reviews.llvm.org/D77943
2020-04-12 09:29:07 +03:00
River Riddle 8938dea44a [mlir][IR] Manually register command line options for MLIRContext and AsmPrinter
Summary: This revision makes the registration of command line options for these two files manual with `registerMLIRContextCLOptions` and `registerAsmPrinterCLOptions` methods. This removes the last remaining static constructors within lib/.

Differential Revision: https://reviews.llvm.org/D77960
2020-04-11 23:13:00 -07:00
River Riddle 1fc6efaf6a [mlir][StorageUniquer] Replace all usages of std::function with function_ref.
Summary: std::function has a notoriously large amount of malloc traffic, whereas function_ref is a cheaper and more efficient alternative.

Differential Revision: https://reviews.llvm.org/D77959
2020-04-11 23:07:52 -07:00
Chris Lattner aef4ec00f9 Change the identifier table in MLIRContext to use StringSet instead of
StringMap<char>, saving a byte due to the StringMapEntry specialization
for a value of NoneType.  NFC.
2020-04-11 22:07:39 -07:00
Stephen Neuendorffer 4956871c0e [MLIR] CMake cleanup for mlir-opt
A few libraries which are also Dialect libraries where independently
in the link line for mlir-opt.  Remove them.

Differential Revision: https://reviews.llvm.org/D77927
2020-04-11 22:02:16 -07:00
Stephen Neuendorffer 4c18e1d3af [MLIR] add cmake abstraction for translation libraries
Differential Revision: https://reviews.llvm.org/D77926
2020-04-11 22:02:16 -07:00
Chris Lattner ed87d9d643 Change the implementation of mlir::hash_value(Identifier) to be consistent
with DenseMapInfo<mlir::Identifier>::getHashValue. NFC.

Adjust a few variable names to follow MLIR convention while here NFC.
2020-04-11 21:59:48 -07:00
Chris Lattner 0031c7f7da Implement some micro-optimizations for Identifier. NFC
Summary:
Identifier doesn't maintain a length, so every time strref() is called,
it does a strlen.  In the case of comparisons, this isn't necessary:
there is no need to scan a string to get its length, then rescan it to
do the comparison.  Just done one comparison.

This also moves some assertions in Identifier::get as another
microoptimization for 'assertions enabled' modes.

Reviewers: rriddle!

Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, grosul1, frgossen, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D77958
2020-04-11 21:48:52 -07:00
Uday Bondhugula 75ea9e4e40 [MLIR][NFC] add doc cross links from/to std.alloca
Add doc cross links between std.alloca and AutomaticAllocationScope.

Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, grosul1, frgossen, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D77956
2020-04-12 03:33:19 +05:30
River Riddle 89b007037f [mlir][docs] Remove the MLIR prefix from several titles.
This prefix is already implied by the doc location and functions only as
filler.
2020-04-11 14:49:03 -07:00
River Riddle 55de49ac1c [mlir][docs] Refactor the layout of the docs folder
Summary:
This revision performs a few refactorings on the main docs folder. Namely it:
* Adds a new Rationale/ folder to contain various rationale documents
* Moves several "getting started" documents to the Tutorials/ folder
* Cleans up the titles of various documents

Differential Revision: https://reviews.llvm.org/D77934
2020-04-11 11:47:01 -07:00
Jonathan Roelofs 0dbaafaa3a [mlir][docs] Explain the EDSC acronym. NFC
Differential Revision: https://reviews.llvm.org/D77914
2020-04-11 09:11:35 -06:00
Jonathan Roelofs 015ebd2930 [mlir][toy] Fix comment typo. NFC
Differential Revision: https://reviews.llvm.org/D77917
2020-04-11 09:11:35 -06:00
Jonathan Roelofs 3737be8902 [mlir][toy][docs] Fix reference to generated ToyCombine.inc. NFC
Differential Revision: https://reviews.llvm.org/D77916
2020-04-11 09:11:35 -06:00
Jonathan Roelofs 2f7707db02 [mlir][toy][docs] Reword for better sentence flow. NFC 2020-04-11 09:11:34 -06:00
Uday Bondhugula cbcb12fd44 [MLIR] Handle in-place folding properly in greedy pattern rewrite driver
OperatioFolder::tryToFold performs both true folding and in a few
instances in-place updates through op rewrites. In the latter case, we
should still be applying the supplied pattern rewrites in the same
iteration; however this wasn't the case since tryToFold returned
success() for both true folding and in-place updates, and the patterns
for the in-place updated ops were being applied only in the next
iteration of the driver's outer loop. This fix would make it converge
faster.

Differential Revision: https://reviews.llvm.org/D77485
2020-04-11 19:57:29 +05:30
River Riddle a517191a47 [mlir][NFC] Refactor ClassID into a TypeID class.
Summary: ClassID is a bit janky right now as it involves passing a magic pointer around. This revision hides the internal implementation mechanism within a new class TypeID. This class is a value-typed wrapper around the original ClassID implementation.

Differential Revision: https://reviews.llvm.org/D77768
2020-04-10 23:52:33 -07:00
River Riddle 7824768b2e [mlir][Pass] Add a new `Pass::getArgument` hook
Summary: This hook allows for passes to specify the command line argument without the need for registration. More concretely this will allow for generating pass crash reproducers without needing to have the passes registered. This should remove the need for production tools to register passes, leaving that solely to development tools like mlir-opt.

Differential Revision: https://reviews.llvm.org/D77907
2020-04-10 22:50:14 -07:00
River Riddle 33f76e2381 [mlir][Pass] Allow duplicate pass registration.
Summary: With users registering their own dependencies, duplicate pass registration becomes more and more common. This revision relaxes that pass registration be unique. This is safe to assume given that we key on the passID, which is guaranteed to be unique per pass class.

Differential Revision: https://reviews.llvm.org/D77909
2020-04-10 14:49:59 -07:00
River Riddle aba1acc89c [mlir][ODS] Add support for optional operands and results with a new Optional directive.
Summary: This revision adds support for specifying operands or results as "optional". This is a special case of variadic where the number of elements is either 0 or 1. Operands and results of this kind will have accessors generated using Value instead of the range types, making it more natural to interface with.

Differential Revision: https://reviews.llvm.org/D77863
2020-04-10 14:12:06 -07:00
Christopher Tetreault 92dde8a657 Clean up usages of asserting vector getters in Type
Summary:
Remove usages of asserting vector getters in Type in preparation for the
VectorType refactor. The existence of these functions complicates the
refactor while adding little value.

Reviewers: rriddle, efriedma, sdesmalen

Reviewed By: sdesmalen

Subscribers: frgossen, mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, aartbik, liufengdb, Joonsoo, grosul1, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D77258
2020-04-10 13:46:18 -07:00
River Riddle 3db57d14ec [mlir] Emit errors if global constructors are found within lib/
Summary: This avoids adding any additional global constructors, like cl::opt. There is a temporary exception on IR/, which has a few cl::opts that require a bit of plumbing to remove.

Differential Revision: https://reviews.llvm.org/D77824
2020-04-10 13:04:32 -07:00
Jacques Pienaar d6b32e39ae [mlir][drr] Allow specifying string in location
Summary:
The string in the location is used to provide metadata for the fused location
or create a NamedLoc. This allows tagging individual locations to convey
additional rewrite information.

Differential Revision: https://reviews.llvm.org/D77840
2020-04-10 12:43:22 -07:00
Nicolas Vasilache 882ba48474 [mlir][Linalg] Create a tool to generate named Linalg ops from a Tensor Comprehensions-like specification.
Summary:

This revision adds a tool that generates the ODS and C++ implementation for "named" Linalg ops according to the [RFC discussion](https://llvm.discourse.group/t/rfc-declarative-named-ops-in-the-linalg-dialect/745).

While the mechanisms and language aspects are by no means set in stone, this revision allows connecting the pieces end-to-end from a mathematical-like specification.

Some implementation details and short-term decisions taken for the purpose of bootstrapping and that are not set in stone include:

    1. using a "[Tensor Comprehension](https://arxiv.org/abs/1802.04730)-inspired" syntax
    2. implicit and eager discovery of dims and symbols when parsing
    3. using EDSC ops to specify the computation (e.g. std_addf, std_mul_f, ...)

A followup revision will connect this tool to tablegen mechanisms and allow the emission of named Linalg ops that automatically lower to various loop forms and run end to end.

For the following "Tensor Comprehension-inspired" string:

```
    def batch_matmul(A: f32(Batch, M, K), B: f32(K, N)) -> (C: f32(Batch, M, N)) {
      C(b, m, n) = std_addf<k>(std_mulf(A(b, m, k), B(k, n)));
    }
```

With -gen-ods-decl=1, this emits (modulo formatting):

```
      def batch_matmulOp : LinalgNamedStructured_Op<"batch_matmul", [
        NInputs<2>,
        NOutputs<1>,
        NamedStructuredOpTraits]> {
          let arguments = (ins Variadic<LinalgOperand>:$views);
          let results = (outs Variadic<AnyRankedTensor>:$output_tensors);
          let extraClassDeclaration = [{
            llvm::Optional<SmallVector<StringRef, 8>> referenceIterators();
            llvm::Optional<SmallVector<AffineMap, 8>> referenceIndexingMaps();
            void regionBuilder(ArrayRef<BlockArgument> args);
          }];
          let hasFolder = 1;
      }
```

With -gen-ods-impl, this emits (modulo formatting):

```
      llvm::Optional<SmallVector<StringRef, 8>> batch_matmul::referenceIterators() {
          return SmallVector<StringRef, 8>{ getParallelIteratorTypeName(),
                                            getParallelIteratorTypeName(),
                                            getParallelIteratorTypeName(),
                                            getReductionIteratorTypeName() };
      }
      llvm::Optional<SmallVector<AffineMap, 8>> batch_matmul::referenceIndexingMaps()
      {
        MLIRContext *context = getContext();
        AffineExpr d0, d1, d2, d3;
        bindDims(context, d0, d1, d2, d3);
        return SmallVector<AffineMap, 8>{
            AffineMap::get(4, 0, {d0, d1, d3}),
            AffineMap::get(4, 0, {d3, d2}),
            AffineMap::get(4, 0, {d0, d1, d2}) };
      }
      void batch_matmul::regionBuilder(ArrayRef<BlockArgument> args) {
        using namespace edsc;
        using namespace intrinsics;
        ValueHandle _0(args[0]), _1(args[1]), _2(args[2]);

        ValueHandle _4 = std_mulf(_0, _1);
        ValueHandle _5 = std_addf(_2, _4);
        (linalg_yield(ValueRange{ _5 }));
      }
```

Differential Revision: https://reviews.llvm.org/D77067
2020-04-10 13:59:25 -04:00
Uday Bondhugula c197edb135 [MLIR][NFC] fix doc comment for isKnownIsolatedFromAbove
Fix doc comment for Operation::isKnownIsolatedFromAbove().
2020-04-10 19:15:21 +05:30
Lei Zhang 3e94943d4b [mlir][spirv] Update doc regarding availability and type conversion
Differential Revision: https://reviews.llvm.org/D77803
2020-04-10 08:42:51 -04:00
Kiran Kumar T P 7ecee63e71 [MLIR] Support for taskwait and taskyield operations, and translating the same to LLVM IR
This patch adds support for taskwait and taskyield operations in OpenMP dialect and translation of the these constructs to LLVM IR. The OpenMP IRBuilder is used for this translation.
The patch includes code changes and a testcase modifications.

Differential Revision: https://reviews.llvm.org/D77634
2020-04-10 07:42:34 +00:00
Uday Bondhugula a5b9316b24 [MLIR][NFC] applyPatternsGreedily -> applyPatternsAndFoldGreedily
Rename mlir::applyPatternsGreedily -> applyPatternsAndFoldGreedily. The
new name is a more accurate description of the method - it performs
both, application of the specified patterns and folding of all ops in
the op's region irrespective of whether any patterns have been supplied.

Differential Revision: https://reviews.llvm.org/D77478
2020-04-10 12:55:21 +05:30
Uday Bondhugula db054d7115 [MLIR] Introduce an op trait that defines a new scope for auto allocation
Introduce a new operation property / trait (AutomaticAllocationScope)
for operations with regions that define a new scope for automatic allocations;
such allocations (typically realized on stack) are automatically freed when
control leaves such ops' regions. std.alloca's are freed at the closest
surrounding op that has this trait. All FunctionLike operations should normally
have this trait.

Differential Revision: https://reviews.llvm.org/D77787
2020-04-10 12:05:52 +05:30
Chris Lattner 1c0efa8b54 tweak formatting of input to match the output as suggested by River, NFC. 2020-04-09 15:26:22 -07:00
Chris Lattner ab64fd39d2 Allow single-bit integer types to have signs. A signed one bit integer is either 0 or -1.
Reviewers: rriddle!

Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, grosul1, frgossen, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D77832
2020-04-09 15:23:06 -07:00
Nicolas Vasilache 2d32ee0d7a [mlir][Vector] Update lowering of vector ops to llvm intrinsics to use row-major.
Summary:
LLVM matrix intrinsics recently introduced an option to support row-major mode.
This matches the MLIR vector model, this revision switches to row-major.

A corner case related to degenerate sizes was also fixed upstream.
This revision removes the guard against this corner case.

A bug was uncovered on the output vector construction which this revision also fixes.

Lastly, this has been tested on a small size and benchmarked independently: no visible performance regression is observed.

In the future, when matrix intrinsics support per op attribute, we can more aggressively translate to that and avoid inserting MLIR-level transposes.

This has been tested independently to work on small matrices.

Differential Revision: https://reviews.llvm.org/D77761
2020-04-09 16:37:28 -04:00
Eli Friedman 133049d0ed [opaque pointers] Fix uses of deprecated CreateCall/CreateInvoke. 2020-04-09 13:24:55 -07:00
Nicolas Vasilache 8345b86d9a [mlir][Vector] Add lowering of 1-D vector transfer_read/write to masked load/store
Summary:
This revision adds support to lower 1-D vector transfers to LLVM.
A mask of the vector length is created that compares the base offset + linear index to the dim of the vector.
In each position where this does not overflow (i.e. offset + vector index < dim), the mask is set to 1.

A notable fact is that the lowering uses llvm.dialect_cast to allow writing code in the simplest form by targeting the simplest mix of vector and LLVM dialects and
letting other conversions kick in.

Differential Revision: https://reviews.llvm.org/D77703
2020-04-09 16:17:05 -04:00
Nicolas Vasilache 4408e6a96a [mlir][test] NFC - Rename cblas to mlir_test_cblas
The "cblas" lib under mlir/test is meant as a simple integration demonstration.
However it is installed and ends up conflicting with external projects who want to
define the real cblas.
Rename to avoid conflicts.

Differential revision: https://reviews.llvm.org/D76615
2020-04-09 16:13:33 -04:00
River Riddle bd1ccfe6df [mlir] Add a new RewritePattern::hasBoundedRewriteRecursion hook.
Summary: Some pattern rewriters, like dialect conversion, prohibit the unbounded recursion(or reapplication) of patterns on generated IR. Most patterns are not written with recursive application in mind, so will generally explode the stack if uncaught. This revision adds a hook to RewritePattern, `hasBoundedRewriteRecursion`, to signal that the pattern can safely be applied to the generated IR of a previous application of the same pattern. This allows for establishing a contract between the pattern and rewriter that the pattern knows and can handle the potential recursive application.

Differential Revision: https://reviews.llvm.org/D77782
2020-04-09 12:42:28 -07:00
Uday Bondhugula d314b7d5ca [MLIR] ShapedType accessor minor fixes + add isDynamicDim accessor
Minor fixes and cleanup for ShapedType accessors, use
ShapedType::kDynamicSize, add ShapedType::isDynamicDim.

Differential Revision: https://reviews.llvm.org/D77710
2020-04-09 08:47:50 +05:30
River Riddle 293c5210ec [mlir][NFC] Wrap the cl::opts in JitRunner within a struct to avoid global initializers.
Summary: This avoids the need for having global static initializers within the JITRunner support library, and only constructs the options when the runner is invoked.

Differential Revision: https://reviews.llvm.org/D77760
2020-04-08 18:33:37 -07:00
River Riddle 21605a1207 [mlir] Mark ClassID::getID as LLVM_EXTERNAL_VISIBILITY to ensure only one version exists
Summary: ClassID is used as a type id and must be unique in the face of shared libraries to ensure correctness. This fixes failures related to BUILD_SHARED_LIBs on macos.

Differential Revision: https://reviews.llvm.org/D77764
2020-04-08 16:51:48 -07:00
Jonathan Roelofs 223154d267 [mlir] Remove need for static global ctors from mlir-translate
Summary: https://bugs.llvm.org/show_bug.cgi?id=45436

Reviewers: mehdi_amini, mravishankar, antiagainst, rriddle, stephenneuendorffer

Reviewed By: mehdi_amini, rriddle, stephenneuendorffer

Subscribers: frgossen, stephenneuendorffer, jholewinski, mgorny, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, aartbik, liufengdb, Joonsoo, bader, grosul1, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D77515
2020-04-08 16:52:33 -06:00
River Riddle 67bdda6350 [mlir][NFC] Wrap static DenseMap inside of a function to avoid the need for a global static initializer
This also helps to abstract away the exact implementation details of the loopup method if we wish to change it in the future.
2020-04-08 14:18:35 -07:00
Nicolas Vasilache 6fb6a4d7f9 [mlir][Linalg] Add a test for a fused Linalg pass based on DRR to go from matmul to vectors
This revision builds a simple "fused pass" consisting of 2 levels of tiling, memory promotion and vectorization using linalg transformations written as composable pattern rewrites.
2020-04-08 16:54:40 -04:00
River Riddle c6e917d2d3 [mlir][NFC] Remove cl::opts for LoopUnroll now that the pass uses PassOptions
instead.

These were missed when the opts were replaced, and are unused.
2020-04-08 13:24:09 -07:00
River Riddle 400ad6f95d [mlir] Eliminate the remaining usages of cl::opt instead of PassOption.
Summary: Pass options are a better choice for various reasons and avoid the need for static constructors.

Differential Revision: https://reviews.llvm.org/D77707
2020-04-08 13:05:08 -07:00
Uday Bondhugula ae8ebeca51 [MLIR] Fix test case typos in unroll.mlir
Fix check line typos in test/Dialect/Affine/unroll.mlir.

Differential Revision: https://reviews.llvm.org/D77738
2020-04-08 22:21:07 +05:30
Andy Davis 7006daa548 [MLIR][Vector] Update ShapeCastOp folder to use producer-consumer value forwarding.
Summary:
Update ShapeCastOp folder to use producer-consumer value forwarding.
Support is added for tracking sub-vectors through trivial shape cast operations,
where the sub-vector shape is preserved across shape cast operations and only
leading ones are added or removed.
Support is preserved for cancelling shape cast operations.
One unit test is added and two are updated.

Reviewers: aartbik, nicolasvasilache

Reviewed By: aartbik, nicolasvasilache

Subscribers: frgossen, mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, grosul1, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D77253
2020-04-08 08:55:37 -07:00
Uday Bondhugula 3156b5422e [MLIR] Fix more gcc-5 build issues from D77528
820c420d4e1c630b5ead285917c6ecdd2f5092ad did not really fix all build
issues by D77528. This gets rid of two unnecessary 'using' declarations.

Differential Revision: https://reviews.llvm.org/D77726
2020-04-08 19:21:50 +05:30
Uday Bondhugula a59008a3a5 [MLIR] Fix gcc-5 build failure cause by D77528
Fix gcc-5 build failure cause by D77528

Differential Revision: https://reviews.llvm.org/D77719
2020-04-08 17:27:12 +05:30
Uday Bondhugula 01d97a3549 [MLIR] Add support to use aligned_alloc to lower AllocOp from std to llvm
Support to recognize and deal with aligned_alloc was recently added to
LLVM's TLI/MemoryBuiltins and its various optimization passes. This
revision adds support for generation of aligned_alloc's when lowering
AllocOp from std to LLVM. Setting 'use-aligned_alloc=1' will lead to
aligned_alloc being used for all heap allocations. An alignment and size
that works with the constraints of aligned_alloc is chosen.

Using aligned_alloc is preferable to "using malloc and adjusting the
allocated pointer to align for indexing" because the pointer access
arithmetic done for the latter only makes it harder for LLVM passes to
deal with for analysis, optimization, attribute deduction, and rewrites.

Differential Revision: https://reviews.llvm.org/D77528
2020-04-08 15:10:19 +05:30
Christian Sigg 06ddb7946b [MLIR] Add missing colon after CHECKs.
Reviewers: herhut

Reviewed By: herhut

Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, grosul1, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D77709
2020-04-08 11:16:06 +02:00
Nicolas Vasilache 3cb1f35df2 [mlir][Linalg] Use subview instead of linalg.slice in Promotion.cpp
This revision removes the reliance of Promotion on `linalg.slice` which is meant
for the rank-reducing case.

Differential Revision: https://reviews.llvm.org/D77676
2020-04-07 23:52:31 -04:00
Lukas Sommer d86ece13d9 Keep output file after successful execution of mlir-opt
Invoke `keep()` on the output file of `mlir-opt` in case the invocation of `MlirOptMain` was successful, to make sure the output file is not deleted on exit from `mlir-opt`.
Fixes a similar problem in `standalone-opt` from the example for an out-of-tree, standalone MLIR dialect.

This revision also adds a missing parameter to the invocation of `MlirOptMain` in `standalone-opt`.

Differential Revision: https://reviews.llvm.org/D77643
2020-04-08 03:37:45 +00:00
River Riddle 8b7e669e68 [mlir][AsmFormat] Avoid invalidating the iterator when verifying attributes
Summary: 'it' may get invalidated when recursing into optional groups. This revision refactors the inner loop to avoid the need to compare the iterator after invalidation.

Differential Revision: https://reviews.llvm.org/D77686
2020-04-07 15:54:56 -07:00
Stephen Neuendorffer 19fec004e2 [MLIR] Add note for file-line numbers in tablegen errors for assembly formats
Error messages for the custom assembly format are difficult to understand
because there are no line numbers.  This happens because the assembly format
is parsed as a standalone line, separate from it's parent file, with no useful
location information.  Fixing this properly probably requires quite a bit
of invasive plumbing through the SourceMgr, similar to how included files
are handled

This proposal is a less invasive short term solution.  When generating an
error message we generate an additional note which at least properly describes
the operation definition the error occured in, if not the actual line number
of the assemblyFormat definition.

A typical message is like:

error: type of operand #0, named 'operand', is not buildable and a buildable type cannot be inferred
  $operand type($result) attr-dict
  ^
/src/llvm-project/mlir/test/mlir-tblgen/op-format-spec.td:296:1: note: in custom assembly format for this operation
def ZCoverageInvalidC : TestFormat_Op<"variable_invalid_c", [{
^
note: suggest adding a type constraint to the operation or adding a 'type($operand)' directive to the custom assembly format
  $operand type($result) attr-dict
  ^

Differential Revision: https://reviews.llvm.org/D77488
2020-04-07 15:06:51 -07:00
Stephen Neuendorffer 75f60c698f [MLIR] Cleanup mlir-tblgen error messages for custom assembly formats.
The messages are somewhat cryptic, since they are not complete sentences,
include lots of ambiguous words, like 'format' which are hard to parse,
and include names from the users code which may, or may not make sense in
the context of the message.  Start to clean this up and provide some
guidance for fixes.

Also, add a test for one of the messages which didn't have a test at all.

Differential Revision: https://reviews.llvm.org/D77449
2020-04-07 15:06:50 -07:00
River Riddle 5fee925beb [mlir][Pass] Update the documentation for the declarative pass specification
The pass tablegen backend now generates base classes instead of utilities, so this revision updates the documentation to reflect that.
2020-04-07 14:21:32 -07:00
River Riddle 1834ad4a69 [mlir][Pass] Update the PassGen to generate base classes instead of utilities
Summary:
This is much cleaner, and fits the same structure as many other tablegen backends. This was not done originally as the CRTP in the pass classes made it overly verbose/complex.

Differential Revision: https://reviews.llvm.org/D77367
2020-04-07 14:08:52 -07:00
River Riddle 80aca1eaf7 [mlir][Pass] Remove the use of CRTP from the Pass classes
This revision removes all of the CRTP from the pass hierarchy in preparation for using the tablegen backend instead. This creates a much cleaner interface in the C++ code, and naturally fits with the rest of the infrastructure. A new utility class, PassWrapper, is added to replicate the existing behavior for passes not suitable for using the tablegen backend.

Differential Revision: https://reviews.llvm.org/D77350
2020-04-07 14:08:52 -07:00
River Riddle 722f909f7a [mlir][Pass][NFC] Replace usages of ModulePass with OperationPass<ModuleOp>
ModulePass doesn't provide any special utilities and thus doesn't give enough benefit to warrant a special pass class. This revision replaces all usages with the more general OperationPass.

Differential Revision: https://reviews.llvm.org/D77339
2020-04-07 14:08:52 -07:00
Jacques Pienaar 3f7439b280 [mlir][DRR] Add location directive
Summary:
Add directive to indicate the location to give to op being created. This
directive is optional and if unused the location will still be the fused
location of all source operations.

Currently this directive only works with other op locations, reusing an
existing op location or a fusion of op locations. But doesn't yet support
supplying metadata for the FusedLoc.

Based off initial revision by antiagainst@ and effectively mirrors GlobalIsel
debug_locations directive.

Differential Revision: https://reviews.llvm.org/D77649
2020-04-07 13:38:25 -07:00
Stella Laurenzo f5deb0878d Remove FxpMathOps dialect and Quantizer tool.
Summary:
* Removal of FxpMathOps was discussed on the mailing list.
* Will send a courtesy note about also removing the Quantizer (which had some dependencies on FxpMathOps).
* These were only ever used for experimental purposes and we know how to get them back from history as needed.
* There is a new proposal for more generalized quantization tooling, so moving these older experiments out of the way helps clean things up.

Subscribers: mgorny, mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, grosul1, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D77479
2020-04-07 13:22:39 -07:00
River Riddle c0a33aaa80 [mlir][Diagnostic] Don't store Operation arguments as a DiagnosticArgument
Summary: Diagnostics may be cached in the parallel diagnostic handler to preserve proper ordering. Storing the Operation as a DiagnosticArgument is problematic as the operation may be erased or changed before it finally gets printed.

Differential Revision: https://reviews.llvm.org/D77675
2020-04-07 12:49:06 -07:00
Lei Zhang 47b234944d [mlir][spirv] Fix wrong Phi parent block for back-to-back loops
If we have two back-to-back loops with block arguments, the OpPhi
instructions generated for the second loop's block arguments should
have use the merge block of the first SPIR-V loop structure as
their incoming parent block.

Differential Revision: https://reviews.llvm.org/D77543
2020-04-07 12:54:54 -04:00
Lei Zhang 2d3eb493d4 [mlir][vulkan-runner] Fix createLowerToLLVMPass interface
createLowerToLLVMPass() now requires a struct for passing in arguments
after 7023f4b4cb.
2020-04-07 12:54:54 -04:00
Uday Bondhugula 7023f4b4cb [MLIR] Introduce std.alloca op
Introduce the alloca op for stack memory allocation. When converting to the
LLVM dialect, this is lowered to an llvm.alloca. Refactor the std to
llvm conversion for alloc op to reuse with alloca. Drop useAlloca option
with alloc op lowering.

Differential Revision: https://reviews.llvm.org/D76602
2020-04-07 15:45:07 +05:30
Uday Bondhugula 70da33bf30 [MLIR] fix/update affine data copy utility for max/min bounds
Fix point-wise copy generation to work with bounds that have max/min.
Change structure of copy loop nest to use absolute loop indices and
subtracting base from the indexes of the fast buffers. Update supporting
utilities: Fix FlatAffineConstraints::getLowerAndUpperBound to look at
equalities as well and for a missing division. Update unionBoundingBox
to not discard common constraints (leads to a tighter system). Update
MemRefRegion::getConstantBoundingSizeAndShape to add memref dimension
constraints. Run removeTrivialRedundancy at the end of
MemRefRegion::compute.  Run single iteration loop promotion and
load/store canonicalization after affine data copy (in its test pass as
well).

Differential Revision: https://reviews.llvm.org/D77320
2020-04-07 13:55:42 +05:30
Eli Friedman 68b03aee1a Remove SequentialType from the type heirarchy.
Now that we have scalable vectors, there's a distinction that isn't
getting captured in the original SequentialType: some vectors don't have
a known element count, so counting the number of elements doesn't make
sense.

In some cases, there's a better way to express the commonality using
other methods. If we're dealing with GEPs, there's GEP methods; if we're
dealing with a ConstantDataSequential, we can query its element type
directly.

In the relatively few remaining cases, I just decided to write out
the type checks. We're talking about relatively few places, and I think
the abstraction doesn't really carry its weight. (See thread "[RFC]
Refactor class hierarchy of VectorType in the IR" on llvmdev.)

Differential Revision: https://reviews.llvm.org/D75661
2020-04-06 17:03:49 -07:00
Jacques Pienaar d3a31c4db4 Remove case in rewritergen unmatched opdefgen side
The rewriter generates a call to build that is not handled by opdef generator
and so will fail to compile. Also if this is a root node being replaced
(depth 0) then using the more generic build method in the rewrite suffices.
2020-04-06 16:03:49 -07:00
Chris Lattner 8ba7a2d5df Minor typo improvements in documentation, NFC. 2020-04-06 13:18:49 -07:00
River Riddle ae9edbcea2 [mlir][AsmPrinter] Change value numbering for local scope to be the next isolated operation.
Summary: This revision updates the value numbering when printing to number from the next parent operation that is isolated from above. This is the highest level to number from that still ensures thread-safety. This revision also changes the behavior of Operator::operator<< to use local scope to avoid thread races when numbering operations.

Differential Revision: https://reviews.llvm.org/D77525
2020-04-06 11:09:29 -07:00
Jean-Michel Gorius d3df2da4a9 [mlir] Fix typo in docs/DefiningAttributesAndTypes.md 2020-04-06 19:38:34 +02:00
Nicolas Vasilache 8f229989d5 [mlir][Linalg] Add a linalg.tensor_reshape to operate on tensors
Summary:
This revision adds a tensor_reshape operation that operates on tensors.
In the tensor world the constraints are less stringent and we can allow more
arbitrary dynamic reshapes, as long as they are contractions.

The expansion of a dynamic dimension into multiple dynamic dimensions is under-specified and is punted on for now.

Differential Revision: https://reviews.llvm.org/D77360
2020-04-06 11:19:17 -04:00
Djordje Todorovic da5fe23e84 [mlir][LowerToAffineLoops] Handle tensors of rank 0
This will fix the case:

  $ toyc -emit=jit test.toy
  $ cat test.toy
  def main() {
    var a = 1;
    print(a);
  }

Without this patch it would trigger an assertion.

Differential Revision: https://reviews.llvm.org/D77464
2020-04-06 14:51:03 +02:00
Alexander Belyaev c2d03e4ef1 [MLIR] Change return type of ParallelOp::getInductionVars to ValueRange.
The current return type sometimes leads to code like
to_vector<2>(ValueRange(loop.getInductionIvs())). It would be nice to
shorten it. Users who need access to Block::BlockArgListType (if there
are any), can always call getBody()->getArguments(); if needed.

Also remove getNumInductionVars(), since there is getNumLoops().

Differential Revision: https://reviews.llvm.org/D77526
2020-04-06 10:11:02 +02:00
Lei Zhang 322c235a52 [mlir][spirv] NFC: remove uncessary return after llvm_unreachable 2020-04-05 20:00:56 -04:00
River Riddle 74d44c43e8 [mlir] Refactor and cleanup the translation facilities.
Summary:
This revision performs several cleanups on the translation infra:
* Removes the TranslateCLParser library and consolidates into Translation
  - This was a weird library that existed in Support, and didn't really justify being a standalone library.
* Cleans up the internal registration and consolidates all of the translation functions within one registry.

Differential Revision: https://reviews.llvm.org/D77514
2020-04-05 16:21:21 -07:00
River Riddle c9da04d660 [mlir] Only number the parent operation in Block::printAsOperand
Summary: Blocks are numbered locally within a region, so numbering above the parent region is unnecessary.

Differential Revision: https://reviews.llvm.org/D77510
2020-04-05 16:17:13 -07:00
Uday Bondhugula 34392b518f [MLIR][NFC] Make AsmPrinter messages on null structures consistent
Make AsmPrinter messages on null structures consistent: use <<NULL ...>>.

Differential Revision: https://reviews.llvm.org/D77509
2020-04-06 01:14:36 +05:30
River Riddle 8d0bc03482 [mlir] Update the documentation on Canonicalization
Summary: This updates the canonicalization documentation, and properly documents the different ways of canonicalizing operations.

Differential Revision: https://reviews.llvm.org/D77490
2020-04-05 12:12:25 -07:00
River Riddle c7b83a4fe5 [mlir][Pass] Add documentation for the declarative pass specification
Summary:
This revision adds a section to WritingAPass to document the declarative specification, and how to use it.

Differential Revision: https://reviews.llvm.org/D77102
2020-04-05 11:52:00 -07:00
Mehdi Amini 96eb38418b Make the AsmPrinter print "<<NULL TYPE>>" instead of crashing on null types
Even if this indicates in general a problem at call sites, the printer
is used for debugging and avoiding crashing is friendlier for example
when used in diagnostics or other printer.

Differential Revision: https://reviews.llvm.org/D77481
2020-04-05 18:36:18 +00:00
Uday Bondhugula 3f9cdd44d7 [MLIR] Add pattern rewriter util to erase block; remove dead else
Add a pattern rewriter utility to erase blocks (while notifying the
pattern rewriting driver of the erased ops). Use this to remove trivial
else blocks in affine.if ops.

Differential Revision: https://reviews.llvm.org/D77083
2020-04-05 19:24:43 +05:30
Uday Bondhugula cc6738949d [MLIR][NFC] fix name operand -> userOp
The wrong name was confusing to read. value.getUsers() yields
Operation *s.

Differential Revision: https://reviews.llvm.org/D77486
2020-04-05 19:17:15 +05:30
Uday Bondhugula f875e55ba9 [MLIR] fix greedy pattern rewrite driver iteration on change
Removing dead ops should make the outer loop of the pattern rewriting
driver run again. Although its operands are added to the worklist, if no
changes happenned to them or remaining ops in the worklist, the driver
wouldn't run once again - but it should be.

Differential Revision: https://reviews.llvm.org/D77483
2020-04-05 19:15:46 +05:30
Alexander Belyaev 51e3709c2b [MLIR] Don't insert YieldOp for non-void loop.for by default.
The ForOp::build ensures that there is a block terminator which is great for
the default use case when there are no iter_args and loop.for returns no
results.  In non-zero results case we always need to call replaceOpWithNewOp
which is not the nicest thing in the world. We can stop inserting YieldOp when
iter_args is non-empty. IfOp::build already behaves similarly.
2020-04-05 11:48:22 +02:00
River Riddle 0359b86d8b [mlir][ODS] Add support for variadic regions.
Summary: This revision adds support for marking the last region as variadic in the ODS region list with the VariadicRegion directive.

Differential Revision: https://reviews.llvm.org/D77455
2020-04-05 01:03:38 -07:00
Kazuaki Ishizaki 5aacce3db2 [mlir] NFC: Fix trivial typo
Differential Revision: https://reviews.llvm.org/D77473
2020-04-05 11:30:30 +09:00
Jean-Michel Gorius 160f5aa65f [mlir] Add an out-of-tree dialect example
This adds a minimal out-of-tree dialect template which can be used to start work on a standalone dialect implementation without having to integrate it in the main LLVM tree.

It mostly sets up the directory structure and provides CMakeLists.txt files to build a dialect library, an opt-like tool to operate on that dialect as well as tests. It could be expanded in the future to add examples of more user-defined operations, types, attributes, generated enums, transforms, etc. and linked to a tutorial.

Differential Revision: https://reviews.llvm.org/D77133
2020-04-04 17:16:43 +00:00
Frederik Gossen 1a2370bfb8 [MLIR] Fix shape inference in toy tutorial
The implementation of shape inference in the toy tutorial did not conform to the correct algorithmic description.
The result was only correct because all operations appear to be processed in sequence.

Differential Revision: https://reviews.llvm.org/D77382
2020-04-04 04:34:21 +00:00
Frederik Gossen 0f37454c72 Fix typos in toy tutorial
Fix two typos throughout the chapters.

Differential Revision: https://reviews.llvm.org/D77397
2020-04-04 03:17:24 +00:00
River Riddle e3bb36370d [mlir][DeclarativeParser] Emit an error if a `:` follows an attribute with a non-constant type.
Summary: The attribute grammar includes an optional trailing colon type, so for attributes without a constant buildable type this will generally lead to unexpected and undesired behavior. Given that, it's better to just error out on these cases.

Differential Revision: https://reviews.llvm.org/D77293
2020-04-03 19:23:56 -07:00
River Riddle 79afdfab9a [mlir] Change the default of `mlir-print-op-on-diagnostic` to true
Summary: It is a very common user trap to think that the location printed along with the diagnostic is the same as the current operation that caused the error. This revision changes the behavior to always print the current operation, except for when diagnostics are being verified. This is achieved by moving the command line flags in IR/ to be options on the MLIRContext.

Differential Revision: https://reviews.llvm.org/D77095
2020-04-03 19:02:51 -07:00
Alex Zinenko 340e1b2077 [mlir] LoopToStandard conversion: support "if/else" with results
Summary:
A recent extension allowed the `loop.if` operation to return results yielded by
its regions. However, such operations could not be lowered to a CFG of standard
operations because it would have required to modify the argument list of a
block, which is not allowed in a conversion pattern. Now that the conversion
infrastructure supports block creation, use it to create a block with an
argument list that dominates the operations following the `loop.if` and forward
the results as arguments of this block.

Depends On D77416

Differential Revision: https://reviews.llvm.org/D77418
2020-04-03 23:49:03 +02:00
Nicolas Vasilache e33a636e26 [mlir][Linalg] Employ finer-grained control of C interface emission
Summary:
Linalg makes it possible to interface codegen with externally precompiled HPC libraries. The mechanism to allow such interop uses a normalized ABI and the emission of C interface wrappers.

The mechanism controlling these C interface emission is too aggressive and makes it very easy to obtained undefined symbols for external function (e.g. the ones coming from libm).

This revision uses the newly introduced llvm.emit_c_interface function attribute which allows controlling this behavior at a function granularity. As a consequence LinalgToLLVM does not need to activate the C wrapper emission when adding the StdToLLVM patterns.

Differential Revision: https://reviews.llvm.org/D77364
2020-04-03 16:14:53 -04:00
Alex Zinenko f27f1e8c27 [mlir] DialectConversion: support block creation in ConversionPatternRewriter
PatternRewriter and derived classes provide a set of virtual methods to
manipulate blocks, which ConversionPatternRewriter overrides to keep track of
the manipulations and undo them in case the conversion fails. However, one can
currently create a block only by splitting another block into two. This not
only makes the API inconsistent (`splitBlock` is allowed in conversion
patterns, but `createBlock` is not), but it also make it impossible for one to
create blocks with argument lists different from those of already existing
blocks since in-place block updates are not supported either. Such
functionality precludes dialect conversion infrastructure from being used more
extensively on region-containing ops, for example, for value-returning "if"
operations. At the same time, ConversionPatternRewriter already allows one to
undo block creation as block creation is one of the primitive operations in
already supported region inlining.

Support block creation in conversion patterns by hooking `createBlock` on the
block action undo mechanism. This requires to make `Builder::createBlock`
virtual, similarly to Op insertion. This is a minimal change to the Builder
infrastructure that will later help support additional use cases such as block
signature changes. `createBlock` now additionally takes the types of the block
arguments that are added immediately so as to avoid in-place argument list
manipulation that would be illegal in conversion patterns.
2020-04-03 20:30:03 +02:00
Stephen Neuendorffer 0c0831f74b [CMAKE] Plumb include_directories() into tablegen()
Previously, the tablegen() cmake command, which defines custom
commands for running tablegen, included several hardcoded paths.  This
becomes unwieldy as there are more users for which these paths are
insufficient.  For most targets, cmake uses include_directories() and
the INCLUDE_DIRECTORIES directory property to specify include paths.
This change picks up the INCLUDE_DIRECTORIES property and adds it
to the include path used when running tablegen.  As a side effect, this
allows us to remove several hard coded paths to tablegen that are redundant
with specified include_directories().

I haven't removed the hardcoded path to CMAKE_CURRENT_SOURCE_DIR, which
seems generically useful.  There are several users in clang which apparently
don't have the current directory as an include_directories().  This could
be considered separately.

The new version of this path uses list APPEND rather than list TRANSFORM,
in order to be compatible with cmake 3.4.3. If we update to cmake 3.12 then
we can use list TRANSFORM instead.

Differential Revision: https://reviews.llvm.org/D77156
2020-04-03 11:23:38 -07:00
Stephen Neuendorffer f288c21687 Revert "[CMAKE] Plumb include_directories() into tablegen()"
This reverts commit ae044c5b0c.

This breaks the buildbots, which use an older version of cmake.
2020-04-03 10:47:36 -07:00
Stephen Neuendorffer ae044c5b0c [CMAKE] Plumb include_directories() into tablegen()
Previously, the tablegen() cmake command, which defines custom
commands for running tablegen, included several hardcoded paths.  This
becomes unwieldy as there are more users for which these paths are
insufficient.  For most targets, cmake uses include_directories() and
the INCLUDE_DIRECTORIES directory property to specify include paths.
This change picks up the INCLUDE_DIRECTORIES property and adds it
to the include path used when running tablegen.  As a side effect, this
allows us to remove several hard coded paths to tablegen that are redundant
with specified include_directories().

I haven't removed the hardcoded path to CMAKE_CURRENT_SOURCE_DIR, which
seems generically useful.  There are several users in clang which apparently
don't have the current directory as an include_directories().  This could
be considered separately.

Differential Revision: https://reviews.llvm.org/D77156
2020-04-03 10:38:25 -07:00
Benjamin Kramer 71305033d1 [LoopOps] Return ArrayRefs from accessors instead of iterator_ranges
Same funcitonality, but a bit friendlier for users passing it along to
APIs that take ArrayRefs.
2020-04-03 17:13:22 +02:00
Denis Khalikov 0718e3ae31 [mlir][vulkan-runner] Add support for 3D memrefs.
Summary:
Add support for 3D memrefs in mlir-vulkan-runner and simple test.

Differential Revision: https://reviews.llvm.org/D77157
2020-04-03 15:10:40 +03:00
Benjamin Kramer 02cb21df3f Make helpers static. NFC. 2020-04-03 12:48:25 +02:00
Alex Grosul 3a5192098c [mlir][VectorOps] Implement canonicalization for TransposeOp.
Two back-to-back transpose operations are combined into a single transpose, which uses a combination of their permutation vectors.

Differential Revision: https://reviews.llvm.org/D77331
2020-04-02 18:36:40 -07:00
Nicolas Vasilache aef0877b1b [mlir][Linalg] NFC - Rename Linalg and Vector EDSCs to avoid collisions
A certain number of EDSCs have a named form (e.g. `linalg.matmul`) and a generic form (e.g. `linalg.generic` with matmul traits).
Despite living in different namespaces, using the same name is confusiong in clients.
Rename them as `linalg_matmul` and `linalg_generic_matmul` respectively.
2020-04-02 21:09:49 -04:00
Mehdi Amini ee4d034277 Change pass registration generated code to allow users to selectively register passes
This slightly tweaks the generated code from:

  #ifdef GEN_PASS_REGISTRATION
  ::mlir::registerPass("flag1", ...
  ::mlir::registerPass("flag2", ...
  #endif // GEN_PASS_REGISTRATION

to:

  #ifdef GEN_PASS_REGISTRATION
  #define GEN_PASS_REGISTRATION_Pass1
  #define GEN_PASS_REGISTRATION_Pass2
  #endif // GEN_PASS_REGISTRATION

  #ifdef GEN_PASS_REGISTRATION_Pass1
  ::mlir::registerPass("flag1", ...
  #endif
  #ifdef GEN_PASS_REGISTRATION_Pass1
  ::mlir::registerPass("flag2", ...
  #endif

That way the generated code can be included by defining the
`GEN_PASS_REGISTRATION` macro as currenty and register all the passes,
but one can also define only `GEN_PASS_REGISTRATION_Pass1` to register a
subset of the passes.

Differential Revision: https://reviews.llvm.org/D77322
2020-04-02 18:58:47 +00:00
Nicolas Vasilache add9f1a5dc [mlir][LLVM] Finer-grained control for C interface emission
C interface emission is controlled by a flag and has coarse granularity.
With this coarse control, interfaces are emitted for all external functions.
This makes is easy to get undefined symbols.

This revision adds support for controlling per-function emission with an "emit_c_interface" attribute.
2020-04-02 13:07:10 -04:00
Alex Zinenko 802bb8b5c2 [mlir] StandardToLLVM conversion: remove dead code
This code is unused since 04ed07bc17,
but it was not removed in that commit.
2020-04-02 18:52:40 +02:00
Alex Zinenko 0a2131b7e2 [mlir] LLVMFuncOp: provide a capability to pass attributes through to LLVM IR
Summary:
LLVM IR functions can have arbitrary attributes attached to them, some of which
affect may affect code transformations. Until we can model all attributes
consistently, provide a pass-through mechanism that forwards attributes from
the LLVMFuncOp in MLIR to LLVM IR functions during translation. This mechanism
relies on LLVM IR being able to recognize string representations of the
attributes and performs some additional checking to avoid hitting assertions
within LLVM code.

Differential Revision: https://reviews.llvm.org/D77072
2020-04-02 12:52:46 +02:00
Uday Bondhugula 7c771631c6 [MLIR][NFC] drop unnecessary matches in affine dma generate test case
Drop unnecessary matches in affine DMA generate test case.

Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, grosul1, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D77243
2020-04-02 03:02:07 +05:30
Uday Bondhugula 5e8093134a [MLIR] Add method to drop duplicate result exprs from AffineMap
Add a method that given an affine map returns another with just its unique
results. Use this to drop redundant bounds in max/min for affine.for. Update
affine.for's canonicalization pattern and createCanonicalizedForOp to use
this.

Differential Revision: https://reviews.llvm.org/D77237
2020-04-02 03:00:19 +05:30
River Riddle 8bf1583b71 [mlir] Move LLVMPassIncGen to LLVMIR/Transforms/CMakeLists.txt
This fixes a build error with the make generator for a missing
sub-directory.
2020-04-01 14:10:05 -07:00
Nicolas Vasilache c4c20376f7 [mlir][Linalg][Doc] Minor doc fixes 2020-04-01 13:41:45 -04:00
Mehdi Amini b8c260c38d Remove linking all targets from `mlir-opt` (NFC)
There is no need to directly depends on this from mlir-opt, some library
may transitively depend on a subset of the targets when enabled (like
NVPTX for Cuda codegen tests) but this is handled by CMake already.
2020-04-01 17:21:07 +00:00
Mehdi Amini 0dd21130ef Add LLVM_ATTRIBUTE_UNUSED to function used only in assert (NFC) 2020-04-01 17:21:07 +00:00
Uday Bondhugula 572890f1d3 [MLIR][NFC] clean up affine data copy test case
Capture maps to test better; drop unnecessary matches

Differential Revision: https://reviews.llvm.org/D77196
2020-04-01 22:37:49 +05:30
Uday Bondhugula 68316afb29 [MLIR][NFC] loop transforms/analyis utils cleanup / modernize
Modernize/cleanup code in loop transforms utils - a lot of this code was
written prior to the currently available IR support / code style. This
patch also does some variable renames including inst -> op, comment
updates, turns getCleanupLoopLowerBound into a local function.

Differential Revision: https://reviews.llvm.org/D77175
2020-04-01 22:36:25 +05:30
MaheshRavishankar 9b31e595d7 [mlir] Modify GPU to SPIR-V conversion to respect
spv.interface_var_abi attributes if it exists already.

Differential Revision: https://reviews.llvm.org/D77195
2020-04-01 09:34:49 -07:00
Tres Popp a67cd71acd [MLIR] Implement LoopLikeInterface for loop.parallel
Summary:
This is to allow optimizations like loop invariant code motion to work
on the ParallelOp.

Additional small cleanup on the ForOp implementation of
LoopLikeInterface and the test file of loop-invariant-code-motion.

Differential Revision: https://reviews.llvm.org/D77128
2020-04-01 16:47:57 +02:00
River Riddle 9be4be3e53 [mlir][Pass] Add support for generating pass documention from the tablegen definition
Summary:
This revision adds support for auto-generating pass documentation, replacing the need to manually keep Passes.md up-to-date. This matches the behavior already in place for dialect and interface documentation.

Differential Revision: https://reviews.llvm.org/D76660
2020-04-01 02:10:46 -07:00
River Riddle 9a277af2d4 [mlir][Pass] Add support for generating pass utilities via tablegen
This revision adds support for generating utilities for passes such as options/statistics/etc. that can be inferred from the tablegen definition. This removes additional boilerplate from the pass, and also makes it easier to remove the reliance on the pass registry to provide certain things(e.g. the pass argument).

Differential Revision: https://reviews.llvm.org/D76659
2020-04-01 02:10:46 -07:00
River Riddle 3dddd8969f [mlir][Pass] Move the registration of conversion passes to tablegen
This removes the need to statically register conversion passes, and also puts all of the conversions within one centralized file.

Differential Revision: https://reviews.llvm.org/D76658
2020-04-01 02:10:46 -07:00
River Riddle e3d834a54a [mlir][Pass] Move the registration of dialect passes to tablegen
This generates a Passes.td for all of the dialects that have transformation passes. This removes the need for global registration for all of the dialect passes.

Differential Revision: https://reviews.llvm.org/D76657
2020-04-01 02:10:46 -07:00
River Riddle 8155e41ac6 [mlir][Pass] Add a tablegen backend for defining Pass information
This will greatly simplify a number of things related to passes:
* Enables generation of pass registration
* Enables generation of boiler plate pass utilities
* Enables generation of pass documentation

This revision focuses on adding the basic structure and adds support for generating the registration for passes in the Transforms/ directory. Future revisions will add more support and move more passes over.

Differential Revision: https://reviews.llvm.org/D76656
2020-04-01 02:10:46 -07:00
Ulysse Beaugnon 49af380942 Add a method to build affine maps with zero or more results.
Summary:
The commit provides a single method to build affine maps with zero or more
results. Users of mlir::AffineMap previously had to dispatch between two methods
depending on the number of results.

At the same time, this commit fixes the method for building affine map with zero
results that was previously ignoring its `symbolCount` argument.

Differential Revision: https://reviews.llvm.org/D77126
2020-04-01 10:47:18 +02:00
Tres Popp 90b7bbffdd [MLIR] Rename collapsePLoops -> collapseParallelLoops
Summary:
Additionally, NFC code cleanups were done.

This is to address additional comments on
https://reviews.llvm.org/D76363

Differential Revision: https://reviews.llvm.org/D77052
2020-04-01 10:15:13 +02:00
Tres Popp 61bab7c31a [MLIR] Replace OpBuilder(Block) with atBlockBegin and atBlockEnd
Summary:
OpBuilder(Block) is specifically replaced with
OpBuilder::atBlockEnd(Block);

This is to make insertion behavior clear due to there being no one
correct answer for which location in a block the default insertion
point should be.

Differential Revision: https://reviews.llvm.org/D77060
2020-04-01 10:06:41 +02:00
Hanhan Wang 6dd696ae4f [mlir][Linalg] Extend fusion to support WAW atm on buffers.
Summary:
The RAW fusion happens only if the produecer block dominates the consumer block.
The WAW pattern also works with the precondition. I.e., if a producer can
dominate the consumer, they can fairly fuse together.

Since they are all tilable, we can think the pattern like this way:

Input:
```
linalg_op1 view

tile_loop
  subview_2
  linalg_op2 subview_2
```

Tile the first Linalg op as same as the second Linalg.
```
tile_loop
  subview_1
  linalg_op1 subview_1

tile_loop
  subview_2
  liangl_op2 subview_2
```

Since the first Linalg op is tilable in the same way and the computation are
independently, it's fair to fuse it with the second Linalg op.
```
tile_loop
  subview_1
  linalg_op1 subview_1
  linalg_op2 subview_2
```

In short, this patch includes:
- Handling both RAW and WAW pattern.
- Adding a interface method to get input and output buffers.
- Exposing a method to get a StringRef of a dependency type.
- Fixing existing WAW tests and add one more use case: initialize the buffer
  before conv op.

Differential Revision: https://reviews.llvm.org/D76897
2020-03-31 21:33:50 -07:00
Hanhan Wang 69ddee1d2a [mlir][Linalg] Introduce linalg.pooling_min/max/sum op.
Summary:
Performs an N-D pooling operation similarly to the description in the TF
documentation:
https://www.tensorflow.org/api_docs/python/tf/nn/pool

Different from the description, this operation doesn't perform on batch and
channel. It only takes tensors of rank `N`.

```
  output[x[0], ..., x[N-1]] =
    REDUCE_{z[0], ..., z[N-1]}
      input[
            x[0] * strides[0] - pad_before[0] + dilation_rate[0]*z[0],
            ...
            x[N-1]*strides[N-1] - pad_before[N-1] + dilation_rate[N-1]*z[N-1]
            ],
```

The required optional arguments are:
  - strides: an i64 array specifying the stride (i.e. step) for window
    loops.
  - dilations: an i64 array specifying the filter upsampling/input
    downsampling rate
  - padding: an i64 array of pairs (low, high) specifying the number of
    elements to pad along a dimension.

If strides or dilations attributes are missing then the default value is
one for each of the input dimensions. Similarly, padding values are zero
for both low and high in each of the dimensions, if not specified.

Differential Revision: https://reviews.llvm.org/D76414
2020-03-31 21:21:54 -07:00
Alex Grosul 855e738be2 [VectorOps] Implement a simple folder for identity vector.transpose operations.
Differential Revision: https://reviews.llvm.org/D77088
2020-03-31 17:03:10 -07:00
Lei Zhang ee77607ca6 [mlir][spirv] Include SPIR-V op definitions in main SPIR-V doc
Differential Revision: https://reviews.llvm.org/D77174
2020-03-31 18:29:17 -04:00
Uday Bondhugula e1fb9d5372 [MLIR][NFC] modernize affine.for unroll test pass
The walk code here was written before any of the support was
available in IR/. Replace/cleanup.

Differential Revision: https://reviews.llvm.org/D77166
2020-04-01 02:22:28 +05:30
Lei Zhang d26435c170 [mlir][spirv] Change op doc description autogen separator
This commit changes the separator line for dividing auto-generated
docs from spec and manually added appendix from "### Custom assembly
form" to "<!-- End of AutoGen section -->". This is in preparation
to use the declarative assembly form in MLIR core. We will replace
more and more manually written assembly forms to be autogenerated.

Differential Revision: https://reviews.llvm.org/D77158
2020-03-31 15:28:06 -04:00
Uday Bondhugula 5f9bf3f656 [MLIR][NFC] Move test/Transforms/lower-affine.mlir -> test/Conversion
Move lower-affine.mlir from test/Transforms to
test/Conversion/AffineToStandard/. Other related NFC.

Signed-off-by: Uday Bondhugula <uday@polymagelabs.com>

Differential Revision: https://reviews.llvm.org/D77008
2020-03-31 23:34:50 +05:30
Uday Bondhugula 7fca0e9797 [MLIR] Add simple runner utilities for timing
Add utilities print_flops, rtclock for timing / benchmarking. Add
mlir_runner_utils_dir test conf variable.

Signed-off-by: Uday Bondhugula <uday@polymagelabs.com>

Differential Revision: https://reviews.llvm.org/D76912
2020-03-31 23:08:29 +05:30
MaheshRavishankar da7b6fe942 [mlir][Linalg] Allow tiling of batch dimension for convolution ops with padding.
Existing tiling implementation of Linalg would still work for tiling
the batch dimensions of the convolution op.

Differential Revision: https://reviews.llvm.org/D76637
2020-03-31 09:22:38 -07:00
Andy Davis 31a346cc35 [MLIR][Vector] Add support for TupleGetOp folding through InsertSlicesOp and ExtractSlicesOp.
Summary:
Add support for TupleGetOp folding through InsertSlicesOp and ExtractSlicesOp.
Vector-to-vector transformations for unrolling and lowering to hardware vectors
can generate chains of structured vector operations (InsertSlicesOp,
ExtractSlicesOp and ShapeCastOp) between the producer of a hardware vector
value and its consumer. Because InsertSlicesOp, ExtractSlicesOp and ShapeCastOp
are structured, we can track the location (tuple index and vector offsets) of
the consumer vector value through the chain of structured operations to the
producer, enabling a much more powerful producer-consumer fowarding of values
through structured ops and tuple, which in turn enables a more powerful
TupleGetOp folding transformation.

Reviewers: nicolasvasilache, aartbik

Reviewed By: aartbik

Subscribers: grosul1, mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D76889
2020-03-31 08:39:17 -07:00
Ahmed Taei 221fa96cd4 Fix linalg.generic access of hoisted constants
Summary: Otherwise the added @generic_const_int will fail

Reviewers: nicolasvasilache, rriddle, mravishankar

Subscribers: mehdi_amini, jpienaar, burmako, shauheen, antiagainst, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, grosul1, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D77109
2020-03-30 21:15:41 -07:00
Mehdi Amini 111c932855 Fix test: add `-allow-unregistered-dialect` to Affine/loop-permute.mlir test (missed during rebase) 2020-03-30 20:14:47 +00:00
Mehdi Amini bab5bcf8fd Add a flag on the context to protect against creation of operations in unregistered dialects
Differential Revision: https://reviews.llvm.org/D76903
2020-03-30 19:37:31 +00:00
River Riddle 01c857bc83 [mlir] Update all dialects docs to use 'dialect-namespace' in the header 2020-03-30 12:25:15 -07:00
Stella Laurenzo 0af6d27e2e Add /bigobj for SPIRV dialect on MSVC.
Summary: This object file has grown beyond the default limit, and elsewhere in LLVM, we seem to be setting this flag as a one-off, so continuing that here.

Reviewers: mravishankar, antiagainst

Subscribers: mgorny, mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, arpith-jacob, mgester, lucyrfox, liufengdb, Joonsoo, bader, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D77002
2020-03-30 12:00:00 -07:00
Uday Bondhugula f273e5c507 [MLIR] Fix permuteLoops utility
Rewrite mlir::permuteLoops (affine loop permutation utility) to fix
incorrect approach. Avoiding using sinkLoops entirely - use single move
approach. Add test pass.

This fixes https://bugs.llvm.org/show_bug.cgi?id=45328

Depends on D77003.

Signed-off-by: Uday Bondhugula <uday@polymagelabs.com>

Differential Revision: https://reviews.llvm.org/D77004
2020-03-30 23:38:23 +05:30
scentini 3b20970de8 Fix unused-variable error when assertions are disabled 2020-03-30 13:55:43 +02:00
Hanhan Wang 65c7031370 [mlir] Fix typos in DeclarativeRewrites.md
Differential Revision: https://reviews.llvm.org/D77040
2020-03-30 01:20:41 -07:00
River Riddle 16f27b70a5 [mlir][NFC] Update dialect/op documentation to be consistent
Summary:
This revision performs a lot of different cleanups on operation documentation to ensure that they are consistent, e.g. using mlir code blocks, formatting, etc.

This revision also includes the auto-generated documentation into the hand-written documentation for the dialects that have a specific top-level dialect file. This updates the documentation for all dialects aside from SPIRV and STD. These dialects will be updated in a followup.

Differential Revision: https://reviews.llvm.org/D76734
2020-03-29 22:02:23 -07:00
River Riddle f86104bb68 [mlir][NFC] Use the auto-generated op documentation in the standard dialect documentation
Summary: This revision updates the dialect documentation to use the auto-generated markdown for operations. This allows for updating some out-of-date bits of documentation, and allows for displaying a large of number of newly added operations that did not have a counter part in Standard.md.

Differential Revision: https://reviews.llvm.org/D76743
2020-03-29 21:53:40 -07:00
River Riddle 3d44f48edc [mlir][Diagnostics] Don't print note source line if it is the same as the previous diagnostic
Summary: This revision updates the SourceMgrDiagnosticHandler to not print the source location of a note if it is the same location as the previously printed diagnostic. This helps avoid redundancy, and potential confusion, when looking at the diagnostic output.

Differential Revision: https://reviews.llvm.org/D76787
2020-03-29 21:43:44 -07:00
Uday Bondhugula 4e4ea2cde4 [MLIR] Add missing asserts in interchangeLoops util, doc comment update
Add missing assert checks for input to mlir::interchangeLoops utility.
Rename interchangeLoops -> permuteLoops; update doc comments to clarify
inputs / return val. Other than the assert checks, this is NFC.

Signed-off-by: Uday Bondhugula <uday@polymagelabs.com>

Differential Revision: https://reviews.llvm.org/D77003
2020-03-30 00:03:12 +05:30
Kazuaki Ishizaki b632bd88a6 [mlir] NFC: fix trivial typo in documents
Reviewers: mravishankar, antiagainst, nicolasvasilache, herhut, aartbik, mehdi_amini, bondhugula

Reviewed By: mehdi_amini, bondhugula

Subscribers: bondhugula, jdoerfert, mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, csigg, arpith-jacob, mgester, lucyrfox, aartbik, liufengdb, Joonsoo, bader, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D76993
2020-03-30 00:34:23 +09:00
Aaron Smith 6dab806712 [mlir] Add exp2 conversion to llvm.intr.exp2 2020-03-29 01:23:08 -07:00
Mehdi Amini 9dd92a5697 Remove spurious duplicated header include (NFC) 2020-03-28 03:49:53 +00:00
Sean Silva 6677477190 Verify number of result types in generated builder.
Summary: This just bit me and is nasty to debug.

Differential Revision: https://reviews.llvm.org/D76888
2020-03-27 20:05:42 -07:00
Uday Bondhugula fec6c5ac5e [MLIR][NFC] Move TestDialect -> Dialect/Test
Move test/lib/TestDialect to test/lib/Dialect/Test - makes the dir
structure more uniform.

Signed-off-by: Uday Bondhugula <uday@polymagelabs.com>

Differential Revision: https://reviews.llvm.org/D76677
2020-03-28 07:12:55 +05:30
Uday Bondhugula 43a95a543f [MLIR] Introduce full/partial tile separation using if/else
This patch introduces a utility to separate full tiles from partial
tiles when tiling affine loop nests where trip counts are unknown or
where tile sizes don't divide trip counts. A conditional guard is
generated to separate out the full tile (with constant trip count loops)
into the then block of an 'affine.if' and the partial tile to the else
block. The separation allows the 'then' block (which has constant trip
count loops) to be optimized better subsequently: for eg. for
unroll-and-jam, register tiling, vectorization without leading to
cleanup code, or to offload to accelerators. Among techniques from the
literature, the if/else based separation leads to the most compact
cleanup code for multi-dimensional cases (because a single version is
used to model all partial tiles).

INPUT

  affine.for %i0 = 0 to %M {
    affine.for %i1 = 0 to %N {
      "foo"() : () -> ()
    }
  }

OUTPUT AFTER TILING W/O SEPARATION

  map0 = affine_map<(d0) -> (d0)>
  map1 = affine_map<(d0)[s0] -> (d0 + 32, s0)>

  affine.for %arg2 = 0 to %M step 32 {
    affine.for %arg3 = 0 to %N step 32 {
      affine.for %arg4 = #map0(%arg2) to min #map1(%arg2)[%M] {
        affine.for %arg5 = #map0(%arg3) to min #map1(%arg3)[%N] {
          "foo"() : () -> ()
        }
      }
    }
  }

  OUTPUT AFTER TILING WITH SEPARATION

  map0 = affine_map<(d0) -> (d0)>
  map1 = affine_map<(d0) -> (d0 + 32)>
  map2 = affine_map<(d0)[s0] -> (d0 + 32, s0)>

  #set0 = affine_set<(d0, d1)[s0, s1] : (-d0 + s0 - 32 >= 0, -d1 + s1 - 32 >= 0)>

  affine.for %arg2 = 0 to %M step 32 {
    affine.for %arg3 = 0 to %N step 32 {
      affine.if #set0(%arg2, %arg3)[%M, %N] {
        // Full tile.
        affine.for %arg4 = #map0(%arg2) to #map1(%arg2) {
          affine.for %arg5 = #map0(%arg3) to #map1(%arg3) {
            "foo"() : () -> ()
          }
        }
      } else {
        // Partial tile.
        affine.for %arg4 = #map0(%arg2) to min #map2(%arg2)[%M] {
          affine.for %arg5 = #map0(%arg3) to min #map2(%arg3)[%N] {
            "foo"() : () -> ()
          }
        }
      }
    }
  }

The separation is tested via a cmd line flag on the loop tiling pass.
The utility itself allows one to pass in any band of contiguously nested
loops, and can be used by other transforms/utilities. The current
implementation works for hyperrectangular loop nests.

Signed-off-by: Uday Bondhugula <uday@polymagelabs.com>

Differential Revision: https://reviews.llvm.org/D76700
2020-03-28 06:58:35 +05:30
Kazuaki Ishizaki e5a8512655 [mlir] NFC: fix trivial typo in source files
Summary: fix trivial typos in the source files

Reviewers: mravishankar, antiagainst, nicolasvasilache, herhut, rriddle, aartbik

Reviewed By: antiagainst, rriddle

Subscribers: mehdi_amini, rriddle, jpienaar, burmako, shauheen, antiagainst, nicolasvasilache, csigg, arpith-jacob, mgester, lucyrfox, aartbik, liufengdb, Joonsoo, bader, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D76876
2020-03-28 10:12:49 +09:00
Sean Silva 569e4f9bc9 `shape` dialect: add some ops
- add `to_extent_tensor`
 - rename `create_shape` to `from_extent_tensor` for symmetry
- add `split_at` and `concat` ops for basic shape manipulations

This set of ops is inspired by the requirements of lowering a dynamic-shape-aware batch matmul op. For such an op, the "matrix" dimensions aren't subject to broadcasting but the others are, and so we need to slice, broadcast, and reconstruct the final output shape. Furthermore, the actual broadcasting op used downstream uses a tensor of extents as its preferred shape interface for the actual op that does the broadcasting.

However, this functionality is quite general. It's obvious that `to_extent_tensor` is needed long-term to support many common patterns that involve computations on shapes. We can evolve the shape manipulation ops introduced here. The specific choices made here took into consideration the potentially unranked nature of the !shape.shape type, which means that a simple listing of dimensions to extract isn't possible in general.

Differential Revision: https://reviews.llvm.org/D76817
2020-03-27 16:38:42 -07:00
Lei Zhang d0af438161 [mlir][spirv] Add return to function to please MSVC
This suppresses the "not all control paths return a value" warning.
2020-03-27 18:52:15 -04:00
Alexandre Ganea 667781592a [mlir] On Windows, silence warning on functions definition
This fixes a number of warnings, where a function is re-defined after it is tagged as "being imported":

D:\llvm-project\mlir\lib\ExecutionEngine\CRunnerUtils.cpp(24,17): warning: 'print_i32' redeclared without 'dllimport' attribute: 'dllexport' attribute added [-Winconsistent-dllimport]
extern "C" void print_i32(int32_t i) { fprintf(stdout, "%" PRId32, i); }
                ^
D:\llvm-project\mlir\include\mlir/ExecutionEngine/CRunnerUtils.h(168,42): note: previous declaration is here
extern "C" MLIR_CRUNNERUTILS_EXPORT void print_i32(int32_t i);
                                         ^

Differential Revision: https://reviews.llvm.org/D76654
2020-03-27 12:24:12 -04:00
Marcel Koester 86bbbb317b [mlir] Extended Dominance analysis with a function to find the nearest common dominator of two given blocks.
The Dominance analysis currently misses a utility function to find the nearest common dominator of two given blocks. This is required for a huge variety of different control-flow analyses and transformations. This commit adds this function and moves the getNode function from DominanceInfo to DominanceInfoBase, as it also works for post dominators.

Differential Revision: https://reviews.llvm.org/D75507
2020-03-27 14:55:40 +01:00
Stephan Herhut ac9d742bbe [MLIR][LLVM] Make index type bitwidth configurable.
This change adds a new option to the StandardToLLVM lowering to configure
the bitwidth of the index type independently of the target architecture's
pointer size.

Differential revision: https://reviews.llvm.org/D76353
2020-03-27 12:42:54 +01:00
Denis Khalikov 8f4ab8c7d7 [mlir][vulkan-runner] Add support for 2D memref.
Summary:
This patch adds support for 2D memref in mlir-vulkan-runner.

Differential Revision: https://reviews.llvm.org/D76737
2020-03-27 13:59:17 +03:00
Alex Zinenko c16c07d4b9 [mlir] StandardToLLVM: use template aliases instead of dummy classes
Multiple operation conversions from the Standard dialect to the LLVM dialect
are trivial one-to-one conversions that use only the pattern defined in base
utility classes such as OneToOneConvertToLLVMPattern and
VectorConvertToLLVMPattern. Use template aliases ("using" declarations) instead
of creating derived classes without new functionality.
2020-03-27 11:14:44 +01:00
Uday Bondhugula ad4b4acbb0 [MLIR][NFC] drop some unnecessary includes
Drop unnecessary includes

Differential Revision: https://reviews.llvm.org/D76898
2020-03-27 09:17:27 +05:30
Marius Brehler 6946ca4b4c [mlir] Rename CMake target MLIRQuantOps to MLIRQuant
With commit 4d60f47 VectorOps was renamed to Vector and the naming of
the CMake target was adjusted. With commit 363dd3f QuantOps was
renamed to Quant, but the naming of the CMake target is left
untouched. This renames the CMake target.
2020-03-26 11:03:29 -07:00
Sean Silva 3dceb6d246 Allow IndexType inside tensors.
It's common in many dialects to use tensors to themselves hold tensor shapes (for example, the shape is itself the result of some non-trivial calculation). Currently, such dialects have to use `tensor<?xi64>` or worse (like allowing either i32 or i64 tensors to represent shapes). `tensor<?xindex>` is the natural type to represent this, but is currently disallowed. This patch allows it.

Differential Revision: https://reviews.llvm.org/D76726
2020-03-26 10:52:48 -07:00