Coverage Report

Created: 2020-02-25 14:32

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