17905da65SAmit Sabne //===- LoopInvariantCodeMotion.cpp - Code to perform loop fusion-----------===//
27905da65SAmit Sabne //
356222a06SMehdi Amini // Part of the MLIR Project, under the Apache License v2.0 with LLVM Exceptions.
456222a06SMehdi Amini // See https://llvm.org/LICENSE.txt for license information.
556222a06SMehdi Amini // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67905da65SAmit Sabne //
756222a06SMehdi Amini //===----------------------------------------------------------------------===//
87905da65SAmit Sabne //
97905da65SAmit Sabne // This file implements loop invariant code motion.
107905da65SAmit Sabne //
117905da65SAmit Sabne //===----------------------------------------------------------------------===//
127905da65SAmit Sabne 
137905da65SAmit Sabne #include "mlir/Transforms/Passes.h"
14b843cc5dSStephan Herhut 
15b843cc5dSStephan Herhut #include "mlir/IR/Builders.h"
16b843cc5dSStephan Herhut #include "mlir/IR/Function.h"
17b843cc5dSStephan Herhut #include "mlir/Pass/Pass.h"
18b843cc5dSStephan Herhut #include "mlir/Transforms/LoopLikeInterface.h"
19b843cc5dSStephan Herhut #include "mlir/Transforms/SideEffectsInterface.h"
207a43da60SAmit Sabne #include "llvm/ADT/SmallPtrSet.h"
217905da65SAmit Sabne #include "llvm/Support/CommandLine.h"
227905da65SAmit Sabne #include "llvm/Support/Debug.h"
237905da65SAmit Sabne 
247905da65SAmit Sabne #define DEBUG_TYPE "licm"
257905da65SAmit Sabne 
267905da65SAmit Sabne using namespace mlir;
277905da65SAmit Sabne 
287905da65SAmit Sabne namespace {
297905da65SAmit Sabne 
30b843cc5dSStephan Herhut using SideEffecting = SideEffectsInterface::SideEffecting;
31b843cc5dSStephan Herhut 
327905da65SAmit Sabne /// Loop invariant code motion (LICM) pass.
33b843cc5dSStephan Herhut struct LoopInvariantCodeMotion : public OperationPass<LoopInvariantCodeMotion> {
34b843cc5dSStephan Herhut public:
35b843cc5dSStephan Herhut   void runOnOperation() override;
367905da65SAmit Sabne };
377905da65SAmit Sabne 
38b843cc5dSStephan Herhut // Checks whether the given op can be hoisted by checking that
39b843cc5dSStephan Herhut // - the op and any of its contained operations do not depend on SSA values
40b843cc5dSStephan Herhut //   defined inside of the loop (by means of calling definedOutside).
41b843cc5dSStephan Herhut // - the op has no side-effects. If sideEffecting is Never, sideeffects of this
42b843cc5dSStephan Herhut //   op and its nested ops are ignored.
43b843cc5dSStephan Herhut static bool canBeHoisted(Operation *op,
44e62a6956SRiver Riddle                          function_ref<bool(Value)> definedOutside,
45b843cc5dSStephan Herhut                          SideEffecting sideEffecting,
46b843cc5dSStephan Herhut                          SideEffectsInterface &interface) {
47b843cc5dSStephan Herhut   // Check that dependencies are defined outside of loop.
48b843cc5dSStephan Herhut   if (!llvm::all_of(op->getOperands(), definedOutside))
49b843cc5dSStephan Herhut     return false;
50b843cc5dSStephan Herhut   // Check whether this op is side-effect free. If we already know that there
51b843cc5dSStephan Herhut   // can be no side-effects because the surrounding op has claimed so, we can
52b843cc5dSStephan Herhut   // (and have to) skip this step.
53b843cc5dSStephan Herhut   auto thisOpIsSideEffecting = sideEffecting;
54b843cc5dSStephan Herhut   if (thisOpIsSideEffecting != SideEffecting::Never) {
55b843cc5dSStephan Herhut     thisOpIsSideEffecting = interface.isSideEffecting(op);
56b843cc5dSStephan Herhut     // If the op always has sideeffects, we cannot hoist.
57b843cc5dSStephan Herhut     if (thisOpIsSideEffecting == SideEffecting::Always)
587a43da60SAmit Sabne       return false;
597a43da60SAmit Sabne   }
60b843cc5dSStephan Herhut   // Recurse into the regions for this op and check whether the contained ops
61b843cc5dSStephan Herhut   // can be hoisted.
62b843cc5dSStephan Herhut   for (auto &region : op->getRegions()) {
63b843cc5dSStephan Herhut     for (auto &block : region.getBlocks()) {
64b843cc5dSStephan Herhut       for (auto &innerOp : block) {
65b843cc5dSStephan Herhut         if (innerOp.isKnownTerminator())
66b843cc5dSStephan Herhut           continue;
67b843cc5dSStephan Herhut         if (!canBeHoisted(&innerOp, definedOutside, thisOpIsSideEffecting,
68b843cc5dSStephan Herhut                           interface))
697a43da60SAmit Sabne           return false;
707a43da60SAmit Sabne       }
717a43da60SAmit Sabne     }
727a43da60SAmit Sabne   }
737a43da60SAmit Sabne   return true;
747a43da60SAmit Sabne }
757a43da60SAmit Sabne 
76b843cc5dSStephan Herhut static LogicalResult moveLoopInvariantCode(LoopLikeOpInterface looplike,
77b843cc5dSStephan Herhut                                            SideEffectsInterface &interface) {
78b843cc5dSStephan Herhut   auto &loopBody = looplike.getLoopBody();
797a43da60SAmit Sabne 
80b843cc5dSStephan Herhut   // We use two collections here as we need to preserve the order for insertion
81b843cc5dSStephan Herhut   // and this is easiest.
82b843cc5dSStephan Herhut   SmallPtrSet<Operation *, 8> willBeMovedSet;
837905da65SAmit Sabne   SmallVector<Operation *, 8> opsToMove;
847905da65SAmit Sabne 
85b843cc5dSStephan Herhut   // Helper to check whether an operation is loop invariant wrt. SSA properties.
86e62a6956SRiver Riddle   auto isDefinedOutsideOfBody = [&](Value value) {
87*2bdf33ccSRiver Riddle     auto definingOp = value.getDefiningOp();
88b843cc5dSStephan Herhut     return (definingOp && !!willBeMovedSet.count(definingOp)) ||
89b843cc5dSStephan Herhut            looplike.isDefinedOutsideOfLoop(value);
90b843cc5dSStephan Herhut   };
91b843cc5dSStephan Herhut 
92b843cc5dSStephan Herhut   // Do not use walk here, as we do not want to go into nested regions and hoist
93b843cc5dSStephan Herhut   // operations from there. These regions might have semantics unknown to this
94b843cc5dSStephan Herhut   // rewriting. If the nested regions are loops, they will have been processed.
95b843cc5dSStephan Herhut   for (auto &block : loopBody) {
96b843cc5dSStephan Herhut     for (auto &op : block.without_terminator()) {
97b843cc5dSStephan Herhut       if (canBeHoisted(&op, isDefinedOutsideOfBody,
98b843cc5dSStephan Herhut                        mlir::SideEffectsDialectInterface::Recursive,
99b843cc5dSStephan Herhut                        interface)) {
1007905da65SAmit Sabne         opsToMove.push_back(&op);
101b843cc5dSStephan Herhut         willBeMovedSet.insert(&op);
1027905da65SAmit Sabne       }
1037a43da60SAmit Sabne     }
1047a43da60SAmit Sabne   }
1057905da65SAmit Sabne 
106b843cc5dSStephan Herhut   // For all instructions that we found to be invariant, move outside of the
107b843cc5dSStephan Herhut   // loop.
108b843cc5dSStephan Herhut   auto result = looplike.moveOutOfLoop(opsToMove);
109b843cc5dSStephan Herhut   LLVM_DEBUG(looplike.print(llvm::dbgs() << "Modified loop\n"));
110b843cc5dSStephan Herhut   return result;
1117905da65SAmit Sabne }
1127905da65SAmit Sabne 
113b843cc5dSStephan Herhut } // end anonymous namespace
1147905da65SAmit Sabne 
115b843cc5dSStephan Herhut void LoopInvariantCodeMotion::runOnOperation() {
116b843cc5dSStephan Herhut   SideEffectsInterface interface(&getContext());
1170134b5dfSChris Lattner   // Walk through all loops in a function in innermost-loop-first order. This
1180134b5dfSChris Lattner   // way, we first LICM from the inner loop, and place the ops in
1190134b5dfSChris Lattner   // the outer loop, which in turn can be further LICM'ed.
120b843cc5dSStephan Herhut   getOperation()->walk([&](Operation *op) {
121b843cc5dSStephan Herhut     if (auto looplike = dyn_cast<LoopLikeOpInterface>(op)) {
122b843cc5dSStephan Herhut       LLVM_DEBUG(op->print(llvm::dbgs() << "\nOriginal loop\n"));
123b843cc5dSStephan Herhut       if (failed(moveLoopInvariantCode(looplike, interface)))
124b843cc5dSStephan Herhut         signalPassFailure();
125b843cc5dSStephan Herhut     }
1260134b5dfSChris Lattner   });
1277905da65SAmit Sabne }
1287905da65SAmit Sabne 
129b843cc5dSStephan Herhut // Include the generated code for the loop-like interface here, as it otherwise
130b843cc5dSStephan Herhut // has no compilation unit. This works as loop-invariant code motion is the
131b843cc5dSStephan Herhut // only user of that interface.
132b843cc5dSStephan Herhut #include "mlir/Transforms/LoopLikeInterface.cpp.inc"
133b843cc5dSStephan Herhut 
134b843cc5dSStephan Herhut std::unique_ptr<Pass> mlir::createLoopInvariantCodeMotionPass() {
135b843cc5dSStephan Herhut   return std::make_unique<LoopInvariantCodeMotion>();
136b843cc5dSStephan Herhut }
137b843cc5dSStephan Herhut 
1387905da65SAmit Sabne static PassRegistration<LoopInvariantCodeMotion>
139b843cc5dSStephan Herhut     pass("loop-invariant-code-motion",
1407905da65SAmit Sabne          "Hoist loop invariant instructions outside of the loop");
141