1 //===-- AffinePromotion.cpp -----------------------------------------------===//
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 // This transformation is a prototype that promote FIR loops operations
10 // to affine dialect operations.
11 // It is not part of the production pipeline and would need more work in order
12 // to be used in production.
13 // More information can be found in this presentation:
14 // https://slides.com/rajanwalia/deck
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "PassDetail.h"
19 #include "flang/Optimizer/Dialect/FIRDialect.h"
20 #include "flang/Optimizer/Dialect/FIROps.h"
21 #include "flang/Optimizer/Dialect/FIRType.h"
22 #include "flang/Optimizer/Transforms/Passes.h"
23 #include "mlir/Dialect/Affine/IR/AffineOps.h"
24 #include "mlir/Dialect/Func/IR/FuncOps.h"
25 #include "mlir/Dialect/SCF/SCF.h"
26 #include "mlir/IR/BuiltinAttributes.h"
27 #include "mlir/IR/IntegerSet.h"
28 #include "mlir/IR/Visitors.h"
29 #include "mlir/Transforms/DialectConversion.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/Support/Debug.h"
33 
34 #define DEBUG_TYPE "flang-affine-promotion"
35 
36 using namespace fir;
37 
38 namespace {
39 struct AffineLoopAnalysis;
40 struct AffineIfAnalysis;
41 
42 /// Stores analysis objects for all loops and if operations inside a function
43 /// these analysis are used twice, first for marking operations for rewrite and
44 /// second when doing rewrite.
45 struct AffineFunctionAnalysis {
46   explicit AffineFunctionAnalysis(mlir::FuncOp funcOp) {
47     for (fir::DoLoopOp op : funcOp.getOps<fir::DoLoopOp>())
48       loopAnalysisMap.try_emplace(op, op, *this);
49   }
50 
51   AffineLoopAnalysis getChildLoopAnalysis(fir::DoLoopOp op) const;
52 
53   AffineIfAnalysis getChildIfAnalysis(fir::IfOp op) const;
54 
55   llvm::DenseMap<mlir::Operation *, AffineLoopAnalysis> loopAnalysisMap;
56   llvm::DenseMap<mlir::Operation *, AffineIfAnalysis> ifAnalysisMap;
57 };
58 } // namespace
59 
60 static bool analyzeCoordinate(mlir::Value coordinate, mlir::Operation *op) {
61   if (auto blockArg = coordinate.dyn_cast<mlir::BlockArgument>()) {
62     if (isa<fir::DoLoopOp>(blockArg.getOwner()->getParentOp()))
63       return true;
64     LLVM_DEBUG(llvm::dbgs() << "AffineLoopAnalysis: array coordinate is not a "
65                                "loop induction variable (owner not loopOp)\n";
66                op->dump());
67     return false;
68   }
69   LLVM_DEBUG(
70       llvm::dbgs() << "AffineLoopAnalysis: array coordinate is not a loop "
71                       "induction variable (not a block argument)\n";
72       op->dump(); coordinate.getDefiningOp()->dump());
73   return false;
74 }
75 
76 namespace {
77 struct AffineLoopAnalysis {
78   AffineLoopAnalysis() = default;
79 
80   explicit AffineLoopAnalysis(fir::DoLoopOp op, AffineFunctionAnalysis &afa)
81       : legality(analyzeLoop(op, afa)) {}
82 
83   bool canPromoteToAffine() { return legality; }
84 
85 private:
86   bool analyzeBody(fir::DoLoopOp loopOperation,
87                    AffineFunctionAnalysis &functionAnalysis) {
88     for (auto loopOp : loopOperation.getOps<fir::DoLoopOp>()) {
89       auto analysis = functionAnalysis.loopAnalysisMap
90                           .try_emplace(loopOp, loopOp, functionAnalysis)
91                           .first->getSecond();
92       if (!analysis.canPromoteToAffine())
93         return false;
94     }
95     for (auto ifOp : loopOperation.getOps<fir::IfOp>())
96       functionAnalysis.ifAnalysisMap.try_emplace(ifOp, ifOp, functionAnalysis);
97     return true;
98   }
99 
100   bool analyzeLoop(fir::DoLoopOp loopOperation,
101                    AffineFunctionAnalysis &functionAnalysis) {
102     LLVM_DEBUG(llvm::dbgs() << "AffineLoopAnalysis: \n"; loopOperation.dump(););
103     return analyzeMemoryAccess(loopOperation) &&
104            analyzeBody(loopOperation, functionAnalysis);
105   }
106 
107   bool analyzeReference(mlir::Value memref, mlir::Operation *op) {
108     if (auto acoOp = memref.getDefiningOp<ArrayCoorOp>()) {
109       if (acoOp.getMemref().getType().isa<fir::BoxType>()) {
110         // TODO: Look if and how fir.box can be promoted to affine.
111         LLVM_DEBUG(llvm::dbgs() << "AffineLoopAnalysis: cannot promote loop, "
112                                    "array memory operation uses fir.box\n";
113                    op->dump(); acoOp.dump(););
114         return false;
115       }
116       bool canPromote = true;
117       for (auto coordinate : acoOp.getIndices())
118         canPromote = canPromote && analyzeCoordinate(coordinate, op);
119       return canPromote;
120     }
121     if (auto coOp = memref.getDefiningOp<CoordinateOp>()) {
122       LLVM_DEBUG(llvm::dbgs()
123                      << "AffineLoopAnalysis: cannot promote loop, "
124                         "array memory operation uses non ArrayCoorOp\n";
125                  op->dump(); coOp.dump(););
126 
127       return false;
128     }
129     LLVM_DEBUG(llvm::dbgs() << "AffineLoopAnalysis: unknown type of memory "
130                                "reference for array load\n";
131                op->dump(););
132     return false;
133   }
134 
135   bool analyzeMemoryAccess(fir::DoLoopOp loopOperation) {
136     for (auto loadOp : loopOperation.getOps<fir::LoadOp>())
137       if (!analyzeReference(loadOp.getMemref(), loadOp))
138         return false;
139     for (auto storeOp : loopOperation.getOps<fir::StoreOp>())
140       if (!analyzeReference(storeOp.getMemref(), storeOp))
141         return false;
142     return true;
143   }
144 
145   bool legality{};
146 };
147 } // namespace
148 
149 AffineLoopAnalysis
150 AffineFunctionAnalysis::getChildLoopAnalysis(fir::DoLoopOp op) const {
151   auto it = loopAnalysisMap.find_as(op);
152   if (it == loopAnalysisMap.end()) {
153     LLVM_DEBUG(llvm::dbgs() << "AffineFunctionAnalysis: not computed for:\n";
154                op.dump(););
155     op.emitError("error in fetching loop analysis in AffineFunctionAnalysis\n");
156     return {};
157   }
158   return it->getSecond();
159 }
160 
161 namespace {
162 /// Calculates arguments for creating an IntegerSet. symCount, dimCount are the
163 /// final number of symbols and dimensions of the affine map. Integer set if
164 /// possible is in Optional IntegerSet.
165 struct AffineIfCondition {
166   using MaybeAffineExpr = llvm::Optional<mlir::AffineExpr>;
167 
168   explicit AffineIfCondition(mlir::Value fc) : firCondition(fc) {
169     if (auto condDef = firCondition.getDefiningOp<mlir::arith::CmpIOp>())
170       fromCmpIOp(condDef);
171   }
172 
173   bool hasIntegerSet() const { return integerSet.hasValue(); }
174 
175   mlir::IntegerSet getIntegerSet() const {
176     assert(hasIntegerSet() && "integer set is missing");
177     return integerSet.getValue();
178   }
179 
180   mlir::ValueRange getAffineArgs() const { return affineArgs; }
181 
182 private:
183   MaybeAffineExpr affineBinaryOp(mlir::AffineExprKind kind, mlir::Value lhs,
184                                  mlir::Value rhs) {
185     return affineBinaryOp(kind, toAffineExpr(lhs), toAffineExpr(rhs));
186   }
187 
188   MaybeAffineExpr affineBinaryOp(mlir::AffineExprKind kind, MaybeAffineExpr lhs,
189                                  MaybeAffineExpr rhs) {
190     if (lhs.hasValue() && rhs.hasValue())
191       return mlir::getAffineBinaryOpExpr(kind, lhs.getValue(), rhs.getValue());
192     return {};
193   }
194 
195   MaybeAffineExpr toAffineExpr(MaybeAffineExpr e) { return e; }
196 
197   MaybeAffineExpr toAffineExpr(int64_t value) {
198     return {mlir::getAffineConstantExpr(value, firCondition.getContext())};
199   }
200 
201   /// Returns an AffineExpr if it is a result of operations that can be done
202   /// in an affine expression, this includes -, +, *, rem, constant.
203   /// block arguments of a loopOp or forOp are used as dimensions
204   MaybeAffineExpr toAffineExpr(mlir::Value value) {
205     if (auto op = value.getDefiningOp<mlir::arith::SubIOp>())
206       return affineBinaryOp(
207           mlir::AffineExprKind::Add, toAffineExpr(op.getLhs()),
208           affineBinaryOp(mlir::AffineExprKind::Mul, toAffineExpr(op.getRhs()),
209                          toAffineExpr(-1)));
210     if (auto op = value.getDefiningOp<mlir::arith::AddIOp>())
211       return affineBinaryOp(mlir::AffineExprKind::Add, op.getLhs(),
212                             op.getRhs());
213     if (auto op = value.getDefiningOp<mlir::arith::MulIOp>())
214       return affineBinaryOp(mlir::AffineExprKind::Mul, op.getLhs(),
215                             op.getRhs());
216     if (auto op = value.getDefiningOp<mlir::arith::RemUIOp>())
217       return affineBinaryOp(mlir::AffineExprKind::Mod, op.getLhs(),
218                             op.getRhs());
219     if (auto op = value.getDefiningOp<mlir::arith::ConstantOp>())
220       if (auto intConstant = op.getValue().dyn_cast<IntegerAttr>())
221         return toAffineExpr(intConstant.getInt());
222     if (auto blockArg = value.dyn_cast<mlir::BlockArgument>()) {
223       affineArgs.push_back(value);
224       if (isa<fir::DoLoopOp>(blockArg.getOwner()->getParentOp()) ||
225           isa<mlir::AffineForOp>(blockArg.getOwner()->getParentOp()))
226         return {mlir::getAffineDimExpr(dimCount++, value.getContext())};
227       return {mlir::getAffineSymbolExpr(symCount++, value.getContext())};
228     }
229     return {};
230   }
231 
232   void fromCmpIOp(mlir::arith::CmpIOp cmpOp) {
233     auto lhsAffine = toAffineExpr(cmpOp.getLhs());
234     auto rhsAffine = toAffineExpr(cmpOp.getRhs());
235     if (!lhsAffine.hasValue() || !rhsAffine.hasValue())
236       return;
237     auto constraintPair = constraint(
238         cmpOp.getPredicate(), rhsAffine.getValue() - lhsAffine.getValue());
239     if (!constraintPair)
240       return;
241     integerSet = mlir::IntegerSet::get(dimCount, symCount,
242                                        {constraintPair.getValue().first},
243                                        {constraintPair.getValue().second});
244     return;
245   }
246 
247   llvm::Optional<std::pair<AffineExpr, bool>>
248   constraint(mlir::arith::CmpIPredicate predicate, mlir::AffineExpr basic) {
249     switch (predicate) {
250     case mlir::arith::CmpIPredicate::slt:
251       return {std::make_pair(basic - 1, false)};
252     case mlir::arith::CmpIPredicate::sle:
253       return {std::make_pair(basic, false)};
254     case mlir::arith::CmpIPredicate::sgt:
255       return {std::make_pair(1 - basic, false)};
256     case mlir::arith::CmpIPredicate::sge:
257       return {std::make_pair(0 - basic, false)};
258     case mlir::arith::CmpIPredicate::eq:
259       return {std::make_pair(basic, true)};
260     default:
261       return {};
262     }
263   }
264 
265   llvm::SmallVector<mlir::Value> affineArgs;
266   llvm::Optional<mlir::IntegerSet> integerSet;
267   mlir::Value firCondition;
268   unsigned symCount{0u};
269   unsigned dimCount{0u};
270 };
271 } // namespace
272 
273 namespace {
274 /// Analysis for affine promotion of fir.if
275 struct AffineIfAnalysis {
276   AffineIfAnalysis() = default;
277 
278   explicit AffineIfAnalysis(fir::IfOp op, AffineFunctionAnalysis &afa)
279       : legality(analyzeIf(op, afa)) {}
280 
281   bool canPromoteToAffine() { return legality; }
282 
283 private:
284   bool analyzeIf(fir::IfOp op, AffineFunctionAnalysis &afa) {
285     if (op.getNumResults() == 0)
286       return true;
287     LLVM_DEBUG(llvm::dbgs()
288                    << "AffineIfAnalysis: not promoting as op has results\n";);
289     return false;
290   }
291 
292   bool legality{};
293 };
294 } // namespace
295 
296 AffineIfAnalysis
297 AffineFunctionAnalysis::getChildIfAnalysis(fir::IfOp op) const {
298   auto it = ifAnalysisMap.find_as(op);
299   if (it == ifAnalysisMap.end()) {
300     LLVM_DEBUG(llvm::dbgs() << "AffineFunctionAnalysis: not computed for:\n";
301                op.dump(););
302     op.emitError("error in fetching if analysis in AffineFunctionAnalysis\n");
303     return {};
304   }
305   return it->getSecond();
306 }
307 
308 /// AffineMap rewriting fir.array_coor operation to affine apply,
309 /// %dim = fir.gendim %lowerBound, %upperBound, %stride
310 /// %a = fir.array_coor %arr(%dim) %i
311 /// returning affineMap = affine_map<(i)[lb, ub, st] -> (i*st - lb)>
312 static mlir::AffineMap createArrayIndexAffineMap(unsigned dimensions,
313                                                  MLIRContext *context) {
314   auto index = mlir::getAffineConstantExpr(0, context);
315   auto accuExtent = mlir::getAffineConstantExpr(1, context);
316   for (unsigned i = 0; i < dimensions; ++i) {
317     mlir::AffineExpr idx = mlir::getAffineDimExpr(i, context),
318                      lowerBound = mlir::getAffineSymbolExpr(i * 3, context),
319                      currentExtent =
320                          mlir::getAffineSymbolExpr(i * 3 + 1, context),
321                      stride = mlir::getAffineSymbolExpr(i * 3 + 2, context),
322                      currentPart = (idx * stride - lowerBound) * accuExtent;
323     index = currentPart + index;
324     accuExtent = accuExtent * currentExtent;
325   }
326   return mlir::AffineMap::get(dimensions, dimensions * 3, index);
327 }
328 
329 static Optional<int64_t> constantIntegerLike(const mlir::Value value) {
330   if (auto definition = value.getDefiningOp<mlir::arith::ConstantOp>())
331     if (auto stepAttr = definition.getValue().dyn_cast<IntegerAttr>())
332       return stepAttr.getInt();
333   return {};
334 }
335 
336 static mlir::Type coordinateArrayElement(fir::ArrayCoorOp op) {
337   if (auto refType =
338           op.getMemref().getType().dyn_cast_or_null<ReferenceType>()) {
339     if (auto seqType = refType.getEleTy().dyn_cast_or_null<SequenceType>()) {
340       return seqType.getEleTy();
341     }
342   }
343   op.emitError(
344       "AffineLoopConversion: array type in coordinate operation not valid\n");
345   return mlir::Type();
346 }
347 
348 static void populateIndexArgs(fir::ArrayCoorOp acoOp, fir::ShapeOp shape,
349                               SmallVectorImpl<mlir::Value> &indexArgs,
350                               mlir::PatternRewriter &rewriter) {
351   auto one = rewriter.create<mlir::arith::ConstantOp>(
352       acoOp.getLoc(), rewriter.getIndexType(), rewriter.getIndexAttr(1));
353   auto extents = shape.getExtents();
354   for (auto i = extents.begin(); i < extents.end(); i++) {
355     indexArgs.push_back(one);
356     indexArgs.push_back(*i);
357     indexArgs.push_back(one);
358   }
359 }
360 
361 static void populateIndexArgs(fir::ArrayCoorOp acoOp, fir::ShapeShiftOp shape,
362                               SmallVectorImpl<mlir::Value> &indexArgs,
363                               mlir::PatternRewriter &rewriter) {
364   auto one = rewriter.create<mlir::arith::ConstantOp>(
365       acoOp.getLoc(), rewriter.getIndexType(), rewriter.getIndexAttr(1));
366   auto extents = shape.getPairs();
367   for (auto i = extents.begin(); i < extents.end();) {
368     indexArgs.push_back(*i++);
369     indexArgs.push_back(*i++);
370     indexArgs.push_back(one);
371   }
372 }
373 
374 static void populateIndexArgs(fir::ArrayCoorOp acoOp, fir::SliceOp slice,
375                               SmallVectorImpl<mlir::Value> &indexArgs,
376                               mlir::PatternRewriter &rewriter) {
377   auto extents = slice.getTriples();
378   for (auto i = extents.begin(); i < extents.end();) {
379     indexArgs.push_back(*i++);
380     indexArgs.push_back(*i++);
381     indexArgs.push_back(*i++);
382   }
383 }
384 
385 static void populateIndexArgs(fir::ArrayCoorOp acoOp,
386                               SmallVectorImpl<mlir::Value> &indexArgs,
387                               mlir::PatternRewriter &rewriter) {
388   if (auto shape = acoOp.getShape().getDefiningOp<ShapeOp>())
389     return populateIndexArgs(acoOp, shape, indexArgs, rewriter);
390   if (auto shapeShift = acoOp.getShape().getDefiningOp<ShapeShiftOp>())
391     return populateIndexArgs(acoOp, shapeShift, indexArgs, rewriter);
392   if (auto slice = acoOp.getShape().getDefiningOp<SliceOp>())
393     return populateIndexArgs(acoOp, slice, indexArgs, rewriter);
394   return;
395 }
396 
397 /// Returns affine.apply and fir.convert from array_coor and gendims
398 static std::pair<mlir::AffineApplyOp, fir::ConvertOp>
399 createAffineOps(mlir::Value arrayRef, mlir::PatternRewriter &rewriter) {
400   auto acoOp = arrayRef.getDefiningOp<ArrayCoorOp>();
401   auto affineMap =
402       createArrayIndexAffineMap(acoOp.getIndices().size(), acoOp.getContext());
403   SmallVector<mlir::Value> indexArgs;
404   indexArgs.append(acoOp.getIndices().begin(), acoOp.getIndices().end());
405 
406   populateIndexArgs(acoOp, indexArgs, rewriter);
407 
408   auto affineApply = rewriter.create<mlir::AffineApplyOp>(acoOp.getLoc(),
409                                                           affineMap, indexArgs);
410   auto arrayElementType = coordinateArrayElement(acoOp);
411   auto newType = mlir::MemRefType::get({-1}, arrayElementType);
412   auto arrayConvert = rewriter.create<fir::ConvertOp>(acoOp.getLoc(), newType,
413                                                       acoOp.getMemref());
414   return std::make_pair(affineApply, arrayConvert);
415 }
416 
417 static void rewriteLoad(fir::LoadOp loadOp, mlir::PatternRewriter &rewriter) {
418   rewriter.setInsertionPoint(loadOp);
419   auto affineOps = createAffineOps(loadOp.getMemref(), rewriter);
420   rewriter.replaceOpWithNewOp<mlir::AffineLoadOp>(
421       loadOp, affineOps.second.getResult(), affineOps.first.getResult());
422 }
423 
424 static void rewriteStore(fir::StoreOp storeOp,
425                          mlir::PatternRewriter &rewriter) {
426   rewriter.setInsertionPoint(storeOp);
427   auto affineOps = createAffineOps(storeOp.getMemref(), rewriter);
428   rewriter.replaceOpWithNewOp<mlir::AffineStoreOp>(storeOp, storeOp.getValue(),
429                                                    affineOps.second.getResult(),
430                                                    affineOps.first.getResult());
431 }
432 
433 static void rewriteMemoryOps(Block *block, mlir::PatternRewriter &rewriter) {
434   for (auto &bodyOp : block->getOperations()) {
435     if (isa<fir::LoadOp>(bodyOp))
436       rewriteLoad(cast<fir::LoadOp>(bodyOp), rewriter);
437     if (isa<fir::StoreOp>(bodyOp))
438       rewriteStore(cast<fir::StoreOp>(bodyOp), rewriter);
439   }
440 }
441 
442 namespace {
443 /// Convert `fir.do_loop` to `affine.for`, creates fir.convert for arrays to
444 /// memref, rewrites array_coor to affine.apply with affine_map. Rewrites fir
445 /// loads and stores to affine.
446 class AffineLoopConversion : public mlir::OpRewritePattern<fir::DoLoopOp> {
447 public:
448   using OpRewritePattern::OpRewritePattern;
449   AffineLoopConversion(mlir::MLIRContext *context, AffineFunctionAnalysis &afa)
450       : OpRewritePattern(context), functionAnalysis(afa) {}
451 
452   mlir::LogicalResult
453   matchAndRewrite(fir::DoLoopOp loop,
454                   mlir::PatternRewriter &rewriter) const override {
455     LLVM_DEBUG(llvm::dbgs() << "AffineLoopConversion: rewriting loop:\n";
456                loop.dump(););
457     LLVM_ATTRIBUTE_UNUSED auto loopAnalysis =
458         functionAnalysis.getChildLoopAnalysis(loop);
459     auto &loopOps = loop.getBody()->getOperations();
460     auto loopAndIndex = createAffineFor(loop, rewriter);
461     auto affineFor = loopAndIndex.first;
462     auto inductionVar = loopAndIndex.second;
463 
464     rewriter.startRootUpdate(affineFor.getOperation());
465     affineFor.getBody()->getOperations().splice(
466         std::prev(affineFor.getBody()->end()), loopOps, loopOps.begin(),
467         std::prev(loopOps.end()));
468     rewriter.finalizeRootUpdate(affineFor.getOperation());
469 
470     rewriter.startRootUpdate(loop.getOperation());
471     loop.getInductionVar().replaceAllUsesWith(inductionVar);
472     rewriter.finalizeRootUpdate(loop.getOperation());
473 
474     rewriteMemoryOps(affineFor.getBody(), rewriter);
475 
476     LLVM_DEBUG(llvm::dbgs() << "AffineLoopConversion: loop rewriten to:\n";
477                affineFor.dump(););
478     rewriter.replaceOp(loop, affineFor.getOperation()->getResults());
479     return success();
480   }
481 
482 private:
483   std::pair<mlir::AffineForOp, mlir::Value>
484   createAffineFor(fir::DoLoopOp op, mlir::PatternRewriter &rewriter) const {
485     if (auto constantStep = constantIntegerLike(op.getStep()))
486       if (constantStep.getValue() > 0)
487         return positiveConstantStep(op, constantStep.getValue(), rewriter);
488     return genericBounds(op, rewriter);
489   }
490 
491   // when step for the loop is positive compile time constant
492   std::pair<mlir::AffineForOp, mlir::Value>
493   positiveConstantStep(fir::DoLoopOp op, int64_t step,
494                        mlir::PatternRewriter &rewriter) const {
495     auto affineFor = rewriter.create<mlir::AffineForOp>(
496         op.getLoc(), ValueRange(op.getLowerBound()),
497         mlir::AffineMap::get(0, 1,
498                              mlir::getAffineSymbolExpr(0, op.getContext())),
499         ValueRange(op.getUpperBound()),
500         mlir::AffineMap::get(0, 1,
501                              1 + mlir::getAffineSymbolExpr(0, op.getContext())),
502         step);
503     return std::make_pair(affineFor, affineFor.getInductionVar());
504   }
505 
506   std::pair<mlir::AffineForOp, mlir::Value>
507   genericBounds(fir::DoLoopOp op, mlir::PatternRewriter &rewriter) const {
508     auto lowerBound = mlir::getAffineSymbolExpr(0, op.getContext());
509     auto upperBound = mlir::getAffineSymbolExpr(1, op.getContext());
510     auto step = mlir::getAffineSymbolExpr(2, op.getContext());
511     mlir::AffineMap upperBoundMap = mlir::AffineMap::get(
512         0, 3, (upperBound - lowerBound + step).floorDiv(step));
513     auto genericUpperBound = rewriter.create<mlir::AffineApplyOp>(
514         op.getLoc(), upperBoundMap,
515         ValueRange({op.getLowerBound(), op.getUpperBound(), op.getStep()}));
516     auto actualIndexMap = mlir::AffineMap::get(
517         1, 2,
518         (lowerBound + mlir::getAffineDimExpr(0, op.getContext())) *
519             mlir::getAffineSymbolExpr(1, op.getContext()));
520 
521     auto affineFor = rewriter.create<mlir::AffineForOp>(
522         op.getLoc(), ValueRange(),
523         AffineMap::getConstantMap(0, op.getContext()),
524         genericUpperBound.getResult(),
525         mlir::AffineMap::get(0, 1,
526                              1 + mlir::getAffineSymbolExpr(0, op.getContext())),
527         1);
528     rewriter.setInsertionPointToStart(affineFor.getBody());
529     auto actualIndex = rewriter.create<mlir::AffineApplyOp>(
530         op.getLoc(), actualIndexMap,
531         ValueRange(
532             {affineFor.getInductionVar(), op.getLowerBound(), op.getStep()}));
533     return std::make_pair(affineFor, actualIndex.getResult());
534   }
535 
536   AffineFunctionAnalysis &functionAnalysis;
537 };
538 
539 /// Convert `fir.if` to `affine.if`.
540 class AffineIfConversion : public mlir::OpRewritePattern<fir::IfOp> {
541 public:
542   using OpRewritePattern::OpRewritePattern;
543   AffineIfConversion(mlir::MLIRContext *context, AffineFunctionAnalysis &afa)
544       : OpRewritePattern(context) {}
545   mlir::LogicalResult
546   matchAndRewrite(fir::IfOp op,
547                   mlir::PatternRewriter &rewriter) const override {
548     LLVM_DEBUG(llvm::dbgs() << "AffineIfConversion: rewriting if:\n";
549                op.dump(););
550     auto &ifOps = op.getThenRegion().front().getOperations();
551     auto affineCondition = AffineIfCondition(op.getCondition());
552     if (!affineCondition.hasIntegerSet()) {
553       LLVM_DEBUG(
554           llvm::dbgs()
555               << "AffineIfConversion: couldn't calculate affine condition\n";);
556       return failure();
557     }
558     auto affineIf = rewriter.create<mlir::AffineIfOp>(
559         op.getLoc(), affineCondition.getIntegerSet(),
560         affineCondition.getAffineArgs(), !op.getElseRegion().empty());
561     rewriter.startRootUpdate(affineIf);
562     affineIf.getThenBlock()->getOperations().splice(
563         std::prev(affineIf.getThenBlock()->end()), ifOps, ifOps.begin(),
564         std::prev(ifOps.end()));
565     if (!op.getElseRegion().empty()) {
566       auto &otherOps = op.getElseRegion().front().getOperations();
567       affineIf.getElseBlock()->getOperations().splice(
568           std::prev(affineIf.getElseBlock()->end()), otherOps, otherOps.begin(),
569           std::prev(otherOps.end()));
570     }
571     rewriter.finalizeRootUpdate(affineIf);
572     rewriteMemoryOps(affineIf.getBody(), rewriter);
573 
574     LLVM_DEBUG(llvm::dbgs() << "AffineIfConversion: if converted to:\n";
575                affineIf.dump(););
576     rewriter.replaceOp(op, affineIf.getOperation()->getResults());
577     return success();
578   }
579 };
580 
581 /// Promote fir.do_loop and fir.if to affine.for and affine.if, in the cases
582 /// where such a promotion is possible.
583 class AffineDialectPromotion
584     : public AffineDialectPromotionBase<AffineDialectPromotion> {
585 public:
586   void runOnOperation() override {
587 
588     auto *context = &getContext();
589     auto function = getOperation();
590     markAllAnalysesPreserved();
591     auto functionAnalysis = AffineFunctionAnalysis(function);
592     mlir::RewritePatternSet patterns(context);
593     patterns.insert<AffineIfConversion>(context, functionAnalysis);
594     patterns.insert<AffineLoopConversion>(context, functionAnalysis);
595     mlir::ConversionTarget target = *context;
596     target.addLegalDialect<
597         mlir::AffineDialect, FIROpsDialect, mlir::scf::SCFDialect,
598         mlir::arith::ArithmeticDialect, mlir::func::FuncDialect>();
599     target.addDynamicallyLegalOp<IfOp>([&functionAnalysis](fir::IfOp op) {
600       return !(functionAnalysis.getChildIfAnalysis(op).canPromoteToAffine());
601     });
602     target.addDynamicallyLegalOp<DoLoopOp>([&functionAnalysis](
603                                                fir::DoLoopOp op) {
604       return !(functionAnalysis.getChildLoopAnalysis(op).canPromoteToAffine());
605     });
606 
607     LLVM_DEBUG(llvm::dbgs()
608                    << "AffineDialectPromotion: running promotion on: \n";
609                function.print(llvm::dbgs()););
610     // apply the patterns
611     if (mlir::failed(mlir::applyPartialConversion(function, target,
612                                                   std::move(patterns)))) {
613       mlir::emitError(mlir::UnknownLoc::get(context),
614                       "error in converting to affine dialect\n");
615       signalPassFailure();
616     }
617   }
618 };
619 } // namespace
620 
621 /// Convert FIR loop constructs to the Affine dialect
622 std::unique_ptr<mlir::Pass> fir::createPromoteToAffinePass() {
623   return std::make_unique<AffineDialectPromotion>();
624 }
625