1 //===- LoopInvariantCodeMotion.cpp - Code to perform loop fusion-----------===//
2 //
3 // Copyright 2019 The MLIR Authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //   http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 // =============================================================================
17 //
18 // This file implements loop invariant code motion.
19 //
20 //===----------------------------------------------------------------------===//
21 
22 #include "mlir/AffineOps/AffineOps.h"
23 #include "mlir/Analysis/AffineAnalysis.h"
24 #include "mlir/Analysis/AffineStructures.h"
25 #include "mlir/Analysis/LoopAnalysis.h"
26 #include "mlir/Analysis/SliceAnalysis.h"
27 #include "mlir/Analysis/Utils.h"
28 #include "mlir/IR/AffineExpr.h"
29 #include "mlir/IR/AffineMap.h"
30 #include "mlir/IR/Builders.h"
31 #include "mlir/Pass/Pass.h"
32 #include "mlir/StandardOps/Ops.h"
33 #include "mlir/Transforms/LoopUtils.h"
34 #include "mlir/Transforms/Passes.h"
35 #include "mlir/Transforms/Utils.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/DenseSet.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
42 
43 #define DEBUG_TYPE "licm"
44 
45 using namespace mlir;
46 
47 namespace {
48 
49 /// Loop invariant code motion (LICM) pass.
50 /// TODO(asabne) : The pass is missing zero-trip tests.
51 /// TODO(asabne) : Check for the presence of side effects before hoisting.
52 struct LoopInvariantCodeMotion : public FunctionPass<LoopInvariantCodeMotion> {
53   void runOnFunction() override;
54   void runOnAffineForOp(AffineForOp forOp);
55 };
56 } // end anonymous namespace
57 
58 static bool
59 checkInvarianceOfNestedIfOps(Operation *op, Value *indVar,
60                              SmallPtrSetImpl<Operation *> &definedOps,
61                              SmallPtrSetImpl<Operation *> &opsToHoist);
62 static bool isOpLoopInvariant(Operation &op, Value *indVar,
63                               SmallPtrSetImpl<Operation *> &definedOps,
64                               SmallPtrSetImpl<Operation *> &opsToHoist);
65 
66 static bool
67 areAllOpsInTheBlockListInvariant(Region &blockList, Value *indVar,
68                                  SmallPtrSetImpl<Operation *> &definedOps,
69                                  SmallPtrSetImpl<Operation *> &opsToHoist);
70 
71 static bool isMemRefDereferencingOp(Operation &op) {
72   // TODO(asabne): Support DMA Ops.
73   if (isa<LoadOp>(op) || isa<StoreOp>(op)) {
74     return true;
75   }
76   return false;
77 }
78 
79 FunctionPassBase *mlir::createLoopInvariantCodeMotionPass() {
80   return new LoopInvariantCodeMotion();
81 }
82 
83 // Returns true if the individual op is loop invariant.
84 bool isOpLoopInvariant(Operation &op, Value *indVar,
85                        SmallPtrSetImpl<Operation *> &definedOps,
86                        SmallPtrSetImpl<Operation *> &opsToHoist) {
87   LLVM_DEBUG(llvm::dbgs() << "iterating on op: " << op;);
88 
89   if (isa<AffineIfOp>(op)) {
90     if (!checkInvarianceOfNestedIfOps(&op, indVar, definedOps, opsToHoist)) {
91       return false;
92     }
93   } else if (isa<AffineForOp>(op)) {
94     // If the body of a predicated region has a for loop, we don't hoist the
95     // 'affine.if'.
96     return false;
97   } else if (isa<DmaStartOp>(op) || isa<DmaWaitOp>(op)) {
98     // TODO(asabne): Support DMA ops.
99     return false;
100   } else if (!isa<ConstantOp>(op)) {
101     if (isMemRefDereferencingOp(op)) {
102       Value *memref = isa<LoadOp>(op) ? cast<LoadOp>(op).getMemRef()
103                                       : cast<StoreOp>(op).getMemRef();
104       for (auto *user : memref->getUsers()) {
105         // If this memref has a user that is a DMA, give up because these
106         // operations write to this memref.
107         if (isa<DmaStartOp>(op) || isa<DmaWaitOp>(op)) {
108           return false;
109         }
110         // If the memref used by the load/store is used in a store elsewhere in
111         // the loop nest, we do not hoist. Similarly, if the memref used in a
112         // load is also being stored too, we do not hoist the load.
113         if (isa<StoreOp>(user) || (isa<LoadOp>(user) && isa<StoreOp>(op))) {
114           if (&op != user) {
115             SmallVector<AffineForOp, 8> userIVs;
116             getLoopIVs(*user, &userIVs);
117             // Check that userIVs don't contain the for loop around the op.
118             if (llvm::is_contained(userIVs, getForInductionVarOwner(indVar))) {
119               return false;
120             }
121           }
122         }
123       }
124     }
125 
126     // Insert this op in the defined ops list.
127     definedOps.insert(&op);
128 
129     if (op.getNumOperands() == 0 && !isa<AffineTerminatorOp>(op)) {
130       LLVM_DEBUG(llvm::dbgs() << "\nNon-constant op with 0 operands\n");
131       return false;
132     }
133     for (unsigned int i = 0; i < op.getNumOperands(); ++i) {
134       auto *operandSrc = op.getOperand(i)->getDefiningOp();
135 
136       LLVM_DEBUG(
137           op.getOperand(i)->print(llvm::dbgs() << "\nIterating on operand\n"));
138 
139       // If the loop IV is the operand, this op isn't loop invariant.
140       if (indVar == op.getOperand(i)) {
141         LLVM_DEBUG(llvm::dbgs() << "\nLoop IV is the operand\n");
142         return false;
143       }
144 
145       if (operandSrc != nullptr) {
146         LLVM_DEBUG(llvm::dbgs()
147                    << *operandSrc << "\nIterating on operand src\n");
148 
149         // If the value was defined in the loop (outside of the
150         // if/else region), and that operation itself wasn't meant to
151         // be hoisted, then mark this operation loop dependent.
152         if (definedOps.count(operandSrc) && opsToHoist.count(operandSrc) == 0) {
153           return false;
154         }
155       }
156     }
157   }
158 
159   // If no operand was loop variant, mark this op for motion.
160   opsToHoist.insert(&op);
161   return true;
162 }
163 
164 // Checks if all ops in a region (i.e. list of blocks) are loop invariant.
165 bool areAllOpsInTheBlockListInvariant(
166     Region &blockList, Value *indVar, SmallPtrSetImpl<Operation *> &definedOps,
167     SmallPtrSetImpl<Operation *> &opsToHoist) {
168 
169   for (auto &b : blockList) {
170     for (auto &op : b) {
171       if (!isOpLoopInvariant(op, indVar, definedOps, opsToHoist)) {
172         return false;
173       }
174     }
175   }
176 
177   return true;
178 }
179 
180 // Returns true if the affine.if op can be hoisted.
181 bool checkInvarianceOfNestedIfOps(Operation *op, Value *indVar,
182                                   SmallPtrSetImpl<Operation *> &definedOps,
183                                   SmallPtrSetImpl<Operation *> &opsToHoist) {
184   assert(isa<AffineIfOp>(op));
185   auto ifOp = cast<AffineIfOp>(op);
186 
187   if (!areAllOpsInTheBlockListInvariant(ifOp.getThenBlocks(), indVar,
188                                         definedOps, opsToHoist)) {
189     return false;
190   }
191 
192   if (!areAllOpsInTheBlockListInvariant(ifOp.getElseBlocks(), indVar,
193                                         definedOps, opsToHoist)) {
194     return false;
195   }
196 
197   return true;
198 }
199 
200 void LoopInvariantCodeMotion::runOnAffineForOp(AffineForOp forOp) {
201   auto *loopBody = forOp.getBody();
202   auto *indVar = forOp.getInductionVar();
203 
204   SmallPtrSet<Operation *, 8> definedOps;
205   // This is the place where hoisted instructions would reside.
206   FuncBuilder b(forOp.getOperation());
207 
208   SmallPtrSet<Operation *, 8> opsToHoist;
209   SmallVector<Operation *, 8> opsToMove;
210 
211   for (auto &op : *loopBody) {
212     // We don't hoist for loops.
213     if (!isa<AffineForOp>(op)) {
214       if (!isa<AffineTerminatorOp>(op)) {
215         if (isOpLoopInvariant(op, indVar, definedOps, opsToHoist)) {
216           opsToMove.push_back(&op);
217         }
218       }
219     }
220   }
221 
222   // For all instructions that we found to be invariant, place sequentially
223   // right before the for loop.
224   for (auto *op : opsToMove) {
225     op->moveBefore(forOp);
226   }
227 
228   LLVM_DEBUG(forOp.getOperation()->print(llvm::dbgs() << "Modified loop\n"));
229 
230   // If the for loop body has a single operation (the terminator), erase it.
231   if (forOp.getBody()->getOperations().size() == 1) {
232     assert(isa<AffineTerminatorOp>(forOp.getBody()->front()));
233     forOp.erase();
234   }
235 }
236 
237 void LoopInvariantCodeMotion::runOnFunction() {
238   // Walk through all loops in a function in innermost-loop-first order.  This
239   // way, we first LICM from the inner loop, and place the ops in
240   // the outer loop, which in turn can be further LICM'ed.
241   getFunction().walk<AffineForOp>([&](AffineForOp op) {
242     LLVM_DEBUG(op.getOperation()->print(llvm::dbgs() << "\nOriginal loop\n"));
243     runOnAffineForOp(op);
244   });
245 }
246 
247 static PassRegistration<LoopInvariantCodeMotion>
248     pass("affine-loop-invariant-code-motion",
249          "Hoist loop invariant instructions outside of the loop");
250