#include "mlir/IR/SymbolTable.h"
#include <cassert>
#include <mlir/Analysis/DataFlow/LivenessAnalysis.h>
#include <llvm/Support/DebugLog.h>
#include <mlir/Analysis/DataFlow/SparseAnalysis.h>
#include <mlir/Analysis/DataFlow/Utils.h>
#include <mlir/Analysis/DataFlowFramework.h>
#include <mlir/IR/Operation.h>
#include <mlir/IR/Value.h>
#include <mlir/Interfaces/CallInterfaces.h>
#include <mlir/Interfaces/SideEffectInterfaces.h>
#include <mlir/Support/LLVM.h>
#define DEBUG_TYPE "liveness-analysis"
using namespace mlir;
using namespace mlir::dataflow;
void Liveness::print(raw_ostream &os) const {
os << (isLive ? "live" : "not live");
}
ChangeResult Liveness::markLive() {
bool wasLive = isLive;
isLive = true;
return wasLive ? ChangeResult::NoChange : ChangeResult::Change;
}
ChangeResult Liveness::meet(const AbstractSparseLattice &other) {
const auto *otherLiveness = reinterpret_cast<const Liveness *>(&other);
return otherLiveness->isLive ? markLive() : ChangeResult::NoChange;
}
LogicalResult
LivenessAnalysis::visitOperation(Operation *op, ArrayRef<Liveness *> operands,
ArrayRef<const Liveness *> results) {
LDBG() << "[visitOperation] Enter: "
<< OpWithFlags(op, OpPrintingFlags().skipRegions());
if (!isMemoryEffectFree(op) || op->hasTrait<OpTrait::ReturnLike>()) {
LDBG() << "[visitOperation] Operation has memory effects or is "
"return-like, marking operands live";
for (auto *operand : operands) {
LDBG() << " [visitOperation] Marking operand live: " << operand << " ("
<< operand->isLive << ")";
propagateIfChanged(operand, operand->markLive());
}
}
bool foundLiveResult = false;
for (const Liveness *r : results) {
if (r->isLive && !foundLiveResult) {
LDBG() << "[visitOperation] Found live result, "
"meeting all operands with result: "
<< r;
for (Liveness *operand : operands) {
LDBG() << " [visitOperation] Meeting operand: " << operand
<< " with result: " << r;
meet(operand, *r);
}
foundLiveResult = true;
}
LDBG() << "[visitOperation] Adding dependency for result: " << r
<< " after op: " << OpWithFlags(op, OpPrintingFlags().skipRegions());
addDependency(const_cast<Liveness *>(r), getProgramPointAfter(op));
}
return success();
}
void LivenessAnalysis::visitBranchOperand(OpOperand &operand) {
Operation *op = operand.getOwner();
LDBG() << "Visiting branch operand: " << operand.get()
<< " in op: " << OpWithFlags(op, OpPrintingFlags().skipRegions());
assert((isa<RegionBranchOpInterface>(op) || isa<BranchOpInterface>(op) ||
isa<RegionBranchTerminatorOpInterface>(op)) &&
"expected the op to be `RegionBranchOpInterface`, "
"`BranchOpInterface` or `RegionBranchTerminatorOpInterface`");
bool mayLive = false;
SmallVector<Block *, 4> blocks;
SmallVector<BlockArgument> argumentNotOperand;
if (auto regionBranchOp = dyn_cast<RegionBranchOpInterface>(op)) {
if (op->getNumResults() != 0) {
for (auto [resultIndex, result] : llvm::enumerate(op->getResults())) {
if (getLatticeElement(result)->isLive) {
mayLive = true;
LDBG() << "[visitBranchOperand] Non-forwarded branch operand may be "
"live due to live result #"
<< resultIndex << ": "
<< OpWithFlags(op, OpPrintingFlags().skipRegions());
break;
}
}
} else {
for (Region ®ion : op->getRegions()) {
for (Block &block : region)
blocks.push_back(&block);
}
}
for (Region ®ion : op->getRegions()) {
SmallVector<RegionSuccessor> successors;
regionBranchOp.getSuccessorRegions(region, successors);
for (RegionSuccessor successor : successors) {
if (successor.isParent())
continue;
auto arguments = successor.getSuccessor()->getArguments();
ValueRange regionInputs = successor.getSuccessorInputs();
for (auto argument : arguments) {
if (llvm::find(regionInputs, argument) == regionInputs.end()) {
argumentNotOperand.push_back(argument);
}
}
}
}
} else if (isa<BranchOpInterface>(op)) {
mayLive = true;
LDBG() << "[visitBranchOperand] Non-forwarded branch operand may "
"be live due to branch op interface";
} else {
Operation *parentOp = op->getParentOp();
assert(isa<RegionBranchOpInterface>(parentOp) &&
"expected parent op to implement `RegionBranchOpInterface`");
if (parentOp->getNumResults() != 0) {
for (Value result : parentOp->getResults()) {
if (getLatticeElement(result)->isLive) {
mayLive = true;
LDBG() << "[visitBranchOperand] Non-forwarded branch "
"operand may be live due to parent live result: "
<< result;
break;
}
}
} else {
for (Region ®ion : parentOp->getRegions()) {
for (Block &block : region)
blocks.push_back(&block);
}
}
}
for (Block *block : blocks) {
if (mayLive)
break;
for (Operation &nestedOp : *block) {
if (!isMemoryEffectFree(&nestedOp)) {
mayLive = true;
LDBG() << "Non-forwarded branch operand may be "
"live due to memory effect in block: "
<< block;
break;
}
}
}
if (mayLive) {
Liveness *operandLiveness = getLatticeElement(operand.get());
LDBG() << "Marking branch operand live: " << operand.get();
propagateIfChanged(operandLiveness, operandLiveness->markLive());
for (BlockArgument argument : argumentNotOperand) {
Liveness *argumentLiveness = getLatticeElement(argument);
LDBG() << "Marking RegionBranchOp's argument live: " << argument;
propagateIfChanged(argumentLiveness, argumentLiveness->markLive());
}
}
SmallVector<Liveness *, 4> operandLiveness;
operandLiveness.push_back(getLatticeElement(operand.get()));
for (BlockArgument argument : argumentNotOperand)
operandLiveness.push_back(getLatticeElement(argument));
SmallVector<const Liveness *, 4> resultsLiveness;
for (const Value result : op->getResults())
resultsLiveness.push_back(getLatticeElement(result));
LDBG() << "Visiting operation for non-forwarded branch operand: "
<< OpWithFlags(op, OpPrintingFlags().skipRegions());
(void)visitOperation(op, operandLiveness, resultsLiveness);
if (!isa<RegionBranchTerminatorOpInterface>(op))
return;
Operation *parentOp = op->getParentOp();
SmallVector<const Liveness *, 4> parentResultsLiveness;
for (const Value parentResult : parentOp->getResults())
parentResultsLiveness.push_back(getLatticeElement(parentResult));
LDBG() << "Visiting parent operation for non-forwarded branch operand: "
<< *parentOp;
(void)visitOperation(parentOp, operandLiveness, parentResultsLiveness);
}
void LivenessAnalysis::visitCallOperand(OpOperand &operand) {
LDBG() << "Visiting call operand: " << operand.get()
<< " in op: " << *operand.getOwner();
assert(isa<CallOpInterface>(operand.getOwner()) &&
"expected the op to implement `CallOpInterface`");
Liveness *operandLiveness = getLatticeElement(operand.get());
LDBG() << "Marking call operand live: " << operand.get();
propagateIfChanged(operandLiveness, operandLiveness->markLive());
}
void LivenessAnalysis::setToExitState(Liveness *lattice) {
LDBG() << "setToExitState for lattice: " << lattice;
if (lattice->isLive) {
LDBG() << "Lattice already live, nothing to do";
return;
}
LDBG() << "Marking lattice live due to exit state";
(void)lattice->markLive();
propagateIfChanged(lattice, ChangeResult::Change);
}
RunLivenessAnalysis::RunLivenessAnalysis(Operation *op) {
LDBG() << "Constructing RunLivenessAnalysis for op: " << op->getName();
SymbolTableCollection symbolTable;
loadBaselineAnalyses(solver);
solver.load<LivenessAnalysis>(symbolTable);
LDBG() << "Initializing and running solver";
(void)solver.initializeAndRun(op);
LDBG() << "RunLivenessAnalysis initialized for op: " << op->getName()
<< " check on unreachable code now:";
op->walk([&](Operation *op) {
for (auto result : llvm::enumerate(op->getResults())) {
if (getLiveness(result.value()))
continue;
LDBG() << "Result: " << result.index() << " of "
<< OpWithFlags(op, OpPrintingFlags().skipRegions())
<< " has no liveness info (unreachable), mark dead";
solver.getOrCreateState<Liveness>(result.value());
}
for (auto ®ion : op->getRegions()) {
for (auto &block : region) {
for (auto blockArg : llvm::enumerate(block.getArguments())) {
if (getLiveness(blockArg.value()))
continue;
LDBG() << "Block argument: " << blockArg.index() << " of "
<< OpWithFlags(op, OpPrintingFlags().skipRegions())
<< " has no liveness info, mark dead";
solver.getOrCreateState<Liveness>(blockArg.value());
}
}
}
});
}
const Liveness *RunLivenessAnalysis::getLiveness(Value val) {
return solver.lookupState<Liveness>(val);
}