20#include "llvm/ADT/ScopeExit.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/IRBuilder.h"
23#include "llvm/IR/LLVMContext.h"
24#include "llvm/IR/Module.h"
25#include "llvm/Support/FormatVariadic.h"
26#include "llvm/Transforms/Utils/ModuleUtils.h"
32class SelectObjectAttrImpl
33 :
public gpu::OffloadingLLVMTranslationAttrInterface::FallbackModel<
34 SelectObjectAttrImpl> {
36 gpu::ObjectAttr getSelectedObject(gpu::BinaryOp op)
const;
42 LogicalResult embedBinary(Attribute attribute, Operation *operation,
43 llvm::IRBuilderBase &builder,
44 LLVM::ModuleTranslation &moduleTranslation)
const;
49 Operation *launchFuncOperation,
50 Operation *binaryOperation,
51 llvm::IRBuilderBase &builder,
52 LLVM::ModuleTranslation &moduleTranslation)
const;
57SelectObjectAttrImpl::getSelectedObject(gpu::BinaryOp op)
const {
58 ArrayRef<Attribute> objects = op.getObjectsAttr().getValue();
63 cast<gpu::SelectObjectAttr>(op.getOffloadingHandlerAttr())
67 if (
auto indexAttr = mlir::dyn_cast<IntegerAttr>(
target)) {
68 index = indexAttr.getInt();
70 for (
auto [i, attr] : llvm::enumerate(objects)) {
71 auto obj = mlir::dyn_cast<gpu::ObjectAttr>(attr);
72 if (obj.getTarget() ==
target) {
83 if (index < 0 || index >=
static_cast<int64_t
>(objects.size())) {
84 op->emitError(
"the requested target object couldn't be found");
87 return mlir::dyn_cast<gpu::ObjectAttr>(objects[index]);
91 return moduleName +
"_module";
96 gpu::ObjectAttr
object, Module &module) {
101 bool addNull = (
object.getFormat() == gpu::CompilationTarget::Assembly);
102 StringRef serializedStr =
object.getObject().getValue();
104 ConstantDataArray::getString(module.getContext(), serializedStr, addNull);
105 GlobalVariable *serializedObj =
106 new GlobalVariable(module, serializedCst->getType(),
true,
107 GlobalValue::LinkageTypes::InternalLinkage,
108 serializedCst, moduleName +
"_binary");
109 serializedObj->setAlignment(MaybeAlign(8));
110 serializedObj->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
113 auto optLevel = APInt::getZero(32);
115 if (DictionaryAttr objectProps =
object.getProperties()) {
116 if (
auto section = dyn_cast_or_null<StringAttr>(
118 serializedObj->setSection(section.getValue());
121 if (
auto optAttr = dyn_cast_or_null<IntegerAttr>(objectProps.get(
"O")))
122 optLevel = optAttr.getValue();
125 IRBuilder<> builder(module.getContext());
126 auto *i32Ty = builder.getInt32Ty();
127 auto *i64Ty = builder.getInt64Ty();
128 auto *ptrTy = builder.getPtrTy(0);
129 auto *voidTy = builder.getVoidTy();
132 auto *modulePtr =
new GlobalVariable(
133 module, ptrTy,
false, GlobalValue::InternalLinkage,
134 ConstantPointerNull::get(ptrTy),
137 auto *loadFn = Function::Create(FunctionType::get(voidTy,
false),
138 GlobalValue::InternalLinkage,
139 moduleName +
"_load", module);
140 loadFn->setSection(
".text.startup");
141 auto *loadBlock = BasicBlock::Create(module.getContext(),
"entry", loadFn);
142 builder.SetInsertPoint(loadBlock);
143 Value *moduleObj = [&] {
145 ConstantInt::get(i64Ty, serializedStr.size() + (addNull ? 1 : 0));
146 if (
object.getFormat() == gpu::CompilationTarget::Assembly) {
147 FunctionCallee moduleLoadFn =
module.getOrInsertFunction(
148 "mgpuModuleLoadJIT", FunctionType::get(ptrTy,
156 Constant *optValue = ConstantInt::get(i32Ty, optLevel);
157 return builder.CreateCall(moduleLoadFn,
158 {serializedObj, optValue, binarySize});
160 FunctionCallee moduleLoadFn =
module.getOrInsertFunction(
161 "mgpuModuleLoad", FunctionType::get(ptrTy, {ptrTy, i64Ty}, false));
162 return builder.CreateCall(moduleLoadFn, {serializedObj, binarySize});
164 builder.CreateStore(moduleObj, modulePtr);
165 builder.CreateRetVoid();
166 appendToGlobalCtors(module, loadFn, 123);
168 auto *unloadFn = Function::Create(
169 FunctionType::get(voidTy,
false),
170 GlobalValue::InternalLinkage, moduleName +
"_unload", module);
171 unloadFn->setSection(
".text.startup");
173 BasicBlock::Create(module.getContext(),
"entry", unloadFn);
174 builder.SetInsertPoint(unloadBlock);
175 FunctionCallee moduleUnloadFn =
module.getOrInsertFunction(
176 "mgpuModuleUnload", FunctionType::get(voidTy, ptrTy, false));
177 builder.CreateCall(moduleUnloadFn, builder.CreateLoad(ptrTy, modulePtr));
178 builder.CreateRetVoid();
179 appendToGlobalDtors(module, unloadFn, 123);
185LogicalResult SelectObjectAttrImpl::embedBinary(
186 Attribute attribute, Operation *operation, llvm::IRBuilderBase &builder,
187 LLVM::ModuleTranslation &moduleTranslation)
const {
188 assert(operation &&
"The binary operation must be non null.");
192 auto op = mlir::dyn_cast<gpu::BinaryOp>(operation);
194 operation->
emitError(
"operation must be a GPU binary");
198 gpu::ObjectAttr
object = getSelectedObject(op);
210 LaunchKernel(Module &module, IRBuilderBase &builder,
211 mlir::LLVM::ModuleTranslation &moduleTranslation);
213 FunctionCallee getKernelLaunchFn();
216 FunctionCallee getClusterKernelLaunchFn();
219 FunctionCallee getKernelLaunchCooperativeFn();
222 FunctionCallee getModuleFunctionFn();
225 FunctionCallee getStreamCreateFn();
228 FunctionCallee getStreamDestroyFn();
231 FunctionCallee getStreamSyncFn();
234 Value *getOrCreateFunctionName(StringRef moduleName, StringRef kernelName);
237 Value *createKernelArgArray(mlir::gpu::LaunchFuncOp op);
240 llvm::LogicalResult createKernelLaunch(mlir::gpu::LaunchFuncOp op,
241 mlir::gpu::ObjectAttr
object);
245 IRBuilderBase &builder;
246 mlir::LLVM::ModuleTranslation &moduleTranslation;
251 PointerType *ptrTy{};
256LogicalResult SelectObjectAttrImpl::launchKernel(
257 Attribute attribute, Operation *launchFuncOperation,
258 Operation *binaryOperation, llvm::IRBuilderBase &builder,
259 LLVM::ModuleTranslation &moduleTranslation)
const {
261 assert(launchFuncOperation &&
"The launch func operation must be non null.");
262 if (!launchFuncOperation)
265 auto launchFuncOp = mlir::dyn_cast<gpu::LaunchFuncOp>(launchFuncOperation);
267 launchFuncOperation->
emitError(
"operation must be a GPU launch func Op.");
271 auto binOp = mlir::dyn_cast<gpu::BinaryOp>(binaryOperation);
273 binaryOperation->
emitError(
"operation must be a GPU binary.");
276 gpu::ObjectAttr
object = getSelectedObject(binOp);
280 return llvm::LaunchKernel(*moduleTranslation.
getLLVMModule(), builder,
282 .createKernelLaunch(launchFuncOp,
object);
285llvm::LaunchKernel::LaunchKernel(
286 Module &module, IRBuilderBase &builder,
287 mlir::LLVM::ModuleTranslation &moduleTranslation)
288 : module(module), builder(builder), moduleTranslation(moduleTranslation) {
289 i32Ty = builder.getInt32Ty();
290 i64Ty = builder.getInt64Ty();
291 ptrTy = builder.getPtrTy(0);
292 voidTy = builder.getVoidTy();
293 intPtrTy = builder.getIntPtrTy(module.getDataLayout());
296llvm::FunctionCallee llvm::LaunchKernel::getKernelLaunchFn() {
297 return module.getOrInsertFunction(
299 FunctionType::get(voidTy,
300 ArrayRef<Type *>({ptrTy, intPtrTy, intPtrTy, intPtrTy,
301 intPtrTy, intPtrTy, intPtrTy, i32Ty,
302 ptrTy, ptrTy, ptrTy, i64Ty}),
306llvm::FunctionCallee llvm::LaunchKernel::getClusterKernelLaunchFn() {
307 return module.getOrInsertFunction(
308 "mgpuLaunchClusterKernel",
311 ArrayRef<Type *>({ptrTy, intPtrTy, intPtrTy, intPtrTy, intPtrTy,
312 intPtrTy, intPtrTy, intPtrTy, intPtrTy, intPtrTy,
313 i32Ty, ptrTy, ptrTy, ptrTy}),
317llvm::FunctionCallee llvm::LaunchKernel::getKernelLaunchCooperativeFn() {
318 return module.getOrInsertFunction(
319 "mgpuLaunchKernelCooperative",
322 ArrayRef<Type *>({ptrTy, intPtrTy, intPtrTy, intPtrTy, intPtrTy,
323 intPtrTy, intPtrTy, intPtrTy, intPtrTy, intPtrTy,
324 i32Ty, ptrTy, ptrTy, ptrTy}),
328llvm::FunctionCallee llvm::LaunchKernel::getModuleFunctionFn() {
329 return module.getOrInsertFunction(
330 "mgpuModuleGetFunction",
331 FunctionType::get(ptrTy, ArrayRef<Type *>({ptrTy, ptrTy}), false));
334llvm::FunctionCallee llvm::LaunchKernel::getStreamCreateFn() {
335 return module.getOrInsertFunction("mgpuStreamCreate",
336 FunctionType::get(ptrTy, false));
339llvm::FunctionCallee llvm::LaunchKernel::getStreamDestroyFn() {
340 return module.getOrInsertFunction(
342 FunctionType::get(voidTy, ArrayRef<Type *>({ptrTy}), false));
345llvm::FunctionCallee llvm::LaunchKernel::getStreamSyncFn() {
346 return module.getOrInsertFunction(
347 "mgpuStreamSynchronize",
348 FunctionType::get(voidTy, ArrayRef<Type *>({ptrTy}), false));
353llvm::Value *llvm::LaunchKernel::getOrCreateFunctionName(StringRef moduleName,
354 StringRef kernelName) {
355 std::string globalName =
356 std::string(formatv(
"{0}_{1}_name", moduleName, kernelName));
358 if (GlobalVariable *gv = module.getGlobalVariable(globalName,
true))
361 return builder.CreateGlobalString(kernelName, globalName);
378llvm::LaunchKernel::createKernelArgArray(mlir::gpu::LaunchFuncOp op) {
379 SmallVector<Value *> args =
381 SmallVector<Type *> structTypes(args.size(),
nullptr);
383 for (
auto [i, arg] : llvm::enumerate(args))
384 structTypes[i] = arg->getType();
386 Type *structTy = StructType::create(module.getContext(), structTypes);
387 Value *argStruct = builder.CreateAlloca(structTy, 0u);
388 Value *argArray = builder.CreateAlloca(
389 ptrTy, ConstantInt::get(intPtrTy, structTypes.size()));
392 Value *structMember = builder.CreateStructGEP(structTy, argStruct, i);
393 builder.CreateStore(arg, structMember);
394 Value *arrayMember = builder.CreateConstGEP1_32(ptrTy, argArray, i);
395 builder.CreateStore(structMember, arrayMember);
409llvm::LaunchKernel::createKernelLaunch(mlir::gpu::LaunchFuncOp op,
410 mlir::gpu::ObjectAttr
object) {
411 auto llvmValue = [&](mlir::Value value) -> Value * {
413 assert(v &&
"Value has not been translated.");
418 mlir::gpu::KernelDim3 grid = op.getGridSizeOperandValues();
419 Value *gx = llvmValue(grid.
x), *gy = llvmValue(grid.
y),
420 *gz = llvmValue(grid.
z);
423 mlir::gpu::KernelDim3 block = op.getBlockSizeOperandValues();
424 Value *bx = llvmValue(block.
x), *by = llvmValue(block.
y),
425 *bz = llvmValue(block.
z);
428 Value *dynamicMemorySize =
nullptr;
429 if (mlir::Value dynSz = op.getDynamicSharedMemorySize())
430 dynamicMemorySize = llvmValue(dynSz);
432 dynamicMemorySize = ConstantInt::get(i32Ty, 0);
435 Value *argArray = createKernelArgArray(op);
438 StringRef moduleName = op.getKernelModuleName().getValue();
440 Value *modulePtr =
module.getGlobalVariable(moduleIdentifier.str(), true);
442 return op.emitError() <<
"Couldn't find the binary: " << moduleIdentifier;
443 Value *moduleObj = builder.CreateLoad(ptrTy, modulePtr);
444 Value *functionName = getOrCreateFunctionName(moduleName, op.getKernelName());
445 Value *moduleFunction =
446 builder.CreateCall(getModuleFunctionFn(), {moduleObj, functionName});
450 Value *stream =
nullptr;
452 llvm::scope_exit destroyStream([&]() {
453 builder.CreateCall(getStreamSyncFn(), {stream});
454 builder.CreateCall(getStreamDestroyFn(), {stream});
456 if (mlir::Value asyncObject = op.getAsyncObject()) {
457 stream = llvmValue(asyncObject);
458 destroyStream.release();
460 stream = builder.CreateCall(getStreamCreateFn(), {});
463 llvm::Constant *paramsCount =
464 llvm::ConstantInt::get(i64Ty, op.getNumKernelOperands());
467 Value *nullPtr = ConstantPointerNull::get(ptrTy);
473 if (op.getCooperative()) {
474 Value *cx = ConstantInt::get(intPtrTy, 0);
475 Value *cy = ConstantInt::get(intPtrTy, 0);
476 Value *cz = ConstantInt::get(intPtrTy, 0);
477 if (op.hasClusterSize()) {
478 mlir::gpu::KernelDim3 cluster = op.getClusterSizeOperandValues();
479 cx = llvmValue(cluster.
x);
480 cy = llvmValue(cluster.
y);
481 cz = llvmValue(cluster.
z);
484 getKernelLaunchCooperativeFn(),
485 ArrayRef<Value *>({moduleFunction, gx, gy, gz, cx, cy, cz, bx, by, bz,
486 dynamicMemorySize, stream, argArray, nullPtr}));
487 }
else if (op.hasClusterSize()) {
488 mlir::gpu::KernelDim3 cluster = op.getClusterSizeOperandValues();
489 Value *cx = llvmValue(cluster.
x), *cy = llvmValue(cluster.
y),
490 *cz = llvmValue(cluster.
z);
492 getClusterKernelLaunchFn(),
493 ArrayRef<Value *>({moduleFunction, cx, cy, cz, gx, gy, gz, bx, by, bz,
494 dynamicMemorySize, stream, argArray, nullPtr}));
496 builder.CreateCall(getKernelLaunchFn(),
497 ArrayRef<Value *>({moduleFunction, gx, gy, gz, bx, by,
498 bz, dynamicMemorySize, stream,
499 argArray, nullPtr, paramsCount}));
508 SelectObjectAttr::attachInterface<SelectObjectAttrImpl>(*ctx);
static Twine getModuleIdentifier(StringRef moduleName)
static void launchKernel(sycl::queue *queue, sycl::kernel *kernel, size_t gridX, size_t gridY, size_t gridZ, size_t blockX, size_t blockY, size_t blockZ, size_t sharedMemBytes, void **params, size_t paramsCount)
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
SmallVector< llvm::Value * > lookupValues(ValueRange values)
Looks up remapped a list of remapped values.
llvm::Value * lookupValue(Value value) const
Finds an LLVM IR value corresponding to the given MLIR value.
llvm::Module * getLLVMModule()
Returns the LLVM module in which the IR is being constructed.
MLIRContext is the top-level object for a collection of MLIR operations.
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
static LogicalResult embedBinaryImpl(StringRef moduleName, gpu::ObjectAttr object, Module &module)
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
constexpr StringLiteral elfSectionName
void registerOffloadingLLVMTranslationInterfaceExternalModels(mlir::DialectRegistry ®istry)
Registers the offloading LLVM translation interfaces for gpu.select_object.
Include the generated interface declarations.
@ Constant
Constant integer.