Commit Graph

226 Commits

Author SHA1 Message Date
Mehdi Amini 308571074c Mass update the MLIR license header to mention "Part of the LLVM project"
This is an artifact from merging MLIR into LLVM, the file headers are
now aligned with the rest of the project.
2020-01-26 03:58:30 +00:00
Jacques Pienaar 178562fb35 [mlir] Enable specifying verify on OpInterface
Summary:
Add method in ODS to specify verification for operations implementing a
OpInterface. Use this with infer type op interface to verify that the
inferred type matches the return type and remove special case in
TestPatterns.

This could also have been achieved by using OpInterfaceMethod but verify
seems pretty common and it is not an arbitrary method that just happened
to be named verifyTrait, so having it be defined in special way seems
appropriate/better documenting.

Differential Revision: https://reviews.llvm.org/D73122
2020-01-22 04:43:22 -08:00
Lei Zhang 267483ac70 [mlir][spirv] Support implied extensions and capabilities
In SPIR-V, when a new version is introduced, it is possible some
existing extensions will be incorporated into it so that it becomes
implicitly declared if targeting the new version. This affects
conversion target specification because we need to take this into
account when allowing what extensions to use.

For a capability, it may also implies some other capabilities,
for example, the `Shader` capability implies `Matrix` the capability.
This should also be taken into consideration when preparing the
conversion target: when we specify an capability is allowed, all
its recursively implied capabilities are also allowed.

This commit adds utility functions to query implied extensions for
a given version and implied capabilities for a given capability
and updated SPIRVConversionTarget to use them.

This commit also fixes a bug in availability spec. When a symbol
(op or enum case) can be enabled by an extension, we should drop
it's minimal version requirement. Being enabled by an extension
naturally means the symbol can be used by *any* SPIR-V version
as long as the extension is supported. The grammar still encodes
the 'version' field for such cases, but it should be interpreted
as a different way: rather than meaning a minimal version
requirement, it says the symbol becomes core at that specific
version.

Differential Revision: https://reviews.llvm.org/D72765
2020-01-17 08:01:57 -05:00
Lei Zhang ca4a55fabb [mlir] NFC: put C++ code emission classes in their own files
This exposes thse classes so that they can be used in interfaces.

Differential Revision: https://reviews.llvm.org/D72514
2020-01-10 18:38:59 -05:00
Lei Zhang a81cb1b8bf [mlir][spirv] Allow specifying availability on enum attribute cases
Lots of SPIR-V ops take enum attributes and certain enum cases
need extra capabilities or extensions to be available. This commit
extends to allow specifying availability spec on enum cases.
Extra utility functions are generated for the corresponding enum
classes to return the availability requirement. The availability
interface implemention for a SPIR-V op now goes over all enum
attributes to collect the availability requirements.

Reviewed By: mravishankar

Differential Revision: https://reviews.llvm.org/D71947
2020-01-02 13:19:44 -05:00
River Riddle e62a69561f NFC: Replace ValuePtr with Value and remove it now that Value is value-typed.
ValuePtr was a temporary typedef during the transition to a value-typed Value.

PiperOrigin-RevId: 286945714
2019-12-23 16:36:53 -08:00
Mehdi Amini 56222a0694 Adjust License.txt file to use the LLVM license
PiperOrigin-RevId: 286906740
2019-12-23 15:33:37 -08:00
River Riddle 35807bc4c5 NFC: Introduce new ValuePtr/ValueRef typedefs to simplify the transition to Value being value-typed.
This is an initial step to refactoring the representation of OpResult as proposed in: https://groups.google.com/a/tensorflow.org/g/mlir/c/XXzzKhqqF_0/m/v6bKb08WCgAJ

This change will make it much simpler to incrementally transition all of the existing code to use value-typed semantics.

PiperOrigin-RevId: 286844725
2019-12-22 22:00:23 -08:00
Jacques Pienaar b6d54a1ba3 Unique trait list during ODS Operator trait construction
Concatting lists in TableGen is easy, creating unique lists less so. There is no reason for duplicated op traits so we could throw an error instead but duplicates could occur due to concatting different list of traits in ODS (e.g., for convenience reasons), so just dedup them during Operator trait construction instead.

PiperOrigin-RevId: 286488423
2019-12-19 16:44:56 -08:00
River Riddle 29807ff5e4 Add support for providing a default implementation for an interface method.
This enables providing a default implementation of an interface method. This method is defined on the Trait that is attached to the operation, and thus has all of the same constraints and properties as any other interface method. This allows for interface authors to provide a conservative default implementation for certain methods, without requiring that all users explicitly define it. The default implementation can be specified via the argument directly after the interface method body:

  StaticInterfaceMethod<
    /*desc=*/"Returns whether two array of types are compatible result types for an op.",
    /*retTy=*/"bool",
    /*methodName=*/"isCompatibleReturnTypes",
    /*args=*/(ins "ArrayRef<Type>":$lhs, "ArrayRef<Type>":$rhs),
    /*methodBody=*/[{
      return ConcreteOp::isCompatibleReturnTypes(lhs, rhs);
    }],
    /*defaultImplementation=*/[{
      /// Returns whether two arrays are equal as strongest check for
      /// compatibility by default.
      return lhs == rhs;
    }]

PiperOrigin-RevId: 286226054
2019-12-18 11:09:11 -08:00
Lei Zhang b41162b3af [ODS] Generate builders taking unwrapped value and defaults for attributes
Existing builders generated by ODS require attributes to be passed
in as mlir::Attribute or its subclasses. This is okay foraggregate-
parameter builders, which is primarily to be used by programmatic
C++ code generation; it is inconvenient for separate-parameter
builders meant to be called in manually written C++ code because
it requires developers to wrap raw values into mlir::Attribute by
themselves.

This CL extends to generate additional builder methods that
take raw values for attributes and handles the wrapping in the
builder implementation. Additionally, if an attribute appears
late in the arguments list and has a default value, the default
value is supplied in the declaration if possible.

PiperOrigin-RevId: 283355919
2019-12-02 09:33:57 -08:00
Lei Zhang 4982eaf87c [DRR] Introduce `$_` to ignore op argument match
Right now op argument matching in DRR is position-based, meaning we need to
specify N arguments for an op with N ODS-declared argument. This can be annoying
when we don't want to capture all the arguments. `$_` is to remedy the situation.

PiperOrigin-RevId: 283339992
2019-12-02 07:54:50 -08:00
Lei Zhang 13c6e419ca Add support for AttrSizedOperandSegments/AttrSizedResultSegments
Certain operations can have multiple variadic operands and their size
relationship is not always known statically. For such cases, we need
a per-op-instance specification to divide the operands into logical
groups or segments. This can be modeled by attributes.

This CL introduces C++ trait AttrSizedOperandSegments for operands and
AttrSizedResultSegments for results. The C++ trait just guarantees
such size attribute has the correct type (1D vector) and values
(non-negative), etc. It serves as the basis for ODS sugaring that
with ODS argument declarations we can further verify the number of
elements match the number of ODS-declared operands and we can generate
handy getter methods.

PiperOrigin-RevId: 282467075
2019-11-25 17:26:50 -08:00
River Riddle c35378003c Add support for using the ODS result names as the Asm result names for multi-result operations.
This changes changes the OpDefinitionsGen to automatically add the OpAsmOpInterface for operations with multiple result groups using the provided ODS names. We currently just limit the generation to multi-result ops as most single result operations don't have an interesting name(result/output/etc.). An example is shown below:
// The following operation:
def MyOp : ... {
  let results = (outs AnyType:$first, Variadic<AnyType>:$middle, AnyType);
}

// May now be printed as:
%first, %middle:2, %0 = "my.op" ...

PiperOrigin-RevId: 281834156
2019-11-21 14:55:46 -08:00
Lei Zhang 796ca609eb [ODS] Fix operation argument population to avoid crash
The `Operator` class keeps an `arguments` field, which contains pointers
to `operands` and `attributes` elements. Thus it must be populated after
`operands` and `attributes` are finalized so to have stable pointers.
SmallVector may re-allocate when still having new elements added, which
will invalidate pointers.

PiperOrigin-RevId: 280466896
2019-11-14 11:03:29 -08:00
Lei Zhang aa9dc9446e Expose an isSubclassOf() method on AttrConstraint
PiperOrigin-RevId: 280021408
2019-11-12 11:58:10 -08:00
Lei Zhang 2fa865719b Move BitEnumAttr from SPIRVBase.td to OpBase.td
BitEnumAttr is a mechanism for modelling attributes whose value is
a bitfield. It should not be scoped to the SPIR-V dialect and can
be used by other dialects too.

This CL is mostly shuffling code around and adding tests and docs.
Functionality changes are:

* Fixed to use `getZExtValue()` instead of `getSExtValue()` when
  getting the value from the underlying IntegerAttr for a case.
* Changed to auto-detect whether there is a case whose value is
  all bits unset (i.e., zero). If so handle it specially in all
  helper methods.

PiperOrigin-RevId: 277964926
2019-11-01 11:18:19 -07:00
Lei Zhang cb40e36d3b Fix segfault when no symbol is given to an constraint operand
This fixed the segfault when we see the following pattern:
  Pat<(...), (...), [(... 1, 2, 3), ...]>

PiperOrigin-RevId: 277544300
2019-10-30 11:12:57 -07:00
Lei Zhang 020f9eb68c [DRR] Allow interleaved operands and attributes
Previously DRR assumes attributes to appear after operands. This was the
previous requirements on ODS, but that has changed some time ago. Fix
DRR to also support interleaved operands and attributes.

PiperOrigin-RevId: 275983485
2019-10-21 20:48:17 -07:00
Kazuaki Ishizaki 8bfedb3ca5 Fix minor spelling tweaks (NFC)
Closes tensorflow/mlir#177

PiperOrigin-RevId: 275692653
2019-10-20 00:11:34 -07:00
Lei Zhang 23d21af65c [DRR] Allow capturing and referencing no-result ops
Previously when we bind a symbol to an op in DRR, it means to capture
the op's result(s) and later references will be expanded to result(s).
This means for ops without result, we are replacing the symbol with
nothing. This CL treats non-result op capturing and referencing as a
special case to mean the op itself.

PiperOrigin-RevId: 275269702
2019-10-17 09:02:31 -07:00
Lei Zhang 1358df19ca Add LLVM_DEBUG in RewritersGen.cpp and Pattern.cpp
It's usually hard to understand what went wrong if mlir-tblgen
crashes on some input. This CL adds a few useful LLVM_DEBUG
statements so that we can use mlir-tblegn -debug to figure
out the culprit for a crash.

PiperOrigin-RevId: 275253532
2019-10-17 07:26:22 -07:00
Jacques Pienaar 27e8efedf8 Add DialectType and generate docs for dialect types
Add new `typeDescription` (description was already used by base constraint class) field to type to allow writing longer descriptions about a type being defined. This allows for providing additional information/rationale for a defined type. This currently uses `description` as the heading/name for the type in the generated documentation.

PiperOrigin-RevId: 273299332
2019-10-07 08:41:13 -07:00
Jacques Pienaar 77672c9777 Enable emitting dialect summary & description during op generation
Sort ops per dialect and emit summary & description (if provided) of each dialect before emitting the ops of the dialect.

PiperOrigin-RevId: 273077138
2019-10-05 12:21:51 -07:00
Jacques Pienaar f015b020f3 Add missing file from cmakelist
PiperOrigin-RevId: 272054623
2019-09-30 13:37:54 -07:00
Jacques Pienaar 0b81eb928b Enable autogenerating OpInterface method declarations
Add DeclareOpInterfaceFunctions to enable specifying whether OpInterfaceMethods
for an OpInterface should be generated automatically. This avoids needing to
declare the extra methods, while also allowing adding function declaration by way of trait/inheritance.

Most of this change is mechanical/extracting classes to be reusable.

PiperOrigin-RevId: 272042739
2019-09-30 12:42:58 -07:00
Lei Zhang 94298cea93 Remove unused variables and methods to address compiler warnings
PiperOrigin-RevId: 271256784
2019-09-25 19:05:30 -07:00
Lei Zhang 6934a337f0 [spirv] Add support for BitEnumAttr
Certain enum classes in SPIR-V, like function/loop control and memory
access, are bitmasks. This CL introduces a BitEnumAttr to properly
model this and drive auto-generation of verification code and utility
functions. We still store the attribute using an 32-bit IntegerAttr
for minimal memory footprint and easy (de)serialization. But utility
conversion functions are adjusted to inspect each bit and generate
"|"-concatenated strings for the bits; vice versa.

Each such enum class has a "None" case that means no bit is set. We
need special handling for "None". Because of this, the logic is not
general anymore. So right now the definition is placed in the SPIR-V
dialect. If later this turns out to be useful for other dialects,
then we can see how to properly adjust it and move to OpBase.td.

Added tests for SPV_MemoryAccess to check and demonstrate.

PiperOrigin-RevId: 269350620
2019-09-16 09:23:22 -07:00
Rob Suderman 8f90a442c3 Added a TableGen generator for structured data
Similar to enum, added a generator for structured data. This provide Dictionary that stores a fixed set of values and guarantees the values are valid. It is intended to store a fixed number of values by a given name.

PiperOrigin-RevId: 266437460
2019-08-30 12:52:13 -07:00
Lei Zhang 31cfee6077 Support variadic ops in declarative rewrite rules
This CL extends declarative rewrite rules to support matching and
generating ops with variadic operands/results. For this, the
generated `matchAndRewrite()` method for each pattern now are
changed to

* Use "range" types for the local variables used to store captured
  values (`operand_range` for operands, `ArrayRef<Value *>` for
  values, *Op for results). This allows us to have a unified way
  of handling both single values and value ranges.
* Create local variables for each operand for op creation. If the
  operand is variadic, then a `SmallVector<Value*>` will be created
  to collect all values for that operand; otherwise a `Value*` will
  be created.
* Use a collective result type builder. All result types are
  specified via a single parameter to the builder.

We can use one result pattern to replace multiple results of the
matched root op. When that happens, it will require specifying
types for multiple results. Add a new collective-type builder.

PiperOrigin-RevId: 264588559
2019-08-21 05:35:32 -07:00
Jacques Pienaar 79f53b0cf1 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
2019-08-17 11:06:03 -07:00
jpienaar 12ff145ebf 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
2019-08-13 14:23:28 -07:00
Lei Zhang ac68637ba9 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
2019-08-09 19:04:23 -07:00
Lei Zhang 7768ea9fb3 Qualify StringRef to fix Windows build failure
PiperOrigin-RevId: 261195069
2019-08-01 14:14:31 -07:00
Lei Zhang c72d849eb9 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
2019-08-01 11:51:15 -07:00
Lei Zhang e032d0dc63 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
2019-07-31 16:03:42 -07:00
Jacques Pienaar 4be7e8627f Remove dead code.
PiperOrigin-RevId: 260585594
2019-07-30 06:17:57 -07:00
Lei Zhang 9f02e88946 Support referencing a single value generated by a matched multi-result op
It's quite common that we want to put further constraints on the matched
multi-result op's specific results. This CL enables referencing symbols
bound to source op with the `__N` syntax.

PiperOrigin-RevId: 260122401
2019-07-26 04:31:46 -07:00
Mahesh Ravishankar c6cfebf1af Automatically generate (de)serialization methods for SPIR-V ops
For ops in SPIR-V dialect that are a direct mirror of SPIR-V
operations, the serialization/deserialization methods can be
automatically generated from the Op specification. To enable this an
'autogenSerialization' field is added to SPV_Ops. When set to
non-zero, this will enable the automatic (de)serialization function
generation

Also adding tests that verify the spv.Load, spv.Store and spv.Variable
ops are serialized and deserialized correctly. To fully support these
tests also add serialization and deserialization of float types and
spv.ptr types

PiperOrigin-RevId: 258684764
2019-07-19 11:39:22 -07:00
Lei Zhang 765b77cc70 Better support for attribute wrapper classes when getting def name
Unless we explicitly name a template instantiation in .td file, its def
name will be "anonymous_<number>". We typically give base-level Attr
template instantiation a name by writing `def AnAttr : Attr<...>`. But
when `AnAttr` is further wrapped in classes like OptionalAttr, the name
is lost unless explicitly def'ed again. These implicit-named template
instantiation is fairly common when writing op definitions. Those wrapper
classes are just essentially attaching more information to the attribute.
Without a proper way to trace back to the original attribute def name
can cause problems for consumers wanting to handle attributes according
to their types.

Previously we handled OptionalAttr and DefaultValuedAttr specifically,
but Confined was not supported. And they can compose together to have
Confined<OptionalAttr<...>, [...]>. So this CL moves the baseAttr field
to main Attr class (like isOptional) and set it only on the innermost
wrapper class.

PiperOrigin-RevId: 258341646
2019-07-16 13:45:03 -07:00
Alex Zinenko ead1acaef2 ODS: provide a flag to skip generation of default build methods
Some operations need to override the default behavior of builders, in
particular region-holding operations such as affine.for or tf.graph want to
inject default terminators into the region upon construction, which default
builders won't do.  Provide a flag that disables the generation of default
builders so that the custom builders could use the same function signatures.
This is an intentionally low-level and heavy-weight feature that requires the
entire builder to be implemented, and it should be used sparingly.  Injecting
code into the end of a default builder would depend on the naming scheme of the
default builder arguments that is not visible in the ODS.  Checking that the
signature of a custom builder conflicts with that of a default builder to
prevent emission would require teaching ODG to differentiate between types and
(optional) argument names in the generated C++ code.  If this flag ends up
being used a lot, we should consider adding traits that inject specific code
into the default builder.

PiperOrigin-RevId: 256640069
2019-07-05 02:28:05 -07:00
Lei Zhang 509411c229 [ODS] NFC: Rename EnumAttr to StrEnumAttr to be consistent with IntEnumAttr
PiperOrigin-RevId: 256169019
2019-07-02 10:28:36 -07:00
Lei Zhang 22883036cd EnumsGen: remove dangling assertion
StringAttr-backed enum attribute cases changed to allow explicit values,
But this assertion was not deleted.

Fixes https://github.com/tensorflow/mlir/issues/39

PiperOrigin-RevId: 256090793
2019-07-02 10:27:49 -07:00
Lei Zhang 9dd182e0fa [ODS] Introduce IntEnumAttr
In ODS, right now we use StringAttrs to emulate enum attributes. It is
suboptimal if the op actually can and wants to store the enum as a
single integer value; we are paying extra cost on storing and comparing
the attribute value.

This CL introduces a new enum attribute subclass that are backed by
IntegerAttr. The downside with IntegerAttr-backed enum attributes is
that the assembly form now uses integer values, which is less obvious
than the StringAttr-backed ones. However, that can be remedied by
defining custom assembly form with the help of the conversion utility
functions generated via EnumsGen.

Choices are given to the dialect writers to decide which one to use for
their enum attributes.

PiperOrigin-RevId: 255935542
2019-07-01 09:55:47 -07:00
Lei Zhang 8f77d2afed [spirv] Basic serializer and deserializer
This CL adds the basic SPIR-V serializer and deserializer for converting
SPIR-V module into the binary format and back. Right now only an empty
module with addressing model and memory model is supported; (de)serialize
other components will be added gradually with subsequent CLs.

The purpose of this library is to enable importing SPIR-V binary modules
to run transformations on them and exporting SPIR-V modules to be consumed
by execution environments. The focus is transformations, which inevitably
means changes to the binary module; so it is not designed to be a general
tool for investigating the SPIR-V binary module and does not guarantee
roundtrip equivalence (at least for now).

PiperOrigin-RevId: 254473019
2019-06-22 09:17:21 -07:00
Mahesh Ravishankar d7ba69e811 Add SPIRV Image Type according to the spec described here :
https://www.khronos.org/registry/spir-v/specs/1.0/SPIRV.html#OpTypeImage.

Add new enums to describe Image dimensionality, Image Depth, Arrayed
information, Sampling, Sampler User information, and Image format.
Doesn's support the Optional Access qualifier at this stage

Fix Enum generator for tblgen to add "_" at the beginning if the enum
starts with a number.

PiperOrigin-RevId: 254091423
2019-06-19 23:09:01 -07:00
Lei Zhang 7848505ebd Print proper message saying variadic ops are not supported in RewriterGen
Support for ops with variadic operands/results will come later; but right now
a proper message helps to avoid deciphering confusing error messages later in
the compilation stage.

PiperOrigin-RevId: 254071820
2019-06-19 23:08:52 -07:00
Lei Zhang 3812d956ea [ODS] Support variadic operand/result verification
This CL enables verification code generation for variadic operands and results.
In verify(), we use fallback getter methods to access all the dynamic values
belonging to one static variadic operand/result to reuse the value range
calculation there.

PiperOrigin-RevId: 252288219
2019-06-09 16:24:29 -07:00
Lei Zhang 1be9fc6611 [TableGen] Generating enum definitions and utility functions
Enum attributes can be defined using `EnumAttr`, which requires all its cases
to be defined with `EnumAttrCase`. To facilitate the interaction between
`EnumAttr`s and their C++ consumers, add a new EnumsGen TableGen backend
to generate a few common utilities, including an enum class, `llvm::DenseMapInfo`
for the enum class, conversion functions from/to strings.

This is controlled via the `-gen-enum-decls` and `-gen-enum-defs` command-line
options of `mlir-tblgen`.

PiperOrigin-RevId: 252209623
2019-06-09 16:24:08 -07:00
Lei Zhang 3f517af9ad [ODG] Add iterators for results in Operator
PiperOrigin-RevId: 251417085
2019-06-09 16:16:24 -07:00
Alex Zinenko 252de8eca0 Introduce OpOperandAdaptors and emit them from ODS
When manipulating generic operations, such as in dialect conversion /
rewriting, it is often necessary to view a list of Values as operands to an
operation without creating the operation itself.  The absence of such view
makes dialect conversion patterns, among others, to use magic numbers to obtain
specific operands from a list of rewritten values when converting an operation.
Introduce XOpOperandAdaptor classes that wrap an ArrayRef<Value *> and provide
accessor functions identical to those available in XOp.  This makes it possible
for conversions to use these adaptors to address the operands with names rather
than rely on their position in the list.  The adaptors are generated from ODS
together with the actual operation definitions.

This is another step towards making dialect conversion patterns specific for a
given operation.

Illustrate the approach on conversion patterns in the standard to LLVM dialect
conversion.

PiperOrigin-RevId: 251232899
2019-06-03 19:26:12 -07:00
Lei Zhang 3650df50dd [ODS] Support region names and constraints
Similar to arguments and results, now we require region definition in ops to
    be specified as a DAG expression with the 'region' operator. This way we can
    specify the constraints for each region and optionally give the region a name.

    Two kinds of region constraints are added, one allowing any region, and the
    other requires a certain number of blocks.

--

PiperOrigin-RevId: 250790211
2019-06-01 20:11:42 -07:00
Lei Zhang d4c8c8de42 [ODS] Support numRegions in Op definition
--

PiperOrigin-RevId: 250282024
2019-06-01 20:05:31 -07:00
River Riddle be9b20ff57 NFC: Add a missing include for std::isalnum and std::digit.
--

PiperOrigin-RevId: 250085298
2019-06-01 20:04:03 -07:00
River Riddle 647f8cabb9 Add support to RewritePattern for specifying the potential operations that can be generated during a rewrite. This will enable analyses to start understanding the possible effects of applying a rewrite pattern.
--

PiperOrigin-RevId: 249936309
2019-06-01 20:02:42 -07:00
Jacques Pienaar 4165885a90 Add pattern file location to generated code to trace origin of pattern.
--

PiperOrigin-RevId: 249734666
2019-06-01 19:59:24 -07:00
Lei Zhang 20e0cedfbd [ODS] Allow dialect to specify C++ namespaces
Previously we force the C++ namespaces to be `NS` if `SomeOp` is defined as
    `NS_SomeOp`. This is too rigid as it does not support nested namespaces
    well. This CL adds a "namespace" field into the Dialect class to allow
    flexible namespaces.

--

PiperOrigin-RevId: 249064981
2019-05-20 13:49:27 -07:00
Jacques Pienaar cde4d5a6d9 Remove unnecessary C++ specifier in CPP files. NFC.
These are only required in .h files to disambiguate between C and C++ header files.

--

PiperOrigin-RevId: 248219135
2019-05-20 13:42:13 -07:00
Lei Zhang df5000fd31 [TableGen] Return base attribute's name for anonymous OptionalAttr/DefaultValuedAttr
--

PiperOrigin-RevId: 247693280
2019-05-10 19:30:48 -07:00
Mehdi Amini 91f0781000 Remove extra `;` after function definition (NFC)
Fix a GCC warning

--

PiperOrigin-RevId: 247670176
2019-05-10 19:29:26 -07:00
Jacques Pienaar 2fe8ae4f6c Fix up some mixed sign warnings.
--

PiperOrigin-RevId: 246614498
2019-05-06 08:28:20 -07:00
Jacques Pienaar 041e961802 Add extraClassDeclaration field for ops.
Simple mechanism to allow specifying arbitrary function declarations. The modelling will not cover all cases so allow a means for users to declare a method function that they will define in their C++ files. The goal is to allow full C++ flexibility as the goal is to cover cases not modelled.

--

PiperOrigin-RevId: 245889819
2019-05-06 08:21:58 -07:00
Jacques Pienaar 0ea6154b2a Add Dialect in op definition to capture prefix and documentation.
Enables specifying the documentation for dialect along with defining the ops of the dialect. The doc generator will be expanded in follow up to emit the documentation in the autogenerated files. This is precursor to allowing common base for all ops in a dialect.

    All the dialect documentation is super sparse and just added as placeholder.

    I was tempted (and started) to move ConstantOp to be generated too, but this will be easier post adding extra_methods, so deferring until then.

--

PiperOrigin-RevId: 245759984
2019-05-06 08:20:24 -07:00
Lei Zhang 6749c21d6e [TableGen] Support multiple variadic operands/results
Certain ops can have multiple variadic operands/results, e.g., `tf.DynamicStitch`.
    Even if an op has only one variadic operand/result, it is not necessarily the
    very last one, e.g., `tf.RaggedGather`. This CL enhances TableGen subsystem to be
    able to represent such cases.

    In order to deduce the operand/result value range for each variadic operand,
    currently we only support variadic operands/results all of the same size.
    So two new traits, `SameVariadicOperandSize` and `SameVariadicResultSize` are
    introduced.

--

PiperOrigin-RevId: 245310628
2019-05-06 08:16:54 -07:00
Lei Zhang ce12875333 [TableGen] Refine OpTrait classes and defs to be consistent
--

PiperOrigin-RevId: 245075421
2019-05-06 08:16:11 -07:00
Lei Zhang d0e2019d39 [TableGen] Unify cOp and tAttr into NativeCodeCall
Both cOp and tAttr were used to perform some native C++ code expression.
    Unifying them simplifies the concepts and reduces cognitive burden.

--

PiperOrigin-RevId: 244731946
2019-04-23 22:02:00 -07:00
Lei Zhang 09b623aa93 [TableGen] Capture bound source ops in PatternState
This allows accessing those bound source ops in result patterns, which can be
    useful for invoking native C++ op creation.

    We bind the op entirely here because ops can have multiple results. Design a
    approach to bind to a specific result is not the concern of this commit.

--

PiperOrigin-RevId: 244724750
2019-04-23 22:01:52 -07:00
Lei Zhang 8bb8351710 [TableGen] Fix support for ops whose names have a leading underscore
TensorFlow ops have the convention to use leading underscore to denote
    internal ops.

--

PiperOrigin-RevId: 243627723
2019-04-18 11:48:17 -07:00
Smit Hinsu 0047ef9765 NFC: Simplify named attribute in TableGen generators
Now, op attribute names don't have '.' in their names so the special handling for it
    can be removed. Attributes for functions still have dialect prefix with '.' as separator but TableGen does not deal with functions.

    TESTED with existing unit tests

--

PiperOrigin-RevId: 243287462
2019-04-18 11:47:52 -07:00
Lei Zhang 2dc6d205ac [TableGen] Allocate `Operator` object on heap in `RecordOperatorMap`
Iterators for a `llvm::DenseMap` can be invalidated when an insertion occurs.
    In Pattern's `collectBoundArguments()`, we recursively handle all nested DAG
    nodes and grow the the `RecordOperatorMap`, while retaining a reference.
    This can cause the reference to be invalid and the program to behave randomly.
    Allocate each `Operator` object specifically to solve this issue.

    Also, `llvm::DenseMap` is a great way to map pointers to pointers, or map
    other small types to each other. This avoids placing the `Operator` object
    directly into the map.

--

PiperOrigin-RevId: 243281486
2019-04-18 11:47:43 -07:00
Lei Zhang 138c972d11 [TableGen] Use `tgfmt` to format various predicates and rewrite rules
This CL changes various predicates and rewrite rules to use $-placeholders and
    `tgfmt` as the driver for substitution. This will make the predicates and rewrite
    rules more consistent regarding their arguments and more readable.

--

PiperOrigin-RevId: 243250739
2019-04-18 11:47:35 -07:00
Lei Zhang 48a6aa6c51 [TableGen] Better support for predicate and rewrite rule specification
Currently predicates are written with positional placeholders `{N}` and rely on
    `formatv` as the engine to do substitution. The problem with this approach is that
    the definitions of those positional placeholders are not consistent; they are
    entirely up to the defining predicate of question. For example, `{0}` in various
    attribute constraints is used to mean the attribute, while it is used to main the
    builder for certain attribute transformations. This can become very confusing.

    This CL introduces `tgfmt` as a new mechanism to better support for predicate and
    rewrite rule specification. Instead of entirely relying on positional placeholders,
    `tgfmt` support both positional and special placeholders. The former is used for
    DAG operands. The latter, including $_builder, $_op, $_self, are used as special
    "hooks" to entities in the context. With this, the predicate and rewrite rules
    specification can be more consistent is more readable.

--

PiperOrigin-RevId: 243249671
2019-04-18 11:47:27 -07:00
Lei Zhang 04b6d2f3c1 [TableGen] Make sure op in pattern has the same number of arguments as definition
When an op in the source pattern specifies more arguments than its definition, we
    will have out-of-bound query for op arguments from the definition. That will cause
    crashes. This change fixes it.

--

PiperOrigin-RevId: 242548415
2019-04-08 19:17:56 -07:00
Lei Zhang 4cda344e7b Add methods for building array attributes in Builder
I32/I64/F32/F64/Str array attributes are commonly used in ops. It helps
    to have handy methods for them.

--

PiperOrigin-RevId: 242170569
2019-04-07 18:19:56 -07:00
Lei Zhang b5235d1a9c [TableGen] Support array attribute subclasses and constraints
To support automatically constraint composition of ArrayAttr, a new
    predicate combiner, Concat, is introduced. It prepends a prefix and
    appends a postfix to a child predicate's final predicate string.

--

PiperOrigin-RevId: 242121186
2019-04-05 07:43:32 -07:00
Lei Zhang 3c833344c8 [TableGen] Rework verifier generation and error messages
Previously we bundle the existence check and the MLIR attribute kind check
    in one call. Further constraints (like element bitwidth) have to be split
    into following checks. That is not a nice separation given that we have more
    checks for constraints. Instead, this CL changes to generate a local variable
    for every attribute, check its existence first, then check the constraints.

    Creating a local variable for each attribute also avoids querying it multiple
    times using the raw getAttr() API. This is a win for both performance the
    readability of the generated code.

    This CL also changed the error message to be more greppable by delimiting
    the error message from constraints with boilerplate part with colon.

--

PiperOrigin-RevId: 241906132
2019-04-05 07:40:31 -07:00
Feng Liu a0606ca717 Minor fixes on the typo/naming/style in the Pattern.cpp file
--

PiperOrigin-RevId: 241341334
2019-04-01 10:59:45 -07:00
Lei Zhang b9e38a7972 [TableGen] Add EnumAttrCase and EnumAttr
This CL adds EnumAttr as a general mechanism for modelling enum attributes. Right now
    it is using StringAttr under the hood since MLIR does not have native support for enum
    attributes.

--

PiperOrigin-RevId: 241334043
2019-04-01 10:59:31 -07:00
Jacques Pienaar 1273af232c Add build files and update README.
* Add initial version of build files;
    * Update README with instructions to download and build MLIR from github;

--

PiperOrigin-RevId: 241102092
2019-03-30 11:23:22 -07:00
Feng Liu a38792f7d1 remove the const quantifier before temp variable
PiperOrigin-RevId: 240997262
2019-03-29 17:56:27 -07:00
Feng Liu 5303587448 [TableGen] Support benefit score in pattern definition.
A integer number can be specified in the pattern definition and used as the
adjustment to the default benefit score in the generated rewrite pattern C++
definition.

PiperOrigin-RevId: 240994192
2019-03-29 17:55:55 -07:00
Feng Liu c489f50e6f Add a trait to set the result type by attribute
Before this CL, the result type of the pattern match results need to be as same
as the first operand type, operand broadcast type or a generic tensor type.
This CL adds a new trait to set the result type by attribute. For example, the
TFL_ConstOp can use this to set the output type to its value attribute.

PiperOrigin-RevId: 240441249
2019-03-29 17:43:06 -07:00
Lei Zhang 8f5fa56623 [TableGen] Consolidate constraint related concepts
Previously we have multiple mechanisms to specify op definition and match constraints:
TypeConstraint, AttributeConstraint, Type, Attr, mAttr, mAttrAnyOf, mPat. These variants
are not added because there are so many distinct cases we need to model; essentially,
they are all carrying a predicate. It's just an artifact of implementation.

It's quite confusing for users to grasp these variants and choose among them. Instead,
as the OpBase TableGen file, we need to strike to provide an unified mechanism. Each
dialect has the flexibility to define its own aliases if wanted.

This CL removes mAttr, mAttrAnyOf, mPat. A new base class, Constraint, is added. Now
TypeConstraint and AttrConstraint derive from Constraint. Type and Attr further derive
from TypeConstraint and AttrConstraint, respectively.

Comments are revised and examples are added to make it clear how to use constraints.

PiperOrigin-RevId: 240125076
2019-03-29 17:38:46 -07:00
Jacques Pienaar 509cd739bf Change Value to NamedTypeConstraint and use TypeConstraint.
Previously Value was a pair of name & Type, but for operands/result a TypeConstraint rather then a Type is specified. Update C++ side to match declarative side.

PiperOrigin-RevId: 238984799
2019-03-29 17:22:51 -07:00
Feng Liu c52a812700 [TableGen] Support nested dag attributes arguments in the result pattern
Add support to create a new attribute from multiple attributes. It extended the
DagNode class to represent attribute creation dag. It also changed the
RewriterGen::emitOpCreate method to support this nested dag emit.

An unit test is added.

PiperOrigin-RevId: 238090229
2019-03-29 17:15:57 -07:00
Lei Zhang 18fde7c9d8 [TableGen] Support multiple result patterns
This CL added the ability to generate multiple ops using multiple result
patterns, with each of them replacing one result of the matched source op.

Specifically, the syntax is

```
def : Pattern<(SourceOp ...),
              [(ResultOp1 ...), (ResultOp2 ...), (ResultOp3 ...)]>;
```

Assuming `SourceOp` has three results.

Currently we require that each result op must generate one result, which
can be lifted later when use cases arise.

To help with cases that certain output is unused and we don't care about it,
this CL also introduces a new directive: `verifyUnusedValue`. Checks will
be emitted in the `match()` method to make sure if the corresponding output
is not unused, `match()` returns with `matchFailure()`.

PiperOrigin-RevId: 237513904
2019-03-29 17:07:50 -07:00
Alex Zinenko 95949a0d09 TableGen: allow mixing attributes and operands in the Arguments DAG of Op definition
The existing implementation of the Op definition generator assumes and relies
on the fact that native Op Attributes appear after its value-based operands in
the Arguments list.  Furthermore, the same order is used in the generated
`build` function for the operation.  This is not desirable for some operations
with mandatory attributes that would want the attribute to appear upfront for
better consistency with their textual representation, for example `cmpi` would
prefer the `predicate` attribute to be foremost in the argument list.

Introduce support for using attributes and operands in the Arguments DAG in no
particular order.  This is achieved by maintaining a list of Arguments that
point to either the value or the attribute and are used to generate the `build`
method.

PiperOrigin-RevId: 237002921
2019-03-29 16:59:35 -07:00
River Riddle 73e0297d36 Change the TensorFlow attribute prefix from "tf$" to "tf." to match the specification of dialect attributes. This also fixes tblgen generation of dialect attributes that used the sugared name "tf$attr" as c++ identifiers.
PiperOrigin-RevId: 236924392
2019-03-29 16:58:20 -07:00
Lei Zhang 3f644705eb [TableGen] Use ArrayRef instead of SmallVectorImpl for suitable method
PiperOrigin-RevId: 235577399
2019-03-29 16:41:35 -07:00
Lei Zhang 4887e45546 [TableGen] Fix infinite loop in SubstLeaves substitution
Previously we have `auto pos = std::string::find(...) != std::string::npos` as
if condition to control substring substitution. Instead of the position for the
found substring, `pos` will be a boolean value indicating found nor not. Then
used as the replace start position, we were always replacing starting from 0 or
1. If the replaced substring also has the pattern to be matched, we'll see
an infinite loop.

PiperOrigin-RevId: 235504681
2019-03-29 16:39:47 -07:00
Stella Laurenzo c81b16e279 Spike to define real math ops and lowering of one variant of add to corresponding integer ops.
The only reason in starting with a fixedpoint add is that it is the absolute simplest variant and illustrates the level of abstraction I'm aiming for.

The overall flow would be:
  1. Determine quantization parameters (out of scope of this cl).
  2. Source dialect rules to lower supported math ops to the quantization dialect (out of scope of this cl).
  3. Quantization passes: [-quant-convert-const, -quant-lower-uniform-real-math, -quant-lower-unsupported-to-float] (the last one not implemented yet)
  4. Target specific lowering of the integral arithmetic ops (roughly at the level of gemmlowp) to more fundamental operations (i.e. calls to gemmlowp, simd instructions, DSP instructions, etc).

How I'm doing this should facilitate implementation of just about any kind of backend except TFLite, which has a very course, adhoc surface area for its quantized kernels. Options there include (I'm not taking an opinion on this - just trying to provide options):
  a) Not using any of this: just match q/dbarrier + tf math ops to the supported TFLite quantized op set.
  b) Implement the more fundamental integer math ops on TFLite and convert to those instead of the current op set.

Note that I've hand-waved over the process of choosing appropriate quantization parameters. Getting to that next. As you can see, different implementations will likely have different magic combinations of specific math support, and we will need the target system that has been discussed for some of the esoteric cases (i.e. many DSPs only support POT fixedpoint).

Two unrelated changes to the overall goal of this CL and can be broken out of desired:
  - Adding optional attribute support to TabelGen
  - Allowing TableGen native rewrite hooks to return nullptr, signalling that no rewrite has been done.

PiperOrigin-RevId: 235267229
2019-03-29 16:39:13 -07:00
Jacques Pienaar 1725b485eb Create OpTrait base class & allow operation predicate OpTraits.
* Introduce a OpTrait class in C++ to wrap the TableGen definition;
* Introduce PredOpTrait and rename previous usage of OpTrait to NativeOpTrait;
* PredOpTrait allows specifying a trait of the operation by way of predicate on the operation. This will be used in future to create reusable set of trait building blocks in the definition of operations. E.g., indicating whether to operands have the same type and allowing locally documenting op requirements by trait composition.
  - Some of these building blocks could later evolve into known fixed set as LLVMs backends do, but that can be considered with more data.
* Use the modelling to address one verify TODO in a very local manner.

This subsumes the current custom verify specification which will be removed in a separate mechanical CL.

PiperOrigin-RevId: 234827169
2019-03-29 16:35:11 -07:00
Lei Zhang e0fc503896 [TableGen] Support using Variadic<Type> in results
This CL extended TableGen Operator class to provide accessors for information on op
results.

In OpDefinitionGen, added checks to make sure only the last result can be variadic,
and adjusted traits and builders generation to consider variadic results.

PiperOrigin-RevId: 234596124
2019-03-29 16:31:11 -07:00
Lei Zhang 081299333b [TableGen] Rename Operand to Value to prepare sharing between operand and result
We specify op operands and results in TableGen op definition using the same syntax.
They should be modelled similarly in TableGen driver wrapper classes.

PiperOrigin-RevId: 234153332
2019-03-29 16:29:11 -07:00
Lei Zhang eb3f8dcb93 [TableGen] Use deduced result types for build() of suitable ops
For ops with the SameOperandsAndResultType trait, we know that all result types
should be the same as the first operand's type. So we can generate a build()
method without requiring result types as parameters and also invoke this method
when constructing such ops during expanding rewrite patterns.

Similarly for ops have broadcast behavior, we can define build() method to use
the deduced type as the result type. So we can also calling into this build()
method when constructing ops in RewriterGen.

PiperOrigin-RevId: 233988307
2019-03-29 16:27:40 -07:00
Jacques Pienaar 388fb3751e Add pattern constraints.
Enable matching pattern only if constraint is met. Start with type constraints and more general C++ constraints.

PiperOrigin-RevId: 233830768
2019-03-29 16:26:53 -07:00
Lei Zhang a57b398906 [TableGen] Assign created ops to variables and rewrite with PatternRewriter::replaceOp()
Previously we were using PatternRewrite::replaceOpWithNewOp() to both create the new op
inline and rewrite the matched op. That does not work well if we want to generate multiple
ops in a sequence. To support that, this CL changed to assign each newly created op to a
separate variable.

This CL also refactors how PatternEmitter performs the directive dispatch logic.

PiperOrigin-RevId: 233206819
2019-03-29 16:22:53 -07:00
Lei Zhang 1df6ca5053 [TableGen] Model variadic operands using Variadic<Type>
Previously, we were using the trait mechanism to specify that an op has variadic operands.
That led a discrepancy between how we handle ops with deterministic number of operands.
Besides, we have no way to specify the constraints and match against the variadic operands.

This CL introduced Variadic<Type> as a way to solve the above issues.

PiperOrigin-RevId: 232656104
2019-03-29 16:16:28 -07:00
Smit Hinsu 2927297a1c Add derived type attributes for TensorFlow ops generated by TableGen
Motivation for this change is to remove redundant TF type attributes for
TensorFlow ops. For example, tf$T: "tfdtype$DT_FLOAT". Type attributes can be derived using the MLIR operand or result MLIR types, attribute names and their mapping. This will also allow constant folding of instructions generated within MLIR (and not imported from TensorFlow) without adding type attributes for the instruction.

Derived attributes are populated while exporting MLIR to TF GraphDef using
auto-generated populators. Populators are only available for the ops that are generated by the TableGen.

Also, fixed Operator::getNumArgs method to exclude derived attributes as they are not
part of the arguments.

TESTED with unit test

PiperOrigin-RevId: 232531561
2019-03-29 16:15:08 -07:00
Lei Zhang e0774c008f [TableGen] Use tblgen::DagLeaf to model DAG arguments
This CL added a tblgen::DagLeaf wrapper class with several helper methods for handling
DAG arguments. It helps to refactor the rewriter generation logic to be more higher
level.

This CL also added a tblgen::ConstantAttr wrapper class for constant attributes.

PiperOrigin-RevId: 232050683
2019-03-29 16:06:31 -07:00
Jacques Pienaar 82dc6a878c Add fallback to native code op builder specification for patterns.
This allow for arbitrarily complex builder patterns which is meant to cover initial cases while the modelling is improved and long tail cases/cases for which expanding the DSL would result in worst overall system.

NFC just sorting the emit replace methods alphabetical in the class and file body.

PiperOrigin-RevId: 231890352
2019-03-29 16:04:53 -07:00
Lei Zhang 66647a313a [tablegen] Use tblgen:: classes for NamedAttribute and Operand fields
This is another step towards hiding raw TableGen API calls.

PiperOrigin-RevId: 231580827
2019-03-29 16:02:23 -07:00
Lei Zhang 726dc08e4d [doc] Generate more readable description for attributes
This CL added "description" field to AttrConstraint and Attr, like what we
have for type classes.

PiperOrigin-RevId: 231579853
2019-03-29 16:01:53 -07:00
Lei Zhang 18219caeb2 [doc] Generate more readable description for operands
This CL mandated TypeConstraint and Type to provide descriptions and fixed
various subclasses and definitions to provide so. The purpose is to enforce
good documentation; using empty string as the default just invites oversight.

PiperOrigin-RevId: 231579629
2019-03-29 16:01:38 -07:00
Lei Zhang c224a518f5 TableGen: Use DAG for op results
Similar to op operands and attributes, use DAG to specify operation's results.
This will allow us to provide names and matchers for outputs.

Also Defined `outs` as a marker to indicate the start of op result list.

PiperOrigin-RevId: 231422455
2019-03-29 16:00:22 -07:00
Lei Zhang 1dfc3ac5ce Prefix Operator getter methods with "get" to be consistent
PiperOrigin-RevId: 231416230
2019-03-29 15:59:46 -07:00
Lei Zhang eb753f4aec Add tblgen::Pattern to model Patterns defined in TableGen
Similar to other tblgen:: abstractions, tblgen::Pattern hides the native TableGen
API and provides a nicer API that is more coherent with the TableGen definitions.

PiperOrigin-RevId: 231285143
2019-03-29 15:41:38 -07:00
Jacques Pienaar 0fbf4ff232 Define mAttr in terms of AttrConstraint.
* Matching an attribute and specifying a attribute constraint is the same thing executionally, so represent it such.
* Extract AttrConstraint helper to match TypeConstraint and use that where mAttr was previously used in RewriterGen.

PiperOrigin-RevId: 231213580
2019-03-29 15:41:23 -07:00
Lei Zhang ba1715f407 Pull TableGen op argument definitions into their own files
PiperOrigin-RevId: 230923050
2019-03-29 15:36:52 -07:00
Jacques Pienaar 34c6f8c6e4 Add default attr value & define tf.AvgPool op and use pattern for rewrite.
Add default values to attributes, to allow attribute being left unspecified.  The attr getter will always return an attribute so callers need not check for it, if the attribute is not set then the default will be returned (at present the default will be constructed upon query but this will be changed).

Add op definition for tf.AvgPool in ops.td, rewrite matcher using pattern using attribute matching & transforms. Adding some helper functions to make it simpler.

Handle attributes with dialect prefix and map them to getter without dialect prefix.

Note: VerifyAvgPoolOp could probably be autogenerated by know given the predicate specification on attributes, but deferring that to a follow up.
PiperOrigin-RevId: 230364857
2019-03-29 15:29:59 -07:00
Jacques Pienaar a280e3997e Start doc generation pass.
Start doc generation pass that generates simple markdown output. The output is formatted simply[1] in markdown, but this allows seeing what info we have, where we can refine the op description (e.g., the inputs is probably redundant), what info is missing (e.g., the attributes could probably have a description).

The formatting of the description is still left up to whatever was in the op definition (which luckily, due to the uniformity in the .td file, turned out well but relying on the indentation there is fragile). The mechanism to autogenerate these post changes has not been added yet either. The output file could be run through a markdown formatter too to remove extra spaces.

[1]. This is not proposal for final style :) There could also be a discussion around single doc vs multiple (per dialect, per op), whether we want a TOC, whether operands/attributes should be headings or just formatted differently ...

PiperOrigin-RevId: 230354538
2019-03-29 15:29:29 -07:00
Jacques Pienaar d6f84fa5d9 Add AttrConstraint to enable generating verification for attribute values.
Change MinMaxAttr to match hasValidMinMaxAttribute behavior. Post rewriting the other users of that function it could be removed too. The currently generated error message is:

error: 'tfl.fake_quant' op attribute 'minmax' failed to satisfy constraint of MinMaxAttr
PiperOrigin-RevId: 229775631
2019-03-29 15:25:13 -07:00
Alex Zinenko 05b02bb98e TableGen: implement predicate tree and basic simplification
A recent change in TableGen definitions allowed arbitrary AND/OR predicate
compositions at the cost of removing known-true predicate simplification.
Introduce a more advanced simplification mechanism instead.

In particular, instead of folding predicate C++ expressions directly in
TableGen, keep them as is and build a predicate tree in TableGen C++ library.
The predicate expression-substitution mechanism, necessary to implement complex
predicates for nested classes such as `ContainerType`, is replaced by a
dedicated predicate.  This predicate appears in the predicate tree and can be
used for tree matching and separation.  More specifically, subtrees defined
below such predicate may be subject to different transformations than those
that appear above.  For example, a subtree known to be true above the
substitution predicate is not necessarily true below it.

Use the predicate tree structure to eliminate known-true and known-false
predicates before code emission, as well as to collapse AND and OR predicates
if their value can be deduced based on the value of one child.

PiperOrigin-RevId: 229605997
2019-03-29 15:22:58 -07:00
Jacques Pienaar a5827fc91d Add attribute matching and transform to pattern rewrites.
Start simple with single predicate match & transform rules for attributes.
* Its unclear whether modelling Attr predicates will be needed so start with allowing matching attributes with a single predicate.
*  The input and output attr type often differs and so add ability to specify a transform between the input and output format.

PiperOrigin-RevId: 229580879
2019-03-29 15:22:14 -07:00
Alex Zinenko bd161ae5bc TableGen: untie Attr from Type
In TableGen definitions, the "Type" class has been used for types of things
that can be stored in Attributes, but not necessarily present in the MLIR type
system.  As a consequence, records like "String" or "DerviedAttrBody" were of
class "Type", which can be confusing.  Furthermore, the "builderCall" field of
the "Type" class serves only for attribute construction.  Some TableGen "Type"
subclasses that correspond to MLIR kinds of types do not have a canonical way
of construction only from the data available in TableGen, e.g. MemRefType would
require the list of affine maps.  This leads to a conclusion that the entities
that describe types of objects appearing in Attributes should be independent of
"Type": they have some properties "Type"s don't and vice versa.

Do not parameterize Tablegen "Attr" class by an instance of "Type".  Instead,
provide a "constBuilderCall" field that can be used to build an attribute from
a constant value stored in TableGen instead of indirectly going through
Attribute.Type.builderCall.  Some attributes still don't have a
"constBuilderCall" because they used to depend on types without a
"builderCall".

Drop definitions of class "Type" that don't correspond to MLIR Types.  Provide
infrastructure to define type-dependent attributes and string-backed attributes
for convenience.

PiperOrigin-RevId: 229570087
2019-03-29 15:21:28 -07:00
Alex Zinenko 44e9869f1a TableGen: extract TypeConstraints from Type
MLIR has support for type-polymorphic instructions, i.e. instructions that may
take arguments of different types.  For example, standard arithmetic operands
take scalars, vectors or tensors.  In order to express such instructions in
TableGen, we need to be able to verify that a type object satisfies certain
constraints, but we don't need to construct an instance of this type.  The
existing TableGen definition of Type requires both.  Extract out a
TypeConstraint TableGen class to define restrictions on types.  Define the Type
TableGen class as a subclass of TypeConstraint for consistency.  Accept records
of the TypeConstraint class instead of the Type class as values in the
Arguments class when defining operators.

Replace the predicate logic TableGen class based on conjunctive normal form
with the predicate logic classes allowing for abitrary combinations of
predicates using Boolean operators (AND/OR/NOT).  The combination is
implemented using simple string rewriting of C++ expressions and, therefore,
respects the short-circuit evaluation order.  No logic simplification is
performed at the TableGen level so all expressions must be valid C++.
Maintaining CNF using TableGen only would have been complicated when one needed
to introduce top-level disjunction.  It is also unclear if it could lead to a
significantly simpler emitted C++ code.  In the future, we may replace inplace
predicate string combination with a tree structure that can be simplified in
TableGen's C++ driver.

Combined, these changes allow one to express traits like ArgumentsAreFloatLike
directly in TableGen instead of relying on C++ trait classes.

PiperOrigin-RevId: 229398247
2019-03-29 15:18:23 -07:00
Jacques Pienaar 4c0faef943 Avoid redundant predicate checking in type matching.
Expand type matcher template generator to consider a set of predicates that are known to
hold. This avoids inserting redundant checking for trivially true predicates
(for example predicate that hold according to the op definition). This only targets predicates that trivially holds and does not attempt any logic equivalence proof.

PiperOrigin-RevId: 228880468
2019-03-29 15:09:25 -07:00
Lei Zhang 9b034f0bfd Add tblgen::Attribute to wrap around TableGen Attr defs
This CL added a tblgen::Attribute class to wrap around raw TableGen
Record getValue*() calls on Attr defs, which will provide a nicer
API for handling TableGen Record.

PiperOrigin-RevId: 228581107
2019-03-29 15:06:41 -07:00
Lei Zhang 3e5ee82b81 Put Operator and PredCNF into the tblgen namespace
PiperOrigin-RevId: 228429130
2019-03-29 15:05:38 -07:00
Lei Zhang b2cc2c344e Add tblgen::Type to wrap around TableGen Type defs
This CL added a tblgen::Type class to wrap around raw TableGen
Record getValue*() calls on Type defs, which will provide a
nicer API for handling TableGen Record.

The PredCNF class is also updated to work together with
tblgen::Type.
PiperOrigin-RevId: 228429090
2019-03-29 15:05:23 -07:00
Lei Zhang f8bbe5deca Various tiny refinements over TableGen Operator class
Use "native" vs "derived" to differentiate attributes on ops: native ones
are specified when creating the op as a part of defining the op, while
derived ones are computed from properties of the op.

PiperOrigin-RevId: 228186962
2019-03-29 15:01:56 -07:00
Jacques Pienaar aae85ddce1 Match attributes in input pattern.
Bind attributes similar to operands. Use to rewrite leakyreulo and const rewrite pattern. The attribute type/attributes are not currently checked so should only be used where the attributes match due to the construction of the op.

To support current attribute namespacing, convert __ in attribute name to "$" for matching purposes ('$' is not valid character in variable in TableGen).

Some simplification to make it simpler to specify indented ostream and avoid so many spaces. The goal is not to have perfectly formatted code generated but good enough so that its still easy to read for a user.

PiperOrigin-RevId: 228183639
2019-03-29 15:00:55 -07:00
Jacques Pienaar 8f24943826 Verify type of operands match those specifed in op registry.
Expand type to include matcher predicates. Use CNF form to allow specifying combinations of constraints for type. The matching call for the type is used to verify the construction of the operation as well as in rewrite pattern generation.

The matching initially includes redundant checks (e.g., even if the operand of the op is guaranteed to satisfy some requirement, it is still checked during matcher generation for now). As well as some of the traits specified now check what the generated code already checks. Some of the traits can be removed in future as the verify method will include the relevant checks based on the op definition already.

More work is needed for variadic operands.

CNF form is used so that in the follow up redundant checks in the rewrite patterns could be omitted (e.g., when matching a F32Tensor, one does not need to verify that op X's operand 0 is a Tensor if that is guaranteed by op X's definition). The alternative was to have single matcher function specified, but this would not allow for reasoning about what attributes already hold (at the level of PredAtoms).

Use this new operand type restrictions to rewrite BiasAdd with floating point operands as declarative pattern.

PiperOrigin-RevId: 227991412
2019-03-29 14:58:23 -07:00
Jacques Pienaar dde5bf234d Use Operator class in OpDefinitionsGen. Cleanup NFC.
PiperOrigin-RevId: 227764826
2019-03-29 14:55:22 -07:00
Jacques Pienaar c396c044e6 Match the op via isa instead of string compare.
* Match using isa
  - This limits the rewrite pattern to ops defined in op registry but that is probably better end state (esp. for additional verification).

PiperOrigin-RevId: 227598946
2019-03-29 14:53:37 -07:00
Jacques Pienaar 2a463c36b1 Add convenience wrapper for operator in tblgen
Add convenience wrapper to make it easier to iterate over attributes and operands of operator defined in TableGen file. Use this class in RewriterGen (not used in the op generator yet, will do shortly). Change the RewriterGen to pass the bound arguments explicitly, this is in preparation for multi-op matching.

PiperOrigin-RevId: 227156748
2019-03-29 14:43:43 -07:00