MLIR  14.0.0git
AffineLoopInvariantCodeMotion.cpp
Go to the documentation of this file.
1 //===- AffineLoopInvariantCodeMotion.cpp - Code to perform loop fusion-----===//
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 file implements loop invariant code motion.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PassDetail.h"
22 #include "mlir/IR/AffineExpr.h"
23 #include "mlir/IR/AffineMap.h"
24 #include "mlir/IR/Builders.h"
26 #include "mlir/Transforms/Utils.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/DenseSet.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 
34 #define DEBUG_TYPE "licm"
35 
36 using namespace mlir;
37 
38 namespace {
39 
40 /// Loop invariant code motion (LICM) pass.
41 /// TODO: The pass is missing zero-trip tests.
42 /// TODO: Check for the presence of side effects before hoisting.
43 /// TODO: This code should be removed once the new LICM pass can handle its
44 /// uses.
45 struct LoopInvariantCodeMotion
46  : public AffineLoopInvariantCodeMotionBase<LoopInvariantCodeMotion> {
47  void runOnOperation() override;
48  void runOnAffineForOp(AffineForOp forOp);
49 };
50 } // namespace
51 
52 static bool
54  SmallPtrSetImpl<Operation *> &opsWithUsers,
55  SmallPtrSetImpl<Operation *> &opsToHoist);
56 static bool isOpLoopInvariant(Operation &op, Value indVar, ValueRange iterArgs,
57  SmallPtrSetImpl<Operation *> &opsWithUsers,
58  SmallPtrSetImpl<Operation *> &opsToHoist);
59 
60 static bool
62  ValueRange iterArgs,
63  SmallPtrSetImpl<Operation *> &opsWithUsers,
64  SmallPtrSetImpl<Operation *> &opsToHoist);
65 
66 // Returns true if the individual op is loop invariant.
67 bool isOpLoopInvariant(Operation &op, Value indVar, ValueRange iterArgs,
68  SmallPtrSetImpl<Operation *> &opsWithUsers,
69  SmallPtrSetImpl<Operation *> &opsToHoist) {
70  LLVM_DEBUG(llvm::dbgs() << "iterating on op: " << op;);
71 
72  if (isa<AffineIfOp>(op)) {
73  if (!checkInvarianceOfNestedIfOps(&op, indVar, iterArgs, opsWithUsers,
74  opsToHoist)) {
75  return false;
76  }
77  } else if (auto forOp = dyn_cast<AffineForOp>(op)) {
78  if (!areAllOpsInTheBlockListInvariant(forOp.getLoopBody(), indVar, iterArgs,
79  opsWithUsers, opsToHoist)) {
80  return false;
81  }
82  } else if (isa<AffineDmaStartOp, AffineDmaWaitOp>(op)) {
83  // TODO: Support DMA ops.
84  return false;
85  } else if (!isa<arith::ConstantOp, ConstantOp>(op)) {
86  // Register op in the set of ops that have users.
87  opsWithUsers.insert(&op);
88  if (isa<AffineMapAccessInterface>(op)) {
89  Value memref = isa<AffineReadOpInterface>(op)
90  ? cast<AffineReadOpInterface>(op).getMemRef()
91  : cast<AffineWriteOpInterface>(op).getMemRef();
92  for (auto *user : memref.getUsers()) {
93  // If this memref has a user that is a DMA, give up because these
94  // operations write to this memref.
95  if (isa<AffineDmaStartOp, AffineDmaWaitOp>(op)) {
96  return false;
97  }
98  // If the memref used by the load/store is used in a store elsewhere in
99  // the loop nest, we do not hoist. Similarly, if the memref used in a
100  // load is also being stored too, we do not hoist the load.
101  if (isa<AffineWriteOpInterface>(user) ||
102  (isa<AffineReadOpInterface>(user) &&
103  isa<AffineWriteOpInterface>(op))) {
104  if (&op != user) {
106  getLoopIVs(*user, &userIVs);
107  // Check that userIVs don't contain the for loop around the op.
108  if (llvm::is_contained(userIVs, getForInductionVarOwner(indVar))) {
109  return false;
110  }
111  }
112  }
113  }
114  }
115 
116  if (op.getNumOperands() == 0 && !isa<AffineYieldOp>(op)) {
117  LLVM_DEBUG(llvm::dbgs() << "\nNon-constant op with 0 operands\n");
118  return false;
119  }
120  }
121 
122  // Check operands.
123  for (unsigned int i = 0; i < op.getNumOperands(); ++i) {
124  auto *operandSrc = op.getOperand(i).getDefiningOp();
125 
126  LLVM_DEBUG(
127  op.getOperand(i).print(llvm::dbgs() << "\nIterating on operand\n"));
128 
129  // If the loop IV is the operand, this op isn't loop invariant.
130  if (indVar == op.getOperand(i)) {
131  LLVM_DEBUG(llvm::dbgs() << "\nLoop IV is the operand\n");
132  return false;
133  }
134 
135  // If the one of the iter_args is the operand, this op isn't loop invariant.
136  if (llvm::is_contained(iterArgs, op.getOperand(i))) {
137  LLVM_DEBUG(llvm::dbgs() << "\nOne of the iter_args is the operand\n");
138  return false;
139  }
140 
141  if (operandSrc != nullptr) {
142  LLVM_DEBUG(llvm::dbgs() << *operandSrc << "\nIterating on operand src\n");
143 
144  // If the value was defined in the loop (outside of the
145  // if/else region), and that operation itself wasn't meant to
146  // be hoisted, then mark this operation loop dependent.
147  if (opsWithUsers.count(operandSrc) && opsToHoist.count(operandSrc) == 0) {
148  return false;
149  }
150  }
151  }
152 
153  // If no operand was loop variant, mark this op for motion.
154  opsToHoist.insert(&op);
155  return true;
156 }
157 
158 // Checks if all ops in a region (i.e. list of blocks) are loop invariant.
160  Region &blockList, Value indVar, ValueRange iterArgs,
161  SmallPtrSetImpl<Operation *> &opsWithUsers,
162  SmallPtrSetImpl<Operation *> &opsToHoist) {
163 
164  for (auto &b : blockList) {
165  for (auto &op : b) {
166  if (!isOpLoopInvariant(op, indVar, iterArgs, opsWithUsers, opsToHoist)) {
167  return false;
168  }
169  }
170  }
171 
172  return true;
173 }
174 
175 // Returns true if the affine.if op can be hoisted.
177  ValueRange iterArgs,
178  SmallPtrSetImpl<Operation *> &opsWithUsers,
179  SmallPtrSetImpl<Operation *> &opsToHoist) {
180  assert(isa<AffineIfOp>(op));
181  auto ifOp = cast<AffineIfOp>(op);
182 
183  if (!areAllOpsInTheBlockListInvariant(ifOp.thenRegion(), indVar, iterArgs,
184  opsWithUsers, opsToHoist)) {
185  return false;
186  }
187 
188  if (!areAllOpsInTheBlockListInvariant(ifOp.elseRegion(), indVar, iterArgs,
189  opsWithUsers, opsToHoist)) {
190  return false;
191  }
192 
193  return true;
194 }
195 
196 void LoopInvariantCodeMotion::runOnAffineForOp(AffineForOp forOp) {
197  auto *loopBody = forOp.getBody();
198  auto indVar = forOp.getInductionVar();
199  ValueRange iterArgs = forOp.getRegionIterArgs();
200 
201  // This is the place where hoisted instructions would reside.
202  OpBuilder b(forOp.getOperation());
203 
204  SmallPtrSet<Operation *, 8> opsToHoist;
205  SmallVector<Operation *, 8> opsToMove;
206  SmallPtrSet<Operation *, 8> opsWithUsers;
207 
208  for (auto &op : *loopBody) {
209  // Register op in the set of ops that have users. This set is used
210  // to prevent hoisting ops that depend on these ops that are
211  // not being hoisted.
212  if (!op.use_empty())
213  opsWithUsers.insert(&op);
214  if (!isa<AffineYieldOp>(op)) {
215  if (isOpLoopInvariant(op, indVar, iterArgs, opsWithUsers, opsToHoist)) {
216  opsToMove.push_back(&op);
217  }
218  }
219  }
220 
221  // For all instructions that we found to be invariant, place sequentially
222  // right before the for loop.
223  for (auto *op : opsToMove) {
224  op->moveBefore(forOp);
225  }
226 
227  LLVM_DEBUG(forOp->print(llvm::dbgs() << "Modified loop\n"));
228 }
229 
230 void LoopInvariantCodeMotion::runOnOperation() {
231  // Walk through all loops in a function in innermost-loop-first order. This
232  // way, we first LICM from the inner loop, and place the ops in
233  // the outer loop, which in turn can be further LICM'ed.
234  getOperation().walk([&](AffineForOp op) {
235  LLVM_DEBUG(op->print(llvm::dbgs() << "\nOriginal loop\n"));
236  runOnAffineForOp(op);
237  });
238 }
239 
240 std::unique_ptr<OperationPass<FuncOp>>
242  return std::make_unique<LoopInvariantCodeMotion>();
243 }
void moveBefore(Operation *existingOp)
Unlink this operation from its current block and insert it right before existingOp which may be in th...
Definition: Operation.cpp:440
Include the generated interface declarations.
This class contains a list of basic blocks and a link to the parent operation it is attached to...
Definition: Region.h:26
Operation is a basic unit of execution within MLIR.
Definition: Operation.h:28
static bool checkInvarianceOfNestedIfOps(Operation *op, Value indVar, ValueRange iterArgs, SmallPtrSetImpl< Operation *> &opsWithUsers, SmallPtrSetImpl< Operation *> &opsToHoist)
Value getOperand(unsigned idx)
Definition: Operation.h:219
unsigned getNumOperands()
Definition: Operation.h:215
void getLoopIVs(Operation &op, SmallVectorImpl< AffineForOp > *loops)
Populates &#39;loops&#39; with IVs of the loops surrounding &#39;op&#39; ordered from the outermost &#39;affine...
Definition: Utils.cpp:35
user_range getUsers() const
Definition: Value.h:212
std::unique_ptr< OperationPass< FuncOp > > createAffineLoopInvariantCodeMotionPass()
Creates a loop invariant code motion pass that hoists loop invariant operations out of affine loops...
static bool isOpLoopInvariant(Operation &op, Value indVar, ValueRange iterArgs, SmallPtrSetImpl< Operation *> &opsWithUsers, SmallPtrSetImpl< Operation *> &opsToHoist)
void print(raw_ostream &os)
static bool areAllOpsInTheBlockListInvariant(Region &blockList, Value indVar, ValueRange iterArgs, SmallPtrSetImpl< Operation *> &opsWithUsers, SmallPtrSetImpl< Operation *> &opsToHoist)
bool use_empty()
Returns true if this operation has no uses.
Definition: Operation.h:570
AffineForOp getForInductionVarOwner(Value val)
Returns the loop parent of an induction variable.
Definition: AffineOps.cpp:1844
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:84
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition: Value.cpp:20
This class helps build Operations.
Definition: Builders.h:177
This class provides an abstraction over the different types of ranges over Values.