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,
int priority,
102 bool addNull = (
object.getFormat() == gpu::CompilationTarget::Assembly);
103 StringRef serializedStr =
object.getObject().getValue();
105 ConstantDataArray::getString(module.getContext(), serializedStr, addNull);
106 GlobalVariable *serializedObj =
107 new GlobalVariable(module, serializedCst->getType(),
true,
108 GlobalValue::LinkageTypes::InternalLinkage,
109 serializedCst, moduleName +
"_binary");
110 serializedObj->setAlignment(MaybeAlign(8));
111 serializedObj->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
114 auto optLevel = APInt::getZero(32);
116 if (DictionaryAttr objectProps =
object.getProperties()) {
117 if (
auto section = dyn_cast_or_null<StringAttr>(
119 serializedObj->setSection(section.getValue());
122 if (
auto optAttr = dyn_cast_or_null<IntegerAttr>(objectProps.get(
"O")))
123 optLevel = optAttr.getValue();
126 IRBuilder<> builder(module);
127 auto *i32Ty = builder.getInt32Ty();
128 auto *i64Ty = builder.getInt64Ty();
129 auto *ptrTy = builder.getPtrTy(0);
130 auto *voidTy = builder.getVoidTy();
133 auto *modulePtr =
new GlobalVariable(
134 module, ptrTy,
false, GlobalValue::InternalLinkage,
135 ConstantPointerNull::get(ptrTy),
138 auto *loadFn = Function::Create(FunctionType::get(voidTy,
false),
139 GlobalValue::InternalLinkage,
140 moduleName +
"_load", module);
141 loadFn->setSection(
".text.startup");
142 auto *loadBlock = BasicBlock::Create(module.getContext(),
"entry", loadFn);
143 builder.SetInsertPoint(loadBlock);
144 Value *moduleObj = [&] {
146 ConstantInt::get(i64Ty, serializedStr.size() + (addNull ? 1 : 0));
147 if (
object.getFormat() == gpu::CompilationTarget::Assembly) {
148 FunctionCallee moduleLoadFn =
module.getOrInsertFunction(
149 "mgpuModuleLoadJIT", FunctionType::get(ptrTy,
157 Constant *optValue = ConstantInt::get(i32Ty, optLevel);
158 return builder.CreateCall(moduleLoadFn,
159 {serializedObj, optValue, binarySize});
161 FunctionCallee moduleLoadFn =
module.getOrInsertFunction(
162 "mgpuModuleLoad", FunctionType::get(ptrTy, {ptrTy, i64Ty}, false));
163 return builder.CreateCall(moduleLoadFn, {serializedObj, binarySize});
165 builder.CreateStore(moduleObj, modulePtr);
166 builder.CreateRetVoid();
167 appendToGlobalCtors(module, loadFn, priority);
169 auto *unloadFn = Function::Create(
170 FunctionType::get(voidTy,
false),
171 GlobalValue::InternalLinkage, moduleName +
"_unload", module);
172 unloadFn->setSection(
".text.startup");
174 BasicBlock::Create(module.getContext(),
"entry", unloadFn);
175 builder.SetInsertPoint(unloadBlock);
176 FunctionCallee moduleUnloadFn =
module.getOrInsertFunction(
177 "mgpuModuleUnload", FunctionType::get(voidTy, ptrTy, false));
178 builder.CreateCall(moduleUnloadFn, builder.CreateLoad(ptrTy, modulePtr));
179 builder.CreateRetVoid();
180 appendToGlobalDtors(module, unloadFn, priority);
186LogicalResult SelectObjectAttrImpl::embedBinary(
187 Attribute attribute, Operation *operation, llvm::IRBuilderBase &builder,
188 LLVM::ModuleTranslation &moduleTranslation)
const {
189 assert(operation &&
"The binary operation must be non null.");
193 auto op = mlir::dyn_cast<gpu::BinaryOp>(operation);
195 operation->
emitError(
"operation must be a GPU binary");
199 gpu::ObjectAttr
object = getSelectedObject(op);
203 uint16_t priority = cast<gpu::SelectObjectAttr>(attribute).getPriority();
212 LaunchKernel(Module &module, IRBuilderBase &builder,
213 mlir::LLVM::ModuleTranslation &moduleTranslation);
215 FunctionCallee getKernelLaunchFn();
218 FunctionCallee getClusterKernelLaunchFn();
221 FunctionCallee getKernelLaunchCooperativeFn();
224 FunctionCallee getModuleFunctionFn();
227 FunctionCallee getStreamCreateFn();
230 FunctionCallee getStreamDestroyFn();
233 FunctionCallee getStreamSyncFn();
236 Value *getOrCreateFunctionName(StringRef moduleName, StringRef kernelName);
239 Value *createKernelArgArray(mlir::gpu::LaunchFuncOp op);
242 llvm::LogicalResult createKernelLaunch(mlir::gpu::LaunchFuncOp op,
243 mlir::gpu::ObjectAttr
object);
247 IRBuilderBase &builder;
248 mlir::LLVM::ModuleTranslation &moduleTranslation;
253 PointerType *ptrTy{};
258LogicalResult SelectObjectAttrImpl::launchKernel(
259 Attribute attribute, Operation *launchFuncOperation,
260 Operation *binaryOperation, llvm::IRBuilderBase &builder,
261 LLVM::ModuleTranslation &moduleTranslation)
const {
263 assert(launchFuncOperation &&
"The launch func operation must be non null.");
264 if (!launchFuncOperation)
267 auto launchFuncOp = mlir::dyn_cast<gpu::LaunchFuncOp>(launchFuncOperation);
269 launchFuncOperation->
emitError(
"operation must be a GPU launch func Op.");
273 auto binOp = mlir::dyn_cast<gpu::BinaryOp>(binaryOperation);
275 binaryOperation->
emitError(
"operation must be a GPU binary.");
278 gpu::ObjectAttr
object = getSelectedObject(binOp);
282 return llvm::LaunchKernel(*moduleTranslation.
getLLVMModule(), builder,
284 .createKernelLaunch(launchFuncOp,
object);
287llvm::LaunchKernel::LaunchKernel(
288 Module &module, IRBuilderBase &builder,
289 mlir::LLVM::ModuleTranslation &moduleTranslation)
290 : module(module), builder(builder), moduleTranslation(moduleTranslation) {
291 i32Ty = builder.getInt32Ty();
292 i64Ty = builder.getInt64Ty();
293 ptrTy = builder.getPtrTy(0);
294 voidTy = builder.getVoidTy();
295 intPtrTy = builder.getIntPtrTy(module.getDataLayout());
298llvm::FunctionCallee llvm::LaunchKernel::getKernelLaunchFn() {
299 return module.getOrInsertFunction(
301 FunctionType::get(voidTy,
302 ArrayRef<Type *>({ptrTy, intPtrTy, intPtrTy, intPtrTy,
303 intPtrTy, intPtrTy, intPtrTy, i32Ty,
304 ptrTy, ptrTy, ptrTy, i64Ty}),
308llvm::FunctionCallee llvm::LaunchKernel::getClusterKernelLaunchFn() {
309 return module.getOrInsertFunction(
310 "mgpuLaunchClusterKernel",
313 ArrayRef<Type *>({ptrTy, intPtrTy, intPtrTy, intPtrTy, intPtrTy,
314 intPtrTy, intPtrTy, intPtrTy, intPtrTy, intPtrTy,
315 i32Ty, ptrTy, ptrTy, ptrTy}),
319llvm::FunctionCallee llvm::LaunchKernel::getKernelLaunchCooperativeFn() {
320 return module.getOrInsertFunction(
321 "mgpuLaunchKernelCooperative",
324 ArrayRef<Type *>({ptrTy, intPtrTy, intPtrTy, intPtrTy, intPtrTy,
325 intPtrTy, intPtrTy, intPtrTy, intPtrTy, intPtrTy,
326 i32Ty, ptrTy, ptrTy, ptrTy}),
330llvm::FunctionCallee llvm::LaunchKernel::getModuleFunctionFn() {
331 return module.getOrInsertFunction(
332 "mgpuModuleGetFunction",
333 FunctionType::get(ptrTy, ArrayRef<Type *>({ptrTy, ptrTy}), false));
336llvm::FunctionCallee llvm::LaunchKernel::getStreamCreateFn() {
337 return module.getOrInsertFunction("mgpuStreamCreate",
338 FunctionType::get(ptrTy, false));
341llvm::FunctionCallee llvm::LaunchKernel::getStreamDestroyFn() {
342 return module.getOrInsertFunction(
344 FunctionType::get(voidTy, ArrayRef<Type *>({ptrTy}), false));
347llvm::FunctionCallee llvm::LaunchKernel::getStreamSyncFn() {
348 return module.getOrInsertFunction(
349 "mgpuStreamSynchronize",
350 FunctionType::get(voidTy, ArrayRef<Type *>({ptrTy}), false));
355llvm::Value *llvm::LaunchKernel::getOrCreateFunctionName(StringRef moduleName,
356 StringRef kernelName) {
357 std::string globalName =
358 std::string(formatv(
"{0}_{1}_name", moduleName, kernelName));
360 if (GlobalVariable *gv = module.getGlobalVariable(globalName,
true))
363 return builder.CreateGlobalString(kernelName, globalName);
380llvm::LaunchKernel::createKernelArgArray(mlir::gpu::LaunchFuncOp op) {
381 SmallVector<Value *> args =
383 SmallVector<Type *> structTypes(args.size(),
nullptr);
385 for (
auto [i, arg] : llvm::enumerate(args))
386 structTypes[i] = arg->getType();
388 Type *structTy = StructType::create(module.getContext(), structTypes);
389 Value *argStruct = builder.CreateAlloca(structTy, 0u);
390 Value *argArray = builder.CreateAlloca(
391 ptrTy, ConstantInt::get(intPtrTy, structTypes.size()));
394 Value *structMember = builder.CreateStructGEP(structTy, argStruct, i);
395 builder.CreateStore(arg, structMember);
396 Value *arrayMember = builder.CreateConstGEP1_32(ptrTy, argArray, i);
397 builder.CreateStore(structMember, arrayMember);
413llvm::LaunchKernel::createKernelLaunch(mlir::gpu::LaunchFuncOp op,
414 mlir::gpu::ObjectAttr
object) {
415 auto llvmValue = [&](mlir::Value value) -> Value * {
417 assert(v &&
"Value has not been translated.");
422 mlir::gpu::KernelDim3 grid = op.getGridSizeOperandValues();
423 Value *gx = llvmValue(grid.
x), *gy = llvmValue(grid.
y),
424 *gz = llvmValue(grid.
z);
427 mlir::gpu::KernelDim3 block = op.getBlockSizeOperandValues();
428 Value *bx = llvmValue(block.
x), *by = llvmValue(block.
y),
429 *bz = llvmValue(block.
z);
432 Value *dynamicMemorySize =
nullptr;
433 if (mlir::Value dynSz = op.getDynamicSharedMemorySize())
434 dynamicMemorySize = llvmValue(dynSz);
436 dynamicMemorySize = ConstantInt::get(i32Ty, 0);
441 Value *stack = builder.CreateStackSave();
442 Value *argArray = createKernelArgArray(op);
445 StringRef moduleName = op.getKernelModuleName().getValue();
447 Value *modulePtr =
module.getGlobalVariable(moduleIdentifier.str(), true);
449 return op.emitError() <<
"Couldn't find the binary: " << moduleIdentifier;
450 Value *moduleObj = builder.CreateLoad(ptrTy, modulePtr);
451 Value *functionName = getOrCreateFunctionName(moduleName, op.getKernelName());
452 Value *moduleFunction =
453 builder.CreateCall(getModuleFunctionFn(), {moduleObj, functionName});
457 Value *stream =
nullptr;
459 llvm::scope_exit destroyStream([&]() {
460 builder.CreateCall(getStreamSyncFn(), {stream});
461 builder.CreateCall(getStreamDestroyFn(), {stream});
463 if (mlir::Value asyncObject = op.getAsyncObject()) {
464 stream = llvmValue(asyncObject);
465 destroyStream.release();
467 stream = builder.CreateCall(getStreamCreateFn(), {});
470 llvm::Constant *paramsCount =
471 llvm::ConstantInt::get(i64Ty, op.getNumKernelOperands());
474 Value *nullPtr = ConstantPointerNull::get(ptrTy);
480 if (op.getCooperative()) {
481 Value *cx = ConstantInt::get(intPtrTy, 0);
482 Value *cy = ConstantInt::get(intPtrTy, 0);
483 Value *cz = ConstantInt::get(intPtrTy, 0);
484 if (op.hasClusterSize()) {
485 mlir::gpu::KernelDim3 cluster = op.getClusterSizeOperandValues();
486 cx = llvmValue(cluster.
x);
487 cy = llvmValue(cluster.
y);
488 cz = llvmValue(cluster.
z);
491 getKernelLaunchCooperativeFn(),
492 ArrayRef<Value *>({moduleFunction, gx, gy, gz, cx, cy, cz, bx, by, bz,
493 dynamicMemorySize, stream, argArray, nullPtr}));
494 }
else if (op.hasClusterSize()) {
495 mlir::gpu::KernelDim3 cluster = op.getClusterSizeOperandValues();
496 Value *cx = llvmValue(cluster.
x), *cy = llvmValue(cluster.
y),
497 *cz = llvmValue(cluster.
z);
499 getClusterKernelLaunchFn(),
500 ArrayRef<Value *>({moduleFunction, cx, cy, cz, gx, gy, gz, bx, by, bz,
501 dynamicMemorySize, stream, argArray, nullPtr}));
503 builder.CreateCall(getKernelLaunchFn(),
504 ArrayRef<Value *>({moduleFunction, gx, gy, gz, bx, by,
505 bz, dynamicMemorySize, stream,
506 argArray, nullPtr, paramsCount}));
509 builder.CreateStackRestore(stack);
517 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, int priority, 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.