33#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/StringExtras.h"
35#include "llvm/Support/FormatVariadic.h"
38#define GEN_PASS_DEF_LOWERHOSTCODETOLLVMPASS
39#include "mlir/Conversion/Passes.h.inc"
56 return *op.getBinding();
62 LLVM::MemcpyOp::create(builder, loc, dst, src, size,
false);
72 StringRef kernelModuleName) {
73 return llvm::formatv(
"{0}_{1}_descriptor_set{2}_binding{3}",
74 kernelModuleName.str(), op.getSymName().str(),
75 std::to_string(*op.getDescriptorSet()),
76 std::to_string(*op.getBinding()));
82 return op.getDescriptorSetAttr() && op.getBindingAttr();
90 spirv::ModuleOp moduleOp,
92 auto entryPoints = moduleOp.getOps<spirv::EntryPointOp>();
93 if (!llvm::hasSingleElement(entryPoints)) {
94 return moduleOp.emitError(
95 "The module must contain exactly one entry point function");
97 auto globalVariables = moduleOp.getOps<spirv::GlobalVariableOp>();
98 for (
auto globalOp : globalVariables) {
108 StringRef spvModuleName = moduleOp.getSymName().value_or(
kSPIRVModule);
113 auto entryPoints = moduleOp.getOps<spirv::EntryPointOp>();
114 if (!llvm::hasSingleElement(entryPoints)) {
115 return moduleOp.emitError(
116 "The module must contain exactly one entry point function");
118 spirv::EntryPointOp entryPoint = *entryPoints.begin();
119 StringRef funcName = entryPoint.getFn();
120 auto funcOp = moduleOp.lookupSymbol<spirv::FuncOp>(entryPoint.getFnAttr());
121 StringAttr newFuncName =
122 StringAttr::get(moduleOp->getContext(), spvModuleName +
"_" + funcName);
147 using ConvertOpToLLVMPattern<gpu::LaunchFuncOp>::ConvertOpToLLVMPattern;
150 matchAndRewrite(gpu::LaunchFuncOp launchOp, OpAdaptor adaptor,
151 ConversionPatternRewriter &rewriter)
const override {
152 auto *op = launchOp.getOperation();
153 MLIRContext *context = rewriter.getContext();
154 auto moduleOp = launchOp->getParentOfType<ModuleOp>();
160 StringRef kernelModuleName = launchOp.getKernelModuleName().getValue();
161 std::string spvModuleName =
kSPIRVModule + kernelModuleName.str();
162 auto spvModule = moduleOp.lookupSymbol<spirv::ModuleOp>(
163 StringAttr::get(context, spvModuleName));
165 return launchOp.emitOpError(
"SPIR-V kernel module '")
166 << spvModuleName <<
"' is not found";
175 StringRef kernelFuncName = launchOp.getKernelName().getValue();
176 std::string newKernelFuncName = spvModuleName +
"_" + kernelFuncName.str();
177 auto kernelFunc = moduleOp.lookupSymbol<LLVM::LLVMFuncOp>(
178 StringAttr::get(context, newKernelFuncName));
180 OpBuilder::InsertionGuard guard(rewriter);
181 rewriter.setInsertionPointToStart(moduleOp.getBody());
182 kernelFunc = LLVM::LLVMFuncOp::create(
183 rewriter, rewriter.getUnknownLoc(), newKernelFuncName,
184 LLVM::LLVMFunctionType::get(LLVM::LLVMVoidType::get(context),
186 rewriter.setInsertionPoint(launchOp);
190 DenseMap<uint32_t, spirv::GlobalVariableOp> globalVariableMap;
196 Location loc = launchOp.getLoc();
197 SmallVector<CopyInfo, 4> copyInfo;
198 auto numKernelOperands = launchOp.getNumKernelOperands();
199 auto kernelOperands = adaptor.getOperands().take_back(numKernelOperands);
200 for (
const auto &operand : llvm::enumerate(kernelOperands)) {
202 auto memRefType = dyn_cast<MemRefType>(
203 launchOp.getKernelOperand(operand.index()).getType());
209 SmallVector<Value, 4> sizes;
210 SmallVector<Value, 4> strides;
212 getMemRefDescriptorSizes(loc, memRefType, {}, rewriter, sizes, strides,
214 MemRefDescriptor descriptor(operand.value());
215 Value src = descriptor.allocatedPtr(rewriter, loc);
220 spirv::GlobalVariableOp spirvGlobal = globalVariableMap[operand.index()];
221 auto ptrType = dyn_cast<spirv::PointerType>(spirvGlobal.getType());
224 auto dstGlobalType = typeConverter->convertType(ptrType.getPointeeType());
230 auto dstGlobal = moduleOp.lookupSymbol<LLVM::GlobalOp>(name);
232 OpBuilder::InsertionGuard guard(rewriter);
233 rewriter.setInsertionPointToStart(moduleOp.getBody());
234 dstGlobal = LLVM::GlobalOp::create(
235 rewriter, loc, dstGlobalType,
236 false, LLVM::Linkage::Linkonce, name, Attribute(),
238 rewriter.setInsertionPoint(launchOp);
244 Value dst = LLVM::AddressOfOp::create(
245 rewriter, loc, typeConverter->convertType(spirvGlobal.getType()),
246 dstGlobal.getSymName());
247 copy(loc, dst, src, sizeBytes, rewriter);
252 info.size = sizeBytes;
253 copyInfo.push_back(info);
256 rewriter.replaceOpWithNewOp<LLVM::CallOp>(op, kernelFunc,
258 for (CopyInfo info : copyInfo)
259 copy(loc, info.src, info.dst, info.size, rewriter);
264class LowerHostCodeToLLVM
269 void runOnOperation()
override {
270 ModuleOp moduleOp = getOperation();
273 for (
auto gpuModule :
274 llvm::make_early_inc_range(moduleOp.getOps<gpu::GPUModuleOp>()))
278 for (
auto func : moduleOp.getOps<func::FuncOp>()) {
279 func->setDiscardableAttr(LLVM::LLVMDialect::getEmitCWrapperAttrName(),
284 LowerToLLVMOptions
options(moduleOp.getContext());
286 auto *context = moduleOp.getContext();
287 RewritePatternSet patterns(context);
288 LLVMTypeConverter typeConverter(context,
options);
292 patterns.add<GPULaunchLowering>(typeConverter);
298 ConversionTarget
target(*context);
299 target.addLegalDialect<LLVM::LLVMDialect>();
300 if (
failed(applyPartialConversion(moduleOp,
target, std::move(patterns))))
305 for (
auto spvModule : moduleOp.getOps<spirv::ModuleOp>()) {
static LogicalResult getKernelGlobalVariables(spirv::ModuleOp moduleOp, DenseMap< uint32_t, spirv::GlobalVariableOp > &globalVariableMap)
Fills globalVariableMap with SPIR-V global variables that represent kernel arguments from the given S...
static LogicalResult encodeKernelName(spirv::ModuleOp moduleOp)
Encodes the SPIR-V module's symbolic name into the name of the entry point function.
static void copy(Location loc, Value dst, Value src, Value size, OpBuilder &builder)
Copies the given number of bytes from src to dst pointers.
static constexpr const char kSPIRVModule[]
static std::string createGlobalVariableWithBindName(spirv::GlobalVariableOp op, StringRef kernelModuleName)
Encodes the binding and descriptor set numbers into a new symbolic name.
static unsigned calculateGlobalIndex(spirv::GlobalVariableOp op)
Calculates the index of the kernel's operand that is represented by the given global variable with th...
static bool hasDescriptorSetAndBinding(spirv::GlobalVariableOp op)
Returns true if the given global variable has both a descriptor set number and a binding number.
static constexpr const char kSPIRVModule[]
static llvm::ManagedStatic< PassManagerOptions > options
Utility class for operation conversions targeting the LLVM dialect that match exactly one source oper...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
This class helps build Operations.
static LogicalResult replaceAllSymbolUses(StringAttr oldSymbol, StringAttr newSymbol, Operation *from)
Attempt to replace all uses of the given symbol 'oldSymbol' with the provided symbol 'newSymbol' that...
static void setSymbolName(Operation *symbol, StringAttr name)
Sets the name of the given symbol operation.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
void populateArithToLLVMConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns)
Include the generated interface declarations.
void populateSPIRVToLLVMTypeConversion(LLVMTypeConverter &typeConverter, spirv::ClientAPI clientAPIForAddressSpaceMapping=spirv::ClientAPI::Unknown)
Populates type conversions with additional SPIR-V types.
void populateFuncToLLVMConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, SymbolTableCollection *symbolTables=nullptr)
Collect the patterns to convert from the Func dialect to LLVM.
void populateFinalizeMemRefToLLVMConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, SymbolTableCollection *symbolTables=nullptr)
Collect a set of patterns to convert memory-related operations from the MemRef dialect to the LLVM di...
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap