Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/CodeGen/CGCUDANV.cpp
Line
Count
Source (jump to first uncovered line)
1
//===----- CGCUDANV.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 "CGCUDARuntime.h"
15
#include "CodeGenFunction.h"
16
#include "CodeGenModule.h"
17
#include "clang/AST/Decl.h"
18
#include "clang/Basic/Cuda.h"
19
#include "clang/CodeGen/CodeGenABITypes.h"
20
#include "clang/CodeGen/ConstantInitBuilder.h"
21
#include "llvm/IR/BasicBlock.h"
22
#include "llvm/IR/Constants.h"
23
#include "llvm/IR/DerivedTypes.h"
24
#include "llvm/Support/Format.h"
25
26
using namespace clang;
27
using namespace CodeGen;
28
29
namespace {
30
constexpr unsigned CudaFatMagic = 0x466243b1;
31
constexpr unsigned HIPFatMagic = 0x48495046; // "HIPF"
32
33
class CGNVCUDARuntime : public CGCUDARuntime {
34
35
private:
36
  llvm::IntegerType *IntTy, *SizeTy;
37
  llvm::Type *VoidTy;
38
  llvm::PointerType *CharPtrTy, *VoidPtrTy, *VoidPtrPtrTy;
39
40
  /// Convenience reference to LLVM Context
41
  llvm::LLVMContext &Context;
42
  /// Convenience reference to the current module
43
  llvm::Module &TheModule;
44
  /// Keeps track of kernel launch stubs emitted in this module
45
  struct KernelInfo {
46
    llvm::Function *Kernel;
47
    const Decl *D;
48
  };
49
  llvm::SmallVector<KernelInfo, 16> EmittedKernels;
50
  struct VarInfo {
51
    llvm::GlobalVariable *Var;
52
    const VarDecl *D;
53
    unsigned Flag;
54
  };
55
  llvm::SmallVector<VarInfo, 16> DeviceVars;
56
  /// Keeps track of variable containing handle of GPU binary. Populated by
57
  /// ModuleCtorFunction() and used to create corresponding cleanup calls in
58
  /// ModuleDtorFunction()
59
  llvm::GlobalVariable *GpuBinaryHandle = nullptr;
60
  /// Whether we generate relocatable device code.
61
  bool RelocatableDeviceCode;
62
  /// Mangle context for device.
63
  std::unique_ptr<MangleContext> DeviceMC;
64
65
  llvm::FunctionCallee getSetupArgumentFn() const;
66
  llvm::FunctionCallee getLaunchFn() const;
67
68
  llvm::FunctionType *getRegisterGlobalsFnTy() const;
69
  llvm::FunctionType *getCallbackFnTy() const;
70
  llvm::FunctionType *getRegisterLinkedBinaryFnTy() const;
71
  std::string addPrefixToName(StringRef FuncName) const;
72
  std::string addUnderscoredPrefixToName(StringRef FuncName) const;
73
74
  /// Creates a function to register all kernel stubs generated in this module.
75
  llvm::Function *makeRegisterGlobalsFn();
76
77
  /// Helper function that generates a constant string and returns a pointer to
78
  /// the start of the string.  The result of this function can be used anywhere
79
  /// where the C code specifies const char*.
80
  llvm::Constant *makeConstantString(const std::string &Str,
81
                                     const std::string &Name = "",
82
                                     const std::string &SectionName = "",
83
53
                                     unsigned Alignment = 0) {
84
53
    llvm::Constant *Zeros[] = {llvm::ConstantInt::get(SizeTy, 0),
85
53
                               llvm::ConstantInt::get(SizeTy, 0)};
86
53
    auto ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
87
53
    llvm::GlobalVariable *GV =
88
53
        cast<llvm::GlobalVariable>(ConstStr.getPointer());
89
53
    if (!SectionName.empty()) {
90
10
      GV->setSection(SectionName);
91
10
      // Mark the address as used which make sure that this section isn't
92
10
      // merged and we will really have it in the object file.
93
10
      GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
94
10
    }
95
53
    if (Alignment)
96
10
      GV->setAlignment(Alignment);
97
53
98
53
    return llvm::ConstantExpr::getGetElementPtr(ConstStr.getElementType(),
99
53
                                                ConstStr.getPointer(), Zeros);
100
53
  }
101
102
  /// Helper function that generates an empty dummy function returning void.
103
2
  llvm::Function *makeDummyFunction(llvm::FunctionType *FnTy) {
104
2
    assert(FnTy->getReturnType()->isVoidTy() &&
105
2
           "Can only generate dummy functions returning void!");
106
2
    llvm::Function *DummyFunc = llvm::Function::Create(
107
2
        FnTy, llvm::GlobalValue::InternalLinkage, "dummy", &TheModule);
108
2
109
2
    llvm::BasicBlock *DummyBlock =
110
2
        llvm::BasicBlock::Create(Context, "", DummyFunc);
111
2
    CGBuilderTy FuncBuilder(CGM, Context);
112
2
    FuncBuilder.SetInsertPoint(DummyBlock);
113
2
    FuncBuilder.CreateRetVoid();
114
2
115
2
    return DummyFunc;
116
2
  }
117
118
  void emitDeviceStubBodyLegacy(CodeGenFunction &CGF, FunctionArgList &Args);
119
  void emitDeviceStubBodyNew(CodeGenFunction &CGF, FunctionArgList &Args);
120
  std::string getDeviceSideName(const Decl *ND);
121
122
public:
123
  CGNVCUDARuntime(CodeGenModule &CGM);
124
125
  void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args) override;
126
  void registerDeviceVar(const VarDecl *VD, llvm::GlobalVariable &Var,
127
69
                         unsigned Flags) override {
128
69
    DeviceVars.push_back({&Var, VD, Flags});
129
69
  }
130
131
  /// Creates module constructor function
132
  llvm::Function *makeModuleCtorFunction() override;
133
  /// Creates module destructor function
134
  llvm::Function *makeModuleDtorFunction() override;
135
  /// Construct and return the stub name of a kernel.
136
  std::string getDeviceStubName(llvm::StringRef Name) const override;
137
};
138
139
}
140
141
18
std::string CGNVCUDARuntime::addPrefixToName(StringRef FuncName) const {
142
18
  if (CGM.getLangOpts().HIP)
143
6
    return ((Twine("hip") + Twine(FuncName)).str());
144
12
  return ((Twine("cuda") + Twine(FuncName)).str());
145
12
}
146
std::string
147
84
CGNVCUDARuntime::addUnderscoredPrefixToName(StringRef FuncName) const {
148
84
  if (CGM.getLangOpts().HIP)
149
56
    return ((Twine("__hip") + Twine(FuncName)).str());
150
28
  return ((Twine("__cuda") + Twine(FuncName)).str());
151
28
}
152
153
CGNVCUDARuntime::CGNVCUDARuntime(CodeGenModule &CGM)
154
    : CGCUDARuntime(CGM), Context(CGM.getLLVMContext()),
155
      TheModule(CGM.getModule()),
156
      RelocatableDeviceCode(CGM.getLangOpts().GPURelocatableDeviceCode),
157
      DeviceMC(CGM.getContext().createMangleContext(
158
103
          CGM.getContext().getAuxTargetInfo())) {
159
103
  CodeGen::CodeGenTypes &Types = CGM.getTypes();
160
103
  ASTContext &Ctx = CGM.getContext();
161
103
162
103
  IntTy = CGM.IntTy;
163
103
  SizeTy = CGM.SizeTy;
164
103
  VoidTy = CGM.VoidTy;
165
103
166
103
  CharPtrTy = llvm::PointerType::getUnqual(Types.ConvertType(Ctx.CharTy));
167
103
  VoidPtrTy = cast<llvm::PointerType>(Types.ConvertType(Ctx.VoidPtrTy));
168
103
  VoidPtrPtrTy = VoidPtrTy->getPointerTo();
169
103
}
170
171
18
llvm::FunctionCallee CGNVCUDARuntime::getSetupArgumentFn() const {
172
18
  // cudaError_t cudaSetupArgument(void *, size_t, size_t)
173
18
  llvm::Type *Params[] = {VoidPtrTy, SizeTy, SizeTy};
174
18
  return CGM.CreateRuntimeFunction(
175
18
      llvm::FunctionType::get(IntTy, Params, false),
176
18
      addPrefixToName("SetupArgument"));
177
18
}
178
179
18
llvm::FunctionCallee CGNVCUDARuntime::getLaunchFn() const {
180
18
  if (CGM.getLangOpts().HIP) {
181
6
    // hipError_t hipLaunchByPtr(char *);
182
6
    return CGM.CreateRuntimeFunction(
183
6
        llvm::FunctionType::get(IntTy, CharPtrTy, false), "hipLaunchByPtr");
184
12
  } else {
185
12
    // cudaError_t cudaLaunch(char *);
186
12
    return CGM.CreateRuntimeFunction(
187
12
        llvm::FunctionType::get(IntTy, CharPtrTy, false), "cudaLaunch");
188
12
  }
189
18
}
190
191
13
llvm::FunctionType *CGNVCUDARuntime::getRegisterGlobalsFnTy() const {
192
13
  return llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false);
193
13
}
194
195
4
llvm::FunctionType *CGNVCUDARuntime::getCallbackFnTy() const {
196
4
  return llvm::FunctionType::get(VoidTy, VoidPtrTy, false);
197
4
}
198
199
2
llvm::FunctionType *CGNVCUDARuntime::getRegisterLinkedBinaryFnTy() const {
200
2
  auto CallbackFnTy = getCallbackFnTy();
201
2
  auto RegisterGlobalsFnTy = getRegisterGlobalsFnTy();
202
2
  llvm::Type *Params[] = {RegisterGlobalsFnTy->getPointerTo(), VoidPtrTy,
203
2
                          VoidPtrTy, CallbackFnTy->getPointerTo()};
204
2
  return llvm::FunctionType::get(VoidTy, Params, false);
205
2
}
206
207
43
std::string CGNVCUDARuntime::getDeviceSideName(const Decl *D) {
208
43
  auto *ND = cast<const NamedDecl>(D);
209
43
  std::string DeviceSideName;
210
43
  if (DeviceMC->shouldMangleDeclName(ND)) {
211
10
    SmallString<256> Buffer;
212
10
    llvm::raw_svector_ostream Out(Buffer);
213
10
    DeviceMC->mangleName(ND, Out);
214
10
    DeviceSideName = Out.str();
215
10
  } else
216
33
    DeviceSideName = ND->getIdentifier()->getName();
217
43
  return DeviceSideName;
218
43
}
219
220
void CGNVCUDARuntime::emitDeviceStub(CodeGenFunction &CGF,
221
22
                                     FunctionArgList &Args) {
222
22
  // Ensure either we have different ABIs between host and device compilations,
223
22
  // says host compilation following MSVC ABI but device compilation follows
224
22
  // Itanium C++ ABI or, if they follow the same ABI, kernel names after
225
22
  // mangling should be the same after name stubbing. The later checking is
226
22
  // very important as the device kernel name being mangled in host-compilation
227
22
  // is used to resolve the device binaries to be executed. Inconsistent naming
228
22
  // result in undefined behavior. Even though we cannot check that naming
229
22
  // directly between host- and device-compilations, the host- and
230
22
  // device-mangling in host compilation could help catching certain ones.
231
22
  assert((CGF.CGM.getContext().getAuxTargetInfo() &&
232
22
          (CGF.CGM.getContext().getAuxTargetInfo()->getCXXABI() !=
233
22
           CGF.CGM.getContext().getTargetInfo().getCXXABI())) ||
234
22
         getDeviceStubName(getDeviceSideName(CGF.CurFuncDecl)) ==
235
22
             CGF.CurFn->getName());
236
22
237
22
  EmittedKernels.push_back({CGF.CurFn, CGF.CurFuncDecl});
238
22
  if (CudaFeatureEnabled(CGM.getTarget().getSDKVersion(),
239
22
                         CudaFeature::CUDA_USES_NEW_LAUNCH))
240
4
    emitDeviceStubBodyNew(CGF, Args);
241
18
  else
242
18
    emitDeviceStubBodyLegacy(CGF, Args);
243
22
}
244
245
// CUDA 9.0+ uses new way to launch kernels. Parameters are packed in a local
246
// array and kernels are launched using cudaLaunchKernel().
247
void CGNVCUDARuntime::emitDeviceStubBodyNew(CodeGenFunction &CGF,
248
4
                                            FunctionArgList &Args) {
249
4
  // Build the shadow stack entry at the very start of the function.
250
4
251
4
  // Calculate amount of space we will need for all arguments.  If we have no
252
4
  // args, allocate a single pointer so we still have a valid pointer to the
253
4
  // argument array that we can pass to runtime, even if it will be unused.
254
4
  Address KernelArgs = CGF.CreateTempAlloca(
255
4
      VoidPtrTy, CharUnits::fromQuantity(16), "kernel_args",
256
4
      llvm::ConstantInt::get(SizeTy, std::max<size_t>(1, Args.size())));
257
4
  // Store pointers to the arguments in a locally allocated launch_args.
258
14
  for (unsigned i = 0; i < Args.size(); 
++i10
) {
259
10
    llvm::Value* VarPtr = CGF.GetAddrOfLocalVar(Args[i]).getPointer();
260
10
    llvm::Value *VoidVarPtr = CGF.Builder.CreatePointerCast(VarPtr, VoidPtrTy);
261
10
    CGF.Builder.CreateDefaultAlignedStore(
262
10
        VoidVarPtr, CGF.Builder.CreateConstGEP1_32(KernelArgs.getPointer(), i));
263
10
  }
264
4
265
4
  llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
266
4
267
4
  // Lookup cudaLaunchKernel function.
268
4
  // cudaError_t cudaLaunchKernel(const void *func, dim3 gridDim, dim3 blockDim,
269
4
  //                              void **args, size_t sharedMem,
270
4
  //                              cudaStream_t stream);
271
4
  TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
272
4
  DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
273
4
  IdentifierInfo &cudaLaunchKernelII =
274
4
      CGM.getContext().Idents.get("cudaLaunchKernel");
275
4
  FunctionDecl *cudaLaunchKernelFD = nullptr;
276
4
  for (const auto &Result : DC->lookup(&cudaLaunchKernelII)) {
277
4
    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Result))
278
4
      cudaLaunchKernelFD = FD;
279
4
  }
280
4
281
4
  if (cudaLaunchKernelFD == nullptr) {
282
0
    CGM.Error(CGF.CurFuncDecl->getLocation(),
283
0
              "Can't find declaration for cudaLaunchKernel()");
284
0
    return;
285
0
  }
286
4
  // Create temporary dim3 grid_dim, block_dim.
287
4
  ParmVarDecl *GridDimParam = cudaLaunchKernelFD->getParamDecl(1);
288
4
  QualType Dim3Ty = GridDimParam->getType();
289
4
  Address GridDim =
290
4
      CGF.CreateMemTemp(Dim3Ty, CharUnits::fromQuantity(8), "grid_dim");
291
4
  Address BlockDim =
292
4
      CGF.CreateMemTemp(Dim3Ty, CharUnits::fromQuantity(8), "block_dim");
293
4
  Address ShmemSize =
294
4
      CGF.CreateTempAlloca(SizeTy, CGM.getSizeAlign(), "shmem_size");
295
4
  Address Stream =
296
4
      CGF.CreateTempAlloca(VoidPtrTy, CGM.getPointerAlign(), "stream");
297
4
  llvm::FunctionCallee cudaPopConfigFn = CGM.CreateRuntimeFunction(
298
4
      llvm::FunctionType::get(IntTy,
299
4
                              {/*gridDim=*/GridDim.getType(),
300
4
                               /*blockDim=*/BlockDim.getType(),
301
4
                               /*ShmemSize=*/ShmemSize.getType(),
302
4
                               /*Stream=*/Stream.getType()},
303
4
                              /*isVarArg=*/false),
304
4
      "__cudaPopCallConfiguration");
305
4
306
4
  CGF.EmitRuntimeCallOrInvoke(cudaPopConfigFn,
307
4
                              {GridDim.getPointer(), BlockDim.getPointer(),
308
4
                               ShmemSize.getPointer(), Stream.getPointer()});
309
4
310
4
  // Emit the call to cudaLaunch
311
4
  llvm::Value *Kernel = CGF.Builder.CreatePointerCast(CGF.CurFn, VoidPtrTy);
312
4
  CallArgList LaunchKernelArgs;
313
4
  LaunchKernelArgs.add(RValue::get(Kernel),
314
4
                       cudaLaunchKernelFD->getParamDecl(0)->getType());
315
4
  LaunchKernelArgs.add(RValue::getAggregate(GridDim), Dim3Ty);
316
4
  LaunchKernelArgs.add(RValue::getAggregate(BlockDim), Dim3Ty);
317
4
  LaunchKernelArgs.add(RValue::get(KernelArgs.getPointer()),
318
4
                       cudaLaunchKernelFD->getParamDecl(3)->getType());
319
4
  LaunchKernelArgs.add(RValue::get(CGF.Builder.CreateLoad(ShmemSize)),
320
4
                       cudaLaunchKernelFD->getParamDecl(4)->getType());
321
4
  LaunchKernelArgs.add(RValue::get(CGF.Builder.CreateLoad(Stream)),
322
4
                       cudaLaunchKernelFD->getParamDecl(5)->getType());
323
4
324
4
  QualType QT = cudaLaunchKernelFD->getType();
325
4
  QualType CQT = QT.getCanonicalType();
326
4
  llvm::Type *Ty = CGM.getTypes().ConvertType(CQT);
327
4
  llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(Ty);
328
4
329
4
  const CGFunctionInfo &FI =
330
4
      CGM.getTypes().arrangeFunctionDeclaration(cudaLaunchKernelFD);
331
4
  llvm::FunctionCallee cudaLaunchKernelFn =
332
4
      CGM.CreateRuntimeFunction(FTy, "cudaLaunchKernel");
333
4
  CGF.EmitCall(FI, CGCallee::forDirect(cudaLaunchKernelFn), ReturnValueSlot(),
334
4
               LaunchKernelArgs);
335
4
  CGF.EmitBranch(EndBlock);
336
4
337
4
  CGF.EmitBlock(EndBlock);
338
4
}
339
340
void CGNVCUDARuntime::emitDeviceStubBodyLegacy(CodeGenFunction &CGF,
341
18
                                               FunctionArgList &Args) {
342
18
  // Emit a call to cudaSetupArgument for each arg in Args.
343
18
  llvm::FunctionCallee cudaSetupArgFn = getSetupArgumentFn();
344
18
  llvm::BasicBlock *EndBlock = CGF.createBasicBlock("setup.end");
345
18
  CharUnits Offset = CharUnits::Zero();
346
26
  for (const VarDecl *A : Args) {
347
26
    CharUnits TyWidth, TyAlign;
348
26
    std::tie(TyWidth, TyAlign) =
349
26
        CGM.getContext().getTypeInfoInChars(A->getType());
350
26
    Offset = Offset.alignTo(TyAlign);
351
26
    llvm::Value *Args[] = {
352
26
        CGF.Builder.CreatePointerCast(CGF.GetAddrOfLocalVar(A).getPointer(),
353
26
                                      VoidPtrTy),
354
26
        llvm::ConstantInt::get(SizeTy, TyWidth.getQuantity()),
355
26
        llvm::ConstantInt::get(SizeTy, Offset.getQuantity()),
356
26
    };
357
26
    llvm::CallBase *CB = CGF.EmitRuntimeCallOrInvoke(cudaSetupArgFn, Args);
358
26
    llvm::Constant *Zero = llvm::ConstantInt::get(IntTy, 0);
359
26
    llvm::Value *CBZero = CGF.Builder.CreateICmpEQ(CB, Zero);
360
26
    llvm::BasicBlock *NextBlock = CGF.createBasicBlock("setup.next");
361
26
    CGF.Builder.CreateCondBr(CBZero, NextBlock, EndBlock);
362
26
    CGF.EmitBlock(NextBlock);
363
26
    Offset += TyWidth;
364
26
  }
365
18
366
18
  // Emit the call to cudaLaunch
367
18
  llvm::FunctionCallee cudaLaunchFn = getLaunchFn();
368
18
  llvm::Value *Arg = CGF.Builder.CreatePointerCast(CGF.CurFn, CharPtrTy);
369
18
  CGF.EmitRuntimeCallOrInvoke(cudaLaunchFn, Arg);
370
18
  CGF.EmitBranch(EndBlock);
371
18
372
18
  CGF.EmitBlock(EndBlock);
373
18
}
374
375
/// Creates a function that sets up state on the host side for CUDA objects that
376
/// have a presence on both the host and device sides. Specifically, registers
377
/// the host side of kernel functions and device global variables with the CUDA
378
/// runtime.
379
/// \code
380
/// void __cuda_register_globals(void** GpuBinaryHandle) {
381
///    __cudaRegisterFunction(GpuBinaryHandle,Kernel0,...);
382
///    ...
383
///    __cudaRegisterFunction(GpuBinaryHandle,KernelM,...);
384
///    __cudaRegisterVar(GpuBinaryHandle, GlobalVar0, ...);
385
///    ...
386
///    __cudaRegisterVar(GpuBinaryHandle, GlobalVarN, ...);
387
/// }
388
/// \endcode
389
11
llvm::Function *CGNVCUDARuntime::makeRegisterGlobalsFn() {
390
11
  // No need to register anything
391
11
  if (EmittedKernels.empty() && 
DeviceVars.empty()1
)
392
0
    return nullptr;
393
11
394
11
  llvm::Function *RegisterKernelsFunc = llvm::Function::Create(
395
11
      getRegisterGlobalsFnTy(), llvm::GlobalValue::InternalLinkage,
396
11
      addUnderscoredPrefixToName("_register_globals"), &TheModule);
397
11
  llvm::BasicBlock *EntryBB =
398
11
      llvm::BasicBlock::Create(Context, "entry", RegisterKernelsFunc);
399
11
  CGBuilderTy Builder(CGM, Context);
400
11
  Builder.SetInsertPoint(EntryBB);
401
11
402
11
  // void __cudaRegisterFunction(void **, const char *, char *, const char *,
403
11
  //                             int, uint3*, uint3*, dim3*, dim3*, int*)
404
11
  llvm::Type *RegisterFuncParams[] = {
405
11
      VoidPtrPtrTy, CharPtrTy, CharPtrTy, CharPtrTy, IntTy,
406
11
      VoidPtrTy,    VoidPtrTy, VoidPtrTy, VoidPtrTy, IntTy->getPointerTo()};
407
11
  llvm::FunctionCallee RegisterFunc = CGM.CreateRuntimeFunction(
408
11
      llvm::FunctionType::get(IntTy, RegisterFuncParams, false),
409
11
      addUnderscoredPrefixToName("RegisterFunction"));
410
11
411
11
  // Extract GpuBinaryHandle passed as the first argument passed to
412
11
  // __cuda_register_globals() and generate __cudaRegisterFunction() call for
413
11
  // each emitted kernel.
414
11
  llvm::Argument &GpuBinaryHandlePtr = *RegisterKernelsFunc->arg_begin();
415
11
  for (auto &&I : EmittedKernels) {
416
10
    llvm::Constant *KernelName = makeConstantString(getDeviceSideName(I.D));
417
10
    llvm::Constant *NullPtr = llvm::ConstantPointerNull::get(VoidPtrTy);
418
10
    llvm::Value *Args[] = {
419
10
        &GpuBinaryHandlePtr,
420
10
        Builder.CreateBitCast(I.Kernel, VoidPtrTy),
421
10
        KernelName,
422
10
        KernelName,
423
10
        llvm::ConstantInt::get(IntTy, -1),
424
10
        NullPtr,
425
10
        NullPtr,
426
10
        NullPtr,
427
10
        NullPtr,
428
10
        llvm::ConstantPointerNull::get(IntTy->getPointerTo())};
429
10
    Builder.CreateCall(RegisterFunc, Args);
430
10
  }
431
11
432
11
  // void __cudaRegisterVar(void **, char *, char *, const char *,
433
11
  //                        int, int, int, int)
434
11
  llvm::Type *RegisterVarParams[] = {VoidPtrPtrTy, CharPtrTy, CharPtrTy,
435
11
                                     CharPtrTy,    IntTy,     IntTy,
436
11
                                     IntTy,        IntTy};
437
11
  llvm::FunctionCallee RegisterVar = CGM.CreateRuntimeFunction(
438
11
      llvm::FunctionType::get(IntTy, RegisterVarParams, false),
439
11
      addUnderscoredPrefixToName("RegisterVar"));
440
33
  for (auto &&Info : DeviceVars) {
441
33
    llvm::GlobalVariable *Var = Info.Var;
442
33
    unsigned Flags = Info.Flag;
443
33
    llvm::Constant *VarName = makeConstantString(getDeviceSideName(Info.D));
444
33
    uint64_t VarSize =
445
33
        CGM.getDataLayout().getTypeAllocSize(Var->getValueType());
446
33
    llvm::Value *Args[] = {
447
33
        &GpuBinaryHandlePtr,
448
33
        Builder.CreateBitCast(Var, VoidPtrTy),
449
33
        VarName,
450
33
        VarName,
451
33
        llvm::ConstantInt::get(IntTy, (Flags & ExternDeviceVar) ? 
10
: 0),
452
33
        llvm::ConstantInt::get(IntTy, VarSize),
453
33
        llvm::ConstantInt::get(IntTy, (Flags & ConstantDeviceVar) ? 
116
:
017
),
454
33
        llvm::ConstantInt::get(IntTy, 0)};
455
33
    Builder.CreateCall(RegisterVar, Args);
456
33
  }
457
11
458
11
  Builder.CreateRetVoid();
459
11
  return RegisterKernelsFunc;
460
11
}
461
462
/// Creates a global constructor function for the module:
463
///
464
/// For CUDA:
465
/// \code
466
/// void __cuda_module_ctor(void*) {
467
///     Handle = __cudaRegisterFatBinary(GpuBinaryBlob);
468
///     __cuda_register_globals(Handle);
469
/// }
470
/// \endcode
471
///
472
/// For HIP:
473
/// \code
474
/// void __hip_module_ctor(void*) {
475
///     if (__hip_gpubin_handle == 0) {
476
///         __hip_gpubin_handle  = __hipRegisterFatBinary(GpuBinaryBlob);
477
///         __hip_register_globals(__hip_gpubin_handle);
478
///     }
479
/// }
480
/// \endcode
481
32
llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
482
32
  bool IsHIP = CGM.getLangOpts().HIP;
483
32
  bool IsCUDA = CGM.getLangOpts().CUDA;
484
32
  // No need to generate ctors/dtors if there is no GPU binary.
485
32
  StringRef CudaGpuBinaryFileName = CGM.getCodeGenOpts().CudaGpuBinaryFileName;
486
32
  if (CudaGpuBinaryFileName.empty() && 
!IsHIP21
)
487
17
    return nullptr;
488
15
  if ((IsHIP || 
(6
IsCUDA6
&&
!RelocatableDeviceCode6
)) &&
EmittedKernels.empty()13
&&
489
15
      
DeviceVars.empty()5
)
490
4
    return nullptr;
491
11
492
11
  // void __{cuda|hip}_register_globals(void* handle);
493
11
  llvm::Function *RegisterGlobalsFunc = makeRegisterGlobalsFn();
494
11
  // We always need a function to pass in as callback. Create a dummy
495
11
  // implementation if we don't need to register anything.
496
11
  if (RelocatableDeviceCode && 
!RegisterGlobalsFunc3
)
497
0
    RegisterGlobalsFunc = makeDummyFunction(getRegisterGlobalsFnTy());
498
11
499
11
  // void ** __{cuda|hip}RegisterFatBinary(void *);
500
11
  llvm::FunctionCallee RegisterFatbinFunc = CGM.CreateRuntimeFunction(
501
11
      llvm::FunctionType::get(VoidPtrPtrTy, VoidPtrTy, false),
502
11
      addUnderscoredPrefixToName("RegisterFatBinary"));
503
11
  // struct { int magic, int version, void * gpu_binary, void * dont_care };
504
11
  llvm::StructType *FatbinWrapperTy =
505
11
      llvm::StructType::get(IntTy, IntTy, VoidPtrTy, VoidPtrTy);
506
11
507
11
  // Register GPU binary with the CUDA runtime, store returned handle in a
508
11
  // global variable and save a reference in GpuBinaryHandle to be cleaned up
509
11
  // in destructor on exit. Then associate all known kernels with the GPU binary
510
11
  // handle so CUDA runtime can figure out what to call on the GPU side.
511
11
  std::unique_ptr<llvm::MemoryBuffer> CudaGpuBinary = nullptr;
512
11
  if (!CudaGpuBinaryFileName.empty()) {
513
8
    llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CudaGpuBinaryOrErr =
514
8
        llvm::MemoryBuffer::getFileOrSTDIN(CudaGpuBinaryFileName);
515
8
    if (std::error_code EC = CudaGpuBinaryOrErr.getError()) {
516
0
      CGM.getDiags().Report(diag::err_cannot_open_file)
517
0
          << CudaGpuBinaryFileName << EC.message();
518
0
      return nullptr;
519
0
    }
520
8
    CudaGpuBinary = std::move(CudaGpuBinaryOrErr.get());
521
8
  }
522
11
523
11
  llvm::Function *ModuleCtorFunc = llvm::Function::Create(
524
11
      llvm::FunctionType::get(VoidTy, VoidPtrTy, false),
525
11
      llvm::GlobalValue::InternalLinkage,
526
11
      addUnderscoredPrefixToName("_module_ctor"), &TheModule);
527
11
  llvm::BasicBlock *CtorEntryBB =
528
11
      llvm::BasicBlock::Create(Context, "entry", ModuleCtorFunc);
529
11
  CGBuilderTy CtorBuilder(CGM, Context);
530
11
531
11
  CtorBuilder.SetInsertPoint(CtorEntryBB);
532
11
533
11
  const char *FatbinConstantName;
534
11
  const char *FatbinSectionName;
535
11
  const char *ModuleIDSectionName;
536
11
  StringRef ModuleIDPrefix;
537
11
  llvm::Constant *FatBinStr;
538
11
  unsigned FatMagic;
539
11
  if (IsHIP) {
540
7
    FatbinConstantName = ".hip_fatbin";
541
7
    FatbinSectionName = ".hipFatBinSegment";
542
7
543
7
    ModuleIDSectionName = "__hip_module_id";
544
7
    ModuleIDPrefix = "__hip_";
545
7
546
7
    if (CudaGpuBinary) {
547
4
      // If fatbin is available from early finalization, create a string
548
4
      // literal containing the fat binary loaded from the given file.
549
4
      FatBinStr = makeConstantString(CudaGpuBinary->getBuffer(), "",
550
4
                                     FatbinConstantName, 8);
551
4
    } else {
552
3
      // If fatbin is not available, create an external symbol
553
3
      // __hip_fatbin in section .hip_fatbin. The external symbol is supposed
554
3
      // to contain the fat binary but will be populated somewhere else,
555
3
      // e.g. by lld through link script.
556
3
      FatBinStr = new llvm::GlobalVariable(
557
3
        CGM.getModule(), CGM.Int8Ty,
558
3
        /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr,
559
3
        "__hip_fatbin", nullptr,
560
3
        llvm::GlobalVariable::NotThreadLocal);
561
3
      cast<llvm::GlobalVariable>(FatBinStr)->setSection(FatbinConstantName);
562
3
    }
563
7
564
7
    FatMagic = HIPFatMagic;
565
7
  } else {
566
4
    if (RelocatableDeviceCode)
567
2
      FatbinConstantName = CGM.getTriple().isMacOSX()
568
2
                               ? 
"__NV_CUDA,__nv_relfatbin"0
569
2
                               : "__nv_relfatbin";
570
2
    else
571
2
      FatbinConstantName =
572
2
          CGM.getTriple().isMacOSX() ? 
"__NV_CUDA,__nv_fatbin"0
: ".nv_fatbin";
573
4
    // NVIDIA's cuobjdump looks for fatbins in this section.
574
4
    FatbinSectionName =
575
4
        CGM.getTriple().isMacOSX() ? 
"__NV_CUDA,__fatbin"0
: ".nvFatBinSegment";
576
4
577
4
    ModuleIDSectionName = CGM.getTriple().isMacOSX()
578
4
                              ? 
"__NV_CUDA,__nv_module_id"0
579
4
                              : "__nv_module_id";
580
4
    ModuleIDPrefix = "__nv_";
581
4
582
4
    // For CUDA, create a string literal containing the fat binary loaded from
583
4
    // the given file.
584
4
    FatBinStr = makeConstantString(CudaGpuBinary->getBuffer(), "",
585
4
                                   FatbinConstantName, 8);
586
4
    FatMagic = CudaFatMagic;
587
4
  }
588
11
589
11
  // Create initialized wrapper structure that points to the loaded GPU binary
590
11
  ConstantInitBuilder Builder(CGM);
591
11
  auto Values = Builder.beginStruct(FatbinWrapperTy);
592
11
  // Fatbin wrapper magic.
593
11
  Values.addInt(IntTy, FatMagic);
594
11
  // Fatbin version.
595
11
  Values.addInt(IntTy, 1);
596
11
  // Data.
597
11
  Values.add(FatBinStr);
598
11
  // Unused in fatbin v1.
599
11
  Values.add(llvm::ConstantPointerNull::get(VoidPtrTy));
600
11
  llvm::GlobalVariable *FatbinWrapper = Values.finishAndCreateGlobal(
601
11
      addUnderscoredPrefixToName("_fatbin_wrapper"), CGM.getPointerAlign(),
602
11
      /*constant*/ true);
603
11
  FatbinWrapper->setSection(FatbinSectionName);
604
11
605
11
  // There is only one HIP fat binary per linked module, however there are
606
11
  // multiple constructor functions. Make sure the fat binary is registered
607
11
  // only once. The constructor functions are executed by the dynamic loader
608
11
  // before the program gains control. The dynamic loader cannot execute the
609
11
  // constructor functions concurrently since doing that would not guarantee
610
11
  // thread safety of the loaded program. Therefore we can assume sequential
611
11
  // execution of constructor functions here.
612
11
  if (IsHIP) {
613
7
    auto Linkage = CudaGpuBinary ? 
llvm::GlobalValue::InternalLinkage4
:
614
7
        
llvm::GlobalValue::LinkOnceAnyLinkage3
;
615
7
    llvm::BasicBlock *IfBlock =
616
7
        llvm::BasicBlock::Create(Context, "if", ModuleCtorFunc);
617
7
    llvm::BasicBlock *ExitBlock =
618
7
        llvm::BasicBlock::Create(Context, "exit", ModuleCtorFunc);
619
7
    // The name, size, and initialization pattern of this variable is part
620
7
    // of HIP ABI.
621
7
    GpuBinaryHandle = new llvm::GlobalVariable(
622
7
        TheModule, VoidPtrPtrTy, /*isConstant=*/false,
623
7
        Linkage,
624
7
        /*Initializer=*/llvm::ConstantPointerNull::get(VoidPtrPtrTy),
625
7
        "__hip_gpubin_handle");
626
7
    GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getQuantity());
627
7
    // Prevent the weak symbol in different shared libraries being merged.
628
7
    if (Linkage != llvm::GlobalValue::InternalLinkage)
629
3
      GpuBinaryHandle->setVisibility(llvm::GlobalValue::HiddenVisibility);
630
7
    Address GpuBinaryAddr(
631
7
        GpuBinaryHandle,
632
7
        CharUnits::fromQuantity(GpuBinaryHandle->getAlignment()));
633
7
    {
634
7
      auto HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
635
7
      llvm::Constant *Zero =
636
7
          llvm::Constant::getNullValue(HandleValue->getType());
637
7
      llvm::Value *EQZero = CtorBuilder.CreateICmpEQ(HandleValue, Zero);
638
7
      CtorBuilder.CreateCondBr(EQZero, IfBlock, ExitBlock);
639
7
    }
640
7
    {
641
7
      CtorBuilder.SetInsertPoint(IfBlock);
642
7
      // GpuBinaryHandle = __hipRegisterFatBinary(&FatbinWrapper);
643
7
      llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
644
7
          RegisterFatbinFunc,
645
7
          CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
646
7
      CtorBuilder.CreateStore(RegisterFatbinCall, GpuBinaryAddr);
647
7
      CtorBuilder.CreateBr(ExitBlock);
648
7
    }
649
7
    {
650
7
      CtorBuilder.SetInsertPoint(ExitBlock);
651
7
      // Call __hip_register_globals(GpuBinaryHandle);
652
7
      if (RegisterGlobalsFunc) {
653
7
        auto HandleValue = CtorBuilder.CreateLoad(GpuBinaryAddr);
654
7
        CtorBuilder.CreateCall(RegisterGlobalsFunc, HandleValue);
655
7
      }
656
7
    }
657
7
  } else 
if (4
!RelocatableDeviceCode4
) {
658
2
    // Register binary with CUDA runtime. This is substantially different in
659
2
    // default mode vs. separate compilation!
660
2
    // GpuBinaryHandle = __cudaRegisterFatBinary(&FatbinWrapper);
661
2
    llvm::CallInst *RegisterFatbinCall = CtorBuilder.CreateCall(
662
2
        RegisterFatbinFunc,
663
2
        CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy));
664
2
    GpuBinaryHandle = new llvm::GlobalVariable(
665
2
        TheModule, VoidPtrPtrTy, false, llvm::GlobalValue::InternalLinkage,
666
2
        llvm::ConstantPointerNull::get(VoidPtrPtrTy), "__cuda_gpubin_handle");
667
2
    GpuBinaryHandle->setAlignment(CGM.getPointerAlign().getQuantity());
668
2
    CtorBuilder.CreateAlignedStore(RegisterFatbinCall, GpuBinaryHandle,
669
2
                                   CGM.getPointerAlign());
670
2
671
2
    // Call __cuda_register_globals(GpuBinaryHandle);
672
2
    if (RegisterGlobalsFunc)
673
2
      CtorBuilder.CreateCall(RegisterGlobalsFunc, RegisterFatbinCall);
674
2
675
2
    // Call __cudaRegisterFatBinaryEnd(Handle) if this CUDA version needs it.
676
2
    if (CudaFeatureEnabled(CGM.getTarget().getSDKVersion(),
677
2
                           CudaFeature::CUDA_USES_FATBIN_REGISTER_END)) {
678
0
      // void __cudaRegisterFatBinaryEnd(void **);
679
0
      llvm::FunctionCallee RegisterFatbinEndFunc = CGM.CreateRuntimeFunction(
680
0
          llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false),
681
0
          "__cudaRegisterFatBinaryEnd");
682
0
      CtorBuilder.CreateCall(RegisterFatbinEndFunc, RegisterFatbinCall);
683
0
    }
684
2
  } else {
685
2
    // Generate a unique module ID.
686
2
    SmallString<64> ModuleID;
687
2
    llvm::raw_svector_ostream OS(ModuleID);
688
2
    OS << ModuleIDPrefix << llvm::format("%" PRIx64, FatbinWrapper->getGUID());
689
2
    llvm::Constant *ModuleIDConstant =
690
2
        makeConstantString(ModuleID.str(), "", ModuleIDSectionName, 32);
691
2
692
2
    // Create an alias for the FatbinWrapper that nvcc will look for.
693
2
    llvm::GlobalAlias::create(llvm::GlobalValue::ExternalLinkage,
694
2
                              Twine("__fatbinwrap") + ModuleID, FatbinWrapper);
695
2
696
2
    // void __cudaRegisterLinkedBinary%ModuleID%(void (*)(void *), void *,
697
2
    // void *, void (*)(void **))
698
2
    SmallString<128> RegisterLinkedBinaryName("__cudaRegisterLinkedBinary");
699
2
    RegisterLinkedBinaryName += ModuleID;
700
2
    llvm::FunctionCallee RegisterLinkedBinaryFunc = CGM.CreateRuntimeFunction(
701
2
        getRegisterLinkedBinaryFnTy(), RegisterLinkedBinaryName);
702
2
703
2
    assert(RegisterGlobalsFunc && "Expecting at least dummy function!");
704
2
    llvm::Value *Args[] = {RegisterGlobalsFunc,
705
2
                           CtorBuilder.CreateBitCast(FatbinWrapper, VoidPtrTy),
706
2
                           ModuleIDConstant,
707
2
                           makeDummyFunction(getCallbackFnTy())};
708
2
    CtorBuilder.CreateCall(RegisterLinkedBinaryFunc, Args);
709
2
  }
710
11
711
11
  // Create destructor and register it with atexit() the way NVCC does it. Doing
712
11
  // it during regular destructor phase worked in CUDA before 9.2 but results in
713
11
  // double-free in 9.2.
714
11
  if (llvm::Function *CleanupFn = makeModuleDtorFunction()) {
715
9
    // extern "C" int atexit(void (*f)(void));
716
9
    llvm::FunctionType *AtExitTy =
717
9
        llvm::FunctionType::get(IntTy, CleanupFn->getType(), false);
718
9
    llvm::FunctionCallee AtExitFunc =
719
9
        CGM.CreateRuntimeFunction(AtExitTy, "atexit", llvm::AttributeList(),
720
9
                                  /*Local=*/true);
721
9
    CtorBuilder.CreateCall(AtExitFunc, CleanupFn);
722
9
  }
723
11
724
11
  CtorBuilder.CreateRetVoid();
725
11
  return ModuleCtorFunc;
726
11
}
727
728
/// Creates a global destructor function that unregisters the GPU code blob
729
/// registered by constructor.
730
///
731
/// For CUDA:
732
/// \code
733
/// void __cuda_module_dtor(void*) {
734
///     __cudaUnregisterFatBinary(Handle);
735
/// }
736
/// \endcode
737
///
738
/// For HIP:
739
/// \code
740
/// void __hip_module_dtor(void*) {
741
///     if (__hip_gpubin_handle) {
742
///         __hipUnregisterFatBinary(__hip_gpubin_handle);
743
///         __hip_gpubin_handle = 0;
744
///     }
745
/// }
746
/// \endcode
747
11
llvm::Function *CGNVCUDARuntime::makeModuleDtorFunction() {
748
11
  // No need for destructor if we don't have a handle to unregister.
749
11
  if (!GpuBinaryHandle)
750
2
    return nullptr;
751
9
752
9
  // void __cudaUnregisterFatBinary(void ** handle);
753
9
  llvm::FunctionCallee UnregisterFatbinFunc = CGM.CreateRuntimeFunction(
754
9
      llvm::FunctionType::get(VoidTy, VoidPtrPtrTy, false),
755
9
      addUnderscoredPrefixToName("UnregisterFatBinary"));
756
9
757
9
  llvm::Function *ModuleDtorFunc = llvm::Function::Create(
758
9
      llvm::FunctionType::get(VoidTy, VoidPtrTy, false),
759
9
      llvm::GlobalValue::InternalLinkage,
760
9
      addUnderscoredPrefixToName("_module_dtor"), &TheModule);
761
9
762
9
  llvm::BasicBlock *DtorEntryBB =
763
9
      llvm::BasicBlock::Create(Context, "entry", ModuleDtorFunc);
764
9
  CGBuilderTy DtorBuilder(CGM, Context);
765
9
  DtorBuilder.SetInsertPoint(DtorEntryBB);
766
9
767
9
  Address GpuBinaryAddr(GpuBinaryHandle, CharUnits::fromQuantity(
768
9
                                             GpuBinaryHandle->getAlignment()));
769
9
  auto HandleValue = DtorBuilder.CreateLoad(GpuBinaryAddr);
770
9
  // There is only one HIP fat binary per linked module, however there are
771
9
  // multiple destructor functions. Make sure the fat binary is unregistered
772
9
  // only once.
773
9
  if (CGM.getLangOpts().HIP) {
774
7
    llvm::BasicBlock *IfBlock =
775
7
        llvm::BasicBlock::Create(Context, "if", ModuleDtorFunc);
776
7
    llvm::BasicBlock *ExitBlock =
777
7
        llvm::BasicBlock::Create(Context, "exit", ModuleDtorFunc);
778
7
    llvm::Constant *Zero = llvm::Constant::getNullValue(HandleValue->getType());
779
7
    llvm::Value *NEZero = DtorBuilder.CreateICmpNE(HandleValue, Zero);
780
7
    DtorBuilder.CreateCondBr(NEZero, IfBlock, ExitBlock);
781
7
782
7
    DtorBuilder.SetInsertPoint(IfBlock);
783
7
    DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
784
7
    DtorBuilder.CreateStore(Zero, GpuBinaryAddr);
785
7
    DtorBuilder.CreateBr(ExitBlock);
786
7
787
7
    DtorBuilder.SetInsertPoint(ExitBlock);
788
7
  } else {
789
2
    DtorBuilder.CreateCall(UnregisterFatbinFunc, HandleValue);
790
2
  }
791
9
  DtorBuilder.CreateRetVoid();
792
9
  return ModuleDtorFunc;
793
9
}
794
795
22
std::string CGNVCUDARuntime::getDeviceStubName(llvm::StringRef Name) const {
796
22
  if (!CGM.getLangOpts().HIP)
797
16
    return Name;
798
6
  return (Name + ".stub").str();
799
6
}
800
801
103
CGCUDARuntime *CodeGen::CreateNVCUDARuntime(CodeGenModule &CGM) {
802
103
  return new CGNVCUDARuntime(CGM);
803
103
}