MLIR  20.0.0git
AffineExpr.cpp
Go to the documentation of this file.
1 //===- AffineExpr.cpp - MLIR Affine Expr Classes --------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include <cmath>
10 #include <cstdint>
11 #include <limits>
12 #include <utility>
13 
14 #include "AffineExprDetail.h"
15 #include "mlir/IR/AffineExpr.h"
17 #include "mlir/IR/AffineMap.h"
18 #include "mlir/IR/IntegerSet.h"
19 #include "mlir/Support/TypeID.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Support/MathExtras.h"
22 #include <numeric>
23 #include <optional>
24 
25 using namespace mlir;
26 using namespace mlir::detail;
27 
28 using llvm::divideCeilSigned;
29 using llvm::divideFloorSigned;
30 using llvm::divideSignedWouldOverflow;
31 using llvm::mod;
32 
33 MLIRContext *AffineExpr::getContext() const { return expr->context; }
34 
35 AffineExprKind AffineExpr::getKind() const { return expr->kind; }
36 
37 /// Walk all of the AffineExprs in `e` in postorder. This is a private factory
38 /// method to help handle lambda walk functions. Users should use the regular
39 /// (non-static) `walk` method.
40 template <typename WalkRetTy>
42  function_ref<WalkRetTy(AffineExpr)> callback) {
43  struct AffineExprWalker
44  : public AffineExprVisitor<AffineExprWalker, WalkRetTy> {
45  function_ref<WalkRetTy(AffineExpr)> callback;
46 
47  AffineExprWalker(function_ref<WalkRetTy(AffineExpr)> callback)
48  : callback(callback) {}
49 
50  WalkRetTy visitAffineBinaryOpExpr(AffineBinaryOpExpr expr) {
51  return callback(expr);
52  }
53  WalkRetTy visitConstantExpr(AffineConstantExpr expr) {
54  return callback(expr);
55  }
56  WalkRetTy visitDimExpr(AffineDimExpr expr) { return callback(expr); }
57  WalkRetTy visitSymbolExpr(AffineSymbolExpr expr) { return callback(expr); }
58  };
59 
60  return AffineExprWalker(callback).walkPostOrder(e);
61 }
62 // Explicitly instantiate for the two supported return types.
63 template void mlir::AffineExpr::walk(AffineExpr e,
64  function_ref<void(AffineExpr)> callback);
65 template WalkResult
68 
69 // Dispatch affine expression construction based on kind.
71  AffineExpr rhs) {
72  if (kind == AffineExprKind::Add)
73  return lhs + rhs;
74  if (kind == AffineExprKind::Mul)
75  return lhs * rhs;
76  if (kind == AffineExprKind::FloorDiv)
77  return lhs.floorDiv(rhs);
78  if (kind == AffineExprKind::CeilDiv)
79  return lhs.ceilDiv(rhs);
80  if (kind == AffineExprKind::Mod)
81  return lhs % rhs;
82 
83  llvm_unreachable("unknown binary operation on affine expressions");
84 }
85 
86 /// This method substitutes any uses of dimensions and symbols (e.g.
87 /// dim#0 with dimReplacements[0]) and returns the modified expression tree.
90  ArrayRef<AffineExpr> symReplacements) const {
91  switch (getKind()) {
93  return *this;
94  case AffineExprKind::DimId: {
95  unsigned dimId = llvm::cast<AffineDimExpr>(*this).getPosition();
96  if (dimId >= dimReplacements.size())
97  return *this;
98  return dimReplacements[dimId];
99  }
101  unsigned symId = llvm::cast<AffineSymbolExpr>(*this).getPosition();
102  if (symId >= symReplacements.size())
103  return *this;
104  return symReplacements[symId];
105  }
106  case AffineExprKind::Add:
107  case AffineExprKind::Mul:
110  case AffineExprKind::Mod:
111  auto binOp = llvm::cast<AffineBinaryOpExpr>(*this);
112  auto lhs = binOp.getLHS(), rhs = binOp.getRHS();
113  auto newLHS = lhs.replaceDimsAndSymbols(dimReplacements, symReplacements);
114  auto newRHS = rhs.replaceDimsAndSymbols(dimReplacements, symReplacements);
115  if (newLHS == lhs && newRHS == rhs)
116  return *this;
117  return getAffineBinaryOpExpr(getKind(), newLHS, newRHS);
118  }
119  llvm_unreachable("Unknown AffineExpr");
120 }
121 
123  return replaceDimsAndSymbols(dimReplacements, {});
124 }
125 
128  return replaceDimsAndSymbols({}, symReplacements);
129 }
130 
131 /// Replace dims[offset ... numDims)
132 /// by dims[offset + shift ... shift + numDims).
133 AffineExpr AffineExpr::shiftDims(unsigned numDims, unsigned shift,
134  unsigned offset) const {
136  for (unsigned idx = 0; idx < offset; ++idx)
137  dims.push_back(getAffineDimExpr(idx, getContext()));
138  for (unsigned idx = offset; idx < numDims; ++idx)
139  dims.push_back(getAffineDimExpr(idx + shift, getContext()));
140  return replaceDimsAndSymbols(dims, {});
141 }
142 
143 /// Replace symbols[offset ... numSymbols)
144 /// by symbols[offset + shift ... shift + numSymbols).
145 AffineExpr AffineExpr::shiftSymbols(unsigned numSymbols, unsigned shift,
146  unsigned offset) const {
148  for (unsigned idx = 0; idx < offset; ++idx)
149  symbols.push_back(getAffineSymbolExpr(idx, getContext()));
150  for (unsigned idx = offset; idx < numSymbols; ++idx)
151  symbols.push_back(getAffineSymbolExpr(idx + shift, getContext()));
152  return replaceDimsAndSymbols({}, symbols);
153 }
154 
155 /// Sparse replace method. Return the modified expression tree.
158  auto it = map.find(*this);
159  if (it != map.end())
160  return it->second;
161  switch (getKind()) {
162  default:
163  return *this;
164  case AffineExprKind::Add:
165  case AffineExprKind::Mul:
168  case AffineExprKind::Mod:
169  auto binOp = llvm::cast<AffineBinaryOpExpr>(*this);
170  auto lhs = binOp.getLHS(), rhs = binOp.getRHS();
171  auto newLHS = lhs.replace(map);
172  auto newRHS = rhs.replace(map);
173  if (newLHS == lhs && newRHS == rhs)
174  return *this;
175  return getAffineBinaryOpExpr(getKind(), newLHS, newRHS);
176  }
177  llvm_unreachable("Unknown AffineExpr");
178 }
179 
180 /// Sparse replace method. Return the modified expression tree.
183  map.insert(std::make_pair(expr, replacement));
184  return replace(map);
185 }
186 /// Returns true if this expression is made out of only symbols and
187 /// constants (no dimensional identifiers).
189  switch (getKind()) {
191  return true;
193  return false;
195  return true;
196 
197  case AffineExprKind::Add:
198  case AffineExprKind::Mul:
201  case AffineExprKind::Mod: {
202  auto expr = llvm::cast<AffineBinaryOpExpr>(*this);
203  return expr.getLHS().isSymbolicOrConstant() &&
204  expr.getRHS().isSymbolicOrConstant();
205  }
206  }
207  llvm_unreachable("Unknown AffineExpr");
208 }
209 
210 /// Returns true if this is a pure affine expression, i.e., multiplication,
211 /// floordiv, ceildiv, and mod is only allowed w.r.t constants.
213  switch (getKind()) {
217  return true;
218  case AffineExprKind::Add: {
219  auto op = llvm::cast<AffineBinaryOpExpr>(*this);
220  return op.getLHS().isPureAffine() && op.getRHS().isPureAffine();
221  }
222 
223  case AffineExprKind::Mul: {
224  // TODO: Canonicalize the constants in binary operators to the RHS when
225  // possible, allowing this to merge into the next case.
226  auto op = llvm::cast<AffineBinaryOpExpr>(*this);
227  return op.getLHS().isPureAffine() && op.getRHS().isPureAffine() &&
228  (llvm::isa<AffineConstantExpr>(op.getLHS()) ||
229  llvm::isa<AffineConstantExpr>(op.getRHS()));
230  }
233  case AffineExprKind::Mod: {
234  auto op = llvm::cast<AffineBinaryOpExpr>(*this);
235  return op.getLHS().isPureAffine() &&
236  llvm::isa<AffineConstantExpr>(op.getRHS());
237  }
238  }
239  llvm_unreachable("Unknown AffineExpr");
240 }
241 
242 // Returns the greatest known integral divisor of this affine expression.
244  AffineBinaryOpExpr binExpr(nullptr);
245  switch (getKind()) {
247  [[fallthrough]];
249  return 1;
251  [[fallthrough]];
253  // If the RHS is a constant and divides the known divisor on the LHS, the
254  // quotient is a known divisor of the expression.
255  binExpr = llvm::cast<AffineBinaryOpExpr>(*this);
256  auto rhs = llvm::dyn_cast<AffineConstantExpr>(binExpr.getRHS());
257  // Leave alone undefined expressions.
258  if (rhs && rhs.getValue() != 0) {
259  int64_t lhsDiv = binExpr.getLHS().getLargestKnownDivisor();
260  if (lhsDiv % rhs.getValue() == 0)
261  return std::abs(lhsDiv / rhs.getValue());
262  }
263  return 1;
264  }
266  return std::abs(llvm::cast<AffineConstantExpr>(*this).getValue());
267  case AffineExprKind::Mul: {
268  binExpr = llvm::cast<AffineBinaryOpExpr>(*this);
269  return binExpr.getLHS().getLargestKnownDivisor() *
270  binExpr.getRHS().getLargestKnownDivisor();
271  }
272  case AffineExprKind::Add:
273  [[fallthrough]];
274  case AffineExprKind::Mod: {
275  binExpr = llvm::cast<AffineBinaryOpExpr>(*this);
276  return std::gcd((uint64_t)binExpr.getLHS().getLargestKnownDivisor(),
277  (uint64_t)binExpr.getRHS().getLargestKnownDivisor());
278  }
279  }
280  llvm_unreachable("Unknown AffineExpr");
281 }
282 
283 bool AffineExpr::isMultipleOf(int64_t factor) const {
284  AffineBinaryOpExpr binExpr(nullptr);
285  uint64_t l, u;
286  switch (getKind()) {
288  [[fallthrough]];
290  return factor * factor == 1;
292  return llvm::cast<AffineConstantExpr>(*this).getValue() % factor == 0;
293  case AffineExprKind::Mul: {
294  binExpr = llvm::cast<AffineBinaryOpExpr>(*this);
295  // It's probably not worth optimizing this further (to not traverse the
296  // whole sub-tree under - it that would require a version of isMultipleOf
297  // that on a 'false' return also returns the largest known divisor).
298  return (l = binExpr.getLHS().getLargestKnownDivisor()) % factor == 0 ||
299  (u = binExpr.getRHS().getLargestKnownDivisor()) % factor == 0 ||
300  (l * u) % factor == 0;
301  }
302  case AffineExprKind::Add:
305  case AffineExprKind::Mod: {
306  binExpr = llvm::cast<AffineBinaryOpExpr>(*this);
307  return std::gcd((uint64_t)binExpr.getLHS().getLargestKnownDivisor(),
308  (uint64_t)binExpr.getRHS().getLargestKnownDivisor()) %
309  factor ==
310  0;
311  }
312  }
313  llvm_unreachable("Unknown AffineExpr");
314 }
315 
316 bool AffineExpr::isFunctionOfDim(unsigned position) const {
317  if (getKind() == AffineExprKind::DimId) {
318  return *this == mlir::getAffineDimExpr(position, getContext());
319  }
320  if (auto expr = llvm::dyn_cast<AffineBinaryOpExpr>(*this)) {
321  return expr.getLHS().isFunctionOfDim(position) ||
322  expr.getRHS().isFunctionOfDim(position);
323  }
324  return false;
325 }
326 
327 bool AffineExpr::isFunctionOfSymbol(unsigned position) const {
328  if (getKind() == AffineExprKind::SymbolId) {
329  return *this == mlir::getAffineSymbolExpr(position, getContext());
330  }
331  if (auto expr = llvm::dyn_cast<AffineBinaryOpExpr>(*this)) {
332  return expr.getLHS().isFunctionOfSymbol(position) ||
333  expr.getRHS().isFunctionOfSymbol(position);
334  }
335  return false;
336 }
337 
339  : AffineExpr(ptr) {}
341  return static_cast<ImplType *>(expr)->lhs;
342 }
344  return static_cast<ImplType *>(expr)->rhs;
345 }
346 
348 unsigned AffineDimExpr::getPosition() const {
349  return static_cast<ImplType *>(expr)->position;
350 }
351 
352 /// Returns true if the expression is divisible by the given symbol with
353 /// position `symbolPos`. The argument `opKind` specifies here what kind of
354 /// division or mod operation called this division. It helps in implementing the
355 /// commutative property of the floordiv and ceildiv operations. If the argument
356 ///`exprKind` is floordiv and `expr` is also a binary expression of a floordiv
357 /// operation, then the commutative property can be used otherwise, the floordiv
358 /// operation is not divisible. The same argument holds for ceildiv operation.
359 static bool isDivisibleBySymbol(AffineExpr expr, unsigned symbolPos,
360  AffineExprKind opKind) {
361  // The argument `opKind` can either be Modulo, Floordiv or Ceildiv only.
362  assert((opKind == AffineExprKind::Mod || opKind == AffineExprKind::FloorDiv ||
363  opKind == AffineExprKind::CeilDiv) &&
364  "unexpected opKind");
365  switch (expr.getKind()) {
367  return cast<AffineConstantExpr>(expr).getValue() == 0;
369  return false;
371  return (cast<AffineSymbolExpr>(expr).getPosition() == symbolPos);
372  // Checks divisibility by the given symbol for both operands.
373  case AffineExprKind::Add: {
374  AffineBinaryOpExpr binaryExpr = cast<AffineBinaryOpExpr>(expr);
375  return isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos, opKind) &&
376  isDivisibleBySymbol(binaryExpr.getRHS(), symbolPos, opKind);
377  }
378  // Checks divisibility by the given symbol for both operands. Consider the
379  // expression `(((s1*s0) floordiv w) mod ((s1 * s2) floordiv p)) floordiv s1`,
380  // this is a division by s1 and both the operands of modulo are divisible by
381  // s1 but it is not divisible by s1 always. The third argument is
382  // `AffineExprKind::Mod` for this reason.
383  case AffineExprKind::Mod: {
384  AffineBinaryOpExpr binaryExpr = cast<AffineBinaryOpExpr>(expr);
385  return isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos,
387  isDivisibleBySymbol(binaryExpr.getRHS(), symbolPos,
389  }
390  // Checks if any of the operand divisible by the given symbol.
391  case AffineExprKind::Mul: {
392  AffineBinaryOpExpr binaryExpr = cast<AffineBinaryOpExpr>(expr);
393  return isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos, opKind) ||
394  isDivisibleBySymbol(binaryExpr.getRHS(), symbolPos, opKind);
395  }
396  // Floordiv and ceildiv are divisible by the given symbol when the first
397  // operand is divisible, and the affine expression kind of the argument expr
398  // is same as the argument `opKind`. This can be inferred from commutative
399  // property of floordiv and ceildiv operations and are as follow:
400  // (exp1 floordiv exp2) floordiv exp3 = (exp1 floordiv exp3) floordiv exp2
401  // (exp1 ceildiv exp2) ceildiv exp3 = (exp1 ceildiv exp3) ceildiv expr2
402  // It will fail if operations are not same. For example:
403  // (exps1 ceildiv exp2) floordiv exp3 can not be simplified.
406  AffineBinaryOpExpr binaryExpr = cast<AffineBinaryOpExpr>(expr);
407  if (opKind != expr.getKind())
408  return false;
409  return isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos, expr.getKind());
410  }
411  }
412  llvm_unreachable("Unknown AffineExpr");
413 }
414 
415 /// Divides the given expression by the given symbol at position `symbolPos`. It
416 /// considers the divisibility condition is checked before calling itself. A
417 /// null expression is returned whenever the divisibility condition fails.
418 static AffineExpr symbolicDivide(AffineExpr expr, unsigned symbolPos,
419  AffineExprKind opKind) {
420  // THe argument `opKind` can either be Modulo, Floordiv or Ceildiv only.
421  assert((opKind == AffineExprKind::Mod || opKind == AffineExprKind::FloorDiv ||
422  opKind == AffineExprKind::CeilDiv) &&
423  "unexpected opKind");
424  switch (expr.getKind()) {
426  if (cast<AffineConstantExpr>(expr).getValue() != 0)
427  return nullptr;
428  return getAffineConstantExpr(0, expr.getContext());
430  return nullptr;
432  return getAffineConstantExpr(1, expr.getContext());
433  // Dividing both operands by the given symbol.
434  case AffineExprKind::Add: {
435  AffineBinaryOpExpr binaryExpr = cast<AffineBinaryOpExpr>(expr);
436  return getAffineBinaryOpExpr(
437  expr.getKind(), symbolicDivide(binaryExpr.getLHS(), symbolPos, opKind),
438  symbolicDivide(binaryExpr.getRHS(), symbolPos, opKind));
439  }
440  // Dividing both operands by the given symbol.
441  case AffineExprKind::Mod: {
442  AffineBinaryOpExpr binaryExpr = cast<AffineBinaryOpExpr>(expr);
443  return getAffineBinaryOpExpr(
444  expr.getKind(),
445  symbolicDivide(binaryExpr.getLHS(), symbolPos, expr.getKind()),
446  symbolicDivide(binaryExpr.getRHS(), symbolPos, expr.getKind()));
447  }
448  // Dividing any of the operand by the given symbol.
449  case AffineExprKind::Mul: {
450  AffineBinaryOpExpr binaryExpr = cast<AffineBinaryOpExpr>(expr);
451  if (!isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos, opKind))
452  return binaryExpr.getLHS() *
453  symbolicDivide(binaryExpr.getRHS(), symbolPos, opKind);
454  return symbolicDivide(binaryExpr.getLHS(), symbolPos, opKind) *
455  binaryExpr.getRHS();
456  }
457  // Dividing first operand only by the given symbol.
460  AffineBinaryOpExpr binaryExpr = cast<AffineBinaryOpExpr>(expr);
461  return getAffineBinaryOpExpr(
462  expr.getKind(),
463  symbolicDivide(binaryExpr.getLHS(), symbolPos, expr.getKind()),
464  binaryExpr.getRHS());
465  }
466  }
467  llvm_unreachable("Unknown AffineExpr");
468 }
469 
470 /// Populate `result` with all summand operands of given (potentially nested)
471 /// addition. If the given expression is not an addition, just populate the
472 /// expression itself.
473 /// Example: Add(Add(7, 8), Mul(9, 10)) will return [7, 8, Mul(9, 10)].
475  auto addExpr = dyn_cast<AffineBinaryOpExpr>(expr);
476  if (!addExpr || addExpr.getKind() != AffineExprKind::Add) {
477  result.push_back(expr);
478  return;
479  }
480  getSummandExprs(addExpr.getLHS(), result);
481  getSummandExprs(addExpr.getRHS(), result);
482 }
483 
484 /// Return "true" if `candidate` is a negated expression, i.e., Mul(-1, expr).
485 /// If so, also return the non-negated expression via `expr`.
486 static bool isNegatedAffineExpr(AffineExpr candidate, AffineExpr &expr) {
487  auto mulExpr = dyn_cast<AffineBinaryOpExpr>(candidate);
488  if (!mulExpr || mulExpr.getKind() != AffineExprKind::Mul)
489  return false;
490  if (auto lhs = dyn_cast<AffineConstantExpr>(mulExpr.getLHS())) {
491  if (lhs.getValue() == -1) {
492  expr = mulExpr.getRHS();
493  return true;
494  }
495  }
496  if (auto rhs = dyn_cast<AffineConstantExpr>(mulExpr.getRHS())) {
497  if (rhs.getValue() == -1) {
498  expr = mulExpr.getLHS();
499  return true;
500  }
501  }
502  return false;
503 }
504 
505 /// Return "true" if `lhs` % `rhs` is guaranteed to evaluate to zero based on
506 /// the fact that `lhs` contains another modulo expression that ensures that
507 /// `lhs` is divisible by `rhs`. This is a common pattern in the resulting IR
508 /// after loop peeling.
509 ///
510 /// Example: lhs = ub - ub % step
511 /// rhs = step
512 /// => (ub - ub % step) % step is guaranteed to evaluate to 0.
514  unsigned numDims, unsigned numSymbols) {
515  // TODO: Try to unify this function with `getBoundForAffineExpr`.
516  // Collect all summands in lhs.
517  SmallVector<AffineExpr> summands;
518  getSummandExprs(lhs, summands);
519  // Look for Mul(-1, Mod(x, rhs)) among the summands. If x matches the
520  // remaining summands, then lhs % rhs is guaranteed to evaluate to 0.
521  for (int64_t i = 0, e = summands.size(); i < e; ++i) {
522  AffineExpr current = summands[i];
523  AffineExpr beforeNegation;
524  if (!isNegatedAffineExpr(current, beforeNegation))
525  continue;
526  AffineBinaryOpExpr innerMod = dyn_cast<AffineBinaryOpExpr>(beforeNegation);
527  if (!innerMod || innerMod.getKind() != AffineExprKind::Mod)
528  continue;
529  if (innerMod.getRHS() != rhs)
530  continue;
531  // Sum all remaining summands and subtract x. If that expression can be
532  // simplified to zero, then the remaining summands and x are equal.
534  for (int64_t j = 0; j < e; ++j)
535  if (i != j)
536  diff = diff + summands[j];
537  diff = diff - innerMod.getLHS();
538  diff = simplifyAffineExpr(diff, numDims, numSymbols);
539  auto constExpr = dyn_cast<AffineConstantExpr>(diff);
540  if (constExpr && constExpr.getValue() == 0)
541  return true;
542  }
543  return false;
544 }
545 
546 /// Simplify a semi-affine expression by handling modulo, floordiv, or ceildiv
547 /// operations when the second operand simplifies to a symbol and the first
548 /// operand is divisible by that symbol. It can be applied to any semi-affine
549 /// expression. Returned expression can either be a semi-affine or pure affine
550 /// expression.
551 static AffineExpr simplifySemiAffine(AffineExpr expr, unsigned numDims,
552  unsigned numSymbols) {
553  switch (expr.getKind()) {
557  return expr;
558  case AffineExprKind::Add:
559  case AffineExprKind::Mul: {
560  AffineBinaryOpExpr binaryExpr = cast<AffineBinaryOpExpr>(expr);
561  return getAffineBinaryOpExpr(
562  expr.getKind(),
563  simplifySemiAffine(binaryExpr.getLHS(), numDims, numSymbols),
564  simplifySemiAffine(binaryExpr.getRHS(), numDims, numSymbols));
565  }
566  // Check if the simplification of the second operand is a symbol, and the
567  // first operand is divisible by it. If the operation is a modulo, a constant
568  // zero expression is returned. In the case of floordiv and ceildiv, the
569  // symbol from the simplification of the second operand divides the first
570  // operand. Otherwise, simplification is not possible.
573  case AffineExprKind::Mod: {
574  AffineBinaryOpExpr binaryExpr = cast<AffineBinaryOpExpr>(expr);
575  AffineExpr sLHS =
576  simplifySemiAffine(binaryExpr.getLHS(), numDims, numSymbols);
577  AffineExpr sRHS =
578  simplifySemiAffine(binaryExpr.getRHS(), numDims, numSymbols);
579  if (isModOfModSubtraction(sLHS, sRHS, numDims, numSymbols))
580  return getAffineConstantExpr(0, expr.getContext());
581  AffineSymbolExpr symbolExpr = dyn_cast<AffineSymbolExpr>(
582  simplifySemiAffine(binaryExpr.getRHS(), numDims, numSymbols));
583  if (!symbolExpr)
584  return getAffineBinaryOpExpr(expr.getKind(), sLHS, sRHS);
585  unsigned symbolPos = symbolExpr.getPosition();
586  if (!isDivisibleBySymbol(binaryExpr.getLHS(), symbolPos, expr.getKind()))
587  return getAffineBinaryOpExpr(expr.getKind(), sLHS, sRHS);
588  if (expr.getKind() == AffineExprKind::Mod)
589  return getAffineConstantExpr(0, expr.getContext());
590  return symbolicDivide(sLHS, symbolPos, expr.getKind());
591  }
592  }
593  llvm_unreachable("Unknown AffineExpr");
594 }
595 
596 static AffineExpr getAffineDimOrSymbol(AffineExprKind kind, unsigned position,
597  MLIRContext *context) {
598  auto assignCtx = [context](AffineDimExprStorage *storage) {
599  storage->context = context;
600  };
601 
602  StorageUniquer &uniquer = context->getAffineUniquer();
603  return uniquer.get<AffineDimExprStorage>(
604  assignCtx, static_cast<unsigned>(kind), position);
605 }
606 
607 AffineExpr mlir::getAffineDimExpr(unsigned position, MLIRContext *context) {
608  return getAffineDimOrSymbol(AffineExprKind::DimId, position, context);
609 }
610 
612  : AffineExpr(ptr) {}
614  return static_cast<ImplType *>(expr)->position;
615 }
616 
617 AffineExpr mlir::getAffineSymbolExpr(unsigned position, MLIRContext *context) {
618  return getAffineDimOrSymbol(AffineExprKind::SymbolId, position, context);
619 }
620 
622  : AffineExpr(ptr) {}
624  return static_cast<ImplType *>(expr)->constant;
625 }
626 
627 bool AffineExpr::operator==(int64_t v) const {
628  return *this == getAffineConstantExpr(v, getContext());
629 }
630 
632  auto assignCtx = [context](AffineConstantExprStorage *storage) {
633  storage->context = context;
634  };
635 
636  StorageUniquer &uniquer = context->getAffineUniquer();
637  return uniquer.get<AffineConstantExprStorage>(assignCtx, constant);
638 }
639 
642  MLIRContext *context) {
643  return llvm::to_vector(llvm::map_range(constants, [&](int64_t constant) {
644  return getAffineConstantExpr(constant, context);
645  }));
646 }
647 
648 /// Simplify add expression. Return nullptr if it can't be simplified.
650  auto lhsConst = dyn_cast<AffineConstantExpr>(lhs);
651  auto rhsConst = dyn_cast<AffineConstantExpr>(rhs);
652  // Fold if both LHS, RHS are a constant and the sum does not overflow.
653  if (lhsConst && rhsConst) {
654  int64_t sum;
655  if (llvm::AddOverflow(lhsConst.getValue(), rhsConst.getValue(), sum)) {
656  return nullptr;
657  }
658  return getAffineConstantExpr(sum, lhs.getContext());
659  }
660 
661  // Canonicalize so that only the RHS is a constant. (4 + d0 becomes d0 + 4).
662  // If only one of them is a symbolic expressions, make it the RHS.
663  if (isa<AffineConstantExpr>(lhs) ||
664  (lhs.isSymbolicOrConstant() && !rhs.isSymbolicOrConstant())) {
665  return rhs + lhs;
666  }
667 
668  // At this point, if there was a constant, it would be on the right.
669 
670  // Addition with a zero is a noop, return the other input.
671  if (rhsConst) {
672  if (rhsConst.getValue() == 0)
673  return lhs;
674  }
675  // Fold successive additions like (d0 + 2) + 3 into d0 + 5.
676  auto lBin = dyn_cast<AffineBinaryOpExpr>(lhs);
677  if (lBin && rhsConst && lBin.getKind() == AffineExprKind::Add) {
678  if (auto lrhs = dyn_cast<AffineConstantExpr>(lBin.getRHS()))
679  return lBin.getLHS() + (lrhs.getValue() + rhsConst.getValue());
680  }
681 
682  // Detect "c1 * expr + c_2 * expr" as "(c1 + c2) * expr".
683  // c1 is rRhsConst, c2 is rLhsConst; firstExpr, secondExpr are their
684  // respective multiplicands.
685  std::optional<int64_t> rLhsConst, rRhsConst;
686  AffineExpr firstExpr, secondExpr;
687  AffineConstantExpr rLhsConstExpr;
688  auto lBinOpExpr = dyn_cast<AffineBinaryOpExpr>(lhs);
689  if (lBinOpExpr && lBinOpExpr.getKind() == AffineExprKind::Mul &&
690  (rLhsConstExpr = dyn_cast<AffineConstantExpr>(lBinOpExpr.getRHS()))) {
691  rLhsConst = rLhsConstExpr.getValue();
692  firstExpr = lBinOpExpr.getLHS();
693  } else {
694  rLhsConst = 1;
695  firstExpr = lhs;
696  }
697 
698  auto rBinOpExpr = dyn_cast<AffineBinaryOpExpr>(rhs);
699  AffineConstantExpr rRhsConstExpr;
700  if (rBinOpExpr && rBinOpExpr.getKind() == AffineExprKind::Mul &&
701  (rRhsConstExpr = dyn_cast<AffineConstantExpr>(rBinOpExpr.getRHS()))) {
702  rRhsConst = rRhsConstExpr.getValue();
703  secondExpr = rBinOpExpr.getLHS();
704  } else {
705  rRhsConst = 1;
706  secondExpr = rhs;
707  }
708 
709  if (rLhsConst && rRhsConst && firstExpr == secondExpr)
710  return getAffineBinaryOpExpr(
711  AffineExprKind::Mul, firstExpr,
712  getAffineConstantExpr(*rLhsConst + *rRhsConst, lhs.getContext()));
713 
714  // When doing successive additions, bring constant to the right: turn (d0 + 2)
715  // + d1 into (d0 + d1) + 2.
716  if (lBin && lBin.getKind() == AffineExprKind::Add) {
717  if (auto lrhs = dyn_cast<AffineConstantExpr>(lBin.getRHS())) {
718  return lBin.getLHS() + rhs + lrhs;
719  }
720  }
721 
722  // Detect and transform "expr - q * (expr floordiv q)" to "expr mod q", where
723  // q may be a constant or symbolic expression. This leads to a much more
724  // efficient form when 'c' is a power of two, and in general a more compact
725  // and readable form.
726 
727  // Process '(expr floordiv c) * (-c)'.
728  if (!rBinOpExpr)
729  return nullptr;
730 
731  auto lrhs = rBinOpExpr.getLHS();
732  auto rrhs = rBinOpExpr.getRHS();
733 
734  AffineExpr llrhs, rlrhs;
735 
736  // Check if lrhsBinOpExpr is of the form (expr floordiv q) * q, where q is a
737  // symbolic expression.
738  auto lrhsBinOpExpr = dyn_cast<AffineBinaryOpExpr>(lrhs);
739  // Check rrhsConstOpExpr = -1.
740  auto rrhsConstOpExpr = dyn_cast<AffineConstantExpr>(rrhs);
741  if (rrhsConstOpExpr && rrhsConstOpExpr.getValue() == -1 && lrhsBinOpExpr &&
742  lrhsBinOpExpr.getKind() == AffineExprKind::Mul) {
743  // Check llrhs = expr floordiv q.
744  llrhs = lrhsBinOpExpr.getLHS();
745  // Check rlrhs = q.
746  rlrhs = lrhsBinOpExpr.getRHS();
747  auto llrhsBinOpExpr = dyn_cast<AffineBinaryOpExpr>(llrhs);
748  if (!llrhsBinOpExpr || llrhsBinOpExpr.getKind() != AffineExprKind::FloorDiv)
749  return nullptr;
750  if (llrhsBinOpExpr.getRHS() == rlrhs && lhs == llrhsBinOpExpr.getLHS())
751  return lhs % rlrhs;
752  }
753 
754  // Process lrhs, which is 'expr floordiv c'.
755  // expr + (expr // c * -c) = expr % c
756  AffineBinaryOpExpr lrBinOpExpr = dyn_cast<AffineBinaryOpExpr>(lrhs);
757  if (!lrBinOpExpr || rhs.getKind() != AffineExprKind::Mul ||
758  lrBinOpExpr.getKind() != AffineExprKind::FloorDiv)
759  return nullptr;
760 
761  llrhs = lrBinOpExpr.getLHS();
762  rlrhs = lrBinOpExpr.getRHS();
763 
764  if (lhs == llrhs && rlrhs == -rrhs) {
765  return lhs % rlrhs;
766  }
767  return nullptr;
768 }
769 
771  return *this + getAffineConstantExpr(v, getContext());
772 }
774  if (auto simplified = simplifyAdd(*this, other))
775  return simplified;
776 
778  return uniquer.get<AffineBinaryOpExprStorage>(
779  /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::Add), *this, other);
780 }
781 
782 /// Simplify a multiply expression. Return nullptr if it can't be simplified.
784  auto lhsConst = dyn_cast<AffineConstantExpr>(lhs);
785  auto rhsConst = dyn_cast<AffineConstantExpr>(rhs);
786 
787  if (lhsConst && rhsConst) {
788  int64_t product;
789  if (llvm::MulOverflow(lhsConst.getValue(), rhsConst.getValue(), product)) {
790  return nullptr;
791  }
793  }
794 
795  if (!lhs.isSymbolicOrConstant() && !rhs.isSymbolicOrConstant())
796  return nullptr;
797 
798  // Canonicalize the mul expression so that the constant/symbolic term is the
799  // RHS. If both the lhs and rhs are symbolic, swap them if the lhs is a
800  // constant. (Note that a constant is trivially symbolic).
801  if (!rhs.isSymbolicOrConstant() || isa<AffineConstantExpr>(lhs)) {
802  // At least one of them has to be symbolic.
803  return rhs * lhs;
804  }
805 
806  // At this point, if there was a constant, it would be on the right.
807 
808  // Multiplication with a one is a noop, return the other input.
809  if (rhsConst) {
810  if (rhsConst.getValue() == 1)
811  return lhs;
812  // Multiplication with zero.
813  if (rhsConst.getValue() == 0)
814  return rhsConst;
815  }
816 
817  // Fold successive multiplications: eg: (d0 * 2) * 3 into d0 * 6.
818  auto lBin = dyn_cast<AffineBinaryOpExpr>(lhs);
819  if (lBin && rhsConst && lBin.getKind() == AffineExprKind::Mul) {
820  if (auto lrhs = dyn_cast<AffineConstantExpr>(lBin.getRHS()))
821  return lBin.getLHS() * (lrhs.getValue() * rhsConst.getValue());
822  }
823 
824  // When doing successive multiplication, bring constant to the right: turn (d0
825  // * 2) * d1 into (d0 * d1) * 2.
826  if (lBin && lBin.getKind() == AffineExprKind::Mul) {
827  if (auto lrhs = dyn_cast<AffineConstantExpr>(lBin.getRHS())) {
828  return (lBin.getLHS() * rhs) * lrhs;
829  }
830  }
831 
832  return nullptr;
833 }
834 
836  return *this * getAffineConstantExpr(v, getContext());
837 }
839  if (auto simplified = simplifyMul(*this, other))
840  return simplified;
841 
843  return uniquer.get<AffineBinaryOpExprStorage>(
844  /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::Mul), *this, other);
845 }
846 
847 // Unary minus, delegate to operator*.
849  return *this * getAffineConstantExpr(-1, getContext());
850 }
851 
852 // Delegate to operator+.
853 AffineExpr AffineExpr::operator-(int64_t v) const { return *this + (-v); }
855  return *this + (-other);
856 }
857 
859  auto lhsConst = dyn_cast<AffineConstantExpr>(lhs);
860  auto rhsConst = dyn_cast<AffineConstantExpr>(rhs);
861 
862  if (!rhsConst || rhsConst.getValue() == 0)
863  return nullptr;
864 
865  if (lhsConst) {
866  if (divideSignedWouldOverflow(lhsConst.getValue(), rhsConst.getValue()))
867  return nullptr;
868  return getAffineConstantExpr(
869  divideFloorSigned(lhsConst.getValue(), rhsConst.getValue()),
870  lhs.getContext());
871  }
872 
873  // Fold floordiv of a multiply with a constant that is a multiple of the
874  // divisor. Eg: (i * 128) floordiv 64 = i * 2.
875  if (rhsConst == 1)
876  return lhs;
877 
878  // Simplify `(expr * lrhs) floordiv rhsConst` when `lrhs` is known to be a
879  // multiple of `rhsConst`.
880  auto lBin = dyn_cast<AffineBinaryOpExpr>(lhs);
881  if (lBin && lBin.getKind() == AffineExprKind::Mul) {
882  if (auto lrhs = dyn_cast<AffineConstantExpr>(lBin.getRHS())) {
883  // `rhsConst` is known to be a nonzero constant.
884  if (lrhs.getValue() % rhsConst.getValue() == 0)
885  return lBin.getLHS() * (lrhs.getValue() / rhsConst.getValue());
886  }
887  }
888 
889  // Simplify (expr1 + expr2) floordiv divConst when either expr1 or expr2 is
890  // known to be a multiple of divConst.
891  if (lBin && lBin.getKind() == AffineExprKind::Add) {
892  int64_t llhsDiv = lBin.getLHS().getLargestKnownDivisor();
893  int64_t lrhsDiv = lBin.getRHS().getLargestKnownDivisor();
894  // rhsConst is known to be a nonzero constant.
895  if (llhsDiv % rhsConst.getValue() == 0 ||
896  lrhsDiv % rhsConst.getValue() == 0)
897  return lBin.getLHS().floorDiv(rhsConst.getValue()) +
898  lBin.getRHS().floorDiv(rhsConst.getValue());
899  }
900 
901  return nullptr;
902 }
903 
904 AffineExpr AffineExpr::floorDiv(uint64_t v) const {
906 }
908  if (auto simplified = simplifyFloorDiv(*this, other))
909  return simplified;
910 
912  return uniquer.get<AffineBinaryOpExprStorage>(
913  /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::FloorDiv), *this,
914  other);
915 }
916 
918  auto lhsConst = dyn_cast<AffineConstantExpr>(lhs);
919  auto rhsConst = dyn_cast<AffineConstantExpr>(rhs);
920 
921  if (!rhsConst || rhsConst.getValue() == 0)
922  return nullptr;
923 
924  if (lhsConst) {
925  if (divideSignedWouldOverflow(lhsConst.getValue(), rhsConst.getValue()))
926  return nullptr;
927  return getAffineConstantExpr(
928  divideCeilSigned(lhsConst.getValue(), rhsConst.getValue()),
929  lhs.getContext());
930  }
931 
932  // Fold ceildiv of a multiply with a constant that is a multiple of the
933  // divisor. Eg: (i * 128) ceildiv 64 = i * 2.
934  if (rhsConst.getValue() == 1)
935  return lhs;
936 
937  // Simplify `(expr * lrhs) ceildiv rhsConst` when `lrhs` is known to be a
938  // multiple of `rhsConst`.
939  auto lBin = dyn_cast<AffineBinaryOpExpr>(lhs);
940  if (lBin && lBin.getKind() == AffineExprKind::Mul) {
941  if (auto lrhs = dyn_cast<AffineConstantExpr>(lBin.getRHS())) {
942  // `rhsConst` is known to be a nonzero constant.
943  if (lrhs.getValue() % rhsConst.getValue() == 0)
944  return lBin.getLHS() * (lrhs.getValue() / rhsConst.getValue());
945  }
946  }
947 
948  return nullptr;
949 }
950 
951 AffineExpr AffineExpr::ceilDiv(uint64_t v) const {
953 }
955  if (auto simplified = simplifyCeilDiv(*this, other))
956  return simplified;
957 
959  return uniquer.get<AffineBinaryOpExprStorage>(
960  /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::CeilDiv), *this,
961  other);
962 }
963 
965  auto lhsConst = dyn_cast<AffineConstantExpr>(lhs);
966  auto rhsConst = dyn_cast<AffineConstantExpr>(rhs);
967 
968  // mod w.r.t zero or negative numbers is undefined and preserved as is.
969  if (!rhsConst || rhsConst.getValue() < 1)
970  return nullptr;
971 
972  if (lhsConst) {
973  // mod never overflows.
974  return getAffineConstantExpr(mod(lhsConst.getValue(), rhsConst.getValue()),
975  lhs.getContext());
976  }
977 
978  // Fold modulo of an expression that is known to be a multiple of a constant
979  // to zero if that constant is a multiple of the modulo factor. Eg: (i * 128)
980  // mod 64 is folded to 0, and less trivially, (i*(j*4*(k*32))) mod 128 = 0.
981  if (lhs.getLargestKnownDivisor() % rhsConst.getValue() == 0)
982  return getAffineConstantExpr(0, lhs.getContext());
983 
984  // Simplify (expr1 + expr2) mod divConst when either expr1 or expr2 is
985  // known to be a multiple of divConst.
986  auto lBin = dyn_cast<AffineBinaryOpExpr>(lhs);
987  if (lBin && lBin.getKind() == AffineExprKind::Add) {
988  int64_t llhsDiv = lBin.getLHS().getLargestKnownDivisor();
989  int64_t lrhsDiv = lBin.getRHS().getLargestKnownDivisor();
990  // rhsConst is known to be a positive constant.
991  if (llhsDiv % rhsConst.getValue() == 0)
992  return lBin.getRHS() % rhsConst.getValue();
993  if (lrhsDiv % rhsConst.getValue() == 0)
994  return lBin.getLHS() % rhsConst.getValue();
995  }
996 
997  // Simplify (e % a) % b to e % b when b evenly divides a
998  if (lBin && lBin.getKind() == AffineExprKind::Mod) {
999  auto intermediate = dyn_cast<AffineConstantExpr>(lBin.getRHS());
1000  if (intermediate && intermediate.getValue() >= 1 &&
1001  mod(intermediate.getValue(), rhsConst.getValue()) == 0) {
1002  return lBin.getLHS() % rhsConst.getValue();
1003  }
1004  }
1005 
1006  return nullptr;
1007 }
1008 
1010  return *this % getAffineConstantExpr(v, getContext());
1011 }
1013  if (auto simplified = simplifyMod(*this, other))
1014  return simplified;
1015 
1016  StorageUniquer &uniquer = getContext()->getAffineUniquer();
1017  return uniquer.get<AffineBinaryOpExprStorage>(
1018  /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::Mod), *this, other);
1019 }
1020 
1022  SmallVector<AffineExpr, 8> dimReplacements(map.getResults().begin(),
1023  map.getResults().end());
1024  return replaceDimsAndSymbols(dimReplacements, {});
1025 }
1026 raw_ostream &mlir::operator<<(raw_ostream &os, AffineExpr expr) {
1027  expr.print(os);
1028  return os;
1029 }
1030 
1031 /// Constructs an affine expression from a flat ArrayRef. If there are local
1032 /// identifiers (neither dimensional nor symbolic) that appear in the sum of
1033 /// products expression, `localExprs` is expected to have the AffineExpr
1034 /// for it, and is substituted into. The ArrayRef `flatExprs` is expected to be
1035 /// in the format [dims, symbols, locals, constant term].
1037  unsigned numDims,
1038  unsigned numSymbols,
1039  ArrayRef<AffineExpr> localExprs,
1040  MLIRContext *context) {
1041  // Assert expected numLocals = flatExprs.size() - numDims - numSymbols - 1.
1042  assert(flatExprs.size() - numDims - numSymbols - 1 == localExprs.size() &&
1043  "unexpected number of local expressions");
1044 
1045  auto expr = getAffineConstantExpr(0, context);
1046  // Dimensions and symbols.
1047  for (unsigned j = 0; j < numDims + numSymbols; j++) {
1048  if (flatExprs[j] == 0)
1049  continue;
1050  auto id = j < numDims ? getAffineDimExpr(j, context)
1051  : getAffineSymbolExpr(j - numDims, context);
1052  expr = expr + id * flatExprs[j];
1053  }
1054 
1055  // Local identifiers.
1056  for (unsigned j = numDims + numSymbols, e = flatExprs.size() - 1; j < e;
1057  j++) {
1058  if (flatExprs[j] == 0)
1059  continue;
1060  auto term = localExprs[j - numDims - numSymbols] * flatExprs[j];
1061  expr = expr + term;
1062  }
1063 
1064  // Constant term.
1065  int64_t constTerm = flatExprs[flatExprs.size() - 1];
1066  if (constTerm != 0)
1067  expr = expr + constTerm;
1068  return expr;
1069 }
1070 
1071 /// Constructs a semi-affine expression from a flat ArrayRef. If there are
1072 /// local identifiers (neither dimensional nor symbolic) that appear in the sum
1073 /// of products expression, `localExprs` is expected to have the AffineExprs for
1074 /// it, and is substituted into. The ArrayRef `flatExprs` is expected to be in
1075 /// the format [dims, symbols, locals, constant term]. The semi-affine
1076 /// expression is constructed in the sorted order of dimension and symbol
1077 /// position numbers. Note: local expressions/ids are used for mod, div as well
1078 /// as symbolic RHS terms for terms that are not pure affine.
1080  unsigned numDims,
1081  unsigned numSymbols,
1082  ArrayRef<AffineExpr> localExprs,
1083  MLIRContext *context) {
1084  assert(!flatExprs.empty() && "flatExprs cannot be empty");
1085 
1086  // Assert expected numLocals = flatExprs.size() - numDims - numSymbols - 1.
1087  assert(flatExprs.size() - numDims - numSymbols - 1 == localExprs.size() &&
1088  "unexpected number of local expressions");
1089 
1090  AffineExpr expr = getAffineConstantExpr(0, context);
1091 
1092  // We design indices as a pair which help us present the semi-affine map as
1093  // sum of product where terms are sorted based on dimension or symbol
1094  // position: <keyA, keyB> for expressions of the form dimension * symbol,
1095  // where keyA is the position number of the dimension and keyB is the
1096  // position number of the symbol. For dimensional expressions we set the index
1097  // as (position number of the dimension, -1), as we want dimensional
1098  // expressions to appear before symbolic and product of dimensional and
1099  // symbolic expressions having the dimension with the same position number.
1100  // For symbolic expression set the index as (position number of the symbol,
1101  // maximum of last dimension and symbol position) number. For example, we want
1102  // the expression we are constructing to look something like: d0 + d0 * s0 +
1103  // s0 + d1*s1 + s1.
1104 
1105  // Stores the affine expression corresponding to a given index.
1107  // Stores the constant coefficient value corresponding to a given
1108  // dimension, symbol or a non-pure affine expression stored in `localExprs`.
1109  DenseMap<std::pair<unsigned, signed>, int64_t> coefficients;
1110  // Stores the indices as defined above, and later sorted to produce
1111  // the semi-affine expression in the desired form.
1113 
1114  // Example: expression = d0 + d0 * s0 + 2 * s0.
1115  // indices = [{0,-1}, {0, 0}, {0, 1}]
1116  // coefficients = [{{0, -1}, 1}, {{0, 0}, 1}, {{0, 1}, 2}]
1117  // indexToExprMap = [{{0, -1}, d0}, {{0, 0}, d0 * s0}, {{0, 1}, s0}]
1118 
1119  // Adds entries to `indexToExprMap`, `coefficients` and `indices`.
1120  auto addEntry = [&](std::pair<unsigned, signed> index, int64_t coefficient,
1121  AffineExpr expr) {
1122  assert(!llvm::is_contained(indices, index) &&
1123  "Key is already present in indices vector and overwriting will "
1124  "happen in `indexToExprMap` and `coefficients`!");
1125 
1126  indices.push_back(index);
1127  coefficients.insert({index, coefficient});
1128  indexToExprMap.insert({index, expr});
1129  };
1130 
1131  // Design indices for dimensional or symbolic terms, and store the indices,
1132  // constant coefficient corresponding to the indices in `coefficients` map,
1133  // and affine expression corresponding to indices in `indexToExprMap` map.
1134 
1135  // Ensure we do not have duplicate keys in `indexToExpr` map.
1136  unsigned offsetSym = 0;
1137  signed offsetDim = -1;
1138  for (unsigned j = numDims; j < numDims + numSymbols; ++j) {
1139  if (flatExprs[j] == 0)
1140  continue;
1141  // For symbolic expression set the index as <position number
1142  // of the symbol, max(dimCount, symCount)> number,
1143  // as we want symbolic expressions with the same positional number to
1144  // appear after dimensional expressions having the same positional number.
1145  std::pair<unsigned, signed> indexEntry(
1146  j - numDims, std::max(numDims, numSymbols) + offsetSym++);
1147  addEntry(indexEntry, flatExprs[j],
1148  getAffineSymbolExpr(j - numDims, context));
1149  }
1150 
1151  // Denotes semi-affine product, modulo or division terms, which has been added
1152  // to the `indexToExpr` map.
1153  SmallVector<bool, 4> addedToMap(flatExprs.size() - numDims - numSymbols - 1,
1154  false);
1155  unsigned lhsPos, rhsPos;
1156  // Construct indices for product terms involving dimension, symbol or constant
1157  // as lhs/rhs, and store the indices, constant coefficient corresponding to
1158  // the indices in `coefficients` map, and affine expression corresponding to
1159  // in indices in `indexToExprMap` map.
1160  for (const auto &it : llvm::enumerate(localExprs)) {
1161  AffineExpr expr = it.value();
1162  if (flatExprs[numDims + numSymbols + it.index()] == 0)
1163  continue;
1164  AffineExpr lhs = cast<AffineBinaryOpExpr>(expr).getLHS();
1165  AffineExpr rhs = cast<AffineBinaryOpExpr>(expr).getRHS();
1166  if (!((isa<AffineDimExpr>(lhs) || isa<AffineSymbolExpr>(lhs)) &&
1167  (isa<AffineDimExpr>(rhs) || isa<AffineSymbolExpr>(rhs) ||
1168  isa<AffineConstantExpr>(rhs)))) {
1169  continue;
1170  }
1171  if (isa<AffineConstantExpr>(rhs)) {
1172  // For product/modulo/division expressions, when rhs of modulo/division
1173  // expression is constant, we put 0 in place of keyB, because we want
1174  // them to appear earlier in the semi-affine expression we are
1175  // constructing. When rhs is constant, we place 0 in place of keyB.
1176  if (isa<AffineDimExpr>(lhs)) {
1177  lhsPos = cast<AffineDimExpr>(lhs).getPosition();
1178  std::pair<unsigned, signed> indexEntry(lhsPos, offsetDim--);
1179  addEntry(indexEntry, flatExprs[numDims + numSymbols + it.index()],
1180  expr);
1181  } else {
1182  lhsPos = cast<AffineSymbolExpr>(lhs).getPosition();
1183  std::pair<unsigned, signed> indexEntry(
1184  lhsPos, std::max(numDims, numSymbols) + offsetSym++);
1185  addEntry(indexEntry, flatExprs[numDims + numSymbols + it.index()],
1186  expr);
1187  }
1188  } else if (isa<AffineDimExpr>(lhs)) {
1189  // For product/modulo/division expressions having lhs as dimension and rhs
1190  // as symbol, we order the terms in the semi-affine expression based on
1191  // the pair: <keyA, keyB> for expressions of the form dimension * symbol,
1192  // where keyA is the position number of the dimension and keyB is the
1193  // position number of the symbol.
1194  lhsPos = cast<AffineDimExpr>(lhs).getPosition();
1195  rhsPos = cast<AffineSymbolExpr>(rhs).getPosition();
1196  std::pair<unsigned, signed> indexEntry(lhsPos, rhsPos);
1197  addEntry(indexEntry, flatExprs[numDims + numSymbols + it.index()], expr);
1198  } else {
1199  // For product/modulo/division expressions having both lhs and rhs as
1200  // symbol, we design indices as a pair: <keyA, keyB> for expressions
1201  // of the form dimension * symbol, where keyA is the position number of
1202  // the dimension and keyB is the position number of the symbol.
1203  lhsPos = cast<AffineSymbolExpr>(lhs).getPosition();
1204  rhsPos = cast<AffineSymbolExpr>(rhs).getPosition();
1205  std::pair<unsigned, signed> indexEntry(
1206  lhsPos, std::max(numDims, numSymbols) + offsetSym++);
1207  addEntry(indexEntry, flatExprs[numDims + numSymbols + it.index()], expr);
1208  }
1209  addedToMap[it.index()] = true;
1210  }
1211 
1212  for (unsigned j = 0; j < numDims; ++j) {
1213  if (flatExprs[j] == 0)
1214  continue;
1215  // For dimensional expressions we set the index as <position number of the
1216  // dimension, 0>, as we want dimensional expressions to appear before
1217  // symbolic ones and products of dimensional and symbolic expressions
1218  // having the dimension with the same position number.
1219  std::pair<unsigned, signed> indexEntry(j, offsetDim--);
1220  addEntry(indexEntry, flatExprs[j], getAffineDimExpr(j, context));
1221  }
1222 
1223  // Constructing the simplified semi-affine sum of product/division/mod
1224  // expression from the flattened form in the desired sorted order of indices
1225  // of the various individual product/division/mod expressions.
1226  llvm::sort(indices);
1227  for (const std::pair<unsigned, unsigned> index : indices) {
1228  assert(indexToExprMap.lookup(index) &&
1229  "cannot find key in `indexToExprMap` map");
1230  expr = expr + indexToExprMap.lookup(index) * coefficients.lookup(index);
1231  }
1232 
1233  // Local identifiers.
1234  for (unsigned j = numDims + numSymbols, e = flatExprs.size() - 1; j < e;
1235  j++) {
1236  // If the coefficient of the local expression is 0, continue as we need not
1237  // add it in out final expression.
1238  if (flatExprs[j] == 0 || addedToMap[j - numDims - numSymbols])
1239  continue;
1240  auto term = localExprs[j - numDims - numSymbols] * flatExprs[j];
1241  expr = expr + term;
1242  }
1243 
1244  // Constant term.
1245  int64_t constTerm = flatExprs.back();
1246  if (constTerm != 0)
1247  expr = expr + constTerm;
1248  return expr;
1249 }
1250 
1252  unsigned numSymbols)
1253  : numDims(numDims), numSymbols(numSymbols), numLocals(0) {
1254  operandExprStack.reserve(8);
1255 }
1256 
1257 // In pure affine t = expr * c, we multiply each coefficient of lhs with c.
1258 //
1259 // In case of semi affine multiplication expressions, t = expr * symbolic_expr,
1260 // introduce a local variable p (= expr * symbolic_expr), and the affine
1261 // expression expr * symbolic_expr is added to `localExprs`.
1263  assert(operandExprStack.size() >= 2);
1265  operandExprStack.pop_back();
1267 
1268  // Flatten semi-affine multiplication expressions by introducing a local
1269  // variable in place of the product; the affine expression
1270  // corresponding to the quantifier is added to `localExprs`.
1271  if (!isa<AffineConstantExpr>(expr.getRHS())) {
1272  SmallVector<int64_t, 8> mulLhs(lhs);
1273  MLIRContext *context = expr.getContext();
1275  localExprs, context);
1277  localExprs, context);
1278  return addLocalVariableSemiAffine(mulLhs, rhs, a * b, lhs, lhs.size());
1279  }
1280 
1281  // Get the RHS constant.
1282  int64_t rhsConst = rhs[getConstantIndex()];
1283  for (int64_t &lhsElt : lhs)
1284  lhsElt *= rhsConst;
1285 
1286  return success();
1287 }
1288 
1290  assert(operandExprStack.size() >= 2);
1291  const auto &rhs = operandExprStack.back();
1292  auto &lhs = operandExprStack[operandExprStack.size() - 2];
1293  assert(lhs.size() == rhs.size());
1294  // Update the LHS in place.
1295  for (unsigned i = 0, e = rhs.size(); i < e; i++) {
1296  lhs[i] += rhs[i];
1297  }
1298  // Pop off the RHS.
1299  operandExprStack.pop_back();
1300  return success();
1301 }
1302 
1303 //
1304 // t = expr mod c <=> t = expr - c*q and c*q <= expr <= c*q + c - 1
1305 //
1306 // A mod expression "expr mod c" is thus flattened by introducing a new local
1307 // variable q (= expr floordiv c), such that expr mod c is replaced with
1308 // 'expr - c * q' and c * q <= expr <= c * q + c - 1 are added to localVarCst.
1309 //
1310 // In case of semi-affine modulo expressions, t = expr mod symbolic_expr,
1311 // introduce a local variable m (= expr mod symbolic_expr), and the affine
1312 // expression expr mod symbolic_expr is added to `localExprs`.
1314  assert(operandExprStack.size() >= 2);
1315 
1317  operandExprStack.pop_back();
1319  MLIRContext *context = expr.getContext();
1320 
1321  // Flatten semi affine modulo expressions by introducing a local
1322  // variable in place of the modulo value, and the affine expression
1323  // corresponding to the quantifier is added to `localExprs`.
1324  if (!isa<AffineConstantExpr>(expr.getRHS())) {
1325  SmallVector<int64_t, 8> modLhs(lhs);
1326  AffineExpr dividendExpr = getAffineExprFromFlatForm(
1327  lhs, numDims, numSymbols, localExprs, context);
1329  localExprs, context);
1330  AffineExpr modExpr = dividendExpr % divisorExpr;
1331  return addLocalVariableSemiAffine(modLhs, rhs, modExpr, lhs, lhs.size());
1332  }
1333 
1334  int64_t rhsConst = rhs[getConstantIndex()];
1335  if (rhsConst <= 0)
1336  return failure();
1337 
1338  // Check if the LHS expression is a multiple of modulo factor.
1339  unsigned i, e;
1340  for (i = 0, e = lhs.size(); i < e; i++)
1341  if (lhs[i] % rhsConst != 0)
1342  break;
1343  // If yes, modulo expression here simplifies to zero.
1344  if (i == lhs.size()) {
1345  std::fill(lhs.begin(), lhs.end(), 0);
1346  return success();
1347  }
1348 
1349  // Add a local variable for the quotient, i.e., expr % c is replaced by
1350  // (expr - q * c) where q = expr floordiv c. Do this while canceling out
1351  // the GCD of expr and c.
1352  SmallVector<int64_t, 8> floorDividend(lhs);
1353  uint64_t gcd = rhsConst;
1354  for (int64_t lhsElt : lhs)
1355  gcd = std::gcd(gcd, (uint64_t)std::abs(lhsElt));
1356  // Simplify the numerator and the denominator.
1357  if (gcd != 1) {
1358  for (int64_t &floorDividendElt : floorDividend)
1359  floorDividendElt = floorDividendElt / static_cast<int64_t>(gcd);
1360  }
1361  int64_t floorDivisor = rhsConst / static_cast<int64_t>(gcd);
1362 
1363  // Construct the AffineExpr form of the floordiv to store in localExprs.
1364 
1365  AffineExpr dividendExpr = getAffineExprFromFlatForm(
1366  floorDividend, numDims, numSymbols, localExprs, context);
1367  AffineExpr divisorExpr = getAffineConstantExpr(floorDivisor, context);
1368  AffineExpr floorDivExpr = dividendExpr.floorDiv(divisorExpr);
1369  int loc;
1370  if ((loc = findLocalId(floorDivExpr)) == -1) {
1371  addLocalFloorDivId(floorDividend, floorDivisor, floorDivExpr);
1372  // Set result at top of stack to "lhs - rhsConst * q".
1373  lhs[getLocalVarStartIndex() + numLocals - 1] = -rhsConst;
1374  } else {
1375  // Reuse the existing local id.
1376  lhs[getLocalVarStartIndex() + loc] = -rhsConst;
1377  }
1378  return success();
1379 }
1380 
1381 LogicalResult
1383  return visitDivExpr(expr, /*isCeil=*/true);
1384 }
1385 LogicalResult
1387  return visitDivExpr(expr, /*isCeil=*/false);
1388 }
1389 
1391  operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0));
1392  auto &eq = operandExprStack.back();
1393  assert(expr.getPosition() < numDims && "Inconsistent number of dims");
1394  eq[getDimStartIndex() + expr.getPosition()] = 1;
1395  return success();
1396 }
1397 
1398 LogicalResult
1400  operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0));
1401  auto &eq = operandExprStack.back();
1402  assert(expr.getPosition() < numSymbols && "inconsistent number of symbols");
1403  eq[getSymbolStartIndex() + expr.getPosition()] = 1;
1404  return success();
1405 }
1406 
1407 LogicalResult
1409  operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0));
1410  auto &eq = operandExprStack.back();
1411  eq[getConstantIndex()] = expr.getValue();
1412  return success();
1413 }
1414 
1415 LogicalResult SimpleAffineExprFlattener::addLocalVariableSemiAffine(
1416  ArrayRef<int64_t> lhs, ArrayRef<int64_t> rhs, AffineExpr localExpr,
1417  SmallVectorImpl<int64_t> &result, unsigned long resultSize) {
1418  assert(result.size() == resultSize &&
1419  "`result` vector passed is not of correct size");
1420  int loc;
1421  if ((loc = findLocalId(localExpr)) == -1) {
1422  if (failed(addLocalIdSemiAffine(lhs, rhs, localExpr)))
1423  return failure();
1424  }
1425  std::fill(result.begin(), result.end(), 0);
1426  if (loc == -1)
1427  result[getLocalVarStartIndex() + numLocals - 1] = 1;
1428  else
1429  result[getLocalVarStartIndex() + loc] = 1;
1430  return success();
1431 }
1432 
1433 // t = expr floordiv c <=> t = q, c * q <= expr <= c * q + c - 1
1434 // A floordiv is thus flattened by introducing a new local variable q, and
1435 // replacing that expression with 'q' while adding the constraints
1436 // c * q <= expr <= c * q + c - 1 to localVarCst (done by
1437 // IntegerRelation::addLocalFloorDiv).
1438 //
1439 // A ceildiv is similarly flattened:
1440 // t = expr ceildiv c <=> t = (expr + c - 1) floordiv c
1441 //
1442 // In case of semi affine division expressions, t = expr floordiv symbolic_expr
1443 // or t = expr ceildiv symbolic_expr, introduce a local variable q (= expr
1444 // floordiv/ceildiv symbolic_expr), and the affine floordiv/ceildiv is added to
1445 // `localExprs`.
1446 LogicalResult SimpleAffineExprFlattener::visitDivExpr(AffineBinaryOpExpr expr,
1447  bool isCeil) {
1448  assert(operandExprStack.size() >= 2);
1449 
1450  MLIRContext *context = expr.getContext();
1452  operandExprStack.pop_back();
1454 
1455  // Flatten semi affine division expressions by introducing a local
1456  // variable in place of the quotient, and the affine expression corresponding
1457  // to the quantifier is added to `localExprs`.
1458  if (!isa<AffineConstantExpr>(expr.getRHS())) {
1459  SmallVector<int64_t, 8> divLhs(lhs);
1461  localExprs, context);
1463  localExprs, context);
1464  AffineExpr divExpr = isCeil ? a.ceilDiv(b) : a.floorDiv(b);
1465  return addLocalVariableSemiAffine(divLhs, rhs, divExpr, lhs, lhs.size());
1466  }
1467 
1468  // This is a pure affine expr; the RHS is a positive constant.
1469  int64_t rhsConst = rhs[getConstantIndex()];
1470  if (rhsConst <= 0)
1471  return failure();
1472 
1473  // Simplify the floordiv, ceildiv if possible by canceling out the greatest
1474  // common divisors of the numerator and denominator.
1475  uint64_t gcd = std::abs(rhsConst);
1476  for (int64_t lhsElt : lhs)
1477  gcd = std::gcd(gcd, (uint64_t)std::abs(lhsElt));
1478  // Simplify the numerator and the denominator.
1479  if (gcd != 1) {
1480  for (int64_t &lhsElt : lhs)
1481  lhsElt = lhsElt / static_cast<int64_t>(gcd);
1482  }
1483  int64_t divisor = rhsConst / static_cast<int64_t>(gcd);
1484  // If the divisor becomes 1, the updated LHS is the result. (The
1485  // divisor can't be negative since rhsConst is positive).
1486  if (divisor == 1)
1487  return success();
1488 
1489  // If the divisor cannot be simplified to one, we will have to retain
1490  // the ceil/floor expr (simplified up until here). Add an existential
1491  // quantifier to express its result, i.e., expr1 div expr2 is replaced
1492  // by a new identifier, q.
1493  AffineExpr a =
1495  AffineExpr b = getAffineConstantExpr(divisor, context);
1496 
1497  int loc;
1498  AffineExpr divExpr = isCeil ? a.ceilDiv(b) : a.floorDiv(b);
1499  if ((loc = findLocalId(divExpr)) == -1) {
1500  if (!isCeil) {
1501  SmallVector<int64_t, 8> dividend(lhs);
1502  addLocalFloorDivId(dividend, divisor, divExpr);
1503  } else {
1504  // lhs ceildiv c <=> (lhs + c - 1) floordiv c
1505  SmallVector<int64_t, 8> dividend(lhs);
1506  dividend.back() += divisor - 1;
1507  addLocalFloorDivId(dividend, divisor, divExpr);
1508  }
1509  }
1510  // Set the expression on stack to the local var introduced to capture the
1511  // result of the division (floor or ceil).
1512  std::fill(lhs.begin(), lhs.end(), 0);
1513  if (loc == -1)
1514  lhs[getLocalVarStartIndex() + numLocals - 1] = 1;
1515  else
1516  lhs[getLocalVarStartIndex() + loc] = 1;
1517  return success();
1518 }
1519 
1520 // Add a local identifier (needed to flatten a mod, floordiv, ceildiv expr).
1521 // The local identifier added is always a floordiv of a pure add/mul affine
1522 // function of other identifiers, coefficients of which are specified in
1523 // dividend and with respect to a positive constant divisor. localExpr is the
1524 // simplified tree expression (AffineExpr) corresponding to the quantifier.
1526  int64_t divisor,
1527  AffineExpr localExpr) {
1528  assert(divisor > 0 && "positive constant divisor expected");
1529  for (SmallVector<int64_t, 8> &subExpr : operandExprStack)
1530  subExpr.insert(subExpr.begin() + getLocalVarStartIndex() + numLocals, 0);
1531  localExprs.push_back(localExpr);
1532  numLocals++;
1533  // dividend and divisor are not used here; an override of this method uses it.
1534 }
1535 
1537  ArrayRef<int64_t> lhs, ArrayRef<int64_t> rhs, AffineExpr localExpr) {
1538  for (SmallVector<int64_t, 8> &subExpr : operandExprStack)
1539  subExpr.insert(subExpr.begin() + getLocalVarStartIndex() + numLocals, 0);
1540  localExprs.push_back(localExpr);
1541  ++numLocals;
1542  // lhs and rhs are not used here; an override of this method uses them.
1543  return success();
1544 }
1545 
1546 int SimpleAffineExprFlattener::findLocalId(AffineExpr localExpr) {
1548  if ((it = llvm::find(localExprs, localExpr)) == localExprs.end())
1549  return -1;
1550  return it - localExprs.begin();
1551 }
1552 
1553 /// Simplify the affine expression by flattening it and reconstructing it.
1555  unsigned numSymbols) {
1556  // Simplify semi-affine expressions separately.
1557  if (!expr.isPureAffine())
1558  expr = simplifySemiAffine(expr, numDims, numSymbols);
1559 
1560  SimpleAffineExprFlattener flattener(numDims, numSymbols);
1561  // has poison expression
1562  if (failed(flattener.walkPostOrder(expr)))
1563  return expr;
1564  ArrayRef<int64_t> flattenedExpr = flattener.operandExprStack.back();
1565  if (!expr.isPureAffine() &&
1566  expr == getAffineExprFromFlatForm(flattenedExpr, numDims, numSymbols,
1567  flattener.localExprs,
1568  expr.getContext()))
1569  return expr;
1570  AffineExpr simplifiedExpr =
1571  expr.isPureAffine()
1572  ? getAffineExprFromFlatForm(flattenedExpr, numDims, numSymbols,
1573  flattener.localExprs, expr.getContext())
1574  : getSemiAffineExprFromFlatForm(flattenedExpr, numDims, numSymbols,
1575  flattener.localExprs,
1576  expr.getContext());
1577 
1578  flattener.operandExprStack.pop_back();
1579  assert(flattener.operandExprStack.empty());
1580  return simplifiedExpr;
1581 }
1582 
1583 std::optional<int64_t> mlir::getBoundForAffineExpr(
1584  AffineExpr expr, unsigned numDims, unsigned numSymbols,
1585  ArrayRef<std::optional<int64_t>> constLowerBounds,
1586  ArrayRef<std::optional<int64_t>> constUpperBounds, bool isUpper) {
1587  // Handle divs and mods.
1588  if (auto binOpExpr = dyn_cast<AffineBinaryOpExpr>(expr)) {
1589  // If the LHS of a floor or ceil is bounded and the RHS is a constant, we
1590  // can compute an upper bound.
1591  if (binOpExpr.getKind() == AffineExprKind::FloorDiv) {
1592  auto rhsConst = dyn_cast<AffineConstantExpr>(binOpExpr.getRHS());
1593  if (!rhsConst || rhsConst.getValue() < 1)
1594  return std::nullopt;
1595  auto bound =
1596  getBoundForAffineExpr(binOpExpr.getLHS(), numDims, numSymbols,
1597  constLowerBounds, constUpperBounds, isUpper);
1598  if (!bound)
1599  return std::nullopt;
1600  return divideFloorSigned(*bound, rhsConst.getValue());
1601  }
1602  if (binOpExpr.getKind() == AffineExprKind::CeilDiv) {
1603  auto rhsConst = dyn_cast<AffineConstantExpr>(binOpExpr.getRHS());
1604  if (rhsConst && rhsConst.getValue() >= 1) {
1605  auto bound =
1606  getBoundForAffineExpr(binOpExpr.getLHS(), numDims, numSymbols,
1607  constLowerBounds, constUpperBounds, isUpper);
1608  if (!bound)
1609  return std::nullopt;
1610  return divideCeilSigned(*bound, rhsConst.getValue());
1611  }
1612  return std::nullopt;
1613  }
1614  if (binOpExpr.getKind() == AffineExprKind::Mod) {
1615  // lhs mod c is always <= c - 1 and non-negative. In addition, if `lhs` is
1616  // bounded such that lb <= lhs <= ub and lb floordiv c == ub floordiv c
1617  // (same "interval"), then lb mod c <= lhs mod c <= ub mod c.
1618  auto rhsConst = dyn_cast<AffineConstantExpr>(binOpExpr.getRHS());
1619  if (rhsConst && rhsConst.getValue() >= 1) {
1620  int64_t rhsConstVal = rhsConst.getValue();
1621  auto lb = getBoundForAffineExpr(binOpExpr.getLHS(), numDims, numSymbols,
1622  constLowerBounds, constUpperBounds,
1623  /*isUpper=*/false);
1624  auto ub =
1625  getBoundForAffineExpr(binOpExpr.getLHS(), numDims, numSymbols,
1626  constLowerBounds, constUpperBounds, isUpper);
1627  if (ub && lb &&
1628  divideFloorSigned(*lb, rhsConstVal) ==
1629  divideFloorSigned(*ub, rhsConstVal))
1630  return isUpper ? mod(*ub, rhsConstVal) : mod(*lb, rhsConstVal);
1631  return isUpper ? rhsConstVal - 1 : 0;
1632  }
1633  }
1634  }
1635  // Flatten the expression.
1636  SimpleAffineExprFlattener flattener(numDims, numSymbols);
1637  auto simpleResult = flattener.walkPostOrder(expr);
1638  // has poison expression
1639  if (failed(simpleResult))
1640  return std::nullopt;
1641  ArrayRef<int64_t> flattenedExpr = flattener.operandExprStack.back();
1642  // TODO: Handle local variables. We can get hold of flattener.localExprs and
1643  // get bound on the local expr recursively.
1644  if (flattener.numLocals > 0)
1645  return std::nullopt;
1646  int64_t bound = 0;
1647  // Substitute the constant lower or upper bound for the dimensional or
1648  // symbolic input depending on `isUpper` to determine the bound.
1649  for (unsigned i = 0, e = numDims + numSymbols; i < e; ++i) {
1650  if (flattenedExpr[i] > 0) {
1651  auto &constBound = isUpper ? constUpperBounds[i] : constLowerBounds[i];
1652  if (!constBound)
1653  return std::nullopt;
1654  bound += *constBound * flattenedExpr[i];
1655  } else if (flattenedExpr[i] < 0) {
1656  auto &constBound = isUpper ? constLowerBounds[i] : constUpperBounds[i];
1657  if (!constBound)
1658  return std::nullopt;
1659  bound += *constBound * flattenedExpr[i];
1660  }
1661  }
1662  // Constant term.
1663  bound += flattenedExpr.back();
1664  return bound;
1665 }
static int64_t product(ArrayRef< int64_t > vals)
static AffineExpr symbolicDivide(AffineExpr expr, unsigned symbolPos, AffineExprKind opKind)
Divides the given expression by the given symbol at position symbolPos.
Definition: AffineExpr.cpp:418
static AffineExpr simplifyMul(AffineExpr lhs, AffineExpr rhs)
Simplify a multiply expression. Return nullptr if it can't be simplified.
Definition: AffineExpr.cpp:783
static AffineExpr simplifyMod(AffineExpr lhs, AffineExpr rhs)
Definition: AffineExpr.cpp:964
static AffineExpr simplifyAdd(AffineExpr lhs, AffineExpr rhs)
Simplify add expression. Return nullptr if it can't be simplified.
Definition: AffineExpr.cpp:649
static AffineExpr getSemiAffineExprFromFlatForm(ArrayRef< int64_t > flatExprs, unsigned numDims, unsigned numSymbols, ArrayRef< AffineExpr > localExprs, MLIRContext *context)
Constructs a semi-affine expression from a flat ArrayRef.
static AffineExpr simplifyCeilDiv(AffineExpr lhs, AffineExpr rhs)
Definition: AffineExpr.cpp:917
static AffineExpr simplifyFloorDiv(AffineExpr lhs, AffineExpr rhs)
Definition: AffineExpr.cpp:858
static bool isNegatedAffineExpr(AffineExpr candidate, AffineExpr &expr)
Return "true" if candidate is a negated expression, i.e., Mul(-1, expr).
Definition: AffineExpr.cpp:486
static AffineExpr getAffineDimOrSymbol(AffineExprKind kind, unsigned position, MLIRContext *context)
Definition: AffineExpr.cpp:596
static bool isModOfModSubtraction(AffineExpr lhs, AffineExpr rhs, unsigned numDims, unsigned numSymbols)
Return "true" if lhs % rhs is guaranteed to evaluate to zero based on the fact that lhs contains anot...
Definition: AffineExpr.cpp:513
static void getSummandExprs(AffineExpr expr, SmallVector< AffineExpr > &result)
Populate result with all summand operands of given (potentially nested) addition.
Definition: AffineExpr.cpp:474
static bool isDivisibleBySymbol(AffineExpr expr, unsigned symbolPos, AffineExprKind opKind)
Returns true if the expression is divisible by the given symbol with position symbolPos.
Definition: AffineExpr.cpp:359
static AffineExpr simplifySemiAffine(AffineExpr expr, unsigned numDims, unsigned numSymbols)
Simplify a semi-affine expression by handling modulo, floordiv, or ceildiv operations when the second...
Definition: AffineExpr.cpp:551
static MLIRContext * getContext(OpFoldResult val)
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
Affine binary operation expression.
Definition: AffineExpr.h:227
AffineExpr getLHS() const
Definition: AffineExpr.cpp:340
AffineBinaryOpExpr(AffineExpr::ImplType *ptr)
Definition: AffineExpr.cpp:338
AffineExpr getRHS() const
Definition: AffineExpr.cpp:343
An integer constant appearing in affine expression.
Definition: AffineExpr.h:252
AffineConstantExpr(AffineExpr::ImplType *ptr=nullptr)
Definition: AffineExpr.cpp:621
int64_t getValue() const
Definition: AffineExpr.cpp:623
A dimensional identifier appearing in an affine expression.
Definition: AffineExpr.h:236
AffineDimExpr(AffineExpr::ImplType *ptr)
Definition: AffineExpr.cpp:347
unsigned getPosition() const
Definition: AffineExpr.cpp:348
See documentation for AffineExprVisitorBase.
RetTy walkPostOrder(AffineExpr expr)
Base type for affine expression.
Definition: AffineExpr.h:68
AffineExpr replaceDimsAndSymbols(ArrayRef< AffineExpr > dimReplacements, ArrayRef< AffineExpr > symReplacements) const
This method substitutes any uses of dimensions and symbols (e.g.
Definition: AffineExpr.cpp:89
AffineExpr shiftDims(unsigned numDims, unsigned shift, unsigned offset=0) const
Replace dims[offset ...
Definition: AffineExpr.cpp:133
AffineExpr operator+(int64_t v) const
Definition: AffineExpr.cpp:770
bool isSymbolicOrConstant() const
Returns true if this expression is made out of only symbols and constants, i.e., it does not involve ...
Definition: AffineExpr.cpp:188
AffineExpr operator*(int64_t v) const
Definition: AffineExpr.cpp:835
bool operator==(AffineExpr other) const
Definition: AffineExpr.h:76
bool isPureAffine() const
Returns true if this is a pure affine expression, i.e., multiplication, floordiv, ceildiv,...
Definition: AffineExpr.cpp:212
AffineExpr shiftSymbols(unsigned numSymbols, unsigned shift, unsigned offset=0) const
Replace symbols[offset ...
Definition: AffineExpr.cpp:145
AffineExpr operator-() const
Definition: AffineExpr.cpp:848
AffineExpr floorDiv(uint64_t v) const
Definition: AffineExpr.cpp:904
ImplType * expr
Definition: AffineExpr.h:209
RetT walk(FnT &&callback) const
Walk all of the AffineExpr's in this expression in postorder.
Definition: AffineExpr.h:130
AffineExprKind getKind() const
Return the classification for this type.
Definition: AffineExpr.cpp:35
bool isMultipleOf(int64_t factor) const
Return true if the affine expression is a multiple of 'factor'.
Definition: AffineExpr.cpp:283
int64_t getLargestKnownDivisor() const
Returns the greatest known integral divisor of this affine expression.
Definition: AffineExpr.cpp:243
AffineExpr compose(AffineMap map) const
Compose with an AffineMap.
bool isFunctionOfDim(unsigned position) const
Return true if the affine expression involves AffineDimExpr position.
Definition: AffineExpr.cpp:316
bool isFunctionOfSymbol(unsigned position) const
Return true if the affine expression involves AffineSymbolExpr position.
Definition: AffineExpr.cpp:327
AffineExpr replaceDims(ArrayRef< AffineExpr > dimReplacements) const
Dim-only version of replaceDimsAndSymbols.
Definition: AffineExpr.cpp:122
AffineExpr operator%(uint64_t v) const
MLIRContext * getContext() const
Definition: AffineExpr.cpp:33
AffineExpr replace(AffineExpr expr, AffineExpr replacement) const
Sparse replace method.
Definition: AffineExpr.cpp:181
AffineExpr replaceSymbols(ArrayRef< AffineExpr > symReplacements) const
Symbol-only version of replaceDimsAndSymbols.
Definition: AffineExpr.cpp:127
AffineExpr ceilDiv(uint64_t v) const
Definition: AffineExpr.cpp:951
void print(raw_ostream &os) const
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition: AffineMap.h:46
ArrayRef< AffineExpr > getResults() const
Definition: AffineMap.cpp:407
A symbolic identifier appearing in an affine expression.
Definition: AffineExpr.h:244
AffineSymbolExpr(AffineExpr::ImplType *ptr)
Definition: AffineExpr.cpp:611
unsigned getPosition() const
Definition: AffineExpr.cpp:613
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
StorageUniquer & getAffineUniquer()
Returns the storage uniquer used for creating affine constructs.
virtual void addLocalFloorDivId(ArrayRef< int64_t > dividend, int64_t divisor, AffineExpr localExpr)
LogicalResult visitSymbolExpr(AffineSymbolExpr expr)
std::vector< SmallVector< int64_t, 8 > > operandExprStack
LogicalResult visitDimExpr(AffineDimExpr expr)
LogicalResult visitFloorDivExpr(AffineBinaryOpExpr expr)
LogicalResult visitConstantExpr(AffineConstantExpr expr)
virtual LogicalResult addLocalIdSemiAffine(ArrayRef< int64_t > lhs, ArrayRef< int64_t > rhs, AffineExpr localExpr)
Add a local identifier (needed to flatten a mod, floordiv, ceildiv, mul expr) when the rhs is a symbo...
LogicalResult visitModExpr(AffineBinaryOpExpr expr)
LogicalResult visitAddExpr(AffineBinaryOpExpr expr)
LogicalResult visitCeilDivExpr(AffineBinaryOpExpr expr)
LogicalResult visitMulExpr(AffineBinaryOpExpr expr)
SmallVector< AffineExpr, 4 > localExprs
SimpleAffineExprFlattener(unsigned numDims, unsigned numSymbols)
A utility class to get or create instances of "storage classes".
Storage * get(function_ref< void(Storage *)> initFn, TypeID id, Args &&...args)
Gets a uniqued instance of 'Storage'.
A utility result that is used to signal how to proceed with an ongoing walk:
Definition: Visitors.h:33
AttrTypeReplacer.
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition: Matchers.h:285
Fraction abs(const Fraction &f)
Definition: Fraction.h:106
Include the generated interface declarations.
std::optional< int64_t > getBoundForAffineExpr(AffineExpr expr, unsigned numDims, unsigned numSymbols, ArrayRef< std::optional< int64_t >> constLowerBounds, ArrayRef< std::optional< int64_t >> constUpperBounds, bool isUpper)
Get a lower or upper (depending on isUpper) bound for expr while using the constant lower and upper b...
AffineExprKind
Definition: AffineExpr.h:40
@ CeilDiv
RHS of ceildiv is always a constant or a symbolic expression.
@ Mul
RHS of mul is always a constant or a symbolic expression.
@ Mod
RHS of mod is always a constant or a symbolic expression with a positive value.
@ DimId
Dimensional identifier.
@ FloorDiv
RHS of floordiv is always a constant or a symbolic expression.
@ Constant
Constant integer.
@ SymbolId
Symbolic identifier.
AffineExpr getAffineBinaryOpExpr(AffineExprKind kind, AffineExpr lhs, AffineExpr rhs)
Definition: AffineExpr.cpp:70
AffineExpr getAffineExprFromFlatForm(ArrayRef< int64_t > flatExprs, unsigned numDims, unsigned numSymbols, ArrayRef< AffineExpr > localExprs, MLIRContext *context)
Constructs an affine expression from a flat ArrayRef.
AffineExpr getAffineConstantExpr(int64_t constant, MLIRContext *context)
Definition: AffineExpr.cpp:631
AffineExpr simplifyAffineExpr(AffineExpr expr, unsigned numDims, unsigned numSymbols)
Simplify an affine expression by flattening and some amount of simple analysis.
SmallVector< AffineExpr > getAffineConstantExprs(ArrayRef< int64_t > constants, MLIRContext *context)
Definition: AffineExpr.cpp:641
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
Definition: AffineExpr.cpp:607
AffineExpr getAffineSymbolExpr(unsigned position, MLIRContext *context)
Definition: AffineExpr.cpp:617
raw_ostream & operator<<(raw_ostream &os, const AliasResult &result)
Definition: AliasAnalysis.h:78
A binary operation appearing in an affine expression.
An integer constant appearing in affine expression.
A dimensional or symbolic identifier appearing in an affine expression.
Base storage class appearing in an affine expression.
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.