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" 14 #include "mlir/Analysis/AffineAnalysis.h" 15 #include "mlir/Analysis/AffineStructures.h" 16 #include "mlir/Analysis/LoopAnalysis.h" 17 #include "mlir/Analysis/SliceAnalysis.h" 18 #include "mlir/Analysis/Utils.h" 19 #include "mlir/Dialect/Affine/IR/AffineOps.h" 20 #include "mlir/Dialect/Affine/Passes.h" 21 #include "mlir/IR/AffineExpr.h" 22 #include "mlir/IR/AffineMap.h" 23 #include "mlir/IR/Builders.h" 24 #include "mlir/Transforms/LoopUtils.h" 25 #include "mlir/Transforms/Utils.h" 26 #include "llvm/ADT/DenseMap.h" 27 #include "llvm/ADT/DenseSet.h" 28 #include "llvm/ADT/SmallPtrSet.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/Debug.h" 31 #include "llvm/Support/raw_ostream.h" 32 33 #define DEBUG_TYPE "licm" 34 35 using namespace mlir; 36 37 namespace { 38 39 /// Loop invariant code motion (LICM) pass. 40 /// TODO(asabne) : The pass is missing zero-trip tests. 41 /// TODO(asabne) : Check for the presence of side effects before hoisting. 42 /// TODO: This code should be removed once the new LICM pass can handle its 43 /// uses. 44 struct LoopInvariantCodeMotion 45 : public AffineLoopInvariantCodeMotionBase<LoopInvariantCodeMotion> { 46 void runOnFunction() override; 47 void runOnAffineForOp(AffineForOp forOp); 48 }; 49 } // end anonymous namespace 50 51 static bool 52 checkInvarianceOfNestedIfOps(Operation *op, Value indVar, 53 SmallPtrSetImpl<Operation *> &definedOps, 54 SmallPtrSetImpl<Operation *> &opsToHoist); 55 static bool isOpLoopInvariant(Operation &op, Value indVar, 56 SmallPtrSetImpl<Operation *> &definedOps, 57 SmallPtrSetImpl<Operation *> &opsToHoist); 58 59 static bool 60 areAllOpsInTheBlockListInvariant(Region &blockList, Value indVar, 61 SmallPtrSetImpl<Operation *> &definedOps, 62 SmallPtrSetImpl<Operation *> &opsToHoist); 63 64 static bool isMemRefDereferencingOp(Operation &op) { 65 // TODO(asabne): Support DMA Ops. 66 return isa<AffineLoadOp, AffineStoreOp>(op); 67 } 68 69 // Returns true if the individual op is loop invariant. 70 bool isOpLoopInvariant(Operation &op, Value indVar, 71 SmallPtrSetImpl<Operation *> &definedOps, 72 SmallPtrSetImpl<Operation *> &opsToHoist) { 73 LLVM_DEBUG(llvm::dbgs() << "iterating on op: " << op;); 74 75 if (isa<AffineIfOp>(op)) { 76 if (!checkInvarianceOfNestedIfOps(&op, indVar, definedOps, opsToHoist)) { 77 return false; 78 } 79 } else if (isa<AffineForOp>(op)) { 80 // If the body of a predicated region has a for loop, we don't hoist the 81 // 'affine.if'. 82 return false; 83 } else if (isa<AffineDmaStartOp>(op) || isa<AffineDmaWaitOp>(op)) { 84 // TODO(asabne): Support DMA ops. 85 return false; 86 } else if (!isa<ConstantOp>(op)) { 87 if (isMemRefDereferencingOp(op)) { 88 Value memref = isa<AffineLoadOp>(op) 89 ? cast<AffineLoadOp>(op).getMemRef() 90 : cast<AffineStoreOp>(op).getMemRef(); 91 for (auto *user : memref.getUsers()) { 92 // If this memref has a user that is a DMA, give up because these 93 // operations write to this memref. 94 if (isa<AffineDmaStartOp>(op) || isa<AffineDmaWaitOp>(op)) { 95 return false; 96 } 97 // If the memref used by the load/store is used in a store elsewhere in 98 // the loop nest, we do not hoist. Similarly, if the memref used in a 99 // load is also being stored too, we do not hoist the load. 100 if (isa<AffineStoreOp>(user) || 101 (isa<AffineLoadOp>(user) && isa<AffineStoreOp>(op))) { 102 if (&op != user) { 103 SmallVector<AffineForOp, 8> userIVs; 104 getLoopIVs(*user, &userIVs); 105 // Check that userIVs don't contain the for loop around the op. 106 if (llvm::is_contained(userIVs, getForInductionVarOwner(indVar))) { 107 return false; 108 } 109 } 110 } 111 } 112 } 113 114 // Insert this op in the defined ops list. 115 definedOps.insert(&op); 116 117 if (op.getNumOperands() == 0 && !isa<AffineTerminatorOp>(op)) { 118 LLVM_DEBUG(llvm::dbgs() << "\nNon-constant op with 0 operands\n"); 119 return false; 120 } 121 for (unsigned int i = 0; i < op.getNumOperands(); ++i) { 122 auto *operandSrc = op.getOperand(i).getDefiningOp(); 123 124 LLVM_DEBUG( 125 op.getOperand(i).print(llvm::dbgs() << "\nIterating on operand\n")); 126 127 // If the loop IV is the operand, this op isn't loop invariant. 128 if (indVar == op.getOperand(i)) { 129 LLVM_DEBUG(llvm::dbgs() << "\nLoop IV is the operand\n"); 130 return false; 131 } 132 133 if (operandSrc != nullptr) { 134 LLVM_DEBUG(llvm::dbgs() 135 << *operandSrc << "\nIterating on operand src\n"); 136 137 // If the value was defined in the loop (outside of the 138 // if/else region), and that operation itself wasn't meant to 139 // be hoisted, then mark this operation loop dependent. 140 if (definedOps.count(operandSrc) && opsToHoist.count(operandSrc) == 0) { 141 return false; 142 } 143 } 144 } 145 } 146 147 // If no operand was loop variant, mark this op for motion. 148 opsToHoist.insert(&op); 149 return true; 150 } 151 152 // Checks if all ops in a region (i.e. list of blocks) are loop invariant. 153 bool areAllOpsInTheBlockListInvariant( 154 Region &blockList, Value indVar, SmallPtrSetImpl<Operation *> &definedOps, 155 SmallPtrSetImpl<Operation *> &opsToHoist) { 156 157 for (auto &b : blockList) { 158 for (auto &op : b) { 159 if (!isOpLoopInvariant(op, indVar, definedOps, opsToHoist)) { 160 return false; 161 } 162 } 163 } 164 165 return true; 166 } 167 168 // Returns true if the affine.if op can be hoisted. 169 bool checkInvarianceOfNestedIfOps(Operation *op, Value indVar, 170 SmallPtrSetImpl<Operation *> &definedOps, 171 SmallPtrSetImpl<Operation *> &opsToHoist) { 172 assert(isa<AffineIfOp>(op)); 173 auto ifOp = cast<AffineIfOp>(op); 174 175 if (!areAllOpsInTheBlockListInvariant(ifOp.thenRegion(), indVar, definedOps, 176 opsToHoist)) { 177 return false; 178 } 179 180 if (!areAllOpsInTheBlockListInvariant(ifOp.elseRegion(), indVar, definedOps, 181 opsToHoist)) { 182 return false; 183 } 184 185 return true; 186 } 187 188 void LoopInvariantCodeMotion::runOnAffineForOp(AffineForOp forOp) { 189 auto *loopBody = forOp.getBody(); 190 auto indVar = forOp.getInductionVar(); 191 192 SmallPtrSet<Operation *, 8> definedOps; 193 // This is the place where hoisted instructions would reside. 194 OpBuilder b(forOp.getOperation()); 195 196 SmallPtrSet<Operation *, 8> opsToHoist; 197 SmallVector<Operation *, 8> opsToMove; 198 199 for (auto &op : *loopBody) { 200 // We don't hoist for loops. 201 if (!isa<AffineForOp>(op)) { 202 if (!isa<AffineTerminatorOp>(op)) { 203 if (isOpLoopInvariant(op, indVar, definedOps, opsToHoist)) { 204 opsToMove.push_back(&op); 205 } 206 } 207 } 208 } 209 210 // For all instructions that we found to be invariant, place sequentially 211 // right before the for loop. 212 for (auto *op : opsToMove) { 213 op->moveBefore(forOp); 214 } 215 216 LLVM_DEBUG(forOp.getOperation()->print(llvm::dbgs() << "Modified loop\n")); 217 } 218 219 void LoopInvariantCodeMotion::runOnFunction() { 220 // Walk through all loops in a function in innermost-loop-first order. This 221 // way, we first LICM from the inner loop, and place the ops in 222 // the outer loop, which in turn can be further LICM'ed. 223 getFunction().walk([&](AffineForOp op) { 224 LLVM_DEBUG(op.getOperation()->print(llvm::dbgs() << "\nOriginal loop\n")); 225 runOnAffineForOp(op); 226 }); 227 } 228 229 std::unique_ptr<OperationPass<FuncOp>> 230 mlir::createAffineLoopInvariantCodeMotionPass() { 231 return std::make_unique<LoopInvariantCodeMotion>(); 232 } 233