#include "mlir/Conversion/MathToFuncs/MathToFuncs.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/Math/IR/Math.h"
#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/Dialect/Utils/IndexingUtils.h"
#include "mlir/Dialect/Vector/IR/VectorOps.h"
#include "mlir/Dialect/Vector/Utils/VectorUtils.h"
#include "mlir/IR/ImplicitLocOpBuilder.h"
#include "mlir/IR/TypeUtilities.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/Debug.h"
namespace mlir {
#define GEN_PASS_DEF_CONVERTMATHTOFUNCS
#include "mlir/Conversion/Passes.h.inc"
}
using namespace mlir;
#define DEBUG_TYPE "math-to-funcs"
#define DBGS() (llvm::dbgs() << "[" DEBUG_TYPE "]: ")
namespace {
template <typename Op>
struct VecOpToScalarOp : public OpRewritePattern<Op> {
public:
using OpRewritePattern<Op>::OpRewritePattern;
LogicalResult matchAndRewrite(Op op, PatternRewriter &rewriter) const final;
};
using GetFuncCallbackTy = function_ref<func::FuncOp(Operation *, Type)>;
class IPowIOpLowering : public OpRewritePattern<math::IPowIOp> {
public:
IPowIOpLowering(MLIRContext *context, GetFuncCallbackTy cb)
: OpRewritePattern<math::IPowIOp>(context), getFuncOpCallback(cb) {}
LogicalResult matchAndRewrite(math::IPowIOp op,
PatternRewriter &rewriter) const final;
private:
GetFuncCallbackTy getFuncOpCallback;
};
class FPowIOpLowering : public OpRewritePattern<math::FPowIOp> {
public:
FPowIOpLowering(MLIRContext *context, GetFuncCallbackTy cb)
: OpRewritePattern<math::FPowIOp>(context), getFuncOpCallback(cb) {}
LogicalResult matchAndRewrite(math::FPowIOp op,
PatternRewriter &rewriter) const final;
private:
GetFuncCallbackTy getFuncOpCallback;
};
class CtlzOpLowering : public OpRewritePattern<math::CountLeadingZerosOp> {
public:
CtlzOpLowering(MLIRContext *context, GetFuncCallbackTy cb)
: OpRewritePattern<math::CountLeadingZerosOp>(context),
getFuncOpCallback(cb) {}
LogicalResult matchAndRewrite(math::CountLeadingZerosOp op,
PatternRewriter &rewriter) const final;
private:
GetFuncCallbackTy getFuncOpCallback;
};
}
template <typename Op>
LogicalResult
VecOpToScalarOp<Op>::matchAndRewrite(Op op, PatternRewriter &rewriter) const {
Type opType = op.getType();
Location loc = op.getLoc();
auto vecType = dyn_cast<VectorType>(opType);
if (!vecType)
return rewriter.notifyMatchFailure(op, "not a vector operation");
if (!vecType.hasRank())
return rewriter.notifyMatchFailure(op, "unknown vector rank");
ArrayRef<int64_t> shape = vecType.getShape();
int64_t numElements = vecType.getNumElements();
Type resultElementType = vecType.getElementType();
Attribute initValueAttr;
if (isa<FloatType>(resultElementType))
initValueAttr = FloatAttr::get(resultElementType, 0.0);
else
initValueAttr = IntegerAttr::get(resultElementType, 0);
Value result = rewriter.create<arith::ConstantOp>(
loc, DenseElementsAttr::get(vecType, initValueAttr));
SmallVector<int64_t> strides = computeStrides(shape);
for (int64_t linearIndex = 0; linearIndex < numElements; ++linearIndex) {
SmallVector<int64_t> positions = delinearize(linearIndex, strides);
SmallVector<Value> operands;
for (Value input : op->getOperands())
operands.push_back(
rewriter.create<vector::ExtractOp>(loc, input, positions));
Value scalarOp =
rewriter.create<Op>(loc, vecType.getElementType(), operands);
result =
rewriter.create<vector::InsertOp>(loc, scalarOp, result, positions);
}
rewriter.replaceOp(op, result);
return success();
}
static FunctionType getElementalFuncTypeForOp(Operation *op) {
SmallVector<Type, 1> resultTys(op->getNumResults());
SmallVector<Type, 2> inputTys(op->getNumOperands());
std::transform(op->result_type_begin(), op->result_type_end(),
resultTys.begin(),
[](Type ty) { return getElementTypeOrSelf(ty); });
std::transform(op->operand_type_begin(), op->operand_type_end(),
inputTys.begin(),
[](Type ty) { return getElementTypeOrSelf(ty); });
return FunctionType::get(op->getContext(), inputTys, resultTys);
}
static func::FuncOp createElementIPowIFunc(ModuleOp *module, Type elementType) {
assert(isa<IntegerType>(elementType) &&
"non-integer element type for IPowIOp");
ImplicitLocOpBuilder builder =
ImplicitLocOpBuilder::atBlockEnd(module->getLoc(), module->getBody());
std::string funcName("__mlir_math_ipowi");
llvm::raw_string_ostream nameOS(funcName);
nameOS << '_' << elementType;
FunctionType funcType = FunctionType::get(
builder.getContext(), {elementType, elementType}, elementType);
auto funcOp = builder.create<func::FuncOp>(funcName, funcType);
LLVM::linkage::Linkage inlineLinkage = LLVM::linkage::Linkage::LinkonceODR;
Attribute linkage =
LLVM::LinkageAttr::get(builder.getContext(), inlineLinkage);
funcOp->setAttr("llvm.linkage", linkage);
funcOp.setPrivate();
Block *entryBlock = funcOp.addEntryBlock();
Region *funcBody = entryBlock->getParent();
Value bArg = funcOp.getArgument(0);
Value pArg = funcOp.getArgument(1);
builder.setInsertionPointToEnd(entryBlock);
Value zeroValue = builder.create<arith::ConstantOp>(
elementType, builder.getIntegerAttr(elementType, 0));
Value oneValue = builder.create<arith::ConstantOp>(
elementType, builder.getIntegerAttr(elementType, 1));
Value minusOneValue = builder.create<arith::ConstantOp>(
elementType,
builder.getIntegerAttr(elementType,
APInt(elementType.getIntOrFloatBitWidth(), -1ULL,
true)));
auto pIsZero =
builder.create<arith::CmpIOp>(arith::CmpIPredicate::eq, pArg, zeroValue);
Block *thenBlock = builder.createBlock(funcBody);
builder.create<func::ReturnOp>(oneValue);
Block *fallthroughBlock = builder.createBlock(funcBody);
builder.setInsertionPointToEnd(pIsZero->getBlock());
builder.create<cf::CondBranchOp>(pIsZero, thenBlock, fallthroughBlock);
builder.setInsertionPointToEnd(fallthroughBlock);
auto pIsNeg =
builder.create<arith::CmpIOp>(arith::CmpIPredicate::sle, pArg, zeroValue);
builder.createBlock(funcBody);
auto bIsZero =
builder.create<arith::CmpIOp>(arith::CmpIPredicate::eq, bArg, zeroValue);
thenBlock = builder.createBlock(funcBody);
builder.create<func::ReturnOp>(
builder.create<arith::DivSIOp>(oneValue, zeroValue).getResult());
fallthroughBlock = builder.createBlock(funcBody);
builder.setInsertionPointToEnd(bIsZero->getBlock());
builder.create<cf::CondBranchOp>(bIsZero, thenBlock, fallthroughBlock);
builder.setInsertionPointToEnd(fallthroughBlock);
auto bIsOne =
builder.create<arith::CmpIOp>(arith::CmpIPredicate::eq, bArg, oneValue);
thenBlock = builder.createBlock(funcBody);
builder.create<func::ReturnOp>(oneValue);
fallthroughBlock = builder.createBlock(funcBody);
builder.setInsertionPointToEnd(bIsOne->getBlock());
builder.create<cf::CondBranchOp>(bIsOne, thenBlock, fallthroughBlock);
builder.setInsertionPointToEnd(fallthroughBlock);
auto bIsMinusOne = builder.create<arith::CmpIOp>(arith::CmpIPredicate::eq,
bArg, minusOneValue);
builder.createBlock(funcBody);
auto pIsOdd = builder.create<arith::CmpIOp>(
arith::CmpIPredicate::ne, builder.create<arith::AndIOp>(pArg, oneValue),
zeroValue);
thenBlock = builder.createBlock(funcBody);
builder.create<func::ReturnOp>(minusOneValue);
fallthroughBlock = builder.createBlock(funcBody);
builder.setInsertionPointToEnd(pIsOdd->getBlock());
builder.create<cf::CondBranchOp>(pIsOdd, thenBlock, fallthroughBlock);
builder.setInsertionPointToEnd(fallthroughBlock);
builder.create<func::ReturnOp>(oneValue);
fallthroughBlock = builder.createBlock(funcBody);
builder.setInsertionPointToEnd(bIsMinusOne->getBlock());
builder.create<cf::CondBranchOp>(bIsMinusOne, pIsOdd->getBlock(),
fallthroughBlock);
builder.setInsertionPointToEnd(fallthroughBlock);
builder.create<func::ReturnOp>(zeroValue);
Block *loopHeader = builder.createBlock(
funcBody, funcBody->end(), {elementType, elementType, elementType},
{builder.getLoc(), builder.getLoc(), builder.getLoc()});
builder.setInsertionPointToEnd(pIsNeg->getBlock());
builder.create<cf::CondBranchOp>(pIsNeg, bIsZero->getBlock(), loopHeader,
ValueRange{oneValue, bArg, pArg});
Value resultTmp = loopHeader->getArgument(0);
Value baseTmp = loopHeader->getArgument(1);
Value powerTmp = loopHeader->getArgument(2);
builder.setInsertionPointToEnd(loopHeader);
auto powerTmpIsOdd = builder.create<arith::CmpIOp>(
arith::CmpIPredicate::ne,
builder.create<arith::AndIOp>(powerTmp, oneValue), zeroValue);
thenBlock = builder.createBlock(funcBody);
Value newResultTmp = builder.create<arith::MulIOp>(resultTmp, baseTmp);
fallthroughBlock = builder.createBlock(funcBody, funcBody->end(), elementType,
builder.getLoc());
builder.setInsertionPointToEnd(thenBlock);
builder.create<cf::BranchOp>(newResultTmp, fallthroughBlock);
builder.setInsertionPointToEnd(powerTmpIsOdd->getBlock());
builder.create<cf::CondBranchOp>(powerTmpIsOdd, thenBlock, fallthroughBlock,
resultTmp);
newResultTmp = fallthroughBlock->getArgument(0);
builder.setInsertionPointToEnd(fallthroughBlock);
Value newPowerTmp = builder.create<arith::ShRUIOp>(powerTmp, oneValue);
auto newPowerIsZero = builder.create<arith::CmpIOp>(arith::CmpIPredicate::eq,
newPowerTmp, zeroValue);
thenBlock = builder.createBlock(funcBody);
builder.create<func::ReturnOp>(newResultTmp);
fallthroughBlock = builder.createBlock(funcBody);
builder.setInsertionPointToEnd(newPowerIsZero->getBlock());
builder.create<cf::CondBranchOp>(newPowerIsZero, thenBlock, fallthroughBlock);
builder.setInsertionPointToEnd(fallthroughBlock);
Value newBaseTmp = builder.create<arith::MulIOp>(baseTmp, baseTmp);
builder.create<cf::BranchOp>(
ValueRange{newResultTmp, newBaseTmp, newPowerTmp}, loopHeader);
return funcOp;
}
LogicalResult
IPowIOpLowering::matchAndRewrite(math::IPowIOp op,
PatternRewriter &rewriter) const {
auto baseType = dyn_cast<IntegerType>(op.getOperands()[0].getType());
if (!baseType)
return rewriter.notifyMatchFailure(op, "non-integer base operand");
func::FuncOp elementFunc = getFuncOpCallback(op, baseType);
if (!elementFunc)
return rewriter.notifyMatchFailure(op, "missing software implementation");
rewriter.replaceOpWithNewOp<func::CallOp>(op, elementFunc, op.getOperands());
return success();
}
static func::FuncOp createElementFPowIFunc(ModuleOp *module,
FunctionType funcType) {
auto baseType = cast<FloatType>(funcType.getInput(0));
auto powType = cast<IntegerType>(funcType.getInput(1));
ImplicitLocOpBuilder builder =
ImplicitLocOpBuilder::atBlockEnd(module->getLoc(), module->getBody());
std::string funcName("__mlir_math_fpowi");
llvm::raw_string_ostream nameOS(funcName);
nameOS << '_' << baseType;
nameOS << '_' << powType;
auto funcOp = builder.create<func::FuncOp>(funcName, funcType);
LLVM::linkage::Linkage inlineLinkage = LLVM::linkage::Linkage::LinkonceODR;
Attribute linkage =
LLVM::LinkageAttr::get(builder.getContext(), inlineLinkage);
funcOp->setAttr("llvm.linkage", linkage);
funcOp.setPrivate();
Block *entryBlock = funcOp.addEntryBlock();
Region *funcBody = entryBlock->getParent();
Value bArg = funcOp.getArgument(0);
Value pArg = funcOp.getArgument(1);
builder.setInsertionPointToEnd(entryBlock);
Value oneBValue = builder.create<arith::ConstantOp>(
baseType, builder.getFloatAttr(baseType, 1.0));
Value zeroPValue = builder.create<arith::ConstantOp>(
powType, builder.getIntegerAttr(powType, 0));
Value onePValue = builder.create<arith::ConstantOp>(
powType, builder.getIntegerAttr(powType, 1));
Value minPValue = builder.create<arith::ConstantOp>(
powType, builder.getIntegerAttr(powType, llvm::APInt::getSignedMinValue(
powType.getWidth())));
Value maxPValue = builder.create<arith::ConstantOp>(
powType, builder.getIntegerAttr(powType, llvm::APInt::getSignedMaxValue(
powType.getWidth())));
auto pIsZero =
builder.create<arith::CmpIOp>(arith::CmpIPredicate::eq, pArg, zeroPValue);
Block *thenBlock = builder.createBlock(funcBody);
builder.create<func::ReturnOp>(oneBValue);
Block *fallthroughBlock = builder.createBlock(funcBody);
builder.setInsertionPointToEnd(pIsZero->getBlock());
builder.create<cf::CondBranchOp>(pIsZero, thenBlock, fallthroughBlock);
builder.setInsertionPointToEnd(fallthroughBlock);
auto pIsNeg = builder.create<arith::CmpIOp>(arith::CmpIPredicate::sle, pArg,
zeroPValue);
auto pIsMin =
builder.create<arith::CmpIOp>(arith::CmpIPredicate::eq, pArg, minPValue);
Value negP = builder.create<arith::SubIOp>(zeroPValue, pArg);
auto pInit = builder.create<arith::SelectOp>(pIsNeg, negP, pArg);
pInit = builder.create<arith::SelectOp>(pIsMin, maxPValue, pInit);
Block *loopHeader = builder.createBlock(
funcBody, funcBody->end(), {baseType, baseType, powType},
{builder.getLoc(), builder.getLoc(), builder.getLoc()});
builder.setInsertionPointToEnd(pInit->getBlock());
builder.create<cf::BranchOp>(loopHeader, ValueRange{oneBValue, bArg, pInit});
Value resultTmp = loopHeader->getArgument(0);
Value baseTmp = loopHeader->getArgument(1);
Value powerTmp = loopHeader->getArgument(2);
builder.setInsertionPointToEnd(loopHeader);
auto powerTmpIsOdd = builder.create<arith::CmpIOp>(
arith::CmpIPredicate::ne,
builder.create<arith::AndIOp>(powerTmp, onePValue), zeroPValue);
thenBlock = builder.createBlock(funcBody);
Value newResultTmp = builder.create<arith::MulFOp>(resultTmp, baseTmp);
fallthroughBlock = builder.createBlock(funcBody, funcBody->end(), baseType,
builder.getLoc());
builder.setInsertionPointToEnd(thenBlock);
builder.create<cf::BranchOp>(newResultTmp, fallthroughBlock);
builder.setInsertionPointToEnd(powerTmpIsOdd->getBlock());
builder.create<cf::CondBranchOp>(powerTmpIsOdd, thenBlock, fallthroughBlock,
resultTmp);
newResultTmp = fallthroughBlock->getArgument(0);
builder.setInsertionPointToEnd(fallthroughBlock);
Value newPowerTmp = builder.create<arith::ShRUIOp>(powerTmp, onePValue);
auto newPowerIsZero = builder.create<arith::CmpIOp>(arith::CmpIPredicate::eq,
newPowerTmp, zeroPValue);
fallthroughBlock = builder.createBlock(funcBody);
builder.setInsertionPointToEnd(fallthroughBlock);
Value newBaseTmp = builder.create<arith::MulFOp>(baseTmp, baseTmp);
builder.create<cf::BranchOp>(
ValueRange{newResultTmp, newBaseTmp, newPowerTmp}, loopHeader);
Block *loopExit = builder.createBlock(funcBody, funcBody->end(), baseType,
builder.getLoc());
builder.setInsertionPointToEnd(newPowerIsZero->getBlock());
builder.create<cf::CondBranchOp>(newPowerIsZero, loopExit, newResultTmp,
fallthroughBlock, ValueRange{});
newResultTmp = loopExit->getArgument(0);
thenBlock = builder.createBlock(funcBody);
fallthroughBlock = builder.createBlock(funcBody, funcBody->end(), baseType,
builder.getLoc());
builder.setInsertionPointToEnd(loopExit);
builder.create<cf::CondBranchOp>(pIsMin, thenBlock, fallthroughBlock,
newResultTmp);
builder.setInsertionPointToEnd(thenBlock);
newResultTmp = builder.create<arith::MulFOp>(newResultTmp, bArg);
builder.create<cf::BranchOp>(newResultTmp, fallthroughBlock);
newResultTmp = fallthroughBlock->getArgument(0);
thenBlock = builder.createBlock(funcBody);
Block *returnBlock = builder.createBlock(funcBody, funcBody->end(), baseType,
builder.getLoc());
builder.setInsertionPointToEnd(fallthroughBlock);
builder.create<cf::CondBranchOp>(pIsNeg, thenBlock, returnBlock,
newResultTmp);
builder.setInsertionPointToEnd(thenBlock);
newResultTmp = builder.create<arith::DivFOp>(oneBValue, newResultTmp);
builder.create<cf::BranchOp>(newResultTmp, returnBlock);
builder.setInsertionPointToEnd(returnBlock);
builder.create<func::ReturnOp>(returnBlock->getArgument(0));
return funcOp;
}
LogicalResult
FPowIOpLowering::matchAndRewrite(math::FPowIOp op,
PatternRewriter &rewriter) const {
if (dyn_cast<VectorType>(op.getType()))
return rewriter.notifyMatchFailure(op, "non-scalar operation");
FunctionType funcType = getElementalFuncTypeForOp(op);
func::FuncOp elementFunc = getFuncOpCallback(op, funcType);
if (!elementFunc)
return rewriter.notifyMatchFailure(op, "missing software implementation");
rewriter.replaceOpWithNewOp<func::CallOp>(op, elementFunc, op.getOperands());
return success();
}
static func::FuncOp createCtlzFunc(ModuleOp *module, Type elementType) {
if (!isa<IntegerType>(elementType)) {
LLVM_DEBUG({
DBGS() << "non-integer element type for CtlzFunc; type was: ";
elementType.print(llvm::dbgs());
});
llvm_unreachable("non-integer element type");
}
int64_t bitWidth = elementType.getIntOrFloatBitWidth();
Location loc = module->getLoc();
ImplicitLocOpBuilder builder =
ImplicitLocOpBuilder::atBlockEnd(loc, module->getBody());
std::string funcName("__mlir_math_ctlz");
llvm::raw_string_ostream nameOS(funcName);
nameOS << '_' << elementType;
FunctionType funcType =
FunctionType::get(builder.getContext(), {elementType}, elementType);
auto funcOp = builder.create<func::FuncOp>(funcName, funcType);
LLVM::linkage::Linkage inlineLinkage = LLVM::linkage::Linkage::LinkonceODR;
Attribute linkage =
LLVM::LinkageAttr::get(builder.getContext(), inlineLinkage);
funcOp->setAttr("llvm.linkage", linkage);
funcOp.setPrivate();
Block *funcBody = funcOp.addEntryBlock();
builder.setInsertionPointToStart(funcBody);
Value arg = funcOp.getArgument(0);
Type indexType = builder.getIndexType();
Value bitWidthValue = builder.create<arith::ConstantOp>(
elementType, builder.getIntegerAttr(elementType, bitWidth));
Value zeroValue = builder.create<arith::ConstantOp>(
elementType, builder.getIntegerAttr(elementType, 0));
Value inputEqZero =
builder.create<arith::CmpIOp>(arith::CmpIPredicate::eq, arg, zeroValue);
scf::IfOp ifOp = builder.create<scf::IfOp>(
elementType, inputEqZero, true, true);
ifOp.getThenBodyBuilder().create<scf::YieldOp>(loc, bitWidthValue);
auto elseBuilder =
ImplicitLocOpBuilder::atBlockEnd(loc, &ifOp.getElseRegion().front());
Value oneIndex = elseBuilder.create<arith::ConstantOp>(
indexType, elseBuilder.getIndexAttr(1));
Value oneValue = elseBuilder.create<arith::ConstantOp>(
elementType, elseBuilder.getIntegerAttr(elementType, 1));
Value bitWidthIndex = elseBuilder.create<arith::ConstantOp>(
indexType, elseBuilder.getIndexAttr(bitWidth));
Value nValue = elseBuilder.create<arith::ConstantOp>(
elementType, elseBuilder.getIntegerAttr(elementType, 0));
auto loop = elseBuilder.create<scf::ForOp>(
oneIndex, bitWidthIndex, oneIndex,
ValueRange{arg, nValue},
[&](OpBuilder &b, Location loc, Value iv, ValueRange args) {
Value argIter = args[0];
Value nIter = args[1];
Value argIsNonNegative = b.create<arith::CmpIOp>(
loc, arith::CmpIPredicate::slt, argIter, zeroValue);
scf::IfOp ifOp = b.create<scf::IfOp>(
loc, argIsNonNegative,
[&](OpBuilder &b, Location loc) {
b.create<scf::YieldOp>(loc, ValueRange{argIter, nIter});
},
[&](OpBuilder &b, Location loc) {
Value nNext = b.create<arith::AddIOp>(loc, nIter, oneValue);
Value argNext = b.create<arith::ShLIOp>(loc, argIter, oneValue);
b.create<scf::YieldOp>(loc, ValueRange{argNext, nNext});
});
b.create<scf::YieldOp>(loc, ifOp.getResults());
});
elseBuilder.create<scf::YieldOp>(loop.getResult(1));
builder.create<func::ReturnOp>(ifOp.getResult(0));
return funcOp;
}
LogicalResult CtlzOpLowering::matchAndRewrite(math::CountLeadingZerosOp op,
PatternRewriter &rewriter) const {
if (dyn_cast<VectorType>(op.getType()))
return rewriter.notifyMatchFailure(op, "non-scalar operation");
Type type = getElementTypeOrSelf(op.getResult().getType());
func::FuncOp elementFunc = getFuncOpCallback(op, type);
if (!elementFunc)
return rewriter.notifyMatchFailure(op, [&](::mlir::Diagnostic &diag) {
diag << "Missing software implementation for op " << op->getName()
<< " and type " << type;
});
rewriter.replaceOpWithNewOp<func::CallOp>(op, elementFunc, op.getOperand());
return success();
}
namespace {
struct ConvertMathToFuncsPass
: public impl::ConvertMathToFuncsBase<ConvertMathToFuncsPass> {
ConvertMathToFuncsPass() = default;
ConvertMathToFuncsPass(const ConvertMathToFuncsOptions &options)
: impl::ConvertMathToFuncsBase<ConvertMathToFuncsPass>(options) {}
void runOnOperation() override;
private:
bool isFPowIConvertible(math::FPowIOp op);
void generateOpImplementations();
DenseMap<std::pair<OperationName, Type>, func::FuncOp> funcImpls;
};
}
bool ConvertMathToFuncsPass::isFPowIConvertible(math::FPowIOp op) {
auto expTy =
dyn_cast<IntegerType>(getElementTypeOrSelf(op.getRhs().getType()));
return (expTy && expTy.getWidth() >= minWidthOfFPowIExponent);
}
void ConvertMathToFuncsPass::generateOpImplementations() {
ModuleOp module = getOperation();
module.walk([&](Operation *op) {
TypeSwitch<Operation *>(op)
.Case<math::CountLeadingZerosOp>([&](math::CountLeadingZerosOp op) {
if (!convertCtlz)
return;
Type resultType = getElementTypeOrSelf(op.getResult().getType());
auto key = std::pair(op->getName(), resultType);
auto entry = funcImpls.try_emplace(key, func::FuncOp{});
if (entry.second)
entry.first->second = createCtlzFunc(&module, resultType);
})
.Case<math::IPowIOp>([&](math::IPowIOp op) {
Type resultType = getElementTypeOrSelf(op.getResult().getType());
auto key = std::pair(op->getName(), resultType);
auto entry = funcImpls.try_emplace(key, func::FuncOp{});
if (entry.second)
entry.first->second = createElementIPowIFunc(&module, resultType);
})
.Case<math::FPowIOp>([&](math::FPowIOp op) {
if (!isFPowIConvertible(op))
return;
FunctionType funcType = getElementalFuncTypeForOp(op);
auto key = std::pair(op->getName(), funcType);
auto entry = funcImpls.try_emplace(key, func::FuncOp{});
if (entry.second)
entry.first->second = createElementFPowIFunc(&module, funcType);
});
});
}
void ConvertMathToFuncsPass::runOnOperation() {
ModuleOp module = getOperation();
generateOpImplementations();
RewritePatternSet patterns(&getContext());
patterns.add<VecOpToScalarOp<math::IPowIOp>, VecOpToScalarOp<math::FPowIOp>,
VecOpToScalarOp<math::CountLeadingZerosOp>>(
patterns.getContext());
auto getFuncOpByType = [&](Operation *op, Type type) -> func::FuncOp {
auto it = funcImpls.find(std::pair(op->getName(), type));
if (it == funcImpls.end())
return {};
return it->second;
};
patterns.add<IPowIOpLowering, FPowIOpLowering>(patterns.getContext(),
getFuncOpByType);
if (convertCtlz)
patterns.add<CtlzOpLowering>(patterns.getContext(), getFuncOpByType);
ConversionTarget target(getContext());
target.addLegalDialect<arith::ArithDialect, cf::ControlFlowDialect,
func::FuncDialect, scf::SCFDialect,
vector::VectorDialect>();
target.addIllegalOp<math::IPowIOp>();
if (convertCtlz)
target.addIllegalOp<math::CountLeadingZerosOp>();
target.addDynamicallyLegalOp<math::FPowIOp>(
[this](math::FPowIOp op) { return !isFPowIConvertible(op); });
if (failed(applyPartialConversion(module, target, std::move(patterns))))
signalPassFailure();
}