17905da65SAmit Sabne //===- LoopInvariantCodeMotion.cpp - Code to perform loop fusion-----------===//
27905da65SAmit Sabne //
330857107SMehdi Amini // Part of the LLVM 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 
131834ad4aSRiver Riddle #include "PassDetail.h"
147905da65SAmit Sabne #include "mlir/Transforms/Passes.h"
15b843cc5dSStephan Herhut 
16b843cc5dSStephan Herhut #include "mlir/IR/Builders.h"
1765fcddffSRiver Riddle #include "mlir/IR/BuiltinOps.h"
1843959a25SRiver Riddle #include "mlir/Interfaces/LoopLikeInterface.h"
19eb623ae8SStephen Neuendorffer #include "mlir/Interfaces/SideEffectInterfaces.h"
206953cf65SNicolas Vasilache #include "mlir/Transforms/LoopUtils.h"
217a43da60SAmit Sabne #include "llvm/ADT/SmallPtrSet.h"
227905da65SAmit Sabne #include "llvm/Support/CommandLine.h"
237905da65SAmit Sabne #include "llvm/Support/Debug.h"
247905da65SAmit Sabne 
257905da65SAmit Sabne #define DEBUG_TYPE "licm"
267905da65SAmit Sabne 
277905da65SAmit Sabne using namespace mlir;
287905da65SAmit Sabne 
297905da65SAmit Sabne namespace {
307905da65SAmit Sabne /// Loop invariant code motion (LICM) pass.
3180aca1eaSRiver Riddle struct LoopInvariantCodeMotion
321834ad4aSRiver Riddle     : public LoopInvariantCodeMotionBase<LoopInvariantCodeMotion> {
33b843cc5dSStephan Herhut   void runOnOperation() override;
347905da65SAmit Sabne };
35*be0a7e9fSMehdi Amini } // namespace
367905da65SAmit Sabne 
37b843cc5dSStephan Herhut // Checks whether the given op can be hoisted by checking that
38b843cc5dSStephan Herhut // - the op and any of its contained operations do not depend on SSA values
39b843cc5dSStephan Herhut //   defined inside of the loop (by means of calling definedOutside).
40b843cc5dSStephan Herhut // - the op has no side-effects. If sideEffecting is Never, sideeffects of this
41b843cc5dSStephan Herhut //   op and its nested ops are ignored.
4260f914e5SRahul Joshi static bool canBeHoisted(Operation *op,
4360f914e5SRahul Joshi                          function_ref<bool(Value)> definedOutside) {
44b843cc5dSStephan Herhut   // Check that dependencies are defined outside of loop.
45b843cc5dSStephan Herhut   if (!llvm::all_of(op->getOperands(), definedOutside))
46b843cc5dSStephan Herhut     return false;
47b843cc5dSStephan Herhut   // Check whether this op is side-effect free. If we already know that there
48b843cc5dSStephan Herhut   // can be no side-effects because the surrounding op has claimed so, we can
49b843cc5dSStephan Herhut   // (and have to) skip this step.
50b10c6625SRiver Riddle   if (auto memInterface = dyn_cast<MemoryEffectOpInterface>(op)) {
51b10c6625SRiver Riddle     if (!memInterface.hasNoEffect())
52b10c6625SRiver Riddle       return false;
53b10c6625SRiver Riddle     // If the operation doesn't have side effects and it doesn't recursively
54b10c6625SRiver Riddle     // have side effects, it can always be hoisted.
55b10c6625SRiver Riddle     if (!op->hasTrait<OpTrait::HasRecursiveSideEffects>())
56b10c6625SRiver Riddle       return true;
57b10c6625SRiver Riddle 
580ddba0bdSRiver Riddle     // Otherwise, if the operation doesn't provide the memory effect interface
590ddba0bdSRiver Riddle     // and it doesn't have recursive side effects we treat it conservatively as
600ddba0bdSRiver Riddle     // side-effecting.
610ddba0bdSRiver Riddle   } else if (!op->hasTrait<OpTrait::HasRecursiveSideEffects>()) {
620ddba0bdSRiver Riddle     return false;
630ddba0bdSRiver Riddle   }
640ddba0bdSRiver Riddle 
65b843cc5dSStephan Herhut   // Recurse into the regions for this op and check whether the contained ops
66b843cc5dSStephan Herhut   // can be hoisted.
67b843cc5dSStephan Herhut   for (auto &region : op->getRegions()) {
68d1506620SRahul Joshi     for (auto &block : region) {
69b10c6625SRiver Riddle       for (auto &innerOp : block.without_terminator())
70b10c6625SRiver Riddle         if (!canBeHoisted(&innerOp, definedOutside))
717a43da60SAmit Sabne           return false;
727a43da60SAmit Sabne     }
737a43da60SAmit Sabne   }
747a43da60SAmit Sabne   return true;
757a43da60SAmit Sabne }
767a43da60SAmit Sabne 
77e7f7137cSRahul Joshi 
786953cf65SNicolas Vasilache LogicalResult mlir::moveLoopInvariantCode(LoopLikeOpInterface looplike) {
79b843cc5dSStephan Herhut   auto &loopBody = looplike.getLoopBody();
807a43da60SAmit Sabne 
81b843cc5dSStephan Herhut   // We use two collections here as we need to preserve the order for insertion
82b843cc5dSStephan Herhut   // and this is easiest.
83b843cc5dSStephan Herhut   SmallPtrSet<Operation *, 8> willBeMovedSet;
847905da65SAmit Sabne   SmallVector<Operation *, 8> opsToMove;
857905da65SAmit Sabne 
86b843cc5dSStephan Herhut   // Helper to check whether an operation is loop invariant wrt. SSA properties.
87e62a6956SRiver Riddle   auto isDefinedOutsideOfBody = [&](Value value) {
882bdf33ccSRiver Riddle     auto definingOp = value.getDefiningOp();
89b843cc5dSStephan Herhut     return (definingOp && !!willBeMovedSet.count(definingOp)) ||
90b843cc5dSStephan Herhut            looplike.isDefinedOutsideOfLoop(value);
91b843cc5dSStephan Herhut   };
92b843cc5dSStephan Herhut 
93b843cc5dSStephan Herhut   // Do not use walk here, as we do not want to go into nested regions and hoist
94b843cc5dSStephan Herhut   // operations from there. These regions might have semantics unknown to this
95b843cc5dSStephan Herhut   // rewriting. If the nested regions are loops, they will have been processed.
96b843cc5dSStephan Herhut   for (auto &block : loopBody) {
97b843cc5dSStephan Herhut     for (auto &op : block.without_terminator()) {
98b10c6625SRiver Riddle       if (canBeHoisted(&op, isDefinedOutsideOfBody)) {
997905da65SAmit Sabne         opsToMove.push_back(&op);
100b843cc5dSStephan Herhut         willBeMovedSet.insert(&op);
1017905da65SAmit Sabne       }
1027a43da60SAmit Sabne     }
1037a43da60SAmit Sabne   }
1047905da65SAmit Sabne 
105b843cc5dSStephan Herhut   // For all instructions that we found to be invariant, move outside of the
106b843cc5dSStephan Herhut   // loop.
107b843cc5dSStephan Herhut   auto result = looplike.moveOutOfLoop(opsToMove);
108e7f7137cSRahul Joshi   LLVM_DEBUG(looplike.print(llvm::dbgs() << "\n\nModified loop:\n"));
109b843cc5dSStephan Herhut   return result;
1107905da65SAmit Sabne }
1117905da65SAmit Sabne 
112b843cc5dSStephan Herhut void LoopInvariantCodeMotion::runOnOperation() {
1130134b5dfSChris Lattner   // Walk through all loops in a function in innermost-loop-first order. This
1140134b5dfSChris Lattner   // way, we first LICM from the inner loop, and place the ops in
1150134b5dfSChris Lattner   // the outer loop, which in turn can be further LICM'ed.
116b10c6625SRiver Riddle   getOperation()->walk([&](LoopLikeOpInterface loopLike) {
117e7f7137cSRahul Joshi     LLVM_DEBUG(loopLike.print(llvm::dbgs() << "\nOriginal loop:\n"));
118b10c6625SRiver Riddle     if (failed(moveLoopInvariantCode(loopLike)))
119b843cc5dSStephan Herhut       signalPassFailure();
1200134b5dfSChris Lattner   });
1217905da65SAmit Sabne }
1227905da65SAmit Sabne 
123b843cc5dSStephan Herhut std::unique_ptr<Pass> mlir::createLoopInvariantCodeMotionPass() {
124b843cc5dSStephan Herhut   return std::make_unique<LoopInvariantCodeMotion>();
125b843cc5dSStephan Herhut }
126