clang 24.0.0git
CIRGenCUDANV.cpp
Go to the documentation of this file.
1//========- CIRGenCUDANV.cpp - Interface to NVIDIA CUDA Runtime -----=========//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This provides a class for CUDA code generation targeting the NVIDIA CUDA
10// runtime library.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CIRGenCUDARuntime.h"
15#include "CIRGenCXXABI.h"
16#include "CIRGenFunction.h"
17#include "CIRGenModule.h"
18#include "mlir/IR/Operation.h"
20#include "clang/AST/Attrs.inc"
21#include "clang/AST/Decl.h"
24#include "clang/Basic/Cuda.h"
30#include "llvm/Support/Casting.h"
31#include "llvm/Support/MemoryBuffer.h"
32#include "llvm/Support/VirtualFileSystem.h"
33
34using namespace clang;
35using namespace clang::CIRGen;
36
37namespace {
38
39class CIRGenNVCUDARuntime : public CIRGenCUDARuntime {
40protected:
41 StringRef prefix;
42
43 // Map a device stub function to a symbol for identifying kernel in host
44 // code. For CUDA, the symbol for identifying the kernel is the same as the
45 // device stub function. For HIP, they are different.
46 llvm::StringMap<mlir::Operation *> kernelHandles;
47
48 // Map a kernel handle to the kernel stub.
49 llvm::DenseMap<mlir::Operation *, mlir::Operation *> kernelStubs;
50
51 struct VarInfo {
52 cir::GlobalOp var;
53 const VarDecl *d;
54 cir::CUDADeviceVarKind flags;
55 };
56 llvm::SmallVector<VarInfo, 16> deviceVars;
57
58 // Mangle context for device.
59 std::unique_ptr<MangleContext> deviceMC;
60
61private:
62 void emitDeviceStubBodyNew(CIRGenFunction &cgf, cir::FuncOp fn,
63 FunctionArgList &args);
64 void recordDeviceBinary();
65 void transformManagedVars();
66 mlir::Value prepareKernelArgs(CIRGenFunction &cgf, mlir::Location loc,
67 FunctionArgList &args);
68 mlir::Operation *getKernelHandle(cir::FuncOp fn, GlobalDecl gd) override;
69
70 mlir::Operation *getKernelStub(mlir::Operation *handle) override {
71 auto it = kernelStubs.find(handle);
72 assert(it != kernelStubs.end());
73 return it->second;
74 }
75 std::string addPrefixToName(StringRef funcName) const;
76 std::string addUnderscoredPrefixToName(StringRef funcName) const;
77
78public:
79 CIRGenNVCUDARuntime(CIRGenModule &cgm);
80 ~CIRGenNVCUDARuntime();
81
82 void emitDeviceStub(CIRGenFunction &cgf, cir::FuncOp fn,
83 FunctionArgList &args) override;
84
85 void handleVarRegistration(const VarDecl *vd, cir::GlobalOp var) override;
86 void finalizeModule() override;
87 void handleGlobalReplace(cir::GlobalOp oldGV, cir::GlobalOp newGV) override;
88
89 void internalizeDeviceSideVar(const VarDecl *d,
90 cir::GlobalLinkageKind &linkage) override;
91
92 std::string getDeviceSideName(const NamedDecl *nd) override;
93
94 void registerDeviceVar(const VarDecl *vd, cir::GlobalOp &var, bool isExtern,
95 bool isConstant) {
96 // Attach the device var attribute to the GlobalOp
97 auto &builder = cgm.getBuilder();
98 var->setAttr(cir::CUDAVarRegistrationInfoAttr::getMnemonic(),
99 cir::CUDAVarRegistrationInfoAttr::get(
100 builder.getContext(),
101 getDeviceSideName(cast<NamedDecl>(vd)),
102 cir::CUDADeviceVarKind::Variable, isExtern, isConstant,
103 vd->hasAttr<HIPManagedAttr>()));
104 deviceVars.push_back({
105 var,
106 vd,
107 cir::CUDADeviceVarKind::Variable,
108 });
109 }
110
111 void registerDeviceSurf(const VarDecl *vd, cir::GlobalOp &var,
112 bool isExtern) {
113 auto &builder = cgm.getBuilder();
114
115 var->setAttr(cir::CUDAVarRegistrationInfoAttr::getMnemonic(),
116 cir::CUDAVarRegistrationInfoAttr::get(
117 builder.getContext(),
118 getDeviceSideName(cast<NamedDecl>(vd)),
119 cir::CUDADeviceVarKind::Surface, isExtern,
120 /*isConstant=*/false,
121 /*isManaged=*/false));
122
123 deviceVars.push_back({
124 var,
125 vd,
126 cir::CUDADeviceVarKind::Surface,
127 });
128 }
129
130 void registerDeviceTex(const VarDecl *vd, cir::GlobalOp &var, bool isExtern) {
131 auto &builder = cgm.getBuilder();
132
133 var->setAttr(cir::CUDAVarRegistrationInfoAttr::getMnemonic(),
134 cir::CUDAVarRegistrationInfoAttr::get(
135 builder.getContext(),
136 getDeviceSideName(cast<NamedDecl>(vd)),
137 cir::CUDADeviceVarKind::Texture, isExtern,
138 /*isConstant=*/false,
139 /*isManaged=*/false));
140
141 deviceVars.push_back({
142 var,
143 vd,
144 cir::CUDADeviceVarKind::Texture,
145 });
146 }
147};
148
149} // namespace
150
151std::string CIRGenNVCUDARuntime::addPrefixToName(StringRef funcName) const {
152 return (prefix + funcName).str();
153}
154
155std::string
156CIRGenNVCUDARuntime::addUnderscoredPrefixToName(StringRef funcName) const {
157 return ("__" + prefix + funcName).str();
158}
159
160CIRGenNVCUDARuntime::CIRGenNVCUDARuntime(CIRGenModule &cgm)
161 : CIRGenCUDARuntime(cgm),
162 deviceMC(cgm.getASTContext().cudaNVInitDeviceMC()) {
163 if (cgm.getLangOpts().OffloadViaLLVM)
164 cgm.errorNYI("CIRGenNVCUDARuntime: Offload via LLVM");
165 else if (cgm.getLangOpts().HIP)
166 prefix = "hip";
167 else
168 prefix = "cuda";
169}
170
171mlir::Value CIRGenNVCUDARuntime::prepareKernelArgs(CIRGenFunction &cgf,
172 mlir::Location loc,
173 FunctionArgList &args) {
174 CIRGenBuilderTy &builder = cgm.getBuilder();
175
176 // Build void *args[] and populate with the addresses of kernel arguments.
177 auto voidPtrArrayTy = cir::ArrayType::get(cgm.voidPtrTy, args.size());
178 mlir::Value kernelArgs =
179 builder.createAlloca(loc, cir::PointerType::get(voidPtrArrayTy),
180 "kernel_args", CharUnits::fromQuantity(16));
181
182 mlir::Value kernelArgsDecayed =
183 builder.createCast(cir::CastKind::array_to_ptrdecay, kernelArgs,
184 cir::PointerType::get(cgm.voidPtrTy));
185
186 for (const auto &[i, arg] : llvm::enumerate(args)) {
187 mlir::Value index =
188 builder.getConstInt(loc, llvm::APInt(/*numBits=*/32, i));
189 mlir::Value storePos =
190 builder.createPtrStride(loc, kernelArgsDecayed, index);
191 mlir::Value argAddr = cgf.getAddrOfLocalVar(arg).getPointer();
192 mlir::Value argAsVoid = builder.createBitcast(argAddr, cgm.voidPtrTy);
193
194 builder.CIRBaseBuilderTy::createStore(loc, argAsVoid, storePos);
195 }
196
197 return kernelArgsDecayed;
198}
199
200// CUDA 9.0+ uses new way to launch kernels. Parameters are packed in a local
201// array and kernels are launched using cudaLaunchKernel().
202void CIRGenNVCUDARuntime::emitDeviceStubBodyNew(CIRGenFunction &cgf,
203 cir::FuncOp fn,
204 FunctionArgList &args) {
205
206 // This requires arguments to be sent to kernels in a different way.
207 if (cgm.getLangOpts().OffloadViaLLVM)
208 cgm.errorNYI("CIRGenNVCUDARuntime: Offload via LLVM");
209
210 CIRGenBuilderTy &builder = cgm.getBuilder();
211 mlir::Location loc = fn.getLoc();
212
213 // For [cuda|hip]LaunchKernel, we must add another layer of indirection
214 // to arguments. For example, for function `add(int a, float b)`,
215 // we need to pass it as `void *args[2] = { &a, &b }`.
216 mlir::Value kernelArgs = prepareKernelArgs(cgf, loc, args);
217
218 // Lookup cudaLaunchKernel/hipLaunchKernel function.
219 // HIP kernel launching API name depends on -fgpu-default-stream option. For
220 // the default value 'legacy', it is hipLaunchKernel. For 'per-thread',
221 // it is hipLaunchKernel_spt.
222 // cudaError_t cudaLaunchKernel(const void *func, dim3 gridDim, dim3 blockDim,
223 // void **args, size_t sharedMem,
224 // cudaStream_t stream);
225 // hipError_t hipLaunchKernel[_spt](const void *func, dim3 gridDim,
226 // dim3 blockDim, void **args,
227 // size_t sharedMem, hipStream_t stream);
228 TranslationUnitDecl *tuDecl = cgm.getASTContext().getTranslationUnitDecl();
229 DeclContext *dc = TranslationUnitDecl::castToDeclContext(tuDecl);
230
231 // The default stream is usually stream 0 (the legacy default stream).
232 // For per-thread default stream, we need a different LaunchKernel function.
233 std::string kernelLaunchAPI = "LaunchKernel";
234 if (cgm.getLangOpts().GPUDefaultStream ==
235 LangOptions::GPUDefaultStreamKind::PerThread) {
236 if (cgm.getLangOpts().HIP)
237 kernelLaunchAPI += "_spt";
238 else if (cgm.getLangOpts().CUDA)
239 kernelLaunchAPI += "_ptsz";
240 }
241
242 std::string launchKernelName = addPrefixToName(kernelLaunchAPI);
243 const IdentifierInfo &launchII =
244 cgm.getASTContext().Idents.get(launchKernelName);
245 FunctionDecl *cudaLaunchKernelFD = nullptr;
246 for (NamedDecl *result : dc->lookup(&launchII)) {
247 if (FunctionDecl *fd = dyn_cast<FunctionDecl>(result))
248 cudaLaunchKernelFD = fd;
249 }
250
251 if (cudaLaunchKernelFD == nullptr) {
252 cgm.error(cgf.curFuncDecl->getLocation(),
253 "Can't find declaration for " + launchKernelName);
254 return;
255 }
256
257 // Use this function to retrieve arguments for cudaLaunchKernel:
258 // int __[cuda|hip]PopCallConfiguration(dim3 *gridDim, dim3 *blockDim, size_t
259 // *sharedMem, cudaStream_t *stream)
260 //
261 // Here [cuda|hip]Stream_t, while also being the 6th argument of
262 // [cuda|hip]LaunchKernel, is a pointer to some opaque struct.
263
264 mlir::Type dim3Ty = cgf.getTypes().convertType(
265 cudaLaunchKernelFD->getParamDecl(1)->getType());
266 mlir::Type streamTy = cgf.getTypes().convertType(
267 cudaLaunchKernelFD->getParamDecl(5)->getType());
268
269 mlir::Value gridDim =
270 builder.createAlloca(loc, cir::PointerType::get(dim3Ty), "grid_dim",
272 mlir::Value blockDim =
273 builder.createAlloca(loc, cir::PointerType::get(dim3Ty), "block_dim",
275 mlir::Value sharedMem = builder.createAlloca(
276 loc, cir::PointerType::get(cgm.sizeTy), "shared_mem", cgm.getSizeAlign());
277 mlir::Value stream = builder.createAlloca(
278 loc, cir::PointerType::get(streamTy), "stream", cgm.getPointerAlign());
279
280 cir::FuncOp popConfig = cgm.createRuntimeFunction(
281 cir::FuncType::get({gridDim.getType(), blockDim.getType(),
282 sharedMem.getType(), stream.getType()},
283 cgm.sInt32Ty),
284 addUnderscoredPrefixToName("PopCallConfiguration"));
285 cgf.emitRuntimeCall(loc, popConfig, {gridDim, blockDim, sharedMem, stream});
286
287 // Now emit the call to cudaLaunchKernel
288 // [cuda|hip]Error_t [cuda|hip]LaunchKernel(const void *func, dim3 gridDim,
289 // dim3 blockDim,
290 // void **args, size_t sharedMem,
291 // [cuda|hip]Stream_t stream);
292
293 // We now either pick the function or the stub global for cuda, hip
294 // respectively.
295 mlir::Value kernel = [&]() -> mlir::Value {
296 if (cir::GlobalOp globalOp = llvm::dyn_cast_or_null<cir::GlobalOp>(
297 kernelHandles[fn.getSymName()])) {
298 cir::PointerType kernelTy = cir::PointerType::get(globalOp.getSymType());
299 mlir::Value kernelVal = cir::GetGlobalOp::create(builder, loc, kernelTy,
300 globalOp.getSymName());
301 mlir::Value func = builder.createBitcast(kernelVal, cgm.voidPtrTy);
302 return func;
303 }
304 if (cir::FuncOp funcOp = llvm::dyn_cast_or_null<cir::FuncOp>(
305 kernelHandles[fn.getSymName()])) {
306 cir::PointerType kernelTy =
307 cir::PointerType::get(funcOp.getFunctionType());
308 mlir::Value kernelVal =
309 cir::GetGlobalOp::create(builder, loc, kernelTy, funcOp.getSymName());
310 mlir::Value func = builder.createBitcast(kernelVal, cgm.voidPtrTy);
311 return func;
312 }
313 llvm_unreachable("Expected stub handle to be cir::GlobalOp or FuncOp");
314 }();
315
316 CallArgList launchArgs;
317 launchArgs.add(RValue::get(kernel),
318 cudaLaunchKernelFD->getParamDecl(0)->getType());
319 launchArgs.add(
321 cudaLaunchKernelFD->getParamDecl(1)->getType());
322 launchArgs.add(
324 cudaLaunchKernelFD->getParamDecl(2)->getType());
325 launchArgs.add(RValue::get(kernelArgs),
326 cudaLaunchKernelFD->getParamDecl(3)->getType());
327 launchArgs.add(
328 RValue::get(builder.CIRBaseBuilderTy::createLoad(loc, sharedMem)),
329 cudaLaunchKernelFD->getParamDecl(4)->getType());
330 launchArgs.add(RValue::get(builder.CIRBaseBuilderTy::createLoad(loc, stream)),
331 cudaLaunchKernelFD->getParamDecl(5)->getType());
332
333 mlir::Type launchTy =
334 cgm.getTypes().convertType(cudaLaunchKernelFD->getType());
335 mlir::Operation *cudaKernelLauncherFn = cgm.createRuntimeFunction(
336 cast<cir::FuncType>(launchTy), launchKernelName);
337 const CIRGenFunctionInfo &callInfo =
338 cgm.getTypes().arrangeFunctionDeclaration(cudaLaunchKernelFD);
339 cgf.emitCall(callInfo, CIRGenCallee::forDirect(cudaKernelLauncherFn),
340 ReturnValueSlot(), launchArgs, /*isMustTail=*/false);
341
343 !cgf.getLangOpts().HIP)
344 cgm.errorNYI("MSVC CUDA stub handling");
345}
346
347void CIRGenNVCUDARuntime::emitDeviceStub(CIRGenFunction &cgf, cir::FuncOp fn,
348 FunctionArgList &args) {
349
350 if (auto globalOp =
351 llvm::dyn_cast<cir::GlobalOp>(kernelHandles[fn.getSymName()])) {
352 CIRGenBuilderTy &builder = cgm.getBuilder();
353 mlir::Type fnPtrTy = globalOp.getSymType();
354 auto sym = mlir::FlatSymbolRefAttr::get(fn.getSymNameAttr());
355 auto gv = cir::GlobalViewAttr::get(fnPtrTy, sym);
356
357 globalOp->setAttr("initial_value", gv);
358 globalOp->removeAttr("sym_visibility");
359 globalOp->setAttr("alignment", builder.getI64IntegerAttr(
361 }
362
363 // CUDA 9.0 changed the way to launch kernels.
365 CudaFeature::CUDA_USES_NEW_LAUNCH) ||
366 (cgm.getLangOpts().HIP && cgm.getLangOpts().HIPUseNewLaunchAPI) ||
367 cgm.getLangOpts().OffloadViaLLVM)
368 emitDeviceStubBodyNew(cgf, fn, args);
369 else
370 cgm.errorNYI("Emit Stub Body Legacy");
371}
372
374 return new CIRGenNVCUDARuntime(cgm);
375}
376
377CIRGenNVCUDARuntime::~CIRGenNVCUDARuntime() {}
378
379mlir::Operation *CIRGenNVCUDARuntime::getKernelHandle(cir::FuncOp fn,
380 GlobalDecl gd) {
381
382 // Check if we already have a kernel handle for this function
383 auto it = kernelHandles.find(fn.getSymName());
384 if (it != kernelHandles.end()) {
385 mlir::Operation *oldHandle = it->second;
386 // Here we know that the fn did not change. Return it
387 if (kernelStubs[oldHandle] == fn)
388 return oldHandle;
389
390 // We've found the function name, but F itself has changed, so we need to
391 // update the references.
392 if (cgm.getLangOpts().HIP) {
393 // For HIP compilation the handle itself does not change, so we only need
394 // to update the Stub value.
395 kernelStubs[oldHandle] = fn;
396 return oldHandle;
397 }
398 // For non-HIP compilation, erase the old Stub and fall-through to creating
399 // new entries.
400 kernelStubs.erase(oldHandle);
401 }
402
403 // If not targeting HIP, store the function itself
404 if (!cgm.getLangOpts().HIP) {
405 kernelHandles[fn.getSymName()] = fn;
406 kernelStubs[fn] = fn;
407 return fn;
408 }
409
410 // Create a new CIR global variable to represent the kernel handle
411 CIRGenBuilderTy &builder = cgm.getBuilder();
412 StringRef globalName = cgm.getMangledName(
413 gd.getWithKernelReferenceKind(KernelReferenceKind::Kernel));
414 cir::PointerType fnPtrTy = builder.getPointerTo(fn.getFunctionType());
415 cir::GlobalOp globalOp =
416 cgm.createGlobalOp(fn.getLoc(), globalName, fnPtrTy, /*isConstant=*/true);
417
418 globalOp->setAttr("alignment", builder.getI64IntegerAttr(
420
421 // Store references
422 kernelHandles[fn.getSymName()] = globalOp;
423 kernelStubs[globalOp] = fn;
424
425 return globalOp;
426}
427
428void CIRGenNVCUDARuntime::internalizeDeviceSideVar(
429 const VarDecl *d, cir::GlobalLinkageKind &linkage) {
430 if (cgm.getLangOpts().GPURelocatableDeviceCode)
431 cgm.errorNYI(d->getSourceRange(),
432 "internalizeDeviceSideVar: GPU Relocatable Device Code (RDC)");
433
434 // __shared__ variables are odd. Shadows do get created, but
435 // they are not registered with the CUDA runtime, so they
436 // can't really be used to access their device-side
437 // counterparts. It's not clear yet whether it's nvcc's bug or
438 // a feature, but we've got to do the same for compatibility.
439 if (d->hasAttr<CUDADeviceAttr>() || d->hasAttr<CUDAConstantAttr>() ||
440 d->hasAttr<CUDASharedAttr>()) {
441 linkage = cir::GlobalLinkageKind::InternalLinkage;
442 }
443
446 cgm.errorNYI(d->getSourceRange(),
447 "internalizeDeviceSideVar: CUDA Surface/Texture support");
448}
449
450std::string CIRGenNVCUDARuntime::getDeviceSideName(const NamedDecl *nd) {
451 GlobalDecl gd;
452 // nd could be either a kernel or a variable.
453 if (auto *fd = dyn_cast<FunctionDecl>(nd))
454 gd = GlobalDecl(fd, KernelReferenceKind::Kernel);
455 else
456 gd = GlobalDecl(nd);
457 std::string deviceSideName;
458 MangleContext *mc;
459 if (cgm.getLangOpts().CUDAIsDevice)
460 mc = &cgm.getCXXABI().getMangleContext();
461 else
462 mc = deviceMC.get();
463 if (mc->shouldMangleDeclName(nd)) {
464 SmallString<256> buffer;
465 llvm::raw_svector_ostream out(buffer);
466 mc->mangleName(gd, out);
467 deviceSideName = std::string(out.str());
468 } else
469 deviceSideName = std::string(nd->getIdentifier()->getName());
470
471 // Make unique name for device side static file-scope variable for HIP.
472 if (cgm.getASTContext().shouldExternalize(nd) &&
473 cgm.getLangOpts().GPURelocatableDeviceCode) {
474 SmallString<256> buffer;
475 llvm::raw_svector_ostream out(buffer);
476 out << deviceSideName;
478 deviceSideName = std::string(out.str());
479 }
480 return deviceSideName;
481}
482
483void CIRGenNVCUDARuntime::handleVarRegistration(const VarDecl *vd,
484 cir::GlobalOp var) {
485 if (vd->hasAttr<CUDADeviceAttr>() || vd->hasAttr<CUDAConstantAttr>()) {
486 // Shadow variables and their properties must be registered with CUDA
487 // runtime. Skip Extern global variables, which will be registered in
488 // the TU where they are defined.
489 //
490 // Don't register a C++17 inline variable. The local symbol can be
491 // discarded and referencing a discarded local symbol from outside the
492 // comdat (__cuda_register_globals) is disallowed by the ELF spec.
493 //
494 // HIP managed variables need to be always recorded in device and host
495 // compilations for transformation.
496 //
497 // HIP managed variables and variables in CUDADeviceVarODRUsedByHost are
498 // added to llvm.compiler-used, therefore they are safe to be registered.
499 if ((!vd->hasExternalStorage() && !vd->isInline()) ||
500 cgm.getASTContext().CUDADeviceVarODRUsedByHost.contains(vd) ||
501 vd->hasAttr<HIPManagedAttr>()) {
502 registerDeviceVar(vd, var, !vd->hasDefinition(),
503 vd->hasAttr<CUDAConstantAttr>());
504 }
505 } else if (vd->getType()->isCUDADeviceBuiltinSurfaceType()) {
506 // Builtin surfaces and their template arguments are also registered
507 // with CUDA runtime.
508 if (!vd->hasExternalStorage())
509 registerDeviceSurf(vd, var, !vd->hasDefinition());
510
511 } else if (vd->getType()->isCUDADeviceBuiltinTextureType()) {
512 // Builtin textures and their template arguments are also registered
513 // with CUDA runtime.
514 if (!vd->hasExternalStorage())
515 registerDeviceTex(vd, var, !vd->hasDefinition());
516 }
517}
518
519void CIRGenNVCUDARuntime::handleGlobalReplace(cir::GlobalOp oldGV,
520 cir::GlobalOp newGV) {
521 for (auto &info : deviceVars) {
522 if (info.var == oldGV)
523 info.var = newGV;
524 }
525}
526
527/// Whether this translation unit has anything for the CUDA runtime to register.
528/// These are the same two attributes LoweringPrepare collects to decide whether
529/// to build a module ctor, so both sides answer the question from one source.
530static bool hasEntitiesToRegister(mlir::ModuleOp module) {
531 // A walk, not a scan of the module body, so this stays in agreement with the
532 // recursive walk LoweringPrepare collects them with.
533 return module
534 ->walk([](mlir::Operation *op) {
535 if (op->hasAttr(cir::CUDAKernelNameAttr::getMnemonic()) ||
536 op->hasAttr(cir::CUDAVarRegistrationInfoAttr::getMnemonic()))
537 return mlir::WalkResult::interrupt();
538 return mlir::WalkResult::advance();
539 })
540 .wasInterrupted();
541}
542
543/// Read the device-side fat binary and record its contents on the module as
544/// `cir.cu.device_binary`, for LoweringPrepare to build the fatbin global from.
545///
546/// This mirrors the read in CGNVCUDARuntime::makeModuleCtorFunction, guards
547/// included: nothing is read in a compilation that would build no module
548/// constructor.
549void CIRGenNVCUDARuntime::recordDeviceBinary() {
550 StringRef binaryName = cgm.getCodeGenOpts().OffloadBinaryToEmbedFile;
551 if (binaryName.empty())
552 return;
553
554 const LangOptions &langOpts = cgm.getLangOpts();
555 if ((langOpts.HIP || !langOpts.GPURelocatableDeviceCode) &&
557 return;
558
559 llvm::vfs::FileSystem &fs = cgm.getASTContext()
563 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> binaryOrErr =
564 fs.getBufferForFile(binaryName, /*FileSize=*/-1,
565 /*RequiresNullTerminator=*/false);
566 if (std::error_code ec = binaryOrErr.getError()) {
567 cgm.getDiags().Report(diag::err_cannot_open_file)
568 << binaryName << ec.message();
569 return;
570 }
571
572 // Typed as the fatbin global's array type so LoweringPrepare can use this
573 // attribute as the initializer as-is: attributes are uniqued on {value, type}
574 // and never freed, so building a second, typed copy there would keep the fat
575 // binary in memory twice.
576 StringRef bytes = binaryOrErr.get()->getBuffer();
577 mlir::MLIRContext &ctx = cgm.getMLIRContext();
578 auto charTy = cir::IntType::get(&ctx, cgm.getTarget().getCharWidth(),
579 /*isSigned=*/false);
580 auto fatbinTy = cir::ArrayType::get(charTy, bytes.size());
581 cgm.getModule()->setAttr(cir::CIRDialect::getCUDADeviceBinaryAttrName(),
582 mlir::StringAttr::get(bytes, fatbinTy));
583}
584
585// Uses of a managed variable load its address from a pointer the runtime fills.
586void CIRGenNVCUDARuntime::transformManagedVars() {
587 CIRGenBuilderTy &builder = cgm.getBuilder();
588 mlir::ModuleOp module = cgm.getModule();
589 for (auto &&info : deviceVars) {
590 cir::GlobalOp var = info.var;
591 if (info.flags != cir::CUDADeviceVarKind::Variable ||
592 !info.d->hasAttr<HIPManagedAttr>())
593 continue;
594
595 cir::PointerType varPtrTy =
596 builder.getPointerTo(var.getSymType(), var.getAddrSpaceAttr());
597 mlir::ptr::MemorySpaceAttrInterface managedAS = cir::toCIRAddressSpaceAttr(
598 cgm.getMLIRContext(),
599 cgm.getLangOpts().CUDAIsDevice ? LangAS::cuda_device : LangAS::Default);
600 std::optional<mlir::SymbolTable::UseRange> uses = var.getSymbolUses(module);
601
602 std::string name = var.getSymName().str();
603 // An empty comdat would follow the rename.
604 std::optional<llvm::StringRef> comdat = var.getComdat();
605 if (comdat && comdat->empty())
606 var.setComdat(llvm::StringRef(name));
607 cgm.eraseGlobalSymbol(var);
608 var.setSymName(name + ".managed");
609 cgm.insertGlobalSymbol(var);
610
611 cir::GlobalOp managedVar =
612 cgm.createGlobalOp(var.getLoc(), name, varPtrTy,
613 /*isConstant=*/false, managedAS);
614 managedVar.setLinkage(var.getLinkage());
615 if (!var.isDeclaration())
616 managedVar.setInitialValueAttr(builder.getConstNullPtrAttr(varPtrTy));
617 managedVar.setDsoLocal(var.getDsoLocal());
618 managedVar.setGlobalVisibility(var.getGlobalVisibility());
619 mlir::SymbolTable::setSymbolVisibility(
620 managedVar, mlir::SymbolTable::getSymbolVisibility(var));
621 managedVar->setAttr(
622 cir::CUDAExternallyInitializedAttr::getMnemonic(),
623 cir::CUDAExternallyInitializedAttr::get(&cgm.getMLIRContext()));
624
625 // The uses now name the pointer global.
626 cir::PointerType managedPtrTy =
627 builder.getPointerTo(varPtrTy, managedVar.getAddrSpaceAttr());
628 for (mlir::SymbolTable::SymbolUse use : *uses) {
629 auto getGlobalOp = dyn_cast<cir::GetGlobalOp>(use.getUser());
630 if (!getGlobalOp) {
631 cgm.errorNYI(info.d->getSourceRange(),
632 "transformManagedVars: non-instruction use");
633 continue;
634 }
635 mlir::Value addr = getGlobalOp.getAddr();
636 addr.setType(managedPtrTy);
637 mlir::OpBuilder::InsertionGuard guard(builder);
638 builder.setInsertionPointAfter(getGlobalOp);
639 mlir::Value ld = builder.createAlignedLoad(
640 getGlobalOp.getLoc(), varPtrTy, addr,
641 CharUnits::fromQuantity(var.getAlignment().value_or(1)));
642 addr.replaceAllUsesExcept(ld, ld.getDefiningOp());
643 }
644
645 // The runtime allocates them even if device code never uses them.
646 if (cgm.getLangOpts().CUDAIsDevice && !var.isDeclaration()) {
647 cgm.addCompilerUsedGlobal(var);
648 cgm.addCompilerUsedGlobal(managedVar);
649 }
650 }
651}
652
653void CIRGenNVCUDARuntime::finalizeModule() {
654 transformManagedVars();
655 if (!cgm.getLangOpts().CUDAIsDevice) {
656 recordDeviceBinary();
657 return;
658 }
659
660 // Mark ODR-used device variables as compiler used to prevent them from being
661 // eliminated by optimization. This is necessary for device variables
662 // ODR-used by host functions. Sema correctly marks them as ODR-used no
663 // matter whether they are ODR-used by device or host functions.
664 //
665 // We do not need to do this if the variable has used attribute since it
666 // has already been added.
667 //
668 // Static device variables have been externalized at this point, therefore
669 // variables with private or internal linkage need not be added.
670 for (auto &&info : deviceVars) {
671 auto kind = info.flags;
672 bool isDecl = info.var.isDeclaration();
673 bool isLocalLinkage = cir::isLocalLinkage(info.var.getLinkage());
674 bool isVarOrSurfaceOrTexture = (kind == cir::CUDADeviceVarKind::Variable ||
675 kind == cir::CUDADeviceVarKind::Surface ||
676 kind == cir::CUDADeviceVarKind::Texture);
677 bool isUsed = info.d->isUsed();
678 bool hasUsedAttr = info.d->hasAttr<UsedAttr>();
679 if (!isDecl && !isLocalLinkage && isVarOrSurfaceOrTexture && isUsed &&
680 !hasUsedAttr) {
681 if (auto globalValue = mlir::dyn_cast<cir::CIRGlobalValueInterface>(
682 info.var.getOperation())) {
683 cgm.addCompilerUsedGlobal(globalValue);
684 }
685 }
686 }
687}
Defines the clang::ASTContext interface.
static StringRef bytes(const std::vector< T, Allocator > &v)
Provides definitions for the various language-specific address spaces.
static bool hasEntitiesToRegister(mlir::ModuleOp module)
Whether this translation unit has anything for the CUDA runtime to register.
Defines the clang::FileManager interface and associated types.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
Defines the SourceManager interface.
__CUDA_BUILTIN_VAR __cuda_builtin_blockDim_t blockDim
__CUDA_BUILTIN_VAR __cuda_builtin_gridDim_t gridDim
mlir::TypedAttr getConstNullPtrAttr(mlir::Type t)
mlir::Value createCast(mlir::Location loc, cir::CastKind kind, mlir::Value src, mlir::Type newTy)
cir::PtrStrideOp createPtrStride(mlir::Location loc, mlir::Value base, mlir::Value stride)
cir::PointerType getPointerTo(mlir::Type ty)
mlir::Value createAlloca(mlir::Location loc, cir::PointerType addrType, llvm::StringRef name, mlir::IntegerAttr alignment, mlir::Value dynAllocSize)
mlir::Value createBitcast(mlir::Value src, mlir::Type newTy)
SourceManager & getSourceManager()
Definition ASTContext.h:917
TranslationUnitDecl * getTranslationUnitDecl() const
bool shouldExternalize(const Decl *D) const
Whether a C++ static variable or CUDA/HIP kernel should be externalized.
IdentifierTable & Idents
Definition ASTContext.h:856
llvm::SetVector< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:975
mlir::Value getPointer() const
Definition Address.h:98
cir::LoadOp createAlignedLoad(mlir::Location loc, mlir::Type ty, mlir::Value ptr, llvm::MaybeAlign align)
cir::ConstantOp getConstInt(mlir::Location loc, llvm::APSInt intVal)
clang::MangleContext & getMangleContext()
Gets the mangle context.
static CIRGenCallee forDirect(mlir::Operation *funcPtr, const CIRGenCalleeInfo &abstractInfo=CIRGenCalleeInfo())
Definition CIRGenCall.h:92
CIRGenTypes & getTypes() const
const clang::LangOptions & getLangOpts() const
const clang::Decl * curFuncDecl
Address getAddrOfLocalVar(const clang::VarDecl *vd)
Return the address of a local variable.
mlir::Value emitRuntimeCall(mlir::Location loc, cir::FuncOp callee, llvm::ArrayRef< mlir::Value > args={}, mlir::NamedAttrList attrs={})
RValue emitCall(const CIRGenFunctionInfo &funcInfo, const CIRGenCallee &callee, ReturnValueSlot returnValue, const CallArgList &args, cir::CIRCallOpInterface *callOp, bool isMustTail, SourceRange clangLoc)
This class organizes the cross-function state that is used while generating CIR code.
llvm::StringRef getMangledName(clang::GlobalDecl gd)
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
clang::ASTContext & getASTContext() const
void insertGlobalSymbol(mlir::Operation *op)
CIRGenBuilderTy & getBuilder()
clang::DiagnosticsEngine & getDiags() const
const clang::TargetInfo & getTarget() const
void error(SourceLocation loc, llvm::StringRef error)
Emit a general error that something can't be done.
cir::FuncOp createRuntimeFunction(cir::FuncType ty, llvm::StringRef name, mlir::NamedAttrList extraAttrs={}, bool isLocal=false, bool assumeConvergent=false)
void eraseGlobalSymbol(mlir::Operation *op)
const clang::CodeGenOptions & getCodeGenOpts() const
const clang::LangOptions & getLangOpts() const
void printPostfixForExternalizedDecl(llvm::raw_ostream &os, const Decl *d)
Print the postfix for externalized static variable or kernels for single source offloading languages ...
cir::GlobalOp createGlobalOp(mlir::Location loc, llvm::StringRef name, mlir::Type t, bool isConstant=false, mlir::ptr::MemorySpaceAttrInterface addrSpace={}, mlir::Operation *insertPoint=nullptr)
mlir::ModuleOp getModule() const
void addCompilerUsedGlobal(cir::CIRGlobalValueInterface gv)
Add a global value to the llvmCompilerUsed list.
mlir::MLIRContext & getMLIRContext()
CIRGenCXXABI & getCXXABI() const
const CIRGenFunctionInfo & arrangeFunctionDeclaration(const clang::FunctionDecl *fd)
Free functions are functions that are compatible with an ordinary C function pointer type.
mlir::Type convertType(clang::QualType type)
Convert a Clang type into a mlir::Type.
void add(RValue rvalue, clang::QualType type)
Definition CIRGenCall.h:239
Type for representing both the decl and type of parameters to a function.
Definition CIRGenCall.h:193
static RValue get(mlir::Value v)
Definition CIRGenValue.h:83
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
std::string OffloadBinaryToEmbedFile
Name of file passed with -foffload-include-binary option to forward to offloading runtime back-end fo...
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
SourceLocation getLocation() const
Definition DeclBase.h:447
bool hasAttr() const
Definition DeclBase.h:585
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
llvm::vfs::FileSystem & getVirtualFileSystem() const
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2932
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
GlobalDecl getWithKernelReferenceKind(KernelReferenceKind Kind)
Definition GlobalDecl.h:200
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
GPUDefaultStreamKind GPUDefaultStream
The default stream kind used for HIP kernel launching.
bool shouldMangleDeclName(const NamedDecl *D)
Definition Mangle.cpp:129
void mangleName(GlobalDecl GD, raw_ostream &)
Definition Mangle.cpp:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
FileManager & getFileManager() const
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
unsigned getCharWidth() const
Definition TargetInfo.h:528
const llvm::VersionTuple & getSDKVersion() const
static DeclContext * castToDeclContext(const TranslationUnitDecl *D)
Definition Decl.h:152
bool isCUDADeviceBuiltinSurfaceType() const
Check if the type is the CUDA device builtin surface type.
Definition Type.cpp:5654
bool isCUDADeviceBuiltinTextureType() const
Check if the type is the CUDA device builtin texture type.
Definition Type.cpp:5663
QualType getType() const
Definition Decl.h:724
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2170
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1576
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1239
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2360
static bool isLocalLinkage(GlobalLinkageKind linkage)
Definition CIROpsEnums.h:51
mlir::ptr::MemorySpaceAttrInterface toCIRAddressSpaceAttr(mlir::MLIRContext &ctx, clang::LangAS langAS)
Convert an AST LangAS to the appropriate CIR address space attribute interface.
CIRGenCUDARuntime * createNVCUDARuntime(CIRGenModule &cgm)
constexpr Variable var(Literal L)
Returns the variable of L.
Definition CNFFormula.h:64
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
void info(bool Verbose, unsigned Level, const char *Fmt, Ts &&...Args)
Prints an indented note to stderr when Verbose is set.
Definition Utils.h:57
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
Top level wrappers for InstallAPI frontend operations.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
bool CudaFeatureEnabled(llvm::VersionTuple, CudaFeature)
Definition Cuda.cpp:119
U cast(CodeGen::Address addr)
Definition Address.h:327
clang::CharUnits getPointerAlign() const
clang::CharUnits getSizeAlign() const
cir::PointerType voidPtrTy
void* in address space 0