Commit Graph

87 Commits

Author SHA1 Message Date
Nicolas Vasilache 4911978f7e [MLIR] Value types for AffineXXXExpr
This CL makes AffineExprRef into a value type.

Notably:
1. drops llvm isa, cast, dyn_cast on pointer type and uses member functions on
the value type. It may be possible to still use classof  (in a followup CL)
2. AffineBaseExprRef aggressively casts constness away: if we mean the type is
immutable then let's jump in with both feet;
3. Drop implicit casts to the underlying pointer type because that always
results in surprising behavior and is not needed in practice once enough
cleanup has been applied.

The remaining negative I see is that we still need to mix operator. and
operator->. There is an ugly solution that forwards the methods but that ends
up duplicating the class hierarchy which I tried to avoid as much as
possible. But maybe it's not that bad anymore since AffineExpr.h would still
contain a single class hierarchy (the duplication would be impl detail in.cpp)

PiperOrigin-RevId: 216188003
2019-03-29 13:24:31 -07:00
Chris Lattner d2d89cbc19 Rename affineint type to index type. The name 'index' may not be perfect, but is better than the old name. Here is some justification:
1) affineint (as it is named) is not a type suitable for general computation (e.g. the multiply/adds in an integer matmul).  It has undefined width and is undefined on overflow.  They are used as the indices for forstmt because they are intended to be used as indexes inside the loop.

2) It can be used in both cfg and ml functions, and in cfg functions.  As you mention, “symbols” are not affine, and we use affineint values for symbols.

3) Integers aren’t affine, the algorithms applied to them can be. :)

4) The only suitable use for affineint in MLIR is for indexes and dimension sizes (i.e. the bounds of those indexes).

PiperOrigin-RevId: 216057974
2019-03-29 13:24:16 -07:00
Nicolas Vasilache b55b407601 [RFC][MLIR] Use AffineExprRef in place of AffineExpr* in IR
This CL starts by replacing AffineExpr* with value-type AffineExprRef in a few
places in the IR. By a domino effect that is pretty telling of the
inconsistencies in the codebase, const is removed where it makes sense.

The rationale is that the decision was concisously made that unique'd types
have pointer semantics without const specifier. This is fine but we should be
consistent. In the end, the only logical invariant is that there should never
be such a thing as a const AffineExpr*, const AffineMap* or const IntegerSet*
in our codebase.

This CL takes a number of shortcuts to killing const with fire, in particular
forcing const AffineExprRef to return the underlying non-const
AffineExpr*. This will be removed once AffineExpr* has disappeared in
containers but for now such shortcuts allow a bit of sanity in this long quest
for cleanups.

The **only** places where const AffineExpr*, const AffineMap* or const
IntegerSet* may still appear is by transitive needs from containers,
comparison operators etc.

There is still one major thing remaining here: figure out why cast/dyn_cast
return me a const AffineXXX*, which in turn requires a bunch of ugly
const_casts. I suspect this is due to the classof
taking const AffineXXXExpr*. I wonder whether this is a side effect of 1., if
it is coming from llvm itself (I'd doubt it) or something else (clattner@?)

In light of this, the whole discussion about const makes total sense to me now
and I would systematically apply the rule that in the end, we should never
have any const XXX in our codebase for unique'd types (assuming we can remove
them all in containers and no additional constness constraint is added on us
from the outside world).

PiperOrigin-RevId: 215811554
2019-03-29 13:23:05 -07:00
Nicolas Vasilache 544f5e7a9b [MLIR] Remove uses of AffineExpr* outside of IR
This CL uniformizes the uses of AffineExprWrap outside of IR.
The public API of AffineExpr builder is modified to only use AffineExprWrap.
A few places access AffineExprWrap.expr, this is only while the API is in
transition to easily keep track (i.e. make expr private and let the compiler
track the errors).

Parser.cpp exhibits patterns that are dependent on nullptr values so
converting it is left for another CL.

PiperOrigin-RevId: 215642005
2019-03-29 13:22:35 -07:00
Feng Liu 430172ab47 Add support to TF f32_ref type in MLIR
PiperOrigin-RevId: 214722005
2019-03-29 13:20:32 -07:00
Nicolas Vasilache 54e5b4b4c0 [MLIR] Fix AsmPrinter for short-hand bound notation
This CL retricts shorthand notation printing to only the bounds that can
be roundtripped unambiguously; i.e.:
1. ()[]->(%some_cst) ()[]
2. ()[s0]->(s0) ()[%some_symbol]

Upon inspection it turns out that the constant case was lossy so this CL also
updates it.

Note however that fixing this issue exhibits a potential issues in unroll.mlir.
L488 exhibits a map ()[s0] -> (1)()[%arg0] which could be simplified down to
()[]->(1)()[].
This does not seem like a bug but maybe an undesired complexity in the maps
generated by unrolling.
bondhugula@, care to take a look?

PiperOrigin-RevId: 214531410
2019-03-29 13:19:04 -07:00
Nicolas Vasilache f9e50199e9 [MLIR] Fix AsmPrinter.cpp for single ssa-id AffineMap
The AsmPrinter wrongly assumes that all single ssa-id AffineMap
are the identity map for the purpose of printing.
This CL adds the missing level of indirection as well as a test.

This bug was originally shaken off by the experimental TC->MLIR path.

Before this CL, the test would print:
```
mlfunc @mlfuncsimplemap(%arg0 : affineint, %arg1 : affineint, %arg2 : affineint) {
  for %i0 = 0 to %arg0 {
    for %i1 = 0 to %i0 {
                   ~~~   should be %arg1
      %c42_i32 = constant 42 : i32
    }
  }
  return
}
```

PiperOrigin-RevId: 214120817
2019-03-29 13:18:05 -07:00
Chris Lattner d6f8ec7bac Introduce [post]dominator tree and related infrastructure, use it in CFG func
verifier.  We get most of this infrastructure directly from LLVM, we just
need to adapt it to our CFG abstraction.

This has a few unrelated changes engangled in it:
 - getFunction() in various classes was const incorrect, fix it.
 - This moves Verifier.cpp to the analysis library, since Verifier depends on
   dominance and these are both really analyses.
 - IndexedAccessorIterator::reference was defined wrong, leading to really
   exciting template errors that were fun to diagnose.
 - This flips the boolean sense of the foldOperation() function in constant
   folding pass in response to previous patch feedback.

PiperOrigin-RevId: 214046593
2019-03-29 13:17:20 -07:00
Feng Liu 948dea045b Supports TF Complex64/Complex128 types in the tf/mlir roundtrip pass.
Alternatively, we can defined a TFComplexType with a width parameter in the
mlir, then both types can be converted to the same mlir type with different width (like IntegerType).
We chose to use a direct mapping because there are only two TF Complex types.

PiperOrigin-RevId: 213856651
2019-03-29 13:17:02 -07:00
Feng Liu 5f69643cbf Support TF Variant type in the tf/mlir roundtrip pass.
PiperOrigin-RevId: 213748573
2019-03-29 13:16:18 -07:00
Feng Liu 4bc5dc9602 Handle the TF resource data type in the TF/XLA roundtrip pass.
PiperOrigin-RevId: 213650346
2019-03-29 13:16:03 -07:00
Feng Liu 7e004efae2 Add function attributes for ExtFunction, CFGFunction and MLFunction.
PiperOrigin-RevId: 213540509
2019-03-29 13:15:35 -07:00
Chris Lattner e1257e8978 Change unranked tensor syntax from tensor<??f32> to tensor<*xf32> per
discussion on the list.

PiperOrigin-RevId: 212838226
2019-03-29 13:13:42 -07:00
Uday Bondhugula 64812a56c7 Extend getConstantTripCount to deal with a larger subset of loop bounds; make loop
unroll/unroll-and-jam more powerful; add additional affine expr builder methods

- use previously added analysis/simplification to infer multiple of unroll
  factor trip counts, making loop unroll/unroll-and-jam more general.

- for loop unroll, support bounds that are single result affine map's with the
  same set of operands. For unknown loop bounds, loop unroll will now work as
  long as trip count can be determined to be a multiple of unroll factor.

- extend getConstantTripCount to deal with single result affine map's with the
  same operands. move it to mlir/Analysis/LoopAnalysis.cpp

- add additional builder utility methods for affine expr arithmetic
  (difference, mod/floordiv/ceildiv w.r.t postitive constant). simplify code to
  use the utility methods.

- move affine analysis routines to AffineAnalysis.cpp/.h from
  AffineStructures.cpp/.h.

- Rename LoopUnrollJam to LoopUnrollAndJam to match class name.

- add an additional simplification for simplifyFloorDiv, simplifyCeilDiv

- Rename AffineMap::getNumOperands() getNumInputs: an affine map by itself does
  not have operands. Operands are passed to it through affine_apply, from loop
  bounds/if condition's, etc., operands are stored in the latter.

This should be sufficiently powerful for now as far as unroll/unroll-and-jam go for TPU
code generation, and can move to other analyses/transformations.

Loop nests like these are now unrolled without any cleanup loop being generated.

  for %i = 1 to 100 {
    // unroll factor 4: no cleanup loop will be generated.
    for %j = (d0) -> (d0) (%i) to (d0) -> (5*d0 + 3) (%i) {
      %x = "foo"(%j) : (affineint) -> i32
    }
  }

  for %i = 1 to 100 {
    // unroll factor 4: no cleanup loop will be generated.
    for %j = (d0) -> (d0) (%i) to (d0) -> (d0 - d mod 4 - 1) (%i) {
      %y = "foo"(%j) : (affineint) -> i32
    }
  }

  for %i = 1 to 100 {
    for %j = (d0) -> (d0) (%i) to (d0) -> (d0 + 128) (%i) {
      %x = "foo"() : () -> i32
    }
  }

TODO(bondhugula): extend this to LoopUnrollAndJam as well in the next CL (with minor
changes).

PiperOrigin-RevId: 212661212
2019-03-29 13:13:00 -07:00
Chris Lattner 5f11f68405 Several minor infra improvements:
- Make the tf-lower-control flow handle error cases better.  Add a testcase
   that (currently) fails due to type mismatches.
 - Factor more code in the verifier for basic block argument checking, and
   check more invariants.
 - Fix a crasher in the asmprinter on null instructions (which only occurs on
   invalid code).
 - Fix a bug handling conditional branches with no block operands, it would
   access &operands[0] instead of using operands.data().
 - Enhance the mlir-opt driver to use the verifier() in a non-crashing mode,
   allowing issues to be reported as diagnostics.

PiperOrigin-RevId: 211818291
2019-03-29 13:10:11 -07:00
Tatiana Shpeisman 1a56ee7093 Implement operands for the 'if' statement.
This CL also includes two other minor changes:
- change the implemented syntax from 'if (cond)' to 'if cond', as specified by MLIR spec.
- a minor fix to the implementation of the ForStmt.

PiperOrigin-RevId: 210618122
2019-03-29 13:07:16 -07:00
Tatiana Shpeisman d32a28c520 Implement operands for the lower and upper bounds of the for statement.
This revamps implementation of the loop bounds in the ForStmt, using general representation that supports operands. The frequent case of constant bounds is supported
via special access methods.

This also includes:
- Operand iterators for the Statement class.
- OpPointer::is() method to query the class of the Operation.
- Support for the bound shorthand notation parsing and printing.
- Validity checks for the bound operands used as dim ids and symbols

I didn't mean this CL to be so large. It just happened this way, as one thing led to another.

PiperOrigin-RevId: 210204858
2019-03-29 13:05:16 -07:00
Chris Lattner 84259c7def Implement call and call_indirect ops.
This also fixes an infinite recursion in VariadicOperands that this turned up.

PiperOrigin-RevId: 209692932
2019-03-29 13:03:51 -07:00
Uday Bondhugula 00bed4bd99 Extend loop unrolling to unroll by a given factor; add builder for affine
apply op.

- add builder for AffineApplyOp (first one for an operation that has
  non-zero operands)
- add support for loop unrolling by a given factor; uses the affine apply op
  builder.

While on this, change 'step' of ForStmt to be 'unsigned' instead of
AffineConstantExpr *. Add setters for ForStmt lb, ub, step.

Sample Input:

// CHECK-LABEL: mlfunc @loop_nest_unroll_cleanup() {
mlfunc @loop_nest_unroll_cleanup() {
  for %i = 1 to 100 {
    for %j = 0 to 17 {
      %x = "addi32"(%j, %j) : (affineint, affineint) -> i32
      %y = "addi32"(%x, %x) : (i32, i32) -> i32
    }
  }
  return
}

Output:

$ mlir-opt -loop-unroll -unroll-factor=4 /tmp/single2.mlir
#map0 = (d0) -> (d0 + 1)
#map1 = (d0) -> (d0 + 2)
#map2 = (d0) -> (d0 + 3)
mlfunc @loop_nest_unroll_cleanup() {
  for %i0 = 1 to 100 {
    for %i1 = 0 to 17 step 4 {
      %0 = "addi32"(%i1, %i1) : (affineint, affineint) -> i32
      %1 = "addi32"(%0, %0) : (i32, i32) -> i32
      %2 = affine_apply #map0(%i1)
      %3 = "addi32"(%2, %2) : (affineint, affineint) -> i32
      %4 = affine_apply #map1(%i1)
      %5 = "addi32"(%4, %4) : (affineint, affineint) -> i32
      %6 = affine_apply #map2(%i1)
      %7 = "addi32"(%6, %6) : (affineint, affineint) -> i32
    }
    for %i2 = 16 to 17 {
      %8 = "addi32"(%i2, %i2) : (affineint, affineint) -> i32
      %9 = "addi32"(%8, %8) : (i32, i32) -> i32
    }
  }
  return
}

PiperOrigin-RevId: 209676220
2019-03-29 13:03:38 -07:00
Chris Lattner 9265197c4e Implement initial support for function attributes, including parser, printer,
resolver support.

Still TODO are verifier support (to make sure you don't use an attribute for a
function in another module) and the TODO in ModuleParser::finalizeModule that I
will handle in the next patch.

PiperOrigin-RevId: 209361648
2019-03-29 13:02:44 -07:00
Chris Lattner ae79d69922 Implement a module-level symbol table for functions, enforcing uniqueness of
names across the module and auto-renaming conflicts.  Have the parser reject
malformed modules that have redefinitions.

PiperOrigin-RevId: 209227560
2019-03-29 13:02:30 -07:00
Chris Lattner d6c4c748d7 Escape and unescape strings in the parser and printer so they can roundtrip,
print floating point in a structured form that we know can round trip,
enumerate attributes in the visitor so we print affine mapping attributes
symbolically (the majority of the testcase updates).

We still have an issue where the hexadecimal floating point syntax is reparsed
as an integer, but that can evolve in subsequent patches.

PiperOrigin-RevId: 208828876
2019-03-29 13:00:05 -07:00
Tatiana Shpeisman 4e289a4700 Implement return statement as RetOp operation. Add verification of the return statement placement and operands. Add parser and parsing error tests for return statements with non-zero number of operands. Add a few missing tests for ForStmt parsing errors.
Prior to this CL, return statement had no explicit representation in MLIR. Now, it is represented as ReturnOp standard operation and is pretty printed according to the return statement syntax. This way statement walkers can process ML function return operands without making special case for them.

PiperOrigin-RevId: 208092424
2019-03-29 12:58:04 -07:00
Chris Lattner 8159186f57 Rework the cloning infrastructure for statements to be able to take and update
an operand mapping, which simplifies it a bit.  Implement cloning for IfStmt,
rename getThenClause() to getThen() which is unambiguous and less repetitive in
use cases.

PiperOrigin-RevId: 207915990
2019-03-29 12:57:38 -07:00
Uday Bondhugula 8a663870e8 Support for affine integer sets
- introduce affine integer sets into the IR
- parse and print affine integer sets (both inline or outlined) similar to
  affine maps
- use integer set for IfStmt's conditional, and implement parsing of IfStmt's
  conditional

- fixed an affine expr paren omission bug while one this.

TODO: parse/represent/print MLValue operands to affine integer set references.
PiperOrigin-RevId: 207779408
2019-03-29 12:56:58 -07:00
Chris Lattner 9d29310882 Use OperationState to simplify the create<Op> methods, move them out of line,
and simplify some other things.  Change ConstantIntOp to not match affine
integers, since we now have ConstantAffineIntOp.

PiperOrigin-RevId: 207756316
2019-03-29 12:56:44 -07:00
Tatiana Shpeisman a0a6414ca2 Implement ML function arguments. Add representation for argument list in ML Function using TrailingObjects template. Implement argument iterators, parsing and printing.
Unrelated minor change - remove OperationStmt::dropReferences(). Since MLFunction does not have cyclic operand references (it's an AST) destruction can be safely done w/o a special pass to drop references.

PiperOrigin-RevId: 207583024
2019-03-29 12:55:47 -07:00
Uday Bondhugula 65b6e73245 Loop unrolling update.
- deal with non-operation stmt's (if/for stmt's) in loops being unrolled
  (unrolling of non-innermost loops works).
- update uses in unrolled bodies to use results of new operations that may be
  introduced in the unrolled bodies.

Unrolling now works for all kinds of loop nests - perfect nests, imperfect
nests, loops at any depth, and with any kind of operation in the body. (IfStmt
support not done, hence untested there).

Added missing dump/print method for StmtBlock.

TODO: add test case for outer loop unrolling.
PiperOrigin-RevId: 207314286
2019-03-29 12:55:19 -07:00
Tatiana Shpeisman 2dcdec8910 Fix segfaults when printing unlinked statements, instructions and blocks. Fancy printing requires a pointer to the function since SSA values get function-specific names. This CL adds checks to ensure that we don't dereference null pointers in unliked objects. Unlinked statements, instructions and blocks are printed as <<UNLINKED STATEMENT>> etc.
PiperOrigin-RevId: 207293992
2019-03-29 12:55:06 -07:00
James Molloy 2cf3d22932 [mlir] Correctly indent block terminators
These were non-indented, which I thought was deliberate until Chris corrected me in cl/207115253 :)

PiperOrigin-RevId: 207246887
2019-03-29 12:54:24 -07:00
James Molloy 72645b31b8 [mlir] Add a TypeAttr class, allow type attributes
PiperOrigin-RevId: 207235956
2019-03-29 12:54:11 -07:00
Chris Lattner fc1f223447 Have the asmprinter give true/false constants nice names, add a dump/print
method to SSAValue.

PiperOrigin-RevId: 207193088
2019-03-29 12:53:44 -07:00
Chris Lattner 316e884367 Give custom ops the ability to also access general additional attributes in the
parser and printer.  Fix the spelling of 'delimeter'

PiperOrigin-RevId: 207189892
2019-03-29 12:53:31 -07:00
James Molloy 6472f5fbbb [mlir] Fix ReturnInst printing for zero operands
No longer prints a trailing ':'.

PiperOrigin-RevId: 207103812
2019-03-29 12:53:17 -07:00
Uday Bondhugula b92378e8fa More simplification for affine binary op expr's.
- simplify operations with identity elements (multiply by 1, add with 0).
- simplify successive add/mul: fold constants, propagate constants to the
  right.
- simplify floordiv and ceildiv when divisors are constants, and the LHS is a
  multiply expression with RHS constant.
- fix an affine expression printing bug on paren emission.

- while on this, fix affine-map test cases file (memref's using layout maps
  that were duplicates of existing ones should be emitted pointing to the
  unique'd one).

PiperOrigin-RevId: 207046738
2019-03-29 12:52:48 -07:00
James Molloy 1e793eb8dc [mlir] Add a string type
PiperOrigin-RevId: 206977161
2019-03-29 12:52:35 -07:00
Chris Lattner 8eaf382734 Use SFINAE to generalize << overloads, give 'constant' a pretty form,
generalize the asmprinters handling of pretty names to allow arbitrary sugar to
be dumped on various constructs.  Give CFG function arguments nice "arg0" names
like MLFunctions get, and give constant integers pretty names like %c37 for a
constant 377

PiperOrigin-RevId: 206953080
2019-03-29 12:52:07 -07:00
Tatiana Shpeisman 8189a12bce Clean up and extend MLFuncBuilder to allow creating statements in the middle of a statement block. Rename Statement::getFunction() and StmtBlock()::getFunction() to findFunction() to make it clear that this is not a constant time getter.
Fix b/112039912 - we were recording 'i' instead of '%i' for loop induction variables causing "use of undefined SSA value" error.

PiperOrigin-RevId: 206884644
2019-03-29 12:51:38 -07:00
Chris Lattner 5228ec3146 Fix some issues where we weren't printing affine map references symbolically.
Two problems: 1) we didn't visit the types in ops correctly, and 2) the
general "T" version of the OpAsmPrinter inserter would match things like
MemRefType& and print it directly.

PiperOrigin-RevId: 206863642
2019-03-29 12:51:25 -07:00
Chris Lattner ace4df1200 Revise the AffineExpr printing logic to be more careful about paren emission.
This is still (intentionally) generating redundant parens for nested tightly
binding expressions, but I think that is reasonable for readability sake.

This also print x-y instead of x-(y*1)

PiperOrigin-RevId: 206847212
2019-03-29 12:50:59 -07:00
Tatiana Shpeisman 43e2a13605 Use for statement directly as an operand instead of having it pretend to be an induction variable.
PiperOrigin-RevId: 206759180
2019-03-29 12:49:50 -07:00
Tatiana Shpeisman c8b0273f19 Implement induction variables. Pretty print induction variable operands as %i<ssa value number>. Add support for future pretty printing of ML function arguments as %arg<ssa value number>.
Induction variables are implemented by inheriting ForStmt from MLValue. ForStmt provides APIs that make this design decision invisible to the ForStmt users.

This CL in combination with cl/206253643 resolves  http://b/111769060.

PiperOrigin-RevId: 206655937
2019-03-29 12:49:36 -07:00
Chris Lattner 782c348c00 Change mlir-opt.cpp to take a list of passes to run, simplifying the driver
code.  Change printing of affine map's to not print a space between the dim and
symbol list.

PiperOrigin-RevId: 206505419
2019-03-29 12:47:38 -07:00
Chris Lattner 9128a4aa87 Finish parser/printer support for AffineMapOp, implement operand iterators on
VariadicOperands, tidy up some code in the asmprinter, fill out more
verification logic in for LoadOp.

PiperOrigin-RevId: 206443020
2019-03-29 12:47:11 -07:00
Chris Lattner 6e89270b2d Implement support for predecessor iterators on basic blocks, use them to print
out predecessor information in the asmprinter.

PiperOrigin-RevId: 206343174
2019-03-29 12:46:44 -07:00
Jacques Pienaar 6a93e146c0 Add tf_control type and allow $ in bare-id.
* Add tf_control as primitive type;
* Allow $ in bare-id to allow attributes with $ (to make it trivially to mangle a TF attribute);

PiperOrigin-RevId: 206342642
2019-03-29 12:46:30 -07:00
Uday Bondhugula 0af97111d2 Stmt visitors and walkers.
- Update InnermostLoopGatherer to use a post order traversal (linear
  time/single traversal).
- Drop getNumNestedLoops().
- Update isInnermost() to use the StmtWalker.

When using return values in conjunction with walkers, the StmtWalker CRTP
pattern doesn't appear to be of any use. It just requires overriding nearly all
of the methods, which is what InnermostLoopGatherer currently does. Please see
FIXME/ENLIGHTENME comments. TODO: figure this out from this CL discussion.

Note
- Comments on visitor/walker base class are out of date; will update when this
  CL is finalized.

PiperOrigin-RevId: 206340901
2019-03-29 12:46:17 -07:00
Tatiana Shpeisman 9ebd3c7df8 Implement MLValue, statement operands, operation statement operands and values. ML functions now have full support for expressing operations. Induction variables, function arguments and return values are still todo.
PiperOrigin-RevId: 206253643
2019-03-29 12:46:04 -07:00
Chris Lattner f964bad6d1 Implement a proper function list in module, which auto-maintain the parent
pointer, and ensure that functions are deleted when the module is destroyed.

This exposed the fact that MLFunction had no dtor, and that the dtor in
CFGFunction was broken with cyclic references.  Fix both of these problems.

PiperOrigin-RevId: 206051666
2019-03-29 12:43:57 -07:00
Chris Lattner 50f89b4188 Fix FIXME's/TODOs:
- Enhance memref type to allow omission of mappings and address
   spaces (implying a default mapping).
 - Fix printing of function types to properly recurse with printType
   so mappings are printed by name.
 - Simplify parsing of AffineMaps a bit now that we have
   isSymbolicOrConstant()

PiperOrigin-RevId: 206039755
2019-03-29 12:43:42 -07:00