#include "mlir/Dialect/GPU/Transforms/Passes.h"
#include "mlir/AsmParser/AsmParser.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
#include "mlir/Dialect/DLTI/DLTI.h"
#include "mlir/Dialect/GPU/IR/GPUDialect.h"
#include "mlir/Dialect/GPU/Utils/GPUUtils.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/IRMapping.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/SymbolTable.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Transforms/RegionUtils.h"
#include <limits>
namespace mlir {
#define GEN_PASS_DEF_GPULAUNCHSINKINDEXCOMPUTATIONSPASS
#define GEN_PASS_DEF_GPUKERNELOUTLININGPASS
#include "mlir/Dialect/GPU/Transforms/Passes.h.inc"
}
using namespace mlir;
template <typename OpTy>
static void createForAllDimensions(OpBuilder &builder, Location loc,
SmallVectorImpl<Value> &values) {
for (auto dim : {gpu::Dimension::x, gpu::Dimension::y, gpu::Dimension::z})
values.push_back(OpTy::create(builder, loc, builder.getIndexType(), dim));
}
static void injectGpuIndexOperations(Location loc, Region &launchFuncOpBody,
Region &launchOpBody, IRMapping &map,
bool hasCluster = false) {
OpBuilder builder(loc->getContext());
Block &firstBlock = launchOpBody.front();
builder.setInsertionPointToStart(&launchFuncOpBody.front());
SmallVector<Value> indexOps;
createForAllDimensions<gpu::BlockIdOp>(builder, loc, indexOps);
createForAllDimensions<gpu::ThreadIdOp>(builder, loc, indexOps);
createForAllDimensions<gpu::GridDimOp>(builder, loc, indexOps);
createForAllDimensions<gpu::BlockDimOp>(builder, loc, indexOps);
if (hasCluster) {
createForAllDimensions<gpu::ClusterIdOp>(builder, loc, indexOps);
createForAllDimensions<gpu::ClusterDimOp>(builder, loc, indexOps);
}
for (const auto &indexOp : enumerate(indexOps))
map.map(firstBlock.getArgument(indexOp.index()), indexOp.value());
}
static bool isLikelyAnIndexComputation(Operation *op) {
return matchPattern(op, m_Constant()) ||
isa<memref::DimOp, arith::SelectOp, arith::CmpIOp>(op);
}
static bool extractBeneficiaryOps(
Operation *op, const SetVector<Value> &existingDependencies,
SetVector<Operation *> &beneficiaryOps,
llvm::SmallPtrSetImpl<Value> &availableValues,
llvm::function_ref<bool(Operation *)> isSinkingBeneficiary) {
if (beneficiaryOps.count(op))
return true;
if (!isSinkingBeneficiary(op))
return false;
for (Value operand : op->getOperands()) {
if (availableValues.count(operand))
continue;
Operation *definingOp = operand.getDefiningOp();
if ((!definingOp || !extractBeneficiaryOps(definingOp, existingDependencies,
beneficiaryOps, availableValues,
isSinkingBeneficiary)) &&
!existingDependencies.count(operand))
return false;
}
beneficiaryOps.insert(op);
for (Value result : op->getResults())
availableValues.insert(result);
return true;
}
LogicalResult mlir::sinkOperationsIntoLaunchOp(
gpu::LaunchOp launchOp,
llvm::function_ref<bool(Operation *)> isSinkingBeneficiary) {
assert(isSinkingBeneficiary);
Region &launchOpBody = launchOp.getBody();
SetVector<Value> sinkCandidates;
getUsedValuesDefinedAbove(launchOpBody, sinkCandidates);
SetVector<Operation *> toBeSunk;
llvm::SmallPtrSet<Value, 4> availableValues;
for (Value operand : sinkCandidates) {
Operation *operandOp = operand.getDefiningOp();
if (!operandOp)
continue;
extractBeneficiaryOps(operandOp, sinkCandidates, toBeSunk, availableValues,
isSinkingBeneficiary);
}
IRMapping map;
OpBuilder builder(launchOpBody);
for (Operation *op : toBeSunk) {
Operation *clonedOp = builder.clone(*op, map);
for (auto pair : llvm::zip(op->getResults(), clonedOp->getResults()))
replaceAllUsesInRegionWith(std::get<0>(pair), std::get<1>(pair),
launchOp.getBody());
}
return success();
}
static DenseI32ArrayAttr maybeConstantDimsAttr(gpu::KernelDim3 dims) {
SmallVector<int32_t, 3> constants;
MLIRContext *ctx = dims.x.getContext();
for (Value v : {dims.x, dims.y, dims.z}) {
APInt constValue;
if (!matchPattern(v, m_ConstantInt(&constValue)))
return nullptr;
if (constValue.ugt(std::numeric_limits<uint32_t>::max()))
return nullptr;
constants.push_back(
constValue.getLimitedValue(std::numeric_limits<uint32_t>::max()));
}
return DenseI32ArrayAttr::get(ctx, constants);
}
static gpu::GPUFuncOp outlineKernelFuncImpl(gpu::LaunchOp launchOp,
StringRef kernelFnName,
SetVector<Value> &operands) {
Location loc = launchOp.getLoc();
OpBuilder builder(launchOp.getContext());
Region &launchOpBody = launchOp.getBody();
getUsedValuesDefinedAbove(launchOpBody, operands);
SmallVector<Type, 4> kernelOperandTypes;
kernelOperandTypes.reserve(operands.size());
for (Value operand : operands) {
kernelOperandTypes.push_back(operand.getType());
}
FunctionType type =
FunctionType::get(launchOp.getContext(), kernelOperandTypes, {});
auto outlinedFunc = gpu::GPUFuncOp::create(
builder, loc, kernelFnName, type,
TypeRange(ValueRange(launchOp.getWorkgroupAttributions())),
TypeRange(ValueRange(launchOp.getPrivateAttributions())));
outlinedFunc->setAttr(gpu::GPUDialect::getKernelFuncAttrName(),
builder.getUnitAttr());
if (auto blockBounds =
maybeConstantDimsAttr(launchOp.getBlockSizeOperandValues()))
outlinedFunc.setKnownBlockSizeAttr(blockBounds);
if (auto gridBounds =
maybeConstantDimsAttr(launchOp.getGridSizeOperandValues()))
outlinedFunc.setKnownGridSizeAttr(gridBounds);
IRMapping map;
Region &outlinedFuncBody = outlinedFunc.getBody();
injectGpuIndexOperations(loc, outlinedFuncBody, launchOpBody, map,
launchOp.hasClusterSize());
for (const auto &[launchArg, funcArg] :
llvm::zip(launchOp.getWorkgroupAttributions(),
outlinedFunc.getWorkgroupAttributions()))
map.map(launchArg, funcArg);
for (const auto &[launchArg, funcArg] :
llvm::zip(launchOp.getPrivateAttributions(),
outlinedFunc.getPrivateAttributions()))
map.map(launchArg, funcArg);
Block &entryBlock = outlinedFuncBody.front();
for (const auto &operand : enumerate(operands))
map.map(operand.value(), entryBlock.getArgument(operand.index()));
launchOpBody.cloneInto(&outlinedFuncBody, map);
for (Block &block : launchOpBody) {
Block *clonedBlock = map.lookup(&block);
auto terminator = dyn_cast<gpu::TerminatorOp>(clonedBlock->getTerminator());
if (!terminator)
continue;
OpBuilder replacer(terminator);
gpu::ReturnOp::create(replacer, terminator->getLoc());
terminator->erase();
}
Block *clonedLaunchOpEntry = map.lookup(&launchOpBody.front());
entryBlock.getOperations().splice(entryBlock.getOperations().end(),
clonedLaunchOpEntry->getOperations());
clonedLaunchOpEntry->erase();
return outlinedFunc;
}
gpu::GPUFuncOp mlir::outlineKernelFunc(gpu::LaunchOp launchOp,
StringRef kernelFnName,
llvm::SmallVectorImpl<Value> &operands) {
DenseSet<Value> inputOperandSet;
inputOperandSet.insert_range(operands);
SetVector<Value> operandSet(llvm::from_range, operands);
auto funcOp = outlineKernelFuncImpl(launchOp, kernelFnName, operandSet);
for (auto operand : operandSet) {
if (!inputOperandSet.count(operand))
operands.push_back(operand);
}
return funcOp;
}
static void convertToLaunchFuncOp(gpu::LaunchOp launchOp,
gpu::GPUFuncOp kernelFunc,
ValueRange operands) {
OpBuilder builder(launchOp);
Value asyncToken = launchOp.getAsyncToken();
std::optional<gpu::KernelDim3> clusterSize =
launchOp.getClusterSizeOperandValues();
auto launchFunc = gpu::LaunchFuncOp::create(
builder, launchOp.getLoc(), kernelFunc,
launchOp.getGridSizeOperandValues(), launchOp.getBlockSizeOperandValues(),
launchOp.getDynamicSharedMemorySize(), operands,
asyncToken ? asyncToken.getType() : nullptr,
launchOp.getAsyncDependencies(), clusterSize);
launchOp.replaceAllUsesWith(launchFunc);
launchOp.erase();
}
namespace {
class GpuLaunchSinkIndexComputationsPass
: public impl::GpuLaunchSinkIndexComputationsPassBase<
GpuLaunchSinkIndexComputationsPass> {
public:
void runOnOperation() override {
Operation *op = getOperation();
if (op->walk([](gpu::LaunchOp launch) {
if (failed(sinkOperationsIntoLaunchOp(launch,
isLikelyAnIndexComputation)))
return WalkResult::interrupt();
return WalkResult::advance();
}).wasInterrupted())
signalPassFailure();
}
};
class GpuKernelOutliningPass
: public impl::GpuKernelOutliningPassBase<GpuKernelOutliningPass> {
public:
using Base::Base;
LogicalResult initialize(MLIRContext *context) override {
if (!dataLayoutStr.empty()) {
Attribute resultAttr = mlir::parseAttribute(dataLayoutStr, context);
if (!resultAttr)
return failure();
dataLayoutSpec = dyn_cast<DataLayoutSpecInterface>(resultAttr);
if (!dataLayoutSpec)
return failure();
}
return success();
}
void runOnOperation() override {
SymbolTable symbolTable(getOperation());
bool modified = false;
for (auto func : getOperation().getOps<SymbolOpInterface>()) {
Block::iterator insertPt(func->getNextNode());
auto funcWalkResult = func.walk([&](gpu::LaunchOp op) {
SetVector<Value> operands;
std::string kernelFnName;
if (op.getFunction()) {
kernelFnName = op.getFunction()->str();
} else {
kernelFnName =
Twine(op->getParentOfType<SymbolOpInterface>().getName(),
"_kernel")
.str();
}
gpu::GPUFuncOp outlinedFunc =
outlineKernelFuncImpl(op, kernelFnName, operands);
auto kernelModule = createKernelModule(op, outlinedFunc, symbolTable);
symbolTable.insert(kernelModule, insertPt);
convertToLaunchFuncOp(op, outlinedFunc, operands.getArrayRef());
modified = true;
return WalkResult::advance();
});
if (funcWalkResult.wasInterrupted())
return signalPassFailure();
}
if (modified)
getOperation()->setAttr(gpu::GPUDialect::getContainerModuleAttrName(),
UnitAttr::get(&getContext()));
}
private:
gpu::GPUModuleOp createKernelModule(gpu::LaunchOp gpuLaunchOp,
gpu::GPUFuncOp kernelFunc,
const SymbolTable &parentSymbolTable) {
auto *context = getOperation().getContext();
OpBuilder builder(context);
std::string kernelModuleName;
gpu::GPUModuleOp kernelModule;
if (gpuLaunchOp.getModule()) {
kernelModuleName = gpuLaunchOp.getModule()->str();
kernelModule =
parentSymbolTable.lookup<gpu::GPUModuleOp>(kernelModuleName);
} else {
kernelModuleName = kernelFunc.getName();
}
if (!kernelModule) {
kernelModule = gpu::GPUModuleOp::create(builder, kernelFunc.getLoc(),
kernelModuleName);
}
if (dataLayoutSpec)
kernelModule->setAttr(DLTIDialect::kDataLayoutAttrName, dataLayoutSpec);
SymbolTable symbolTable(kernelModule);
symbolTable.insert(kernelFunc);
SmallVector<Operation *, 8> symbolDefWorklist = {kernelFunc};
while (!symbolDefWorklist.empty()) {
if (std::optional<SymbolTable::UseRange> symbolUses =
SymbolTable::getSymbolUses(symbolDefWorklist.pop_back_val())) {
for (SymbolTable::SymbolUse symbolUse : *symbolUses) {
StringAttr symbolName = symbolUse.getSymbolRef().getLeafReference();
if (symbolTable.lookup(symbolName))
continue;
Operation *symbolDefClone =
parentSymbolTable.lookup(symbolName)->clone();
symbolDefWorklist.push_back(symbolDefClone);
symbolTable.insert(symbolDefClone);
}
}
}
return kernelModule;
}
DataLayoutSpecInterface dataLayoutSpec;
};
}