#include "mlir/Transforms/FoldUtils.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/Operation.h"
using namespace mlir;
static Region *
getInsertionRegion(DialectInterfaceCollection<DialectFoldInterface> &interfaces,
Block *insertionBlock) {
while (Region *region = insertionBlock->getParent()) {
auto *parentOp = region->getParentOp();
if (parentOp->mightHaveTrait<OpTrait::IsIsolatedFromAbove>() ||
!parentOp->getBlock())
return region;
auto *interface = interfaces.getInterfaceFor(parentOp);
if (LLVM_UNLIKELY(interface && interface->shouldMaterializeInto(region)))
return region;
insertionBlock = parentOp->getBlock();
}
llvm_unreachable("expected valid insertion region");
}
static Operation *materializeConstant(Dialect *dialect, OpBuilder &builder,
Attribute value, Type type,
Location loc) {
auto insertPt = builder.getInsertionPoint();
(void)insertPt;
if (auto *constOp = dialect->materializeConstant(builder, value, type, loc)) {
assert(insertPt == builder.getInsertionPoint());
assert(matchPattern(constOp, m_Constant()));
return constOp;
}
return nullptr;
}
LogicalResult OperationFolder::tryToFold(
Operation *op, function_ref<void(Operation *)> processGeneratedConstants,
function_ref<void(Operation *)> preReplaceAction, bool *inPlaceUpdate) {
if (inPlaceUpdate)
*inPlaceUpdate = false;
if (isFolderOwnedConstant(op)) {
Block *opBlock = op->getBlock();
if (&opBlock->front() != op && !isFolderOwnedConstant(op->getPrevNode()))
op->moveBefore(&opBlock->front());
return failure();
}
SmallVector<Value, 8> results;
OpBuilder builder(op);
if (failed(tryToFold(builder, op, results, processGeneratedConstants)))
return failure();
if (results.empty()) {
if (inPlaceUpdate)
*inPlaceUpdate = true;
return success();
}
if (preReplaceAction)
preReplaceAction(op);
for (unsigned i = 0, e = results.size(); i != e; ++i)
op->getResult(i).replaceAllUsesWith(results[i]);
op->erase();
return success();
}
bool OperationFolder::insertKnownConstant(Operation *op, Attribute constValue) {
Block *opBlock = op->getBlock();
if (isFolderOwnedConstant(op)) {
if (&opBlock->front() != op && !isFolderOwnedConstant(op->getPrevNode()))
op->moveBefore(&opBlock->front());
return true;
}
if (!constValue) {
matchPattern(op, m_Constant(&constValue));
assert(constValue && "expected `op` to be a constant");
} else {
#ifndef NDEBUG
Attribute expectedValue;
matchPattern(op, m_Constant(&expectedValue));
assert(
expectedValue == constValue &&
"provided constant value was not the expected value of the constant");
#endif
}
Region *insertRegion = getInsertionRegion(interfaces, opBlock);
auto &uniquedConstants = foldScopes[insertRegion];
Operation *&folderConstOp = uniquedConstants[std::make_tuple(
op->getDialect(), constValue, *op->result_type_begin())];
if (folderConstOp) {
op->replaceAllUsesWith(folderConstOp);
op->erase();
return false;
}
Block *insertBlock = &insertRegion->front();
if (opBlock != insertBlock || (&insertBlock->front() != op &&
!isFolderOwnedConstant(op->getPrevNode())))
op->moveBefore(&insertBlock->front());
folderConstOp = op;
referencedDialects[op].push_back(op->getDialect());
return true;
}
void OperationFolder::notifyRemoval(Operation *op) {
auto it = referencedDialects.find(op);
if (it == referencedDialects.end())
return;
Attribute constValue;
matchPattern(op, m_Constant(&constValue));
assert(constValue);
auto &uniquedConstants =
foldScopes[getInsertionRegion(interfaces, op->getBlock())];
auto type = op->getResult(0).getType();
for (auto *dialect : it->second)
uniquedConstants.erase(std::make_tuple(dialect, constValue, type));
referencedDialects.erase(it);
}
void OperationFolder::clear() {
foldScopes.clear();
referencedDialects.clear();
}
Value OperationFolder::getOrCreateConstant(OpBuilder &builder, Dialect *dialect,
Attribute value, Type type,
Location loc) {
OpBuilder::InsertionGuard foldGuard(builder);
auto *insertRegion =
getInsertionRegion(interfaces, builder.getInsertionBlock());
auto &entry = insertRegion->front();
builder.setInsertionPoint(&entry, entry.begin());
auto &uniquedConstants = foldScopes[insertRegion];
Operation *constOp = tryGetOrCreateConstant(uniquedConstants, dialect,
builder, value, type, loc);
return constOp ? constOp->getResult(0) : Value();
}
bool OperationFolder::isFolderOwnedConstant(Operation *op) const {
return referencedDialects.count(op);
}
LogicalResult OperationFolder::tryToFold(
OpBuilder &builder, Operation *op, SmallVectorImpl<Value> &results,
function_ref<void(Operation *)> processGeneratedConstants) {
SmallVector<Attribute, 8> operandConstants;
bool updatedOpOperands = false;
if (op->getNumOperands() >= 2 && op->hasTrait<OpTrait::IsCommutative>()) {
auto isNonConstant = [&](OpOperand &o) {
return !matchPattern(o.get(), m_Constant());
};
auto *firstConstantIt =
llvm::find_if_not(op->getOpOperands(), isNonConstant);
auto *newConstantIt = std::stable_partition(
firstConstantIt, op->getOpOperands().end(), isNonConstant);
updatedOpOperands = firstConstantIt != newConstantIt;
}
operandConstants.assign(op->getNumOperands(), Attribute());
for (unsigned i = 0, e = op->getNumOperands(); i != e; ++i)
matchPattern(op->getOperand(i), m_Constant(&operandConstants[i]));
SmallVector<OpFoldResult, 8> foldResults;
if (failed(op->fold(operandConstants, foldResults)) ||
failed(processFoldResults(builder, op, results, foldResults,
processGeneratedConstants)))
return success(updatedOpOperands);
return success();
}
LogicalResult OperationFolder::processFoldResults(
OpBuilder &builder, Operation *op, SmallVectorImpl<Value> &results,
ArrayRef<OpFoldResult> foldResults,
function_ref<void(Operation *)> processGeneratedConstants) {
if (foldResults.empty())
return success();
assert(foldResults.size() == op->getNumResults());
auto *insertRegion =
getInsertionRegion(interfaces, builder.getInsertionBlock());
auto &entry = insertRegion->front();
OpBuilder::InsertionGuard foldGuard(builder);
builder.setInsertionPoint(&entry, entry.begin());
auto &uniquedConstants = foldScopes[insertRegion];
auto *dialect = op->getDialect();
for (unsigned i = 0, e = op->getNumResults(); i != e; ++i) {
assert(!foldResults[i].isNull() && "expected valid OpFoldResult");
if (auto repl = foldResults[i].dyn_cast<Value>()) {
if (repl.getType() != op->getResult(i).getType()) {
results.clear();
return failure();
}
results.emplace_back(repl);
continue;
}
auto res = op->getResult(i);
Attribute attrRepl = foldResults[i].get<Attribute>();
if (auto *constOp =
tryGetOrCreateConstant(uniquedConstants, dialect, builder, attrRepl,
res.getType(), op->getLoc())) {
Block *opBlock = op->getBlock();
if (opBlock == constOp->getBlock() && &opBlock->front() != constOp)
constOp->moveBefore(&opBlock->front());
results.push_back(constOp->getResult(0));
continue;
}
for (Operation &op : llvm::make_early_inc_range(
llvm::make_range(entry.begin(), builder.getInsertionPoint()))) {
notifyRemoval(&op);
op.erase();
}
results.clear();
return failure();
}
if (processGeneratedConstants) {
for (auto i = entry.begin(), e = builder.getInsertionPoint(); i != e; ++i)
processGeneratedConstants(&*i);
}
return success();
}
Operation *OperationFolder::tryGetOrCreateConstant(
ConstantMap &uniquedConstants, Dialect *dialect, OpBuilder &builder,
Attribute value, Type type, Location loc) {
auto constKey = std::make_tuple(dialect, value, type);
Operation *&constOp = uniquedConstants[constKey];
if (constOp)
return constOp;
if (!(constOp = materializeConstant(dialect, builder, value, type, loc)))
return nullptr;
auto *newDialect = constOp->getDialect();
if (newDialect == dialect) {
referencedDialects[constOp].push_back(dialect);
return constOp;
}
auto newKey = std::make_tuple(newDialect, value, type);
if (auto *existingOp = uniquedConstants.lookup(newKey)) {
constOp->erase();
referencedDialects[existingOp].push_back(dialect);
return constOp = existingOp;
}
referencedDialects[constOp].assign({dialect, newDialect});
auto newIt = uniquedConstants.insert({newKey, constOp});
return newIt.first->second;
}