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 "mlir/IR/AffineExpr.h"
10 #include "AffineExprDetail.h"
11 #include "mlir/IR/AffineExprVisitor.h"
12 #include "mlir/IR/AffineMap.h"
13 #include "mlir/IR/IntegerSet.h"
14 #include "mlir/Support/MathExtras.h"
15 #include "llvm/ADT/STLExtras.h"
16 
17 using namespace mlir;
18 using namespace mlir::detail;
19 
20 MLIRContext *AffineExpr::getContext() const { return expr->context; }
21 
22 AffineExprKind AffineExpr::getKind() const {
23   return static_cast<AffineExprKind>(expr->getKind());
24 }
25 
26 /// Walk all of the AffineExprs in this subgraph in postorder.
27 void AffineExpr::walk(std::function<void(AffineExpr)> callback) const {
28   struct AffineExprWalker : public AffineExprVisitor<AffineExprWalker> {
29     std::function<void(AffineExpr)> callback;
30 
31     AffineExprWalker(std::function<void(AffineExpr)> callback)
32         : callback(callback) {}
33 
34     void visitAffineBinaryOpExpr(AffineBinaryOpExpr expr) { callback(expr); }
35     void visitConstantExpr(AffineConstantExpr expr) { callback(expr); }
36     void visitDimExpr(AffineDimExpr expr) { callback(expr); }
37     void visitSymbolExpr(AffineSymbolExpr expr) { callback(expr); }
38   };
39 
40   AffineExprWalker(callback).walkPostOrder(*this);
41 }
42 
43 // Dispatch affine expression construction based on kind.
44 AffineExpr mlir::getAffineBinaryOpExpr(AffineExprKind kind, AffineExpr lhs,
45                                        AffineExpr rhs) {
46   if (kind == AffineExprKind::Add)
47     return lhs + rhs;
48   if (kind == AffineExprKind::Mul)
49     return lhs * rhs;
50   if (kind == AffineExprKind::FloorDiv)
51     return lhs.floorDiv(rhs);
52   if (kind == AffineExprKind::CeilDiv)
53     return lhs.ceilDiv(rhs);
54   if (kind == AffineExprKind::Mod)
55     return lhs % rhs;
56 
57   llvm_unreachable("unknown binary operation on affine expressions");
58 }
59 
60 /// This method substitutes any uses of dimensions and symbols (e.g.
61 /// dim#0 with dimReplacements[0]) and returns the modified expression tree.
62 AffineExpr
63 AffineExpr::replaceDimsAndSymbols(ArrayRef<AffineExpr> dimReplacements,
64                                   ArrayRef<AffineExpr> symReplacements) const {
65   switch (getKind()) {
66   case AffineExprKind::Constant:
67     return *this;
68   case AffineExprKind::DimId: {
69     unsigned dimId = cast<AffineDimExpr>().getPosition();
70     if (dimId >= dimReplacements.size())
71       return *this;
72     return dimReplacements[dimId];
73   }
74   case AffineExprKind::SymbolId: {
75     unsigned symId = cast<AffineSymbolExpr>().getPosition();
76     if (symId >= symReplacements.size())
77       return *this;
78     return symReplacements[symId];
79   }
80   case AffineExprKind::Add:
81   case AffineExprKind::Mul:
82   case AffineExprKind::FloorDiv:
83   case AffineExprKind::CeilDiv:
84   case AffineExprKind::Mod:
85     auto binOp = cast<AffineBinaryOpExpr>();
86     auto lhs = binOp.getLHS(), rhs = binOp.getRHS();
87     auto newLHS = lhs.replaceDimsAndSymbols(dimReplacements, symReplacements);
88     auto newRHS = rhs.replaceDimsAndSymbols(dimReplacements, symReplacements);
89     if (newLHS == lhs && newRHS == rhs)
90       return *this;
91     return getAffineBinaryOpExpr(getKind(), newLHS, newRHS);
92   }
93   llvm_unreachable("Unknown AffineExpr");
94 }
95 
96 /// Replace symbols[0 .. numDims - 1] by symbols[shift .. shift + numDims - 1].
97 AffineExpr AffineExpr::shiftSymbols(unsigned numSymbols, unsigned shift) const {
98   SmallVector<AffineExpr, 4> symbols;
99   for (unsigned idx = 0; idx < numSymbols; ++idx)
100     symbols.push_back(getAffineSymbolExpr(idx + shift, getContext()));
101   return replaceDimsAndSymbols({}, symbols);
102 }
103 
104 /// Returns true if this expression is made out of only symbols and
105 /// constants (no dimensional identifiers).
106 bool AffineExpr::isSymbolicOrConstant() const {
107   switch (getKind()) {
108   case AffineExprKind::Constant:
109     return true;
110   case AffineExprKind::DimId:
111     return false;
112   case AffineExprKind::SymbolId:
113     return true;
114 
115   case AffineExprKind::Add:
116   case AffineExprKind::Mul:
117   case AffineExprKind::FloorDiv:
118   case AffineExprKind::CeilDiv:
119   case AffineExprKind::Mod: {
120     auto expr = this->cast<AffineBinaryOpExpr>();
121     return expr.getLHS().isSymbolicOrConstant() &&
122            expr.getRHS().isSymbolicOrConstant();
123   }
124   }
125   llvm_unreachable("Unknown AffineExpr");
126 }
127 
128 /// Returns true if this is a pure affine expression, i.e., multiplication,
129 /// floordiv, ceildiv, and mod is only allowed w.r.t constants.
130 bool AffineExpr::isPureAffine() const {
131   switch (getKind()) {
132   case AffineExprKind::SymbolId:
133   case AffineExprKind::DimId:
134   case AffineExprKind::Constant:
135     return true;
136   case AffineExprKind::Add: {
137     auto op = cast<AffineBinaryOpExpr>();
138     return op.getLHS().isPureAffine() && op.getRHS().isPureAffine();
139   }
140 
141   case AffineExprKind::Mul: {
142     // TODO: Canonicalize the constants in binary operators to the RHS when
143     // possible, allowing this to merge into the next case.
144     auto op = cast<AffineBinaryOpExpr>();
145     return op.getLHS().isPureAffine() && op.getRHS().isPureAffine() &&
146            (op.getLHS().template isa<AffineConstantExpr>() ||
147             op.getRHS().template isa<AffineConstantExpr>());
148   }
149   case AffineExprKind::FloorDiv:
150   case AffineExprKind::CeilDiv:
151   case AffineExprKind::Mod: {
152     auto op = cast<AffineBinaryOpExpr>();
153     return op.getLHS().isPureAffine() &&
154            op.getRHS().template isa<AffineConstantExpr>();
155   }
156   }
157   llvm_unreachable("Unknown AffineExpr");
158 }
159 
160 // Returns the greatest known integral divisor of this affine expression.
161 int64_t AffineExpr::getLargestKnownDivisor() const {
162   AffineBinaryOpExpr binExpr(nullptr);
163   switch (getKind()) {
164   case AffineExprKind::SymbolId:
165     LLVM_FALLTHROUGH;
166   case AffineExprKind::DimId:
167     return 1;
168   case AffineExprKind::Constant:
169     return std::abs(this->cast<AffineConstantExpr>().getValue());
170   case AffineExprKind::Mul: {
171     binExpr = this->cast<AffineBinaryOpExpr>();
172     return binExpr.getLHS().getLargestKnownDivisor() *
173            binExpr.getRHS().getLargestKnownDivisor();
174   }
175   case AffineExprKind::Add:
176     LLVM_FALLTHROUGH;
177   case AffineExprKind::FloorDiv:
178   case AffineExprKind::CeilDiv:
179   case AffineExprKind::Mod: {
180     binExpr = cast<AffineBinaryOpExpr>();
181     return llvm::GreatestCommonDivisor64(
182         binExpr.getLHS().getLargestKnownDivisor(),
183         binExpr.getRHS().getLargestKnownDivisor());
184   }
185   }
186   llvm_unreachable("Unknown AffineExpr");
187 }
188 
189 bool AffineExpr::isMultipleOf(int64_t factor) const {
190   AffineBinaryOpExpr binExpr(nullptr);
191   uint64_t l, u;
192   switch (getKind()) {
193   case AffineExprKind::SymbolId:
194     LLVM_FALLTHROUGH;
195   case AffineExprKind::DimId:
196     return factor * factor == 1;
197   case AffineExprKind::Constant:
198     return cast<AffineConstantExpr>().getValue() % factor == 0;
199   case AffineExprKind::Mul: {
200     binExpr = cast<AffineBinaryOpExpr>();
201     // It's probably not worth optimizing this further (to not traverse the
202     // whole sub-tree under - it that would require a version of isMultipleOf
203     // that on a 'false' return also returns the largest known divisor).
204     return (l = binExpr.getLHS().getLargestKnownDivisor()) % factor == 0 ||
205            (u = binExpr.getRHS().getLargestKnownDivisor()) % factor == 0 ||
206            (l * u) % factor == 0;
207   }
208   case AffineExprKind::Add:
209   case AffineExprKind::FloorDiv:
210   case AffineExprKind::CeilDiv:
211   case AffineExprKind::Mod: {
212     binExpr = cast<AffineBinaryOpExpr>();
213     return llvm::GreatestCommonDivisor64(
214                binExpr.getLHS().getLargestKnownDivisor(),
215                binExpr.getRHS().getLargestKnownDivisor()) %
216                factor ==
217            0;
218   }
219   }
220   llvm_unreachable("Unknown AffineExpr");
221 }
222 
223 bool AffineExpr::isFunctionOfDim(unsigned position) const {
224   if (getKind() == AffineExprKind::DimId) {
225     return *this == mlir::getAffineDimExpr(position, getContext());
226   }
227   if (auto expr = this->dyn_cast<AffineBinaryOpExpr>()) {
228     return expr.getLHS().isFunctionOfDim(position) ||
229            expr.getRHS().isFunctionOfDim(position);
230   }
231   return false;
232 }
233 
234 AffineBinaryOpExpr::AffineBinaryOpExpr(AffineExpr::ImplType *ptr)
235     : AffineExpr(ptr) {}
236 AffineExpr AffineBinaryOpExpr::getLHS() const {
237   return static_cast<ImplType *>(expr)->lhs;
238 }
239 AffineExpr AffineBinaryOpExpr::getRHS() const {
240   return static_cast<ImplType *>(expr)->rhs;
241 }
242 
243 AffineDimExpr::AffineDimExpr(AffineExpr::ImplType *ptr) : AffineExpr(ptr) {}
244 unsigned AffineDimExpr::getPosition() const {
245   return static_cast<ImplType *>(expr)->position;
246 }
247 
248 static AffineExpr getAffineDimOrSymbol(AffineExprKind kind, unsigned position,
249                                        MLIRContext *context) {
250   auto assignCtx = [context](AffineDimExprStorage *storage) {
251     storage->context = context;
252   };
253 
254   StorageUniquer &uniquer = context->getAffineUniquer();
255   return uniquer.get<AffineDimExprStorage>(
256       assignCtx, static_cast<unsigned>(kind), position);
257 }
258 
259 AffineExpr mlir::getAffineDimExpr(unsigned position, MLIRContext *context) {
260   return getAffineDimOrSymbol(AffineExprKind::DimId, position, context);
261 }
262 
263 AffineSymbolExpr::AffineSymbolExpr(AffineExpr::ImplType *ptr)
264     : AffineExpr(ptr) {}
265 unsigned AffineSymbolExpr::getPosition() const {
266   return static_cast<ImplType *>(expr)->position;
267 }
268 
269 AffineExpr mlir::getAffineSymbolExpr(unsigned position, MLIRContext *context) {
270   return getAffineDimOrSymbol(AffineExprKind::SymbolId, position, context);
271   ;
272 }
273 
274 AffineConstantExpr::AffineConstantExpr(AffineExpr::ImplType *ptr)
275     : AffineExpr(ptr) {}
276 int64_t AffineConstantExpr::getValue() const {
277   return static_cast<ImplType *>(expr)->constant;
278 }
279 
280 bool AffineExpr::operator==(int64_t v) const {
281   return *this == getAffineConstantExpr(v, getContext());
282 }
283 
284 AffineExpr mlir::getAffineConstantExpr(int64_t constant, MLIRContext *context) {
285   auto assignCtx = [context](AffineConstantExprStorage *storage) {
286     storage->context = context;
287   };
288 
289   StorageUniquer &uniquer = context->getAffineUniquer();
290   return uniquer.get<AffineConstantExprStorage>(
291       assignCtx, static_cast<unsigned>(AffineExprKind::Constant), constant);
292 }
293 
294 /// Simplify add expression. Return nullptr if it can't be simplified.
295 static AffineExpr simplifyAdd(AffineExpr lhs, AffineExpr rhs) {
296   auto lhsConst = lhs.dyn_cast<AffineConstantExpr>();
297   auto rhsConst = rhs.dyn_cast<AffineConstantExpr>();
298   // Fold if both LHS, RHS are a constant.
299   if (lhsConst && rhsConst)
300     return getAffineConstantExpr(lhsConst.getValue() + rhsConst.getValue(),
301                                  lhs.getContext());
302 
303   // Canonicalize so that only the RHS is a constant. (4 + d0 becomes d0 + 4).
304   // If only one of them is a symbolic expressions, make it the RHS.
305   if (lhs.isa<AffineConstantExpr>() ||
306       (lhs.isSymbolicOrConstant() && !rhs.isSymbolicOrConstant())) {
307     return rhs + lhs;
308   }
309 
310   // At this point, if there was a constant, it would be on the right.
311 
312   // Addition with a zero is a noop, return the other input.
313   if (rhsConst) {
314     if (rhsConst.getValue() == 0)
315       return lhs;
316   }
317   // Fold successive additions like (d0 + 2) + 3 into d0 + 5.
318   auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>();
319   if (lBin && rhsConst && lBin.getKind() == AffineExprKind::Add) {
320     if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>())
321       return lBin.getLHS() + (lrhs.getValue() + rhsConst.getValue());
322   }
323 
324   // Detect "c1 * expr + c_2 * expr" as "(c1 + c2) * expr".
325   // c1 is rRhsConst, c2 is rLhsConst; firstExpr, secondExpr are their
326   // respective multiplicands.
327   Optional<int64_t> rLhsConst, rRhsConst;
328   AffineExpr firstExpr, secondExpr;
329   AffineConstantExpr rLhsConstExpr;
330   auto lBinOpExpr = lhs.dyn_cast<AffineBinaryOpExpr>();
331   if (lBinOpExpr && lBinOpExpr.getKind() == AffineExprKind::Mul &&
332       (rLhsConstExpr = lBinOpExpr.getRHS().dyn_cast<AffineConstantExpr>())) {
333     rLhsConst = rLhsConstExpr.getValue();
334     firstExpr = lBinOpExpr.getLHS();
335   } else {
336     rLhsConst = 1;
337     firstExpr = lhs;
338   }
339 
340   auto rBinOpExpr = rhs.dyn_cast<AffineBinaryOpExpr>();
341   AffineConstantExpr rRhsConstExpr;
342   if (rBinOpExpr && rBinOpExpr.getKind() == AffineExprKind::Mul &&
343       (rRhsConstExpr = rBinOpExpr.getRHS().dyn_cast<AffineConstantExpr>())) {
344     rRhsConst = rRhsConstExpr.getValue();
345     secondExpr = rBinOpExpr.getLHS();
346   } else {
347     rRhsConst = 1;
348     secondExpr = rhs;
349   }
350 
351   if (rLhsConst && rRhsConst && firstExpr == secondExpr)
352     return getAffineBinaryOpExpr(
353         AffineExprKind::Mul, firstExpr,
354         getAffineConstantExpr(rLhsConst.getValue() + rRhsConst.getValue(),
355                               lhs.getContext()));
356 
357   // When doing successive additions, bring constant to the right: turn (d0 + 2)
358   // + d1 into (d0 + d1) + 2.
359   if (lBin && lBin.getKind() == AffineExprKind::Add) {
360     if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) {
361       return lBin.getLHS() + rhs + lrhs;
362     }
363   }
364 
365   // Detect and transform "expr - c * (expr floordiv c)" to "expr mod c". This
366   // leads to a much more efficient form when 'c' is a power of two, and in
367   // general a more compact and readable form.
368 
369   // Process '(expr floordiv c) * (-c)'.
370   if (!rBinOpExpr)
371     return nullptr;
372 
373   auto lrhs = rBinOpExpr.getLHS();
374   auto rrhs = rBinOpExpr.getRHS();
375 
376   // Process lrhs, which is 'expr floordiv c'.
377   AffineBinaryOpExpr lrBinOpExpr = lrhs.dyn_cast<AffineBinaryOpExpr>();
378   if (!lrBinOpExpr || lrBinOpExpr.getKind() != AffineExprKind::FloorDiv)
379     return nullptr;
380 
381   auto llrhs = lrBinOpExpr.getLHS();
382   auto rlrhs = lrBinOpExpr.getRHS();
383 
384   if (lhs == llrhs && rlrhs == -rrhs) {
385     return lhs % rlrhs;
386   }
387   return nullptr;
388 }
389 
390 AffineExpr AffineExpr::operator+(int64_t v) const {
391   return *this + getAffineConstantExpr(v, getContext());
392 }
393 AffineExpr AffineExpr::operator+(AffineExpr other) const {
394   if (auto simplified = simplifyAdd(*this, other))
395     return simplified;
396 
397   StorageUniquer &uniquer = getContext()->getAffineUniquer();
398   return uniquer.get<AffineBinaryOpExprStorage>(
399       /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::Add), *this, other);
400 }
401 
402 /// Simplify a multiply expression. Return nullptr if it can't be simplified.
403 static AffineExpr simplifyMul(AffineExpr lhs, AffineExpr rhs) {
404   auto lhsConst = lhs.dyn_cast<AffineConstantExpr>();
405   auto rhsConst = rhs.dyn_cast<AffineConstantExpr>();
406 
407   if (lhsConst && rhsConst)
408     return getAffineConstantExpr(lhsConst.getValue() * rhsConst.getValue(),
409                                  lhs.getContext());
410 
411   assert(lhs.isSymbolicOrConstant() || rhs.isSymbolicOrConstant());
412 
413   // Canonicalize the mul expression so that the constant/symbolic term is the
414   // RHS. If both the lhs and rhs are symbolic, swap them if the lhs is a
415   // constant. (Note that a constant is trivially symbolic).
416   if (!rhs.isSymbolicOrConstant() || lhs.isa<AffineConstantExpr>()) {
417     // At least one of them has to be symbolic.
418     return rhs * lhs;
419   }
420 
421   // At this point, if there was a constant, it would be on the right.
422 
423   // Multiplication with a one is a noop, return the other input.
424   if (rhsConst) {
425     if (rhsConst.getValue() == 1)
426       return lhs;
427     // Multiplication with zero.
428     if (rhsConst.getValue() == 0)
429       return rhsConst;
430   }
431 
432   // Fold successive multiplications: eg: (d0 * 2) * 3 into d0 * 6.
433   auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>();
434   if (lBin && rhsConst && lBin.getKind() == AffineExprKind::Mul) {
435     if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>())
436       return lBin.getLHS() * (lrhs.getValue() * rhsConst.getValue());
437   }
438 
439   // When doing successive multiplication, bring constant to the right: turn (d0
440   // * 2) * d1 into (d0 * d1) * 2.
441   if (lBin && lBin.getKind() == AffineExprKind::Mul) {
442     if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) {
443       return (lBin.getLHS() * rhs) * lrhs;
444     }
445   }
446 
447   return nullptr;
448 }
449 
450 AffineExpr AffineExpr::operator*(int64_t v) const {
451   return *this * getAffineConstantExpr(v, getContext());
452 }
453 AffineExpr AffineExpr::operator*(AffineExpr other) const {
454   if (auto simplified = simplifyMul(*this, other))
455     return simplified;
456 
457   StorageUniquer &uniquer = getContext()->getAffineUniquer();
458   return uniquer.get<AffineBinaryOpExprStorage>(
459       /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::Mul), *this, other);
460 }
461 
462 // Unary minus, delegate to operator*.
463 AffineExpr AffineExpr::operator-() const {
464   return *this * getAffineConstantExpr(-1, getContext());
465 }
466 
467 // Delegate to operator+.
468 AffineExpr AffineExpr::operator-(int64_t v) const { return *this + (-v); }
469 AffineExpr AffineExpr::operator-(AffineExpr other) const {
470   return *this + (-other);
471 }
472 
473 static AffineExpr simplifyFloorDiv(AffineExpr lhs, AffineExpr rhs) {
474   auto lhsConst = lhs.dyn_cast<AffineConstantExpr>();
475   auto rhsConst = rhs.dyn_cast<AffineConstantExpr>();
476 
477   // mlir floordiv by zero or negative numbers is undefined and preserved as is.
478   if (!rhsConst || rhsConst.getValue() < 1)
479     return nullptr;
480 
481   if (lhsConst)
482     return getAffineConstantExpr(
483         floorDiv(lhsConst.getValue(), rhsConst.getValue()), lhs.getContext());
484 
485   // Fold floordiv of a multiply with a constant that is a multiple of the
486   // divisor. Eg: (i * 128) floordiv 64 = i * 2.
487   if (rhsConst == 1)
488     return lhs;
489 
490   // Simplify (expr * const) floordiv divConst when expr is known to be a
491   // multiple of divConst.
492   auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>();
493   if (lBin && lBin.getKind() == AffineExprKind::Mul) {
494     if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) {
495       // rhsConst is known to be a positive constant.
496       if (lrhs.getValue() % rhsConst.getValue() == 0)
497         return lBin.getLHS() * (lrhs.getValue() / rhsConst.getValue());
498     }
499   }
500 
501   // Simplify (expr1 + expr2) floordiv divConst when either expr1 or expr2 is
502   // known to be a multiple of divConst.
503   if (lBin && lBin.getKind() == AffineExprKind::Add) {
504     int64_t llhsDiv = lBin.getLHS().getLargestKnownDivisor();
505     int64_t lrhsDiv = lBin.getRHS().getLargestKnownDivisor();
506     // rhsConst is known to be a positive constant.
507     if (llhsDiv % rhsConst.getValue() == 0 ||
508         lrhsDiv % rhsConst.getValue() == 0)
509       return lBin.getLHS().floorDiv(rhsConst.getValue()) +
510              lBin.getRHS().floorDiv(rhsConst.getValue());
511   }
512 
513   return nullptr;
514 }
515 
516 AffineExpr AffineExpr::floorDiv(uint64_t v) const {
517   return floorDiv(getAffineConstantExpr(v, getContext()));
518 }
519 AffineExpr AffineExpr::floorDiv(AffineExpr other) const {
520   if (auto simplified = simplifyFloorDiv(*this, other))
521     return simplified;
522 
523   StorageUniquer &uniquer = getContext()->getAffineUniquer();
524   return uniquer.get<AffineBinaryOpExprStorage>(
525       /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::FloorDiv), *this,
526       other);
527 }
528 
529 static AffineExpr simplifyCeilDiv(AffineExpr lhs, AffineExpr rhs) {
530   auto lhsConst = lhs.dyn_cast<AffineConstantExpr>();
531   auto rhsConst = rhs.dyn_cast<AffineConstantExpr>();
532 
533   if (!rhsConst || rhsConst.getValue() < 1)
534     return nullptr;
535 
536   if (lhsConst)
537     return getAffineConstantExpr(
538         ceilDiv(lhsConst.getValue(), rhsConst.getValue()), lhs.getContext());
539 
540   // Fold ceildiv of a multiply with a constant that is a multiple of the
541   // divisor. Eg: (i * 128) ceildiv 64 = i * 2.
542   if (rhsConst.getValue() == 1)
543     return lhs;
544 
545   // Simplify (expr * const) ceildiv divConst when const is known to be a
546   // multiple of divConst.
547   auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>();
548   if (lBin && lBin.getKind() == AffineExprKind::Mul) {
549     if (auto lrhs = lBin.getRHS().dyn_cast<AffineConstantExpr>()) {
550       // rhsConst is known to be a positive constant.
551       if (lrhs.getValue() % rhsConst.getValue() == 0)
552         return lBin.getLHS() * (lrhs.getValue() / rhsConst.getValue());
553     }
554   }
555 
556   return nullptr;
557 }
558 
559 AffineExpr AffineExpr::ceilDiv(uint64_t v) const {
560   return ceilDiv(getAffineConstantExpr(v, getContext()));
561 }
562 AffineExpr AffineExpr::ceilDiv(AffineExpr other) const {
563   if (auto simplified = simplifyCeilDiv(*this, other))
564     return simplified;
565 
566   StorageUniquer &uniquer = getContext()->getAffineUniquer();
567   return uniquer.get<AffineBinaryOpExprStorage>(
568       /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::CeilDiv), *this,
569       other);
570 }
571 
572 static AffineExpr simplifyMod(AffineExpr lhs, AffineExpr rhs) {
573   auto lhsConst = lhs.dyn_cast<AffineConstantExpr>();
574   auto rhsConst = rhs.dyn_cast<AffineConstantExpr>();
575 
576   // mod w.r.t zero or negative numbers is undefined and preserved as is.
577   if (!rhsConst || rhsConst.getValue() < 1)
578     return nullptr;
579 
580   if (lhsConst)
581     return getAffineConstantExpr(mod(lhsConst.getValue(), rhsConst.getValue()),
582                                  lhs.getContext());
583 
584   // Fold modulo of an expression that is known to be a multiple of a constant
585   // to zero if that constant is a multiple of the modulo factor. Eg: (i * 128)
586   // mod 64 is folded to 0, and less trivially, (i*(j*4*(k*32))) mod 128 = 0.
587   if (lhs.getLargestKnownDivisor() % rhsConst.getValue() == 0)
588     return getAffineConstantExpr(0, lhs.getContext());
589 
590   // Simplify (expr1 + expr2) mod divConst when either expr1 or expr2 is
591   // known to be a multiple of divConst.
592   auto lBin = lhs.dyn_cast<AffineBinaryOpExpr>();
593   if (lBin && lBin.getKind() == AffineExprKind::Add) {
594     int64_t llhsDiv = lBin.getLHS().getLargestKnownDivisor();
595     int64_t lrhsDiv = lBin.getRHS().getLargestKnownDivisor();
596     // rhsConst is known to be a positive constant.
597     if (llhsDiv % rhsConst.getValue() == 0)
598       return lBin.getRHS() % rhsConst.getValue();
599     if (lrhsDiv % rhsConst.getValue() == 0)
600       return lBin.getLHS() % rhsConst.getValue();
601   }
602 
603   return nullptr;
604 }
605 
606 AffineExpr AffineExpr::operator%(uint64_t v) const {
607   return *this % getAffineConstantExpr(v, getContext());
608 }
609 AffineExpr AffineExpr::operator%(AffineExpr other) const {
610   if (auto simplified = simplifyMod(*this, other))
611     return simplified;
612 
613   StorageUniquer &uniquer = getContext()->getAffineUniquer();
614   return uniquer.get<AffineBinaryOpExprStorage>(
615       /*initFn=*/{}, static_cast<unsigned>(AffineExprKind::Mod), *this, other);
616 }
617 
618 AffineExpr AffineExpr::compose(AffineMap map) const {
619   SmallVector<AffineExpr, 8> dimReplacements(map.getResults().begin(),
620                                              map.getResults().end());
621   return replaceDimsAndSymbols(dimReplacements, {});
622 }
623 raw_ostream &mlir::operator<<(raw_ostream &os, AffineExpr expr) {
624   expr.print(os);
625   return os;
626 }
627 
628 /// Constructs an affine expression from a flat ArrayRef. If there are local
629 /// identifiers (neither dimensional nor symbolic) that appear in the sum of
630 /// products expression, `localExprs` is expected to have the AffineExpr
631 /// for it, and is substituted into. The ArrayRef `flatExprs` is expected to be
632 /// in the format [dims, symbols, locals, constant term].
633 AffineExpr mlir::getAffineExprFromFlatForm(ArrayRef<int64_t> flatExprs,
634                                            unsigned numDims,
635                                            unsigned numSymbols,
636                                            ArrayRef<AffineExpr> localExprs,
637                                            MLIRContext *context) {
638   // Assert expected numLocals = flatExprs.size() - numDims - numSymbols - 1.
639   assert(flatExprs.size() - numDims - numSymbols - 1 == localExprs.size() &&
640          "unexpected number of local expressions");
641 
642   auto expr = getAffineConstantExpr(0, context);
643   // Dimensions and symbols.
644   for (unsigned j = 0; j < numDims + numSymbols; j++) {
645     if (flatExprs[j] == 0)
646       continue;
647     auto id = j < numDims ? getAffineDimExpr(j, context)
648                           : getAffineSymbolExpr(j - numDims, context);
649     expr = expr + id * flatExprs[j];
650   }
651 
652   // Local identifiers.
653   for (unsigned j = numDims + numSymbols, e = flatExprs.size() - 1; j < e;
654        j++) {
655     if (flatExprs[j] == 0)
656       continue;
657     auto term = localExprs[j - numDims - numSymbols] * flatExprs[j];
658     expr = expr + term;
659   }
660 
661   // Constant term.
662   int64_t constTerm = flatExprs[flatExprs.size() - 1];
663   if (constTerm != 0)
664     expr = expr + constTerm;
665   return expr;
666 }
667 
668 SimpleAffineExprFlattener::SimpleAffineExprFlattener(unsigned numDims,
669                                                      unsigned numSymbols)
670     : numDims(numDims), numSymbols(numSymbols), numLocals(0) {
671   operandExprStack.reserve(8);
672 }
673 
674 void SimpleAffineExprFlattener::visitMulExpr(AffineBinaryOpExpr expr) {
675   assert(operandExprStack.size() >= 2);
676   // This is a pure affine expr; the RHS will be a constant.
677   assert(expr.getRHS().isa<AffineConstantExpr>());
678   // Get the RHS constant.
679   auto rhsConst = operandExprStack.back()[getConstantIndex()];
680   operandExprStack.pop_back();
681   // Update the LHS in place instead of pop and push.
682   auto &lhs = operandExprStack.back();
683   for (unsigned i = 0, e = lhs.size(); i < e; i++) {
684     lhs[i] *= rhsConst;
685   }
686 }
687 
688 void SimpleAffineExprFlattener::visitAddExpr(AffineBinaryOpExpr expr) {
689   assert(operandExprStack.size() >= 2);
690   const auto &rhs = operandExprStack.back();
691   auto &lhs = operandExprStack[operandExprStack.size() - 2];
692   assert(lhs.size() == rhs.size());
693   // Update the LHS in place.
694   for (unsigned i = 0, e = rhs.size(); i < e; i++) {
695     lhs[i] += rhs[i];
696   }
697   // Pop off the RHS.
698   operandExprStack.pop_back();
699 }
700 
701 //
702 // t = expr mod c   <=>  t = expr - c*q and c*q <= expr <= c*q + c - 1
703 //
704 // A mod expression "expr mod c" is thus flattened by introducing a new local
705 // variable q (= expr floordiv c), such that expr mod c is replaced with
706 // 'expr - c * q' and c * q <= expr <= c * q + c - 1 are added to localVarCst.
707 void SimpleAffineExprFlattener::visitModExpr(AffineBinaryOpExpr expr) {
708   assert(operandExprStack.size() >= 2);
709   // This is a pure affine expr; the RHS will be a constant.
710   assert(expr.getRHS().isa<AffineConstantExpr>());
711   auto rhsConst = operandExprStack.back()[getConstantIndex()];
712   operandExprStack.pop_back();
713   auto &lhs = operandExprStack.back();
714   // TODO: handle modulo by zero case when this issue is fixed
715   // at the other places in the IR.
716   assert(rhsConst > 0 && "RHS constant has to be positive");
717 
718   // Check if the LHS expression is a multiple of modulo factor.
719   unsigned i, e;
720   for (i = 0, e = lhs.size(); i < e; i++)
721     if (lhs[i] % rhsConst != 0)
722       break;
723   // If yes, modulo expression here simplifies to zero.
724   if (i == lhs.size()) {
725     std::fill(lhs.begin(), lhs.end(), 0);
726     return;
727   }
728 
729   // Add a local variable for the quotient, i.e., expr % c is replaced by
730   // (expr - q * c) where q = expr floordiv c. Do this while canceling out
731   // the GCD of expr and c.
732   SmallVector<int64_t, 8> floorDividend(lhs);
733   uint64_t gcd = rhsConst;
734   for (unsigned i = 0, e = lhs.size(); i < e; i++)
735     gcd = llvm::GreatestCommonDivisor64(gcd, std::abs(lhs[i]));
736   // Simplify the numerator and the denominator.
737   if (gcd != 1) {
738     for (unsigned i = 0, e = floorDividend.size(); i < e; i++)
739       floorDividend[i] = floorDividend[i] / static_cast<int64_t>(gcd);
740   }
741   int64_t floorDivisor = rhsConst / static_cast<int64_t>(gcd);
742 
743   // Construct the AffineExpr form of the floordiv to store in localExprs.
744   MLIRContext *context = expr.getContext();
745   auto dividendExpr = getAffineExprFromFlatForm(
746       floorDividend, numDims, numSymbols, localExprs, context);
747   auto divisorExpr = getAffineConstantExpr(floorDivisor, context);
748   auto floorDivExpr = dividendExpr.floorDiv(divisorExpr);
749   int loc;
750   if ((loc = findLocalId(floorDivExpr)) == -1) {
751     addLocalFloorDivId(floorDividend, floorDivisor, floorDivExpr);
752     // Set result at top of stack to "lhs - rhsConst * q".
753     lhs[getLocalVarStartIndex() + numLocals - 1] = -rhsConst;
754   } else {
755     // Reuse the existing local id.
756     lhs[getLocalVarStartIndex() + loc] = -rhsConst;
757   }
758 }
759 
760 void SimpleAffineExprFlattener::visitCeilDivExpr(AffineBinaryOpExpr expr) {
761   visitDivExpr(expr, /*isCeil=*/true);
762 }
763 void SimpleAffineExprFlattener::visitFloorDivExpr(AffineBinaryOpExpr expr) {
764   visitDivExpr(expr, /*isCeil=*/false);
765 }
766 
767 void SimpleAffineExprFlattener::visitDimExpr(AffineDimExpr expr) {
768   operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0));
769   auto &eq = operandExprStack.back();
770   assert(expr.getPosition() < numDims && "Inconsistent number of dims");
771   eq[getDimStartIndex() + expr.getPosition()] = 1;
772 }
773 
774 void SimpleAffineExprFlattener::visitSymbolExpr(AffineSymbolExpr expr) {
775   operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0));
776   auto &eq = operandExprStack.back();
777   assert(expr.getPosition() < numSymbols && "inconsistent number of symbols");
778   eq[getSymbolStartIndex() + expr.getPosition()] = 1;
779 }
780 
781 void SimpleAffineExprFlattener::visitConstantExpr(AffineConstantExpr expr) {
782   operandExprStack.emplace_back(SmallVector<int64_t, 32>(getNumCols(), 0));
783   auto &eq = operandExprStack.back();
784   eq[getConstantIndex()] = expr.getValue();
785 }
786 
787 // t = expr floordiv c   <=> t = q, c * q <= expr <= c * q + c - 1
788 // A floordiv is thus flattened by introducing a new local variable q, and
789 // replacing that expression with 'q' while adding the constraints
790 // c * q <= expr <= c * q + c - 1 to localVarCst (done by
791 // FlatAffineConstraints::addLocalFloorDiv).
792 //
793 // A ceildiv is similarly flattened:
794 // t = expr ceildiv c   <=> t =  (expr + c - 1) floordiv c
795 void SimpleAffineExprFlattener::visitDivExpr(AffineBinaryOpExpr expr,
796                                              bool isCeil) {
797   assert(operandExprStack.size() >= 2);
798   assert(expr.getRHS().isa<AffineConstantExpr>());
799 
800   // This is a pure affine expr; the RHS is a positive constant.
801   int64_t rhsConst = operandExprStack.back()[getConstantIndex()];
802   // TODO: handle division by zero at the same time the issue is
803   // fixed at other places.
804   assert(rhsConst > 0 && "RHS constant has to be positive");
805   operandExprStack.pop_back();
806   auto &lhs = operandExprStack.back();
807 
808   // Simplify the floordiv, ceildiv if possible by canceling out the greatest
809   // common divisors of the numerator and denominator.
810   uint64_t gcd = std::abs(rhsConst);
811   for (unsigned i = 0, e = lhs.size(); i < e; i++)
812     gcd = llvm::GreatestCommonDivisor64(gcd, std::abs(lhs[i]));
813   // Simplify the numerator and the denominator.
814   if (gcd != 1) {
815     for (unsigned i = 0, e = lhs.size(); i < e; i++)
816       lhs[i] = lhs[i] / static_cast<int64_t>(gcd);
817   }
818   int64_t divisor = rhsConst / static_cast<int64_t>(gcd);
819   // If the divisor becomes 1, the updated LHS is the result. (The
820   // divisor can't be negative since rhsConst is positive).
821   if (divisor == 1)
822     return;
823 
824   // If the divisor cannot be simplified to one, we will have to retain
825   // the ceil/floor expr (simplified up until here). Add an existential
826   // quantifier to express its result, i.e., expr1 div expr2 is replaced
827   // by a new identifier, q.
828   MLIRContext *context = expr.getContext();
829   auto a =
830       getAffineExprFromFlatForm(lhs, numDims, numSymbols, localExprs, context);
831   auto b = getAffineConstantExpr(divisor, context);
832 
833   int loc;
834   auto divExpr = isCeil ? a.ceilDiv(b) : a.floorDiv(b);
835   if ((loc = findLocalId(divExpr)) == -1) {
836     if (!isCeil) {
837       SmallVector<int64_t, 8> dividend(lhs);
838       addLocalFloorDivId(dividend, divisor, divExpr);
839     } else {
840       // lhs ceildiv c <=>  (lhs + c - 1) floordiv c
841       SmallVector<int64_t, 8> dividend(lhs);
842       dividend.back() += divisor - 1;
843       addLocalFloorDivId(dividend, divisor, divExpr);
844     }
845   }
846   // Set the expression on stack to the local var introduced to capture the
847   // result of the division (floor or ceil).
848   std::fill(lhs.begin(), lhs.end(), 0);
849   if (loc == -1)
850     lhs[getLocalVarStartIndex() + numLocals - 1] = 1;
851   else
852     lhs[getLocalVarStartIndex() + loc] = 1;
853 }
854 
855 // Add a local identifier (needed to flatten a mod, floordiv, ceildiv expr).
856 // The local identifier added is always a floordiv of a pure add/mul affine
857 // function of other identifiers, coefficients of which are specified in
858 // dividend and with respect to a positive constant divisor. localExpr is the
859 // simplified tree expression (AffineExpr) corresponding to the quantifier.
860 void SimpleAffineExprFlattener::addLocalFloorDivId(ArrayRef<int64_t> dividend,
861                                                    int64_t divisor,
862                                                    AffineExpr localExpr) {
863   assert(divisor > 0 && "positive constant divisor expected");
864   for (auto &subExpr : operandExprStack)
865     subExpr.insert(subExpr.begin() + getLocalVarStartIndex() + numLocals, 0);
866   localExprs.push_back(localExpr);
867   numLocals++;
868   // dividend and divisor are not used here; an override of this method uses it.
869 }
870 
871 int SimpleAffineExprFlattener::findLocalId(AffineExpr localExpr) {
872   SmallVectorImpl<AffineExpr>::iterator it;
873   if ((it = llvm::find(localExprs, localExpr)) == localExprs.end())
874     return -1;
875   return it - localExprs.begin();
876 }
877 
878 /// Simplify the affine expression by flattening it and reconstructing it.
879 AffineExpr mlir::simplifyAffineExpr(AffineExpr expr, unsigned numDims,
880                                     unsigned numSymbols) {
881   // TODO: only pure affine for now. The simplification here can
882   // be extended to semi-affine maps in the future.
883   if (!expr.isPureAffine())
884     return expr;
885 
886   SimpleAffineExprFlattener flattener(numDims, numSymbols);
887   flattener.walkPostOrder(expr);
888   ArrayRef<int64_t> flattenedExpr = flattener.operandExprStack.back();
889   auto simplifiedExpr =
890       getAffineExprFromFlatForm(flattenedExpr, numDims, numSymbols,
891                                 flattener.localExprs, expr.getContext());
892   flattener.operandExprStack.pop_back();
893   assert(flattener.operandExprStack.empty());
894 
895   return simplifiedExpr;
896 }
897