1572fa964SMogball //===- ControlFlowSinkUtils.cpp - Code to perform control-flow sinking ----===//
2572fa964SMogball //
3572fa964SMogball // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4572fa964SMogball // See https://llvm.org/LICENSE.txt for license information.
5572fa964SMogball // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6572fa964SMogball //
7572fa964SMogball //===----------------------------------------------------------------------===//
8572fa964SMogball //
93628febcSMogball // This file implements utilities for control-flow sinking. Control-flow
10572fa964SMogball // sinking moves operations whose only uses are in conditionally-executed blocks
11572fa964SMogball // into those blocks so that they aren't executed on paths where their results
12572fa964SMogball // are not needed.
13572fa964SMogball //
14572fa964SMogball // Control-flow sinking is not implemented on BranchOpInterface because
15572fa964SMogball // sinking ops into the successors of branch operations may move ops into loops.
16572fa964SMogball // It is idiomatic MLIR to perform optimizations at IR levels that readily
17572fa964SMogball // provide the necessary information.
18572fa964SMogball //
19572fa964SMogball //===----------------------------------------------------------------------===//
20572fa964SMogball
21a70aa7bbSRiver Riddle #include "mlir/Transforms/ControlFlowSinkUtils.h"
22572fa964SMogball #include "mlir/IR/Dominance.h"
23572fa964SMogball #include "mlir/IR/Matchers.h"
24572fa964SMogball #include "mlir/Interfaces/ControlFlowInterfaces.h"
25572fa964SMogball #include <vector>
26572fa964SMogball
27572fa964SMogball #define DEBUG_TYPE "cf-sink"
28572fa964SMogball
29572fa964SMogball using namespace mlir;
30572fa964SMogball
31572fa964SMogball namespace {
32572fa964SMogball /// A helper struct for control-flow sinking.
33572fa964SMogball class Sinker {
34572fa964SMogball public:
35572fa964SMogball /// Create an operation sinker with given dominance info.
Sinker(function_ref<bool (Operation *,Region *)> shouldMoveIntoRegion,function_ref<void (Operation *,Region *)> moveIntoRegion,DominanceInfo & domInfo)36572fa964SMogball Sinker(function_ref<bool(Operation *, Region *)> shouldMoveIntoRegion,
37b73f1d2cSMogball function_ref<void(Operation *, Region *)> moveIntoRegion,
38572fa964SMogball DominanceInfo &domInfo)
39b73f1d2cSMogball : shouldMoveIntoRegion(shouldMoveIntoRegion),
407a80912dSMehdi Amini moveIntoRegion(moveIntoRegion), domInfo(domInfo) {}
41572fa964SMogball
42572fa964SMogball /// Given a list of regions, find operations to sink and sink them. Return the
43572fa964SMogball /// number of operations sunk.
44fa26c7ffSMogball size_t sinkRegions(RegionRange regions);
45572fa964SMogball
46572fa964SMogball private:
47572fa964SMogball /// Given a region and an op which dominates the region, returns true if all
48572fa964SMogball /// users of the given op are dominated by the entry block of the region, and
49572fa964SMogball /// thus the operation can be sunk into the region.
50572fa964SMogball bool allUsersDominatedBy(Operation *op, Region *region);
51572fa964SMogball
52572fa964SMogball /// Given a region and a top-level op (an op whose parent region is the given
53572fa964SMogball /// region), determine whether the defining ops of the op's operands can be
54572fa964SMogball /// sunk into the region.
55572fa964SMogball ///
56572fa964SMogball /// Add moved ops to the work queue.
57572fa964SMogball void tryToSinkPredecessors(Operation *user, Region *region,
58572fa964SMogball std::vector<Operation *> &stack);
59572fa964SMogball
60572fa964SMogball /// Iterate over all the ops in a region and try to sink their predecessors.
61572fa964SMogball /// Recurse on subgraphs using a work queue.
62572fa964SMogball void sinkRegion(Region *region);
63572fa964SMogball
64572fa964SMogball /// The callback to determine whether an op should be moved in to a region.
65572fa964SMogball function_ref<bool(Operation *, Region *)> shouldMoveIntoRegion;
66b73f1d2cSMogball /// The calback to move an operation into the region.
67b73f1d2cSMogball function_ref<void(Operation *, Region *)> moveIntoRegion;
68572fa964SMogball /// Dominance info to determine op user dominance with respect to regions.
69572fa964SMogball DominanceInfo &domInfo;
70572fa964SMogball /// The number of operations sunk.
71671e30a1SMehdi Amini size_t numSunk = 0;
72572fa964SMogball };
73572fa964SMogball } // end anonymous namespace
74572fa964SMogball
allUsersDominatedBy(Operation * op,Region * region)75572fa964SMogball bool Sinker::allUsersDominatedBy(Operation *op, Region *region) {
76572fa964SMogball assert(region->findAncestorOpInRegion(*op) == nullptr &&
77572fa964SMogball "expected op to be defined outside the region");
78572fa964SMogball return llvm::all_of(op->getUsers(), [&](Operation *user) {
79572fa964SMogball // The user is dominated by the region if its containing block is dominated
80572fa964SMogball // by the region's entry block.
81572fa964SMogball return domInfo.dominates(®ion->front(), user->getBlock());
82572fa964SMogball });
83572fa964SMogball }
84572fa964SMogball
tryToSinkPredecessors(Operation * user,Region * region,std::vector<Operation * > & stack)85572fa964SMogball void Sinker::tryToSinkPredecessors(Operation *user, Region *region,
86572fa964SMogball std::vector<Operation *> &stack) {
87572fa964SMogball LLVM_DEBUG(user->print(llvm::dbgs() << "\nContained op:\n"));
88572fa964SMogball for (Value value : user->getOperands()) {
89572fa964SMogball Operation *op = value.getDefiningOp();
90572fa964SMogball // Ignore block arguments and ops that are already inside the region.
91572fa964SMogball if (!op || op->getParentRegion() == region)
92572fa964SMogball continue;
93572fa964SMogball LLVM_DEBUG(op->print(llvm::dbgs() << "\nTry to sink:\n"));
94572fa964SMogball
95572fa964SMogball // If the op's users are all in the region and it can be moved, then do so.
96572fa964SMogball if (allUsersDominatedBy(op, region) && shouldMoveIntoRegion(op, region)) {
97b73f1d2cSMogball moveIntoRegion(op, region);
98572fa964SMogball ++numSunk;
99572fa964SMogball // Add the op to the work queue.
100572fa964SMogball stack.push_back(op);
101572fa964SMogball }
102572fa964SMogball }
103572fa964SMogball }
104572fa964SMogball
sinkRegion(Region * region)105572fa964SMogball void Sinker::sinkRegion(Region *region) {
106572fa964SMogball // Initialize the work queue with all the ops in the region.
107572fa964SMogball std::vector<Operation *> stack;
108572fa964SMogball for (Operation &op : region->getOps())
109572fa964SMogball stack.push_back(&op);
110572fa964SMogball
111572fa964SMogball // Process all the ops depth-first. This ensures that nodes of subgraphs are
112572fa964SMogball // sunk in the correct order.
113572fa964SMogball while (!stack.empty()) {
114572fa964SMogball Operation *op = stack.back();
115572fa964SMogball stack.pop_back();
116572fa964SMogball tryToSinkPredecessors(op, region, stack);
117572fa964SMogball }
118572fa964SMogball }
119572fa964SMogball
sinkRegions(RegionRange regions)120fa26c7ffSMogball size_t Sinker::sinkRegions(RegionRange regions) {
121572fa964SMogball for (Region *region : regions)
122572fa964SMogball if (!region->empty())
123572fa964SMogball sinkRegion(region);
124572fa964SMogball return numSunk;
125572fa964SMogball }
126572fa964SMogball
controlFlowSink(RegionRange regions,DominanceInfo & domInfo,function_ref<bool (Operation *,Region *)> shouldMoveIntoRegion,function_ref<void (Operation *,Region *)> moveIntoRegion)127572fa964SMogball size_t mlir::controlFlowSink(
128fa26c7ffSMogball RegionRange regions, DominanceInfo &domInfo,
129b73f1d2cSMogball function_ref<bool(Operation *, Region *)> shouldMoveIntoRegion,
130b73f1d2cSMogball function_ref<void(Operation *, Region *)> moveIntoRegion) {
131b73f1d2cSMogball return Sinker(shouldMoveIntoRegion, moveIntoRegion, domInfo)
132b73f1d2cSMogball .sinkRegions(regions);
133572fa964SMogball }
134572fa964SMogball
getSinglyExecutedRegionsToSink(RegionBranchOpInterface branch,SmallVectorImpl<Region * > & regions)135572fa964SMogball void mlir::getSinglyExecutedRegionsToSink(RegionBranchOpInterface branch,
136572fa964SMogball SmallVectorImpl<Region *> ®ions) {
137572fa964SMogball // Collect constant operands.
138572fa964SMogball SmallVector<Attribute> operands(branch->getNumOperands(), Attribute());
139*8c258fdaSJakub Kuderski for (auto [idx, operand] : llvm::enumerate(branch->getOperands()))
140*8c258fdaSJakub Kuderski (void)matchPattern(operand, m_Constant(&operands[idx]));
1413628febcSMogball
142572fa964SMogball // Get the invocation bounds.
143572fa964SMogball SmallVector<InvocationBounds> bounds;
144572fa964SMogball branch.getRegionInvocationBounds(operands, bounds);
145572fa964SMogball
146572fa964SMogball // For a simple control-flow sink, only consider regions that are executed at
147572fa964SMogball // most once.
148572fa964SMogball for (auto it : llvm::zip(branch->getRegions(), bounds)) {
149572fa964SMogball const InvocationBounds &bound = std::get<1>(it);
150572fa964SMogball if (bound.getUpperBound() && *bound.getUpperBound() <= 1)
151572fa964SMogball regions.push_back(&std::get<0>(it));
152572fa964SMogball }
153572fa964SMogball }
154