23#include "llvm/ADT/DepthFirstIterator.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/DebugLog.h"
28#define DEBUG_TYPE "licm"
46 for (
OpOperand &operand : child->getOpOperands()) {
48 if (op->
isAncestor(operand.get().getParentRegion()->getParentOp()))
50 if (!condition(operand))
55 return !op->
walk(walkFn).wasInterrupted();
61 op, [&](
OpOperand &operand) {
return definedOutside(operand.
get()); });
71 for (
Region *region : regions) {
72 LDBG() <<
"Original loop:\n"
76 std::queue<Operation *> worklist;
81 auto definedOutside = [&](
Value value) {
82 return isDefinedOutsideRegion(value, region);
85 while (!worklist.empty()) {
92 LDBG() <<
"Checking op: "
94 if (!shouldMoveOutOfRegion(op, region) ||
98 LDBG() <<
"Moving loop-invariant op: "
100 moveOutOfRegion(op, region);
106 if (user->getParentRegion() == region)
116 loopLike.getLoopRegions(),
118 return loopLike.isDefinedOutsideOfLoop(value);
130 LoopLikeOpInterface loopLike,
135 auto definedOutside = [&](
Value value) {
136 return loopLike.isDefinedOutsideOfLoop(value);
140 for (
Block *block : llvm::depth_first(®ion.
front())) {
141 for (
Operation &op : llvm::make_early_inc_range(*block)) {
143 LDBG() <<
"Moving loop-invariant op: "
145 loopLike.moveOutOfLoop(&op);
151 if (!isa<RegionBranchOpInterface>(op) || isa<LoopLikeOpInterface>(op))
163 for (
Region *region : loopLike.getLoopRegions())
170class MatchingSubsets {
173 void insert(SubsetOpInterface op,
bool collectHoistableOps =
true) {
174 allSubsetOps.push_back(op);
175 if (!collectHoistableOps)
177 if (
auto extractionOp =
178 dyn_cast<SubsetExtractionOpInterface>(op.getOperation()))
179 insertExtractionOp(extractionOp);
180 if (
auto insertionOp =
181 dyn_cast<SubsetInsertionOpInterface>(op.getOperation()))
182 insertInsertionOp(insertionOp);
189 auto getHoistableSubsetOps() {
190 return llvm::make_filter_range(
191 llvm::zip(extractions, insertions), [&](
auto pair) {
192 auto [extractionOp, insertionOp] = pair;
194 if (extractionOp && insertionOp &&
195 extractionOp->getResult(0).getType() !=
196 insertionOp.getSourceOperand().get().getType())
199 return allDisjoint(extractionOp, insertionOp);
208 LogicalResult populateSubsetOpsAtIterArg(LoopLikeOpInterface loopLike,
209 BlockArgument iterArg,
210 bool collectHoistableOps =
true);
216 static bool isEquivalent(Value v1, Value v2) {
return true; }
221 bool allDisjoint(SubsetExtractionOpInterface extractionOp,
222 SubsetInsertionOpInterface insertionOp)
const {
223 for (SubsetOpInterface other : allSubsetOps) {
224 if (other == extractionOp || other == insertionOp)
227 !other.operatesOnDisjointSubset(extractionOp, isEquivalent))
230 !other.operatesOnDisjointSubset(insertionOp, isEquivalent))
239 void insertExtractionOp(SubsetExtractionOpInterface extractionOp) {
240 for (
auto it : llvm::enumerate(insertions)) {
243 auto other = cast<SubsetOpInterface>(it.value().getOperation());
244 if (other.operatesOnEquivalentSubset(extractionOp, isEquivalent)) {
245 extractions[it.index()] = extractionOp;
250 extractions.push_back(extractionOp);
251 insertions.push_back({});
257 void insertInsertionOp(SubsetInsertionOpInterface insertionOp) {
258 for (
auto it : llvm::enumerate(extractions)) {
261 auto other = cast<SubsetOpInterface>(it.value().getOperation());
262 if (other.operatesOnEquivalentSubset(insertionOp, isEquivalent)) {
263 insertions[it.index()] = insertionOp;
268 extractions.push_back({});
269 insertions.push_back(insertionOp);
272 SmallVector<SubsetExtractionOpInterface> extractions;
273 SmallVector<SubsetInsertionOpInterface> insertions;
274 SmallVector<SubsetOpInterface> allSubsetOps;
290MatchingSubsets::populateSubsetOpsAtIterArg(LoopLikeOpInterface loopLike,
292 bool collectHoistableOps) {
294 Value value = iterArg;
300 OpOperand *yieldedOperand =
nullptr;
304 Value nextValue = {};
306 for (OpOperand &use : value.
getUses()) {
307 if (
auto nestedLoop = dyn_cast<LoopLikeOpInterface>(use.getOwner())) {
312 auto nestedIterArg = nestedLoop.getTiedLoopRegionIterArg(&use);
318 if (
failed(populateSubsetOpsAtIterArg(nestedLoop, nestedIterArg,
325 nextValue = nestedLoop.getTiedLoopResult(&use);
329 auto subsetOp = dyn_cast<SubsetOpInterface>(use.getOwner());
332 insert(subsetOp, collectHoistableOps);
334 if (
auto insertionOp =
335 dyn_cast<SubsetInsertionOpInterface>(use.getOwner())) {
339 auto dstOp = dyn_cast<DestinationStyleOpInterface>(use.getOwner());
340 if (!dstOp || !dstOp.hasPureTensorSemantics())
345 if (&use != &insertionOp.getDestinationOperand())
351 nextValue = insertionOp.getUpdatedDestination();
365 if (loopLike.getTiedLoopYieldedValue(iterArg) != yieldedOperand)
376 LoopLikeOpInterface loopLike,
379 BlockArgument *it = llvm::find(loopLike.getRegionIterArgs(), iterArg);
380 int64_t iterArgIdx = std::distance(loopLike.getRegionIterArgs().begin(), it);
381 MatchingSubsets subsets;
382 if (failed(subsets.populateSubsetOpsAtIterArg(loopLike, iterArg)))
386 for (
auto it : subsets.getHoistableSubsetOps()) {
387 auto extractionOp = std::get<0>(it);
388 auto insertionOp = std::get<1>(it);
393 return loopLike.isDefinedOutsideOfLoop(operand.
get()) ||
394 &operand == &extractionOp.getSourceOperand();
400 return loopLike.isDefinedOutsideOfLoop(operand.
get()) ||
401 &operand == &insertionOp.getSourceOperand() ||
402 &operand == &insertionOp.getDestinationOperand();
410 if (extractionOp && insertionOp) {
415 return {insertionOp.getSourceOperand().get()};
417 FailureOr<LoopLikeOpInterface> newLoop =
418 loopLike.replaceWithAdditionalYields(
419 rewriter, extractionOp.getResult(),
420 true, newYieldValuesFn);
426 iterArg = loopLike.getRegionIterArgs()[iterArgIdx];
427 OpResult loopResult = loopLike.getTiedLoopResult(iterArg);
428 OpResult newLoopResult = loopLike.getLoopResults()->back();
432 insertionOp.getDestinationOperand().get());
433 extractionOp.getSourceOperand().set(
434 loopLike.getTiedLoopInit(iterArg)->get());
436 insertionOp.getUpdatedDestination());
437 insertionOp.getSourceOperand().set(newLoopResult);
438 insertionOp.getDestinationOperand().set(loopResult);
447 LoopLikeOpInterface loopLike) {
452 i < static_cast<int64_t>(loopLike.getRegionIterArgs().size()); ++i) {
454 loopLike.getRegionIterArgs()[i]);
static OpOperand * getSingleTerminatorUse(Value value)
If the given value has a single use by an op that is a terminator, return that use.
static LoopLikeOpInterface hoistSubsetAtIterArg(RewriterBase &rewriter, LoopLikeOpInterface loopLike, BlockArgument iterArg)
Hoist all subset ops that operate on the idx-th region iter_arg of the given loop-like op and index i...
static size_t hoistFromNestedRegions(Region ®ion, LoopLikeOpInterface loopLike, bool isNested)
Hoists pure loop-invariant ops out of the control-flow regions nested in region, which is part of the...
static bool canBeHoisted(Operation *op, function_ref< bool(OpOperand &)> condition)
Checks whether the given op can be hoisted by checking that.
static bool canBeHoisted(Operation *op, function_ref< bool(Value)> definedOutside)
Helper to know if an op can be hoisted out of the region.
This class represents an argument of a Block.
Block * getOwner() const
Returns the block that owns this argument.
Block represents an ordered list of Operations.
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
IRValueT get() const
Return the current value being used by this operand.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
This class helps build Operations.
This class represents an operand of an operation.
Set of flags used to control the behavior of the various IR print methods (e.g.
This is a value defined by a result of an operation.
This class provides the API for ops that are known to be terminators.
A wrapper class that allows for printing an operation with a set of flags, useful to act as a "stream...
Operation is the basic unit of execution within MLIR.
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
bool isAncestor(Operation *other)
Return true if this operation is an ancestor of the other operation.
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
user_range getUsers()
Returns a range of all users.
Region * getParentRegion()
Returns the region to which the instruction belongs.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
void moveOpBefore(Operation *op, Operation *existingOp)
Unlink this operation from its current block and insert it right before existingOp which may be in th...
void moveOpAfter(Operation *op, Operation *existingOp)
Unlink this operation from its current block and insert it right after existingOp which may be in the...
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
bool hasOneUse() const
Returns true if this value has exactly one use.
static WalkResult advance()
static WalkResult interrupt()
Operation * getOwner() const
Return the owner of this operand.
Include the generated interface declarations.
std::function< SmallVector< Value >( OpBuilder &b, Location loc, ArrayRef< BlockArgument > newBbArgs)> NewYieldValuesFn
A function that returns the additional yielded values during replaceWithAdditionalYields.
LoopLikeOpInterface hoistLoopInvariantSubsets(RewriterBase &rewriter, LoopLikeOpInterface loopLike)
Hoist loop-invariant tensor subsets (subset extraction and subset insertion ops) from loop-like ops.
bool isPure(Operation *op)
Returns true if the given operation is pure, i.e., is speculatable that does not touch memory.
size_t moveLoopInvariantCodeFromNestedRegions(LoopLikeOpInterface loopLike)
Move loop invariant code out of the control-flow regions nested in the body of a loop-like op,...
llvm::function_ref< Fn > function_ref
size_t moveLoopInvariantCode(ArrayRef< Region * > regions, function_ref< bool(Value, Region *)> isDefinedOutsideRegion, function_ref< bool(Operation *, Region *)> shouldMoveOutOfRegion, function_ref< void(Operation *, Region *)> moveOutOfRegion)
Given a list of regions, perform loop-invariant code motion.