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