github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/third_party/mlir/lib/Transforms/LoopInvariantCodeMotion.cpp (about)

     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/Analysis/AffineAnalysis.h"
    23  #include "mlir/Analysis/AffineStructures.h"
    24  #include "mlir/Analysis/LoopAnalysis.h"
    25  #include "mlir/Analysis/SliceAnalysis.h"
    26  #include "mlir/Analysis/Utils.h"
    27  #include "mlir/Dialect/AffineOps/AffineOps.h"
    28  #include "mlir/Dialect/StandardOps/Ops.h"
    29  #include "mlir/IR/AffineExpr.h"
    30  #include "mlir/IR/AffineMap.h"
    31  #include "mlir/IR/Builders.h"
    32  #include "mlir/Pass/Pass.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<AffineLoadOp>(op) || isa<AffineStoreOp>(op)) {
    74      return true;
    75    }
    76    return false;
    77  }
    78  
    79  std::unique_ptr<FunctionPassBase> mlir::createLoopInvariantCodeMotionPass() {
    80    return std::make_unique<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<AffineDmaStartOp>(op) || isa<AffineDmaWaitOp>(op)) {
    98      // TODO(asabne): Support DMA ops.
    99      return false;
   100    } else if (!isa<ConstantOp>(op)) {
   101      if (isMemRefDereferencingOp(op)) {
   102        Value *memref = isa<AffineLoadOp>(op)
   103                            ? cast<AffineLoadOp>(op).getMemRef()
   104                            : cast<AffineStoreOp>(op).getMemRef();
   105        for (auto *user : memref->getUsers()) {
   106          // If this memref has a user that is a DMA, give up because these
   107          // operations write to this memref.
   108          if (isa<AffineDmaStartOp>(op) || isa<AffineDmaWaitOp>(op)) {
   109            return false;
   110          }
   111          // If the memref used by the load/store is used in a store elsewhere in
   112          // the loop nest, we do not hoist. Similarly, if the memref used in a
   113          // load is also being stored too, we do not hoist the load.
   114          if (isa<AffineStoreOp>(user) ||
   115              (isa<AffineLoadOp>(user) && isa<AffineStoreOp>(op))) {
   116            if (&op != user) {
   117              SmallVector<AffineForOp, 8> userIVs;
   118              getLoopIVs(*user, &userIVs);
   119              // Check that userIVs don't contain the for loop around the op.
   120              if (llvm::is_contained(userIVs, getForInductionVarOwner(indVar))) {
   121                return false;
   122              }
   123            }
   124          }
   125        }
   126      }
   127  
   128      // Insert this op in the defined ops list.
   129      definedOps.insert(&op);
   130  
   131      if (op.getNumOperands() == 0 && !isa<AffineTerminatorOp>(op)) {
   132        LLVM_DEBUG(llvm::dbgs() << "\nNon-constant op with 0 operands\n");
   133        return false;
   134      }
   135      for (unsigned int i = 0; i < op.getNumOperands(); ++i) {
   136        auto *operandSrc = op.getOperand(i)->getDefiningOp();
   137  
   138        LLVM_DEBUG(
   139            op.getOperand(i)->print(llvm::dbgs() << "\nIterating on operand\n"));
   140  
   141        // If the loop IV is the operand, this op isn't loop invariant.
   142        if (indVar == op.getOperand(i)) {
   143          LLVM_DEBUG(llvm::dbgs() << "\nLoop IV is the operand\n");
   144          return false;
   145        }
   146  
   147        if (operandSrc != nullptr) {
   148          LLVM_DEBUG(llvm::dbgs()
   149                     << *operandSrc << "\nIterating on operand src\n");
   150  
   151          // If the value was defined in the loop (outside of the
   152          // if/else region), and that operation itself wasn't meant to
   153          // be hoisted, then mark this operation loop dependent.
   154          if (definedOps.count(operandSrc) && opsToHoist.count(operandSrc) == 0) {
   155            return false;
   156          }
   157        }
   158      }
   159    }
   160  
   161    // If no operand was loop variant, mark this op for motion.
   162    opsToHoist.insert(&op);
   163    return true;
   164  }
   165  
   166  // Checks if all ops in a region (i.e. list of blocks) are loop invariant.
   167  bool areAllOpsInTheBlockListInvariant(
   168      Region &blockList, Value *indVar, SmallPtrSetImpl<Operation *> &definedOps,
   169      SmallPtrSetImpl<Operation *> &opsToHoist) {
   170  
   171    for (auto &b : blockList) {
   172      for (auto &op : b) {
   173        if (!isOpLoopInvariant(op, indVar, definedOps, opsToHoist)) {
   174          return false;
   175        }
   176      }
   177    }
   178  
   179    return true;
   180  }
   181  
   182  // Returns true if the affine.if op can be hoisted.
   183  bool checkInvarianceOfNestedIfOps(Operation *op, Value *indVar,
   184                                    SmallPtrSetImpl<Operation *> &definedOps,
   185                                    SmallPtrSetImpl<Operation *> &opsToHoist) {
   186    assert(isa<AffineIfOp>(op));
   187    auto ifOp = cast<AffineIfOp>(op);
   188  
   189    if (!areAllOpsInTheBlockListInvariant(ifOp.thenRegion(), indVar, definedOps,
   190                                          opsToHoist)) {
   191      return false;
   192    }
   193  
   194    if (!areAllOpsInTheBlockListInvariant(ifOp.elseRegion(), indVar, definedOps,
   195                                          opsToHoist)) {
   196      return false;
   197    }
   198  
   199    return true;
   200  }
   201  
   202  void LoopInvariantCodeMotion::runOnAffineForOp(AffineForOp forOp) {
   203    auto *loopBody = forOp.getBody();
   204    auto *indVar = forOp.getInductionVar();
   205  
   206    SmallPtrSet<Operation *, 8> definedOps;
   207    // This is the place where hoisted instructions would reside.
   208    OpBuilder b(forOp.getOperation());
   209  
   210    SmallPtrSet<Operation *, 8> opsToHoist;
   211    SmallVector<Operation *, 8> opsToMove;
   212  
   213    for (auto &op : *loopBody) {
   214      // We don't hoist for loops.
   215      if (!isa<AffineForOp>(op)) {
   216        if (!isa<AffineTerminatorOp>(op)) {
   217          if (isOpLoopInvariant(op, indVar, definedOps, opsToHoist)) {
   218            opsToMove.push_back(&op);
   219          }
   220        }
   221      }
   222    }
   223  
   224    // For all instructions that we found to be invariant, place sequentially
   225    // right before the for loop.
   226    for (auto *op : opsToMove) {
   227      op->moveBefore(forOp);
   228    }
   229  
   230    LLVM_DEBUG(forOp.getOperation()->print(llvm::dbgs() << "Modified loop\n"));
   231  }
   232  
   233  void LoopInvariantCodeMotion::runOnFunction() {
   234    // Walk through all loops in a function in innermost-loop-first order.  This
   235    // way, we first LICM from the inner loop, and place the ops in
   236    // the outer loop, which in turn can be further LICM'ed.
   237    getFunction().walk([&](AffineForOp op) {
   238      LLVM_DEBUG(op.getOperation()->print(llvm::dbgs() << "\nOriginal loop\n"));
   239      runOnAffineForOp(op);
   240    });
   241  }
   242  
   243  static PassRegistration<LoopInvariantCodeMotion>
   244      pass("affine-loop-invariant-code-motion",
   245           "Hoist loop invariant instructions outside of the loop");