platform/upstream/llvm.git
5 years agoAdd alignment support for llvm.alloca
Nicolas Vasilache [Mon, 19 Aug 2019 01:54:50 +0000 (18:54 -0700)]
Add alignment support for llvm.alloca

Extend the LLVM dialect AllocaOp with an alignment attribute.

PiperOrigin-RevId: 264068306

5 years agoInitLLVM already initializes PrettyStackTraceProgram
Jacques Pienaar [Sun, 18 Aug 2019 18:32:26 +0000 (11:32 -0700)]
InitLLVM already initializes PrettyStackTraceProgram

Remove extra PrettyStackTraceProgram and use InitLLVM consistently.

PiperOrigin-RevId: 264041205

5 years agoChange from llvm::make_unique to std::make_unique
Jacques Pienaar [Sat, 17 Aug 2019 18:05:35 +0000 (11:05 -0700)]
Change from llvm::make_unique to std::make_unique

Switch to C++14 standard method as llvm::make_unique has been removed (
https://reviews.llvm.org/D66259). Also mark some targets as c++14 to ease next
integrates.

PiperOrigin-RevId: 263953918

5 years agoNFC: Add header blocks to improve readability.
River Riddle [Sat, 17 Aug 2019 17:22:19 +0000 (10:22 -0700)]
NFC: Add header blocks to improve readability.
PiperOrigin-RevId: 263951251

5 years agoAdd spirv::GlobalVariableOp that allows module level definition of variables
Mahesh Ravishankar [Sat, 17 Aug 2019 17:19:48 +0000 (10:19 -0700)]
Add spirv::GlobalVariableOp that allows module level definition of variables

FuncOps in MLIR use explicit capture. So global variables defined in
module scope need to have a symbol name and this should be used to
refer to the variable within the function. This deviates from SPIR-V
spec, which assigns an SSA value to variables at all scopes that can
be used to refer to the variable, which requires SPIR-V functions to
allow implicit capture. To handle this add a new op,
spirv::GlobalVariableOp that can be used to define module scope
variables.
Since instructions need an SSA value, an new spirv::AddressOfOp is
added to convert a symbol reference to an SSA value for use with other
instructions.
This also means the spirv::EntryPointOp instruction needs to change to
allow initializers to be specified using symbol reference instead of
SSA value
The current spirv::VariableOp which returns an SSA value (as defined
by SPIR-V spec) can still be used to define function-scope variables.
PiperOrigin-RevId: 263951109

5 years agoNFC: Modernize and cleanup standard ops.
River Riddle [Sat, 17 Aug 2019 02:21:50 +0000 (19:21 -0700)]
NFC: Modernize and cleanup standard ops.
PiperOrigin-RevId: 263891926

5 years agoNFC: Refactor the PassInstrumentation framework to operate on Operation instead of...
River Riddle [Sat, 17 Aug 2019 00:59:03 +0000 (17:59 -0700)]
NFC: Refactor the PassInstrumentation framework to operate on Operation instead of llvm::Any.

Now that functions and modules are operations, Operation makes more sense as the opaque object to refer to both.

PiperOrigin-RevId: 263883913

5 years agoNFC: Move the Type::is* predicates to StandardTypes.cpp
River Riddle [Fri, 16 Aug 2019 21:45:37 +0000 (14:45 -0700)]
NFC: Move the Type::is* predicates to StandardTypes.cpp

These methods are currently defined 'inline' in StandardTypes.h, but this may create linker errors if StandardTypes.h isn't included at the use site.

PiperOrigin-RevId: 263850328

5 years agoFix minor typos in the documentation
MLIR Team [Fri, 16 Aug 2019 18:00:31 +0000 (11:00 -0700)]
Fix minor typos in the documentation

PiperOrigin-RevId: 263805025

5 years ago[spirv] Extend spv.array with Layoutinfo
Denis Khalikov [Fri, 16 Aug 2019 17:17:47 +0000 (10:17 -0700)]
[spirv] Extend spv.array with Layoutinfo

Extend spv.array with Layoutinfo to support (de)serialization.

Closes tensorflow/mlir#80

PiperOrigin-RevId: 263795304

5 years agoRefactor DialectConversion to convert the signatures of blocks when they are moved.
River Riddle [Fri, 16 Aug 2019 17:16:09 +0000 (10:16 -0700)]
Refactor DialectConversion to convert the signatures of blocks when they are moved.

Often we want to ensure that block arguments are converted before operations that use them. This refactors the current implementation to be cleaner/less frequent by triggering conversion when a set of blocks are moved/inlined; or when legalization is successful.

PiperOrigin-RevId: 263795005

5 years agoC++14 is now default enabled in LLVM, remove obsolete CMake flag.
Jacques Pienaar [Fri, 16 Aug 2019 15:34:37 +0000 (08:34 -0700)]
C++14 is now default enabled in LLVM, remove obsolete CMake flag.

PiperOrigin-RevId: 263776602

5 years agoRemove C++11 requirement set in cmakelists
Jacques Pienaar [Fri, 16 Aug 2019 15:08:11 +0000 (08:08 -0700)]
Remove C++11 requirement set in cmakelists

C++14 is now the required.

PiperOrigin-RevId: 263772579

5 years agoExtend vector.outerproduct with an optional 3rd argument
Nicolas Vasilache [Fri, 16 Aug 2019 10:52:56 +0000 (03:52 -0700)]
Extend vector.outerproduct with an optional 3rd argument

This CL adds an optional third argument to the vector.outerproduct instruction.
When such a third argument is specified, it is added to the result of the outerproduct and  is lowered to FMA intrinsic when the lowering supports it.

In the future, we can add an attribute on the `vector.outerproduct` instruction to modify the operations for which to emit code (e.g. "+/*", "max/+", "min/+", "log/exp" ...).

This CL additionally performs minor cleanups in the vector lowering and adds tests to improve coverage.

This has been independently verified to result in proper fma instructions for haswell as follows.

Input:
```
func @outerproduct_add(%arg0: vector<17xf32>, %arg1: vector<8xf32>, %arg2: vector<17x8xf32>) -> vector<17x8xf32> {
  %2 = vector.outerproduct %arg0, %arg1, %arg2 : vector<17xf32>, vector<8xf32>
  return %2 : vector<17x8xf32>
}
}
```

Command:
```
mlir-opt vector-to-llvm.mlir -vector-lower-to-llvm-dialect --disable-pass-threading | mlir-opt -lower-to-cfg -lower-to-llvm | mlir-translate --mlir-to-llvmir | opt -O3 | llc -O3 -march=x86-64 -mcpu=haswell -mattr=fma,avx2
```

Output:
```
outerproduct_add:                       # @outerproduct_add
# %bb.0:
        ...
        vmovaps 112(%rbp), %ymm8
        vbroadcastss    %xmm0, %ymm0
        ...
        vbroadcastss    64(%rbp), %ymm15
        vfmadd213ps     144(%rbp), %ymm8, %ymm0 # ymm0 = (ymm8 * ymm0) + mem
        ...
        vfmadd213ps     400(%rbp), %ymm8, %ymm9 # ymm9 = (ymm8 * ymm9) + mem
        ...
```
PiperOrigin-RevId: 263743359

5 years agoSimplify the classes that support SPIR-V conversion.
Mahesh Ravishankar [Thu, 15 Aug 2019 17:54:22 +0000 (10:54 -0700)]
Simplify the classes that support SPIR-V conversion.

Modify the Type converters to have a SPIRVBasicTypeConverter which
only handles conversion from standard types to SPIRV types. Rename
SPIRVEntryFnConverter to SPIRVTypeConverter. This contains the
SPIRVBasicTypeConverter within it.

Remove SPIRVFnLowering class and have separate utility methods to
lower a function as entry function or a non-entry function. The
current setup could end with diamond inheritence that is not very
friendly to use.  For example, you could define the following Op
conversion methods that lower from a dialect "Foo" which resuls in
diamond inheritance.

template<typename OpTy>
class FooDialect : public SPIRVOpLowering<OpTy> {...};
class FooFnLowering : public FooDialect, SPIRVFnLowering {...};

PiperOrigin-RevId: 263597101

5 years agoAdd BuiltIn EnumAttr to SPIR-V dialect
Mahesh Ravishankar [Thu, 15 Aug 2019 17:52:24 +0000 (10:52 -0700)]
Add BuiltIn EnumAttr to SPIR-V dialect

Generate the EnumAttr to represent BuiltIns in SPIR-V dialect. The
builtIn can be specified as a StringAttr with value being the
name of the builtin. Extend Decoration (de)serialization to handle
BuiltIns.
Also fix an error in the SPIR-V dialect generator script.

PiperOrigin-RevId: 263596624

5 years agoExecutionEngine: fix after upstream LLVM ORC update
Alex Zinenko [Thu, 15 Aug 2019 11:50:51 +0000 (04:50 -0700)]
ExecutionEngine: fix after upstream LLVM ORC update

LLVM r368707 updated the APIs in llvm::orc::DynamicLibrarySearchGenerator to
use unique_ptr for holding the instance of the generator.  Update our uses of
DynamicLibrarySearchGenerator in the ExecutionEngine to reflect that.

PiperOrigin-RevId: 263539855

5 years agoAdd support for Dialect interfaces.
River Riddle [Thu, 15 Aug 2019 03:48:35 +0000 (20:48 -0700)]
Add support for Dialect interfaces.

Dialect interfaces are virtual apis registered to a specific dialect instance. Dialect interfaces are generally useful for transformation passes, or analyses, that want to opaquely operate on operations within a given dialect. These interfaces generally involve wide coverage over the entire dialect.

A dialect interface can be defined by inheriting from the CRTP base class DialectInterfaceBase::Base. This class provides the necessary utilities for registering an interface with the dialect so that it can be looked up later. Dialects overriding an interface may register an instance via 'Dialect::addInterfaces'. This API works very similarly to the respective addOperations/addTypes/etc. This will allow for a transformation/utility to later query the interface from an opaque dialect instance via 'getInterface<T>'.

A utility class 'DialectInterfaceCollection' is also provided that will collect all of the dialects that implement a specific interface within a given module. This allows for simplifying the API of interface lookups.

PiperOrigin-RevId: 263489015

5 years agoRefactor ElementsAttr::getValue and DenseElementsAttr::getSplatValue.
River Riddle [Wed, 14 Aug 2019 22:03:25 +0000 (15:03 -0700)]
Refactor ElementsAttr::getValue and DenseElementsAttr::getSplatValue.

All 'getValue' variants now require that the index is valid, queryable via 'isValidIndex'. 'getSplatValue' now requires that the attribute is a proper splat. This allows for querying these methods on DenseElementAttr with all possible value types; e.g. float, int, APInt, etc. This also allows for removing unnecessary conversions to Attribute that really want the underlying value.

PiperOrigin-RevId: 263437337

5 years agoMove remaining linalg ops to ODS - NFC
Nicolas Vasilache [Wed, 14 Aug 2019 21:40:22 +0000 (14:40 -0700)]
Move remaining linalg ops to ODS - NFC

This CL moves the linalg.load/range/store ops to ODS.
Minor cleanups are performed.
Additional invalid IR tests are added for coverage.

PiperOrigin-RevId: 263432110

5 years agoAllow the use of the $cppClass template variable in verifier code blocks.
Ben Vanik [Wed, 14 Aug 2019 17:30:30 +0000 (10:30 -0700)]
Allow the use of the $cppClass template variable in verifier code blocks.

PiperOrigin-RevId: 263378198

5 years agoRefactor linalg.view lowering to LLVM - NFC
Nicolas Vasilache [Wed, 14 Aug 2019 14:01:04 +0000 (07:01 -0700)]
Refactor linalg.view lowering to LLVM - NFC

This CL fuses the emission of size and stride information and makes it clearer which indexings are stepped over when querying the positions. This refactor was motivated by an index calculation bug in the stride computation.

PiperOrigin-RevId: 263341610

5 years agoMove linalg.slice to ODS
Nicolas Vasilache [Wed, 14 Aug 2019 13:02:40 +0000 (06:02 -0700)]
Move linalg.slice to ODS

PiperOrigin-RevId: 263334168

5 years agoAdd a utility script to auto-generate CHECK commands for mlir test cases.
River Riddle [Tue, 13 Aug 2019 23:42:41 +0000 (16:42 -0700)]
Add a utility script to auto-generate CHECK commands for mlir test cases.

This script is a utility to add FileCheck patterns to an mlir file. The script will heuristically insert CHECK/CHECK-LABEL commands for each line within the file. By default this script will also try to insert string substitution blocks for all SSA value names. The script is designed to make adding checks to a test case fast, it is *not* designed to be authoritative about what constitutes a good test!

Note: Some cases may not be handled well, e.g. operands to operations with regions, but this script is only intended to be a starting point.

Example usage:
$ generate-test-checks.py foo.mlir
$ mlir-opt foo.mlir -transformation | generate-test-checks.py

module {
  func @fold_extract_element(%arg0: index) -> (f32, f16, f16, i32) {
    %cst = constant 4.500000e+00 : f32
    %cst_0 = constant -2.000000e+00 : f16
    %cst_1 = constant 0.000000e+00 : f16
    %c64_i32 = constant 64 : i32
    return %cst, %cst_0, %cst_1, %c64_i32 : f32, f16, f16, i32
  }
}

// CHECK-LABEL:   func @fold_extract_element(
// CHECK-SAME:                               [[VAL_0:%.*]]: index) -> (f32, f16, f16, i32) {
// CHECK:           [[VAL_1:%.*]] = constant 4.500000e+00 : f32
// CHECK:           [[VAL_2:%.*]] = constant -2.000000e+00 : f16
// CHECK:           [[VAL_3:%.*]] = constant 0.000000e+00 : f16
// CHECK:           [[VAL_4:%.*]] = constant 64 : i32
// CHECK:           return [[VAL_1]], [[VAL_2]], [[VAL_3]], [[VAL_4]] : f32, f16, f16, i32
// CHECK:         }

PiperOrigin-RevId: 263242983

5 years agoAdd unreachable to avoid GCC -Wreturn-type warning
jpienaar [Tue, 13 Aug 2019 21:22:58 +0000 (14:22 -0700)]
Add unreachable to avoid GCC -Wreturn-type warning

GCC warns of control reaching end of non-void function (-Wreturn-type).

Closes tensorflow/mlir#75

PiperOrigin-RevId: 263214601

5 years agoFix indexing issue in lowering of linalg.slice
Nicolas Vasilache [Tue, 13 Aug 2019 16:20:06 +0000 (09:20 -0700)]
Fix indexing issue in lowering of linalg.slice

This CL fixes the stepping through operands when emitting the view sizes of linalg.slice to LLVMIR. This is now consistent with the strides emission.

A relevant test is added.

Fix suggested by Alex Zinenko, thanks!

PiperOrigin-RevId: 263150922

5 years agoLLVM dialect: introduce fmuladd intrinsic as operation
Alex Zinenko [Tue, 13 Aug 2019 10:40:20 +0000 (03:40 -0700)]
LLVM dialect: introduce fmuladd intrinsic as operation

This operation is important to achieve decent performance in computational
kernels.  In LLVM, it is implemented as an intrinsic (through function
declaration and function call).  Thanks to MLIR's extendable set of operations,
it does not have to differentiate between built-ins and intrinsics, so fmuladd
is introduced as a general type-polymorphic operation.  Custom printing and
parsing will be added later.

PiperOrigin-RevId: 263106305

5 years agoGenerateCubinAccessors: use LLVM dialect constants
Alex Zinenko [Tue, 13 Aug 2019 08:38:54 +0000 (01:38 -0700)]
GenerateCubinAccessors: use LLVM dialect constants

The GenerateCubinAccessors was generating functions that fill
dynamically-allocated memory with the binary constant of a CUBIN attached as a
stirng attribute to the GPU kernel.  This approach was taken to circumvent the
missing support for global constants in the LLVM dialect (and MLIR in general).
Global constants were recently added to the LLVM dialect.  Change the
GenerateCubinAccessors pass to emit a global constant array of characters and a
function that returns a pointer to the first character in the array.

PiperOrigin-RevId: 263092052

5 years agoExpress ownership transfer in PassManager API through std::unique_ptr (NFC)
Mehdi Amini [Tue, 13 Aug 2019 02:12:42 +0000 (19:12 -0700)]
Express ownership transfer in PassManager API through std::unique_ptr (NFC)

Since raw pointers are always passed around for IR construct without
implying any ownership transfer, it can be error prone to have implicit
ownership transferred the same way.
For example this code can seem harmless:

  Pass *pass = ....
  pm.addPass(pass);
  pm.addPass(pass);
  pm.run(module);

PiperOrigin-RevId: 263053082

5 years agoAdd start of textmate language grammar.
Jacques Pienaar [Mon, 12 Aug 2019 19:52:44 +0000 (12:52 -0700)]
Add start of textmate language grammar.

Basic* grammar to start of with, this doesn't handle custom ops and doesn't
handle ops with regions. But useful enough to make reading the .mlir files
easier.

Followed the approach used for emacs & vim and placed in separate directory
under utils.

* I got a little bit carried away trying to handle attributes and tried to do some custom op printing handling, but finally abandoned it. Also first time writing a textmate grammar so I assume a lot can be improved :)

PiperOrigin-RevId: 262985490

5 years agoUse unreachable post switch rather than default case.
Jacques Pienaar [Mon, 12 Aug 2019 16:02:07 +0000 (09:02 -0700)]
Use unreachable post switch rather than default case.

Prefer to enumerate all cases in the switch instead of using default to allow
compiler to flag missing cases. This also avoids -Wcovered-switch-default
warning.

PiperOrigin-RevId: 262935972

5 years agoAvoid passing in line/col for files not registered with SourceMgr.
Jacques Pienaar [Mon, 12 Aug 2019 15:59:36 +0000 (08:59 -0700)]
Avoid passing in line/col for files not registered with SourceMgr.

This can result in index expression overflow in "Loc.getPointer() - ColumnNo"
in SourgeMgr.

loc could also be prefixed to the message additionally in this case.

PiperOrigin-RevId: 262935408

5 years agoUpdate typo
Jacques Pienaar [Mon, 12 Aug 2019 15:32:59 +0000 (08:32 -0700)]
Update typo

cond_br was accidentally typed as br_cond in a few examples.

PiperOrigin-RevId: 262929398

5 years agoLLVM dialect: introduce llvm.addressof to access globals
Alex Zinenko [Mon, 12 Aug 2019 13:10:29 +0000 (06:10 -0700)]
LLVM dialect: introduce llvm.addressof to access globals

This instruction is a local counterpart of llvm.global that takes a symbol
reference to a global and produces an SSA value containing the pointer to it.
Used in combination, these two operations allow one to use globals with other
operations expecting SSA values.  At a cost of IR indirection, we make sure the
functions don't implicitly capture the surrounding SSA values and remain
suitable for parallel processing.

PiperOrigin-RevId: 262908622

5 years agoAdd lowering of vector dialect to LLVM dialect.
Nicolas Vasilache [Mon, 12 Aug 2019 11:08:26 +0000 (04:08 -0700)]
Add lowering of vector dialect to LLVM dialect.

This CL is step 3/n towards building a simple, programmable and portable vector abstraction in MLIR that can go all the way down to generating assembly vector code via LLVM's opt and llc tools.

This CL adds support for converting MLIR n-D vector types to (n-1)-D arrays of 1-D LLVM vectors and a conversion VectorToLLVM that lowers the `vector.extractelement` and `vector.outerproduct` instructions to the proper mix of `llvm.vectorshuffle`, `llvm.extractelement` and `llvm.mulf`.

This has been independently verified to produce proper avx2 code.

Input:
```
func @vec_1d(%arg0: vector<4xf32>, %arg1: vector<8xf32>) -> vector<8xf32> {
  %2 = vector.outerproduct %arg0, %arg1 : vector<4xf32>, vector<8xf32>
  %3 = vector.extractelement %2[0 : i32]: vector<4x8xf32>
  return %3 : vector<8xf32>
}
```

Command:
```
mlir-opt vector-to-llvm.mlir -vector-lower-to-llvm-dialect --disable-pass-threading | mlir-opt -lower-to-cfg -lower-to-llvm | mlir-translate --mlir-to-llvmir | opt -O3 | llc -O3 -march=x86-64 -mcpu=haswell -mattr=fma,avx2
```

Output:
```
vec_1d:                                 # @vec_1d
# %bb.0:
        vbroadcastss    %xmm0, %ymm0
        vmulps  %ymm1, %ymm0, %ymm0
        retq
```
PiperOrigin-RevId: 262895929

5 years agoNFC: Update pattern rewrite API to pass OwningRewritePatternList by const reference.
River Riddle [Mon, 12 Aug 2019 01:33:42 +0000 (18:33 -0700)]
NFC: Update pattern rewrite API to pass OwningRewritePatternList by const reference.

The pattern list is not modified by any of these APIs and should thus be passed with const.

PiperOrigin-RevId: 262844002

5 years agoODS: Round out the definitions of the common integer attributes sizes, adding
Chris Lattner [Mon, 12 Aug 2019 01:16:54 +0000 (18:16 -0700)]
ODS: Round out the definitions of the common integer attributes sizes, adding
1/8/16 bit attrs.  NFC

PiperOrigin-RevId: 262843016

5 years agoRefactor DenseElementAttr::getValues methods to return full ranges for splats.
River Riddle [Sun, 11 Aug 2019 00:26:35 +0000 (17:26 -0700)]
Refactor DenseElementAttr::getValues methods to return full ranges for splats.

The current implementation only returns one element for the splat case, which often comes as a surprise; leading to subtle/confusing bugs. The new behavior will include an iterate over the full range of elements, as defined by the shaped type, by providing the splat value for each iterator index.

PiperOrigin-RevId: 262756780

5 years agoNFC: Standardize the terminology used for parent ops/regions/etc.
River Riddle [Sat, 10 Aug 2019 03:07:25 +0000 (20:07 -0700)]
NFC: Standardize the terminology used for parent ops/regions/etc.

There are currently several different terms used to refer to a parent IR unit in 'get' methods: getParent/getEnclosing/getContaining. This cl standardizes all of these methods to use 'getParent*'.

PiperOrigin-RevId: 262680287

5 years agoNFC: Refactoring PatternSymbolResolver into SymbolInfoMap
Lei Zhang [Sat, 10 Aug 2019 02:03:58 +0000 (19:03 -0700)]
NFC: Refactoring PatternSymbolResolver into SymbolInfoMap

In declarative rewrite rules, a symbol can be bound to op arguments or
results in the source pattern, and it can be bound to op results in the
result pattern. This means given a symbol in the pattern, it can stands
for different things: op operand, op attribute, single op result,
op result pack. We need a better way to model this complexity so that
we can handle according to the specific kind a symbol corresponds to.

Created SymbolInfo class for maintaining the information regarding a
symbol. Also created a companion SymbolInfoMap class for a map of
such symbols, providing insertion and querying depending on use cases.

PiperOrigin-RevId: 262675515

5 years agoNFC: Update usages of OwningRewritePatternList to pass by & instead of &&.
River Riddle [Sat, 10 Aug 2019 00:20:02 +0000 (17:20 -0700)]
NFC: Update usages of OwningRewritePatternList to pass by & instead of &&.

This will allow for reusing the same pattern list, which may be costly to continually reconstruct, on multiple invocations.

PiperOrigin-RevId: 262664599

5 years agoTranslation to LLVM IR: use LogicalResult instead of bool
Alex Zinenko [Fri, 9 Aug 2019 17:45:15 +0000 (10:45 -0700)]
Translation to LLVM IR: use LogicalResult instead of bool

The translation code predates the introduction of LogicalResult and was relying
on the obsolete LLVM convention of returning false on success.  Change it to
use MLIR's LogicalResult abstraction instead. NFC.

PiperOrigin-RevId: 262589432

5 years agoLLVM dialect and translation: support global strings
Alex Zinenko [Fri, 9 Aug 2019 15:59:45 +0000 (08:59 -0700)]
LLVM dialect and translation: support global strings

Unlike regular constant values, strings must be placed in some memory and
referred to through a pointer to that memory.  Until now, they were not
supported in function-local constant declarations with `llvm.constant`.
Introduce support for global strings using `llvm.global`, which would translate
them into global arrays in LLVM IR and thus make sure they have some memory
allocated for storage.

PiperOrigin-RevId: 262569316

5 years agoTranslation to LLVM: support llvm.global
Alex Zinenko [Fri, 9 Aug 2019 15:30:13 +0000 (08:30 -0700)]
Translation to LLVM: support llvm.global

Add support for translating recently introduced llvm.global operations to
global variables in the LLVM IR proper.

PiperOrigin-RevId: 262564700

5 years agoExternal library name mangling support for linalg.
Nicolas Vasilache [Fri, 9 Aug 2019 14:33:34 +0000 (07:33 -0700)]
External library name mangling support for linalg.

This CL introduces the ability to generate the external library name for Linalg operations.
The problem is that neither mlir or C support overloading and we want a simplified form of name mangling that is still reasonable to read.
This CL creates the name of the external call that Linalg expects from the operation name and the type of its arguments.

The interface library names are updated and use new cases are added for FillOp.

PiperOrigin-RevId: 262556833

5 years agoAllow linalg.view to change the underlying elemental type.
Nicolas Vasilache [Fri, 9 Aug 2019 14:28:51 +0000 (07:28 -0700)]
Allow linalg.view to change the underlying elemental type.

This CL adds the ability for linalg.view to act as a bitcast operation.
This will be used when promoting views into faster memory and casting to vector types.

In the process, linalg.view is moved to ODS.

PiperOrigin-RevId: 262556246

5 years agoAdd a higher-order vector.outerproduct operation in MLIR
Nicolas Vasilache [Fri, 9 Aug 2019 13:55:10 +0000 (06:55 -0700)]
Add a higher-order vector.outerproduct operation in MLIR

This CL is step 2/n towards building a simple, programmable and portable vector abstraction in MLIR that can go all the way down to generating assembly vector code via LLVM's opt and llc tools.

This CL adds the vector.outerproduct operation to the MLIR vector dialect as well as the appropriate roundtrip test. Lowering to LLVM will occur in the following CL.

PiperOrigin-RevId: 262552027

5 years agoAdd a higher-order vector.extractelement operation in MLIR
Nicolas Vasilache [Fri, 9 Aug 2019 12:58:19 +0000 (05:58 -0700)]
Add a higher-order vector.extractelement operation in MLIR

This CL is step 2/n towards building a simple, programmable and portable vector abstraction in MLIR that can go all the way down to generating assembly vector code via LLVM's opt and llc tools.

This CL adds the vector.extractelement operation to the MLIR vector dialect as well as the appropriate roundtrip test. Lowering to LLVM will occur in the following CL.

PiperOrigin-RevId: 262545089

5 years agoAdd support for vector ops in the LLVM dialect
Nicolas Vasilache [Fri, 9 Aug 2019 12:24:47 +0000 (05:24 -0700)]
Add support for vector ops in the LLVM dialect

This CL is step 1/n towards building a simple, programmable and portable vector abstraction in MLIR that can go all the way down to generating assembly vector code via LLVM's opt and llc tools.

This CL adds the 3 instructions `llvm.extractelement`, `llvm.insertelement` and `llvm.shufflevector` as documented in the LLVM LangRef "Vector Instructions" section.

The "Experimental Vector Reduction Intrinsics" are left out for now and can be added in the future on a per-need basis.

Appropriate roundtrip and LLVM Target tests are added.

PiperOrigin-RevId: 262542095

5 years agoLLVM Dialect: introduce llvm.global
Alex Zinenko [Fri, 9 Aug 2019 12:01:23 +0000 (05:01 -0700)]
LLVM Dialect: introduce llvm.global

Introduce an operation that defines global constants and variables in the LLVM
dialect, to reflect the corresponding LLVM IR capability. This operation is
expected to live in the top-level module and behaves similarly to
llvm.constant.  It currently does not model many of the attributes supported by
the LLVM IR for global values (memory space, alignment, thread-local, linkage)
and will be extended as the relevant use cases appear.

PiperOrigin-RevId: 262539445

5 years agoAdd support for floating-point comparison 'fcmp' to the LLVM dialect.
Nagy Mostafa [Fri, 9 Aug 2019 01:29:23 +0000 (18:29 -0700)]
Add support for floating-point comparison 'fcmp' to the LLVM dialect.

This adds support for fcmp to the LLVM dialect and adds any necessary lowerings, as well as support for EDSCs.

Closes tensorflow/mlir#69

PiperOrigin-RevId: 262475255

5 years agoEnable TTI for host TargetMachine in JitRunner
Diego Caballero [Thu, 8 Aug 2019 23:02:50 +0000 (16:02 -0700)]
Enable TTI for host TargetMachine in JitRunner

This commit improves JitRunner so that it creates a target machine
for the current CPU host which is used to properly initialize LLVM's
TargetTransformInfo for such a target. This will enable optimizations
such as vectorization in LLVM when using JitRunner. Please, note that,
as part of this work, JITTargetMachineBuilder::detectHost() has been
extended to include the host CPU name and sub-target features as part of
the host CPU detection (https://reviews.llvm.org/D65760).

Closes tensorflow/mlir#71

PiperOrigin-RevId: 262452525

5 years agoBuild SymbolTable upfront in ModuleOp verification.
Mahesh Ravishankar [Thu, 8 Aug 2019 21:40:03 +0000 (14:40 -0700)]
Build SymbolTable upfront in ModuleOp verification.

Building the symbol table upfront from module op allows for O(1)
lookup of the function while verifying duplicate EntryPointOp within
the module.

PiperOrigin-RevId: 262435697

5 years agoAdd SymbolTable trait to spirv::ModuleOp.
Mahesh Ravishankar [Thu, 8 Aug 2019 21:18:39 +0000 (14:18 -0700)]
Add SymbolTable trait to spirv::ModuleOp.

Adding the SymbolTable trait allows looking up the name of the
functions using the symbol table while verifying EntryPointOps instead
of manually tracking the function names.

PiperOrigin-RevId: 262431220

5 years agoLexer: NFC: sort helper methods alphabetically
Alex Zinenko [Thu, 8 Aug 2019 19:18:05 +0000 (12:18 -0700)]
Lexer: NFC: sort helper methods alphabetically

Lexer methods were added progressively as implementation advanced. The rest of
MLIR now tends to sort methods alphabetically for better discoverability in
absence of tooling.  Sort the lexer methods as well.

PiperOrigin-RevId: 262406992

5 years agoFunctionSupport: wrap around bool to have a more semantic callback type
Alex Zinenko [Thu, 8 Aug 2019 19:11:27 +0000 (12:11 -0700)]
FunctionSupport: wrap around bool to have a more semantic callback type

This changes the type of the function type-building callback from
(ArrayRef<Type>, ArrayRef<Type>, bool, string &) to (ArrayRef<Type>,
ArrayRef<Type>, VariadicFlag, String &) to make the intended use clear from the
callback signature alone.

Also rearrange type definitions in Parser.cpp to make them more sorted
alphabetically.

PiperOrigin-RevId: 262405851

5 years agoIntroduce support for variadic function signatures for the LLVM dialect
Alex Zinenko [Thu, 8 Aug 2019 16:41:48 +0000 (09:41 -0700)]
Introduce support for variadic function signatures for the LLVM dialect

LLVM function type has first-class support for variadic functions.  In the
current lowering pipeline, it is emulated using an attribute on functions of
standard function type.  In LLVMFuncOp that has LLVM function type, this can be
modeled directly.  Introduce parsing support for variadic arguments to the
function and use it to support variadic function declarations in LLVMFuncOp.
Function definitions are currently not supported as that would require modeling
va_start/va_end LLVM intrinsics in the dialect and we don't yet have a
consistent story for LLVM intrinsics.

PiperOrigin-RevId: 262372651

5 years agoCommand toyc should be toyc-ch2 in this chapter
Kan Chen [Thu, 8 Aug 2019 16:30:09 +0000 (09:30 -0700)]
Command toyc should be toyc-ch2 in this chapter

Closes tensorflow/mlir#70

PiperOrigin-RevId: 262370485

5 years agoParser: treat implicit top-level module as an SSA name scope
Alex Zinenko [Thu, 8 Aug 2019 16:14:24 +0000 (09:14 -0700)]
Parser: treat implicit top-level module as an SSA name scope

Now that modules are also operations, nothing prevents one from defining SSA
values in the module.  Doing so in an implicit top-level module, i.e. outside
of a `module` operation, was leading to a crash because the implicit module was
not associated with an SSA name scope.  Create a name scope before parsing the
top-level module to fix this.

PiperOrigin-RevId: 262366891

5 years agoAdd canonicalization pattern for linalg.dim
Nicolas Vasilache [Thu, 8 Aug 2019 16:09:29 +0000 (09:09 -0700)]
Add canonicalization pattern for linalg.dim

This CL introduces canonicalization patterns for linalg.dim.
This allows the dimenions of chains of view, slice and subview operations to simplify.
Down the line, when mixed with cse, this also allows better composition of linalg tiling and fusion by tracking operations that give the same result (not in this CL).

PiperOrigin-RevId: 262365865

5 years agoAdd the LLVM IR unreachable instruction to the LLVMIR dialect.
Eric Schweitz [Thu, 8 Aug 2019 08:05:26 +0000 (01:05 -0700)]
Add the LLVM IR unreachable instruction to the LLVMIR dialect.

http://llvm.org/docs/LangRef.html#unreachable-instruction

Closes tensorflow/mlir#64

PiperOrigin-RevId: 262301557

5 years agoNFC: Update FuncOp::addEntryBlock to return the newly inserted block.
River Riddle [Thu, 8 Aug 2019 02:23:35 +0000 (19:23 -0700)]
NFC: Update FuncOp::addEntryBlock to return the newly inserted block.

The entry block is often used recently after insertion. This removes the need to perform an additional lookup in such cases.

PiperOrigin-RevId: 262265671

5 years agoInitialize local variables for opcode to fix MSAN failures
Lei Zhang [Wed, 7 Aug 2019 22:19:02 +0000 (15:19 -0700)]
Initialize local variables for opcode to fix MSAN failures

PiperOrigin-RevId: 262225919

5 years agoAdd utility 'replaceAllUsesWith' methods to Operation.
River Riddle [Wed, 7 Aug 2019 20:48:19 +0000 (13:48 -0700)]
Add utility 'replaceAllUsesWith' methods to Operation.

These methods will allow replacing the uses of results with an existing operation, with the same number of results, or a range of values. This removes a number of hand-rolled result replacement loops and simplifies replacement for operations with multiple results.

PiperOrigin-RevId: 262206600

5 years agoImprove support for opaque types in MLIR, allowing dialects to opt into
Chris Lattner [Wed, 7 Aug 2019 18:49:56 +0000 (11:49 -0700)]
Improve support for opaque types in MLIR, allowing dialects to opt into
supporting opaque types, and providing ODS support for matching them.

PiperOrigin-RevId: 262183028

5 years agoFix verification of zero-dim memref in affine.load/affine.store/std.load/std.store
Diego Caballero [Wed, 7 Aug 2019 17:31:14 +0000 (10:31 -0700)]
Fix verification of zero-dim memref in affine.load/affine.store/std.load/std.store

Verification complained when using zero-dimensional memrefs in
affine.load, affine.store, std.load and std.store. This PR extends
verification so that those memrefs can be used.

Closes tensorflow/mlir#58

COPYBARA_INTEGRATE_REVIEW=https://github.com/tensorflow/mlir/pull/58 from dcaballe:dcaballe/zero-dim 49bcdcd45c52c48beca776431328e5ce551dfa9e
PiperOrigin-RevId: 262164916

5 years agoHave ValueUseIterator template use OperandType instead of IROperand.
Andy Ly [Wed, 7 Aug 2019 03:48:29 +0000 (20:48 -0700)]
Have ValueUseIterator template use OperandType instead of IROperand.

This was causing some issues using helper methods like llvm::make_early_inc_range on Value::getUses(), resulting in IROperand instead of OpOperand.

PiperOrigin-RevId: 262056425

5 years agoNFC: Simplify ModuleTerminatorOp by using the HasParent trait.
River Riddle [Tue, 6 Aug 2019 18:46:01 +0000 (11:46 -0700)]
NFC: Simplify ModuleTerminatorOp by using the HasParent trait.
PiperOrigin-RevId: 261962104

5 years agoRemove ops in regions/blocks from worklist when parent op is being removed via Greedy...
Andy Ly [Tue, 6 Aug 2019 18:08:22 +0000 (11:08 -0700)]
Remove ops in regions/blocks from worklist when parent op is being removed via GreedyPatternRewriteDriver::replaceOp.

This fixes a bug where ops inside the parent op are visited even though the parent op has been removed.

PiperOrigin-RevId: 261953580

5 years agoNFC: Simplify ModuleOp by using the SingleBlockImplicitTerminator trait.
River Riddle [Tue, 6 Aug 2019 17:33:11 +0000 (10:33 -0700)]
NFC: Simplify ModuleOp by using the SingleBlockImplicitTerminator trait.
PiperOrigin-RevId: 261944712

5 years agoEmit matchAndRewrite() for declarative rewrite rules
Lei Zhang [Tue, 6 Aug 2019 14:09:55 +0000 (07:09 -0700)]
Emit matchAndRewrite() for declarative rewrite rules

Previously we are emitting separate match() and rewrite()
methods, which requires conveying a match state struct
in a unique_ptr across these two methods. Changing to
emit matchAndRewrite() simplifies the picture.

PiperOrigin-RevId: 261906804

5 years ago[spirv] Provide decorations in batch for op construction
Lei Zhang [Tue, 6 Aug 2019 14:02:35 +0000 (07:02 -0700)]
[spirv] Provide decorations in batch for op construction

Instead of setting the attributes for decorations one by one
after constructing the op, this CL changes to attach all
the attributes for decorations to the attribute vector for
constructing the op. This should be simpler and more
efficient.

PiperOrigin-RevId: 261905578

5 years agoAdd a region to linalg.generic
Nicolas Vasilache [Tue, 6 Aug 2019 12:50:10 +0000 (05:50 -0700)]
Add a region to linalg.generic

This CL extends the Linalg GenericOp with an alternative way of specifying the body of the computation based on a single block region. The "fun" attribute becomes optional.
Either a SymbolRef "fun" attribute or a single block region must be specified to describe the side-effect-free computation. Upon lowering to loops, the new region body is inlined in the innermost loop.

The parser, verifier and pretty printer are extended.
Appropriate roundtrip, negative and lowering to loop tests are added.

PiperOrigin-RevId: 261895568

5 years agoRefactor Linalg ops to loop lowering (NFC)
Nicolas Vasilache [Tue, 6 Aug 2019 12:37:47 +0000 (05:37 -0700)]
Refactor Linalg ops to loop lowering (NFC)

This CL modifies the LowerLinalgToLoopsPass to use RewritePattern.
This will make it easier to inline Linalg generic functions and regions when emitting to loops in a subsequent CL.

PiperOrigin-RevId: 261894120

5 years agoAdd TTI pass initialization to pass managers.
Diego Caballero [Tue, 6 Aug 2019 05:13:56 +0000 (22:13 -0700)]
Add TTI pass initialization to pass managers.

Many LLVM transformations benefits from knowing the targets. This enables optimizations,
especially in a JIT context when the target is (generally) well-known.

Closes tensorflow/mlir#49

PiperOrigin-RevId: 261840617

5 years agoNFC: Implement OwningRewritePatternList as a class instead of a using directive.
River Riddle [Tue, 6 Aug 2019 01:37:56 +0000 (18:37 -0700)]
NFC: Implement OwningRewritePatternList as a class instead of a using directive.

This allows for proper forward declaration, as opposed to leaking the internal implementation via a using directive. This also allows for all pattern building to go through 'insert' methods on the OwningRewritePatternList, replacing uses of 'push_back' and 'RewriteListBuilder'.

PiperOrigin-RevId: 261816316

5 years agoFix header guard.
Suharsh Sivakumar [Mon, 5 Aug 2019 21:49:32 +0000 (14:49 -0700)]
Fix header guard.

PiperOrigin-RevId: 261774919

5 years agoDrop linalg.range_intersect op
Nicolas Vasilache [Mon, 5 Aug 2019 12:25:50 +0000 (05:25 -0700)]
Drop linalg.range_intersect op

This op is not useful.

PiperOrigin-RevId: 261665736

5 years agoUse SingleBlockImplicitTerminator trait for spv.module
Lei Zhang [Mon, 5 Aug 2019 12:09:34 +0000 (05:09 -0700)]
Use SingleBlockImplicitTerminator trait for spv.module

This trait provides the ensureTerminator() utility function and
the checks to make sure a spv.module is indeed terminated with
spv._module_end.

PiperOrigin-RevId: 261664153

5 years agoIntroduce custom syntax for llvm.func
Alex Zinenko [Mon, 5 Aug 2019 08:57:27 +0000 (01:57 -0700)]
Introduce custom syntax for llvm.func

Similar to all LLVM dialect operations, llvm.func needs to have the custom
syntax.  Use the generic FunctionLike printer and parser to implement it.

PiperOrigin-RevId: 261641755

5 years ago[mlir-translate] Fix test suite.
Denis Khalikov [Mon, 5 Aug 2019 08:39:26 +0000 (01:39 -0700)]
[mlir-translate] Fix test suite.

llvm ir printer was changed at LLVM r367755.
Prints value numbers for unnamed functions argument.

Closes tensorflow/mlir#67

COPYBARA_INTEGRATE_REVIEW=https://github.com/tensorflow/mlir/pull/67 from denis0x0D:sandbox/fix_mlir_translate ae46844e66f34a02e0cf86782ddadc5bce58b30d
PiperOrigin-RevId: 261640048

5 years agoRemove non-needed includes from ConvertControlFlowToCFG.cpp (NFC)
Mehdi Amini [Sun, 4 Aug 2019 17:58:48 +0000 (10:58 -0700)]
Remove non-needed includes from ConvertControlFlowToCFG.cpp (NFC)

The includes related to the LLVM dialect are not used in this file and
introduce an implicit dependencies between the two libraries which isn't
reflected in the CMakeLists.txt, causing non-deterministic build failures.

PiperOrigin-RevId: 261576935

5 years agoFix ExecutionEngine post-update in upstream LLVM
Alex Zinenko [Sun, 4 Aug 2019 14:47:36 +0000 (07:47 -0700)]
Fix ExecutionEngine post-update in upstream LLVM

LLVM r367686 changed the locking scheme to avoid potential deadlocks and the
related llvm::orc::ThreadSafeModule APIs ExecutionEngine was relying upon,
breaking the MLIR build.  Update our use of ThreadSafeModule to unbreak the
build.

PiperOrigin-RevId: 261566571

5 years ago[ODS] Add new definitions for non-negative integer attributes
Lei Zhang [Sat, 3 Aug 2019 23:58:26 +0000 (16:58 -0700)]
[ODS] Add new definitions for non-negative integer attributes

This CL added a new NonNegativeIntAttrBase class and two instantiations,
one for I32 and the other for I64.

PiperOrigin-RevId: 261513292

5 years agoFix clang 5.0 by using type aliases for LLVM DenseSet/Map
Mehdi Amini [Sat, 3 Aug 2019 18:35:22 +0000 (11:35 -0700)]
Fix clang 5.0 by using type aliases for LLVM DenseSet/Map

When inlining the declaration for llvm::DenseSet/DenseMap in the mlir
namespace from a forward declaration, clang does not take the default
for the template parameters if their are declared later.

namespace llvm {
  template<typename Foo>
  class DenseMap;
}
namespace mlir {
  using llvm::DenseMap;
}
namespace llvm {
  template<typename Foo = int>
  class DenseMap {};
}

namespace mlir {
  DenseMap<> map;
}

PiperOrigin-RevId: 261495612

5 years agoAdd a generic Linalg op
Nicolas Vasilache [Fri, 2 Aug 2019 16:53:08 +0000 (09:53 -0700)]
Add a generic Linalg op

This CL introduces a linalg.generic op to represent generic tensor contraction operations on views.

A linalg.generic operation requires a numbers of attributes that are sufficient to emit the computation in scalar form as well as compute the appropriate subviews to enable tiling and fusion.

These attributes are very similar to the attributes for existing operations such as linalg.matmul etc and existing operations can be implemented with the generic form.

In the future, most existing operations can be implemented using the generic form.

This CL starts by splitting out most of the functionality of the linalg::NInputsAndOutputs trait into a ViewTrait that queries the per-instance properties of the op. This allows using the attribute informations.

This exposes an ordering of verifiers issue where ViewTrait::verify uses attributes but the verifiers for those attributes have not been run. The desired behavior would be for the verifiers of the attributes specified in the builder to execute first but it is not the case atm. As a consequence, to emit proper error messages and avoid crashing, some of the
linalg.generic methods are defensive as such:
```
    unsigned getNumInputs() {
      // This is redundant with the `n_views` attribute verifier but ordering of verifiers
      // may exhibit cases where we crash instead of emitting an error message.
      if (!getAttr("n_views") || n_views().getValue().size() != 2)
        return 0;
```

In pretty-printed form, the specific attributes required for linalg.generic are factored out in an independent dictionary named "_". When parsing its content is flattened and the "_name" is dropped. This allows using aliasing for reducing boilerplate at each linalg.generic invocation while benefiting from the Tablegen'd verifier form for each named attribute in the dictionary.

For instance, implementing linalg.matmul in terms of linalg.generic resembles:

```
func @mac(%a: f32, %b: f32, %c: f32) -> f32 {
  %d = mulf %a, %b: f32
  %e = addf %c, %d: f32
  return %e: f32
}
#matmul_accesses = [
  (m, n, k) -> (m, k),
  (m, n, k) -> (k, n),
  (m, n, k) -> (m, n)
]
#matmul_trait = {
  doc = "C(m, n) += A(m, k) * B(k, n)",
  fun = @mac,
  indexing_maps = #matmul_accesses,
  library_call = "linalg_matmul",
  n_views = [2, 1],
  n_loop_types = [2, 1, 0]
}
```

And can be used in multiple places as:
```
  linalg.generic #matmul_trait %A, %B, %C [other-attributes] :
    !linalg.view<?x?xf32>, !linalg.view<?x?xf32>, !linalg.view<?x?xf32>
```

In the future it would be great to have a mechanism to alias / register a new
linalg.op as a pair of linalg.generic, #trait.

Also, note that with one could theoretically only specify the `doc` string and parse all the attributes from it.

PiperOrigin-RevId: 261338740

5 years agoFully qualify DenseMap.
Jacques Pienaar [Fri, 2 Aug 2019 15:27:31 +0000 (08:27 -0700)]
Fully qualify DenseMap.

PiperOrigin-RevId: 261325481

5 years agoAdd StdIndexedValue to EDSC helpers
Diego Caballero [Fri, 2 Aug 2019 15:23:48 +0000 (08:23 -0700)]
Add StdIndexedValue to EDSC helpers

Add StdIndexedValue to EDSC helper so that we can use it
to generated std.load and std.store in EDSC.

Closes tensorflow/mlir#59

PiperOrigin-RevId: 261324965

5 years agoAffineDataCopyGeneration: don't use CL flag values inside the pass
Alex Zinenko [Fri, 2 Aug 2019 15:04:00 +0000 (08:04 -0700)]
AffineDataCopyGeneration: don't use CL flag values inside the pass

AffineDataCopyGeneration pass relied on command line flags for internal logic
in several places, which makes it unusable in a library context (i.e. outside a
standalone mlir-opt binary that does the command line parsing).  Define
configuration flags in the constructor instead, and set them up to command
line-based defaults to maintain the original behavior.

PiperOrigin-RevId: 261322364

5 years agoWritingAPass doc: demonstrate registration of a non-default-constructible pass
Alex Zinenko [Fri, 2 Aug 2019 14:54:30 +0000 (07:54 -0700)]
WritingAPass doc: demonstrate registration of a non-default-constructible pass

This functionality was added recently and is intended to ensure that parametric
passes can be configured programmatically and not only from command-line flags,
which are mostly useless outside of standalone mlir-opt biary.

PiperOrigin-RevId: 261320932

5 years agoAdd missing include to DenseMap in MLIRContext.cpp
Mehdi Amini [Thu, 1 Aug 2019 23:38:26 +0000 (16:38 -0700)]
Add missing include to DenseMap in MLIRContext.cpp

This is fixing the build of MLIR on MacOS when built within TensorFlow

PiperOrigin-RevId: 261223250

5 years agoIntroduce explicit copying optimization by generalizing the DMA generation pass
Uday Bondhugula [Thu, 1 Aug 2019 23:31:15 +0000 (16:31 -0700)]
Introduce explicit copying optimization by generalizing the DMA generation pass

Explicit copying to contiguous buffers is a standard technique to avoid
conflict misses and TLB misses, and improve hardware prefetching
performance. When done in conjunction with cache tiling, it nearly
eliminates all cache conflict and TLB misses, and a single hardware
prefetch stream is needed per data tile.

- generalize/extend DMA generation pass (renamed data copying pass) to
  perform either point-wise explicit copies to fast memory buffers or
  DMAs (depending on a cmd line option). All logic is the same as
  erstwhile -dma-generate.

- -affine-dma-generate is now renamed -affine-data-copy; when -dma flag is
  provided, DMAs are generated, or else explicit copy loops are generated
  (point-wise) by default.

- point-wise copying could be used for CPUs (or GPUs); some indicative
  performance numbers with a "C" version of the MLIR when compiled with
  and without this optimization (about 2x improvement here).

  With a matmul on 4096^2 matrices on a single core of an Intel Core i7
  Skylake i7-8700K with clang 8.0.0:

  clang -O3:                       518s
  clang -O3 with MLIR tiling (128x128):      24.5s
  clang -O3 with MLIR tiling + data copying  12.4s
  (code equivalent to test/Transforms/data-copy.mlir func @matmul)

- fix some misleading comments.

- change default fast-mem space to 0 (more intuitive now with the
  default copy generation using point-wise copies instead of DMAs)

On a simple 3-d matmul loop nest, code generated with -affine-data-copy:

```
  affine.for %arg3 = 0 to 4096 step 128 {
    affine.for %arg4 = 0 to 4096 step 128 {
      %0 = affine.apply #map0(%arg3, %arg4)
      %1 = affine.apply #map1(%arg3, %arg4)
      %2 = alloc() : memref<128x128xf32, 2>
      // Copy-in Out matrix.
      affine.for %arg5 = 0 to 128 {
        %5 = affine.apply #map2(%arg3, %arg5)
        affine.for %arg6 = 0 to 128 {
          %6 = affine.apply #map2(%arg4, %arg6)
          %7 = load %arg2[%5, %6] : memref<4096x4096xf32>
          affine.store %7, %2[%arg5, %arg6] : memref<128x128xf32, 2>
        }
      }
      affine.for %arg5 = 0 to 4096 step 128 {
        %5 = affine.apply #map0(%arg3, %arg5)
        %6 = affine.apply #map1(%arg3, %arg5)
        %7 = alloc() : memref<128x128xf32, 2>
        // Copy-in LHS.
        affine.for %arg6 = 0 to 128 {
          %11 = affine.apply #map2(%arg3, %arg6)
          affine.for %arg7 = 0 to 128 {
            %12 = affine.apply #map2(%arg5, %arg7)
            %13 = load %arg0[%11, %12] : memref<4096x4096xf32>
            affine.store %13, %7[%arg6, %arg7] : memref<128x128xf32, 2>
          }
        }
        %8 = affine.apply #map0(%arg5, %arg4)
        %9 = affine.apply #map1(%arg5, %arg4)
        %10 = alloc() : memref<128x128xf32, 2>
        // Copy-in RHS.
        affine.for %arg6 = 0 to 128 {
          %11 = affine.apply #map2(%arg5, %arg6)
          affine.for %arg7 = 0 to 128 {
            %12 = affine.apply #map2(%arg4, %arg7)
            %13 = load %arg1[%11, %12] : memref<4096x4096xf32>
            affine.store %13, %10[%arg6, %arg7] : memref<128x128xf32, 2>
          }
        }
        // Compute.
        affine.for %arg6 = #map7(%arg3) to #map8(%arg3) {
          affine.for %arg7 = #map7(%arg4) to #map8(%arg4) {
            affine.for %arg8 = #map7(%arg5) to #map8(%arg5) {
              %11 = affine.load %7[-%arg3 + %arg6, -%arg5 + %arg8] : memref<128x128xf32, 2>
              %12 = affine.load %10[-%arg5 + %arg8, -%arg4 + %arg7] : memref<128x128xf32, 2>
              %13 = affine.load %2[-%arg3 + %arg6, -%arg4 + %arg7] : memref<128x128xf32, 2>
              %14 = mulf %11, %12 : f32
              %15 = addf %13, %14 : f32
              affine.store %15, %2[-%arg3 + %arg6, -%arg4 + %arg7] : memref<128x128xf32, 2>
            }
          }
        }
        dealloc %10 : memref<128x128xf32, 2>
        dealloc %7 : memref<128x128xf32, 2>
      }
      %3 = affine.apply #map0(%arg3, %arg4)
      %4 = affine.apply #map1(%arg3, %arg4)
      // Copy out result matrix.
      affine.for %arg5 = 0 to 128 {
        %5 = affine.apply #map2(%arg3, %arg5)
        affine.for %arg6 = 0 to 128 {
          %6 = affine.apply #map2(%arg4, %arg6)
          %7 = affine.load %2[%arg5, %arg6] : memref<128x128xf32, 2>
          store %7, %arg2[%5, %6] : memref<4096x4096xf32>
        }
      }
      dealloc %2 : memref<128x128xf32, 2>
    }
  }
```

With -affine-data-copy -dma:

```
  affine.for %arg3 = 0 to 4096 step 128 {
    %0 = affine.apply #map3(%arg3)
    %1 = alloc() : memref<128xf32, 2>
    %2 = alloc() : memref<1xi32>
    affine.dma_start %arg2[%arg3], %1[%c0], %2[%c0], %c128_0 : memref<4096xf32>, memref<128xf32, 2>, memref<1xi32>
    affine.dma_wait %2[%c0], %c128_0 : memref<1xi32>
    %3 = alloc() : memref<1xi32>
    affine.for %arg4 = 0 to 4096 step 128 {
      %5 = affine.apply #map0(%arg3, %arg4)
      %6 = affine.apply #map1(%arg3, %arg4)
      %7 = alloc() : memref<128x128xf32, 2>
      %8 = alloc() : memref<1xi32>
      affine.dma_start %arg0[%arg3, %arg4], %7[%c0, %c0], %8[%c0], %c16384, %c4096, %c128_2 : memref<4096x4096xf32>, memref<128x128xf32, 2>, memref<1xi32>
      affine.dma_wait %8[%c0], %c16384 : memref<1xi32>
      %9 = affine.apply #map3(%arg4)
      %10 = alloc() : memref<128xf32, 2>
      %11 = alloc() : memref<1xi32>
      affine.dma_start %arg1[%arg4], %10[%c0], %11[%c0], %c128_1 : memref<4096xf32>, memref<128xf32, 2>, memref<1xi32>
      affine.dma_wait %11[%c0], %c128_1 : memref<1xi32>
      affine.for %arg5 = #map3(%arg3) to #map5(%arg3) {
        affine.for %arg6 = #map3(%arg4) to #map5(%arg4) {
          %12 = affine.load %7[-%arg3 + %arg5, -%arg4 + %arg6] : memref<128x128xf32, 2>
          %13 = affine.load %10[-%arg4 + %arg6] : memref<128xf32, 2>
          %14 = affine.load %1[-%arg3 + %arg5] : memref<128xf32, 2>
          %15 = mulf %12, %13 : f32
          %16 = addf %14, %15 : f32
          affine.store %16, %1[-%arg3 + %arg5] : memref<128xf32, 2>
        }
      }
      dealloc %11 : memref<1xi32>
      dealloc %10 : memref<128xf32, 2>
      dealloc %8 : memref<1xi32>
      dealloc %7 : memref<128x128xf32, 2>
    }
    %4 = affine.apply #map3(%arg3)
    affine.dma_start %1[%c0], %arg2[%arg3], %3[%c0], %c128 : memref<128xf32, 2>, memref<4096xf32>, memref<1xi32>
    affine.dma_wait %3[%c0], %c128 : memref<1xi32>
    dealloc %3 : memref<1xi32>
    dealloc %2 : memref<1xi32>
    dealloc %1 : memref<128xf32, 2>
  }
```

Signed-off-by: Uday Bondhugula <uday@polymagelabs.com>
Closes tensorflow/mlir#50

PiperOrigin-RevId: 261221903

5 years agoQualify StringRef to fix Windows build failure
Lei Zhang [Thu, 1 Aug 2019 21:13:55 +0000 (14:13 -0700)]
Qualify StringRef to fix Windows build failure

PiperOrigin-RevId: 261195069

5 years ago[spirv] Add support for specialization constant
Lei Zhang [Thu, 1 Aug 2019 21:12:58 +0000 (14:12 -0700)]
[spirv] Add support for specialization constant

This CL extends the existing spv.constant op to also support
specialization constant by adding an extra unit attribute
on it.

PiperOrigin-RevId: 261194869

5 years agoAdd FIR, the Flang project's IR, to the dialect registry.
Eric Schweitz [Thu, 1 Aug 2019 20:39:21 +0000 (13:39 -0700)]
Add FIR, the Flang project's IR, to the dialect registry.

Closes tensorflow/mlir#62

PiperOrigin-RevId: 261187850

5 years ago[spirv] Add binary logical operations.
Denis Khalikov [Thu, 1 Aug 2019 20:05:28 +0000 (13:05 -0700)]
[spirv] Add binary logical operations.

Add binary logical operations regarding to the spec section 3.32.15:
OpIEqual, OpINotEqual, OpUGreaterThan, OpSGreaterThan,
OpUGreaterThanEqual, OpSGreaterThanEqual, OpULessThan, OpSLessThan,
OpULessThanEqual, OpSLessThanEqual.

Closes tensorflow/mlir#61

PiperOrigin-RevId: 261181281

5 years agoReplace the verifyUnusedValue directive with HasNoUseOf constraint
Lei Zhang [Thu, 1 Aug 2019 18:50:47 +0000 (11:50 -0700)]
Replace the verifyUnusedValue directive with HasNoUseOf constraint

verifyUnusedValue is a bit strange given that it is specified in a
result pattern but used to generate match statements. Now we are
able to support multi-result ops better, we can retire it and replace
it with a HasNoUseOf constraint. This reduces the number of mechanisms.

PiperOrigin-RevId: 261166863

5 years agoMigrate pattern symbol binding tests to use TestDialect
Lei Zhang [Thu, 1 Aug 2019 02:28:39 +0000 (19:28 -0700)]
Migrate pattern symbol binding tests to use TestDialect

PiperOrigin-RevId: 261045611

5 years agoFix support for auxiliary ops in declarative rewrite rules
Lei Zhang [Wed, 31 Jul 2019 23:03:13 +0000 (16:03 -0700)]
Fix support for auxiliary ops in declarative rewrite rules

We allow to generate more ops than what are needed for replacing
the matched root op. Only the last N static values generated are
used as replacement; the others serve as auxiliary ops/values for
building the replacement.

With the introduction of multi-result op support, an op, if used
as a whole, may be used to replace multiple static values of
the matched root op. We need to consider this when calculating
the result range an generated op is to replace.

For example, we can have the following pattern:

```tblgen
def : Pattern<(ThreeResultOp ...),
              [(OneResultOp ...), (OneResultOp ...), (OneResultOp ...)]>;

// Two op to replace all three results
def : Pattern<(ThreeResultOp ...),
              [(TwoResultOp ...), (OneResultOp ...)]>;

// One op to replace all three results
def : Pat<(ThreeResultOp ...), (ThreeResultOp ...)>;

def : Pattern<(ThreeResultOp ...),
              [(AuxiliaryOp ...), (ThreeResultOp ...)]>;
```
PiperOrigin-RevId: 261017235

5 years agoNFC: refactor ODS builder generation
Lei Zhang [Wed, 31 Jul 2019 22:30:46 +0000 (15:30 -0700)]
NFC: refactor ODS builder generation

Previously we use one single method with lots of branches to
generate multiple builders. This makes the method difficult
to follow and modify. This CL splits the method into multiple
dedicated ones, by extracting common logic into helper methods
while leaving logic specific to each builder in their own
methods.

PiperOrigin-RevId: 261011082