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