Coverage Report

Created: 2020-09-15 12:33

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGDeclCXX.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGDeclCXX.cpp - Emit LLVM Code for C++ declarations --------------===//
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 contains code dealing with code generation of C++ declarations
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGCXXABI.h"
14
#include "CGObjCRuntime.h"
15
#include "CGOpenMPRuntime.h"
16
#include "CodeGenFunction.h"
17
#include "TargetInfo.h"
18
#include "clang/AST/Attr.h"
19
#include "clang/Basic/LangOptions.h"
20
#include "llvm/ADT/StringExtras.h"
21
#include "llvm/IR/Intrinsics.h"
22
#include "llvm/IR/MDBuilder.h"
23
#include "llvm/Support/Path.h"
24
25
using namespace clang;
26
using namespace CodeGen;
27
28
static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
29
12.3k
                         ConstantAddress DeclPtr) {
30
12.3k
  assert(
31
12.3k
      (D.hasGlobalStorage() ||
32
12.3k
       (D.hasLocalStorage() && CGF.getContext().getLangOpts().OpenCLCPlusPlus)) &&
33
12.3k
      "VarDecl must have global or local (in the case of OpenCL) storage!");
34
12.3k
  assert(!D.getType()->isReferenceType() &&
35
12.3k
         "Should not call EmitDeclInit on a reference!");
36
12.3k
37
12.3k
  QualType type = D.getType();
38
12.3k
  LValue lv = CGF.MakeAddrLValue(DeclPtr, type);
39
12.3k
40
12.3k
  const Expr *Init = D.getInit();
41
12.3k
  switch (CGF.getEvaluationKind(type)) {
42
7.49k
  case TEK_Scalar: {
43
7.49k
    CodeGenModule &CGM = CGF.CGM;
44
7.49k
    if (lv.isObjCStrong())
45
3
      CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
46
3
                                                DeclPtr, D.getTLSKind());
47
7.49k
    else if (lv.isObjCWeak())
48
2
      CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
49
2
                                              DeclPtr);
50
7.49k
    else
51
7.49k
      CGF.EmitScalarInit(Init, &D, lv, false);
52
7.49k
    return;
53
0
  }
54
3
  case TEK_Complex:
55
3
    CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true);
56
3
    return;
57
4.83k
  case TEK_Aggregate:
58
4.83k
    CGF.EmitAggExpr(Init,
59
4.83k
                    AggValueSlot::forLValue(lv, CGF, AggValueSlot::IsDestructed,
60
4.83k
                                            AggValueSlot::DoesNotNeedGCBarriers,
61
4.83k
                                            AggValueSlot::IsNotAliased,
62
4.83k
                                            AggValueSlot::DoesNotOverlap));
63
4.83k
    return;
64
0
  }
65
0
  llvm_unreachable("bad evaluation kind");
66
0
}
67
68
/// Emit code to cause the destruction of the given variable with
69
/// static storage duration.
70
static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
71
12.6k
                            ConstantAddress Addr) {
72
  // Honor __attribute__((no_destroy)) and bail instead of attempting
73
  // to emit a reference to a possibly nonexistent destructor, which
74
  // in turn can cause a crash. This will result in a global constructor
75
  // that isn't balanced out by a destructor call as intended by the
76
  // attribute. This also checks for -fno-c++-static-destructors and
77
  // bails even if the attribute is not present.
78
12.6k
  QualType::DestructionKind DtorKind = D.needsDestruction(CGF.getContext());
79
12.6k
80
  // FIXME:  __attribute__((cleanup)) ?
81
12.6k
82
12.6k
  switch (DtorKind) {
83
8.01k
  case QualType::DK_none:
84
8.01k
    return;
85
0
86
4.67k
  case QualType::DK_cxx_destructor:
87
4.67k
    break;
88
0
89
6
  case QualType::DK_objc_strong_lifetime:
90
6
  case QualType::DK_objc_weak_lifetime:
91
6
  case QualType::DK_nontrivial_c_struct:
92
    // We don't care about releasing objects during process teardown.
93
6
    assert(!D.getTLSKind() && "should have rejected this");
94
6
    return;
95
4.67k
  }
96
4.67k
97
4.67k
  llvm::FunctionCallee Func;
98
4.67k
  llvm::Constant *Argument;
99
4.67k
100
4.67k
  CodeGenModule &CGM = CGF.CGM;
101
4.67k
  QualType Type = D.getType();
102
4.67k
103
  // Special-case non-array C++ destructors, if they have the right signature.
104
  // Under some ABIs, destructors return this instead of void, and cannot be
105
  // passed directly to __cxa_atexit if the target does not allow this
106
  // mismatch.
107
4.67k
  const CXXRecordDecl *Record = Type->getAsCXXRecordDecl();
108
4.67k
  bool CanRegisterDestructor =
109
4.67k
      Record && 
(4.34k
!CGM.getCXXABI().HasThisReturn(
110
4.34k
                     GlobalDecl(Record->getDestructor(), Dtor_Complete)) ||
111
8
                 CGM.getCXXABI().canCallMismatchedFunctionType());
112
  // If __cxa_atexit is disabled via a flag, a different helper function is
113
  // generated elsewhere which uses atexit instead, and it takes the destructor
114
  // directly.
115
4.67k
  bool UsingExternalHelper = !CGM.getCodeGenOpts().CXAAtExit;
116
4.67k
  if (Record && 
(4.34k
CanRegisterDestructor4.34k
||
UsingExternalHelper1
)) {
117
4.34k
    assert(!Record->hasTrivialDestructor());
118
4.34k
    CXXDestructorDecl *Dtor = Record->getDestructor();
119
4.34k
120
4.34k
    Func = CGM.getAddrAndTypeOfCXXStructor(GlobalDecl(Dtor, Dtor_Complete));
121
4.34k
    if (CGF.getContext().getLangOpts().OpenCL) {
122
7
      auto DestAS =
123
7
          CGM.getTargetCodeGenInfo().getAddrSpaceOfCxaAtexitPtrParam();
124
7
      auto DestTy = CGF.getTypes().ConvertType(Type)->getPointerTo(
125
7
          CGM.getContext().getTargetAddressSpace(DestAS));
126
7
      auto SrcAS = D.getType().getQualifiers().getAddressSpace();
127
7
      if (DestAS == SrcAS)
128
0
        Argument = llvm::ConstantExpr::getBitCast(Addr.getPointer(), DestTy);
129
7
      else
130
        // FIXME: On addr space mismatch we are passing NULL. The generation
131
        // of the global destructor function should be adjusted accordingly.
132
7
        Argument = llvm::ConstantPointerNull::get(DestTy);
133
4.33k
    } else {
134
4.33k
      Argument = llvm::ConstantExpr::getBitCast(
135
4.33k
          Addr.getPointer(), CGF.getTypes().ConvertType(Type)->getPointerTo());
136
4.33k
    }
137
  // Otherwise, the standard logic requires a helper function.
138
336
  } else {
139
336
    Func = CodeGenFunction(CGM)
140
336
           .generateDestroyHelper(Addr, Type, CGF.getDestroyer(DtorKind),
141
336
                                  CGF.needsEHCleanup(DtorKind), &D);
142
336
    Argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
143
336
  }
144
4.67k
145
4.67k
  CGM.getCXXABI().registerGlobalDtor(CGF, D, Func, Argument);
146
4.67k
}
147
148
/// Emit code to cause the variable at the given address to be considered as
149
/// constant from this point onwards.
150
static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
151
92
                              llvm::Constant *Addr) {
152
92
  return CGF.EmitInvariantStart(
153
92
      Addr, CGF.getContext().getTypeSizeInChars(D.getType()));
154
92
}
155
156
141
void CodeGenFunction::EmitInvariantStart(llvm::Constant *Addr, CharUnits Size) {
157
  // Do not emit the intrinsic if we're not optimizing.
158
141
  if (!CGM.getCodeGenOpts().OptimizationLevel)
159
131
    return;
160
10
161
  // Grab the llvm.invariant.start intrinsic.
162
10
  llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
163
  // Overloaded address space type.
164
10
  llvm::Type *ObjectPtr[1] = {Int8PtrTy};
165
10
  llvm::Function *InvariantStart = CGM.getIntrinsic(InvStartID, ObjectPtr);
166
10
167
  // Emit a call with the size in bytes of the object.
168
10
  uint64_t Width = Size.getQuantity();
169
10
  llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(Int64Ty, Width),
170
10
                           llvm::ConstantExpr::getBitCast(Addr, Int8PtrTy)};
171
10
  Builder.CreateCall(InvariantStart, Args);
172
10
}
173
174
void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
175
                                               llvm::Constant *DeclPtr,
176
12.8k
                                               bool PerformInit) {
177
12.8k
178
12.8k
  const Expr *Init = D.getInit();
179
12.8k
  QualType T = D.getType();
180
12.8k
181
  // The address space of a static local variable (DeclPtr) may be different
182
  // from the address space of the "this" argument of the constructor. In that
183
  // case, we need an addrspacecast before calling the constructor.
184
  //
185
  // struct StructWithCtor {
186
  //   __device__ StructWithCtor() {...}
187
  // };
188
  // __device__ void foo() {
189
  //   __shared__ StructWithCtor s;
190
  //   ...
191
  // }
192
  //
193
  // For example, in the above CUDA code, the static local variable s has a
194
  // "shared" address space qualifier, but the constructor of StructWithCtor
195
  // expects "this" in the "generic" address space.
196
12.8k
  unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(T);
197
12.8k
  unsigned ActualAddrSpace = DeclPtr->getType()->getPointerAddressSpace();
198
12.8k
  if (ActualAddrSpace != ExpectedAddrSpace) {
199
12
    llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(T);
200
12
    llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
201
12
    DeclPtr = llvm::ConstantExpr::getAddrSpaceCast(DeclPtr, PTy);
202
12
  }
203
12.8k
204
12.8k
  ConstantAddress DeclAddr(DeclPtr, getContext().getDeclAlign(&D));
205
12.8k
206
12.8k
  if (!T->isReferenceType()) {
207
12.7k
    if (getLangOpts().OpenMP && 
!getLangOpts().OpenMPSimd3.87k
&&
208
1.66k
        D.hasAttr<OMPThreadPrivateDeclAttr>()) {
209
56
      (void)CGM.getOpenMPRuntime().emitThreadPrivateVarDefinition(
210
56
          &D, DeclAddr, D.getAttr<OMPThreadPrivateDeclAttr>()->getLocation(),
211
56
          PerformInit, this);
212
56
    }
213
12.7k
    if (PerformInit)
214
12.3k
      EmitDeclInit(*this, D, DeclAddr);
215
12.7k
    if (CGM.isTypeConstant(D.getType(), true))
216
92
      EmitDeclInvariant(*this, D, DeclPtr);
217
12.6k
    else
218
12.6k
      EmitDeclDestroy(*this, D, DeclAddr);
219
12.7k
    return;
220
12.7k
  }
221
96
222
96
  assert(PerformInit && "cannot have constant initializer which needs "
223
96
         "destruction for reference");
224
96
  RValue RV = EmitReferenceBindingToExpr(Init);
225
96
  EmitStoreOfScalar(RV.getScalarVal(), DeclAddr, false, T);
226
96
}
227
228
/// Create a stub function, suitable for being passed to atexit,
229
/// which passes the given address to the given destructor function.
230
llvm::Function *CodeGenFunction::createAtExitStub(const VarDecl &VD,
231
                                                  llvm::FunctionCallee dtor,
232
207
                                                  llvm::Constant *addr) {
233
  // Get the destructor function type, void(*)(void).
234
207
  llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
235
207
  SmallString<256> FnName;
236
207
  {
237
207
    llvm::raw_svector_ostream Out(FnName);
238
207
    CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out);
239
207
  }
240
207
241
207
  const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
242
207
  llvm::Function *fn = CGM.CreateGlobalInitOrCleanUpFunction(
243
207
      ty, FnName.str(), FI, VD.getLocation());
244
207
245
207
  CodeGenFunction CGF(CGM);
246
207
247
207
  CGF.StartFunction(GlobalDecl(&VD, DynamicInitKind::AtExit),
248
207
                    CGM.getContext().VoidTy, fn, FI, FunctionArgList(),
249
207
                    VD.getLocation(), VD.getInit()->getExprLoc());
250
207
251
207
  llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
252
207
253
  // Make sure the call and the callee agree on calling convention.
254
207
  if (auto *dtorFn = dyn_cast<llvm::Function>(
255
207
          dtor.getCallee()->stripPointerCastsAndAliases()))
256
207
    call->setCallingConv(dtorFn->getCallingConv());
257
207
258
207
  CGF.FinishFunction();
259
207
260
207
  return fn;
261
207
}
262
263
/// Register a global destructor using the C atexit runtime function.
264
void CodeGenFunction::registerGlobalDtorWithAtExit(const VarDecl &VD,
265
                                                   llvm::FunctionCallee dtor,
266
175
                                                   llvm::Constant *addr) {
267
  // Create a function which calls the destructor.
268
175
  llvm::Constant *dtorStub = createAtExitStub(VD, dtor, addr);
269
175
  registerGlobalDtorWithAtExit(dtorStub);
270
175
}
271
272
202
void CodeGenFunction::registerGlobalDtorWithAtExit(llvm::Constant *dtorStub) {
273
  // extern "C" int atexit(void (*f)(void));
274
202
  assert(cast<llvm::Function>(dtorStub)->getFunctionType() ==
275
202
             llvm::FunctionType::get(CGM.VoidTy, false) &&
276
202
         "Argument to atexit has a wrong type.");
277
202
278
202
  llvm::FunctionType *atexitTy =
279
202
      llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
280
202
281
202
  llvm::FunctionCallee atexit =
282
202
      CGM.CreateRuntimeFunction(atexitTy, "atexit", llvm::AttributeList(),
283
202
                                /*Local=*/true);
284
202
  if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit.getCallee()))
285
202
    atexitFn->setDoesNotThrow();
286
202
287
202
  EmitNounwindRuntimeCall(atexit, dtorStub);
288
202
}
289
290
llvm::Value *
291
22
CodeGenFunction::unregisterGlobalDtorWithUnAtExit(llvm::Function *dtorStub) {
292
  // The unatexit subroutine unregisters __dtor functions that were previously
293
  // registered by the atexit subroutine. If the referenced function is found,
294
  // it is removed from the list of functions that are called at normal program
295
  // termination and the unatexit returns a value of 0, otherwise a non-zero
296
  // value is returned.
297
  //
298
  // extern "C" int unatexit(void (*f)(void));
299
22
  assert(dtorStub->getFunctionType() ==
300
22
             llvm::FunctionType::get(CGM.VoidTy, false) &&
301
22
         "Argument to unatexit has a wrong type.");
302
22
303
22
  llvm::FunctionType *unatexitTy =
304
22
      llvm::FunctionType::get(IntTy, {dtorStub->getType()}, /*isVarArg=*/false);
305
22
306
22
  llvm::FunctionCallee unatexit =
307
22
      CGM.CreateRuntimeFunction(unatexitTy, "unatexit", llvm::AttributeList());
308
22
309
22
  cast<llvm::Function>(unatexit.getCallee())->setDoesNotThrow();
310
22
311
22
  return EmitNounwindRuntimeCall(unatexit, dtorStub);
312
22
}
313
314
void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
315
                                         llvm::GlobalVariable *DeclPtr,
316
7.42k
                                         bool PerformInit) {
317
  // If we've been asked to forbid guard variables, emit an error now.
318
  // This diagnostic is hard-coded for Darwin's use case;  we can find
319
  // better phrasing if someone else needs it.
320
7.42k
  if (CGM.getCodeGenOpts().ForbidGuardVariables)
321
1
    CGM.Error(D.getLocation(),
322
1
              "this initialization requires a guard variable, which "
323
1
              "the kernel does not support");
324
7.42k
325
7.42k
  CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
326
7.42k
}
327
328
void CodeGenFunction::EmitCXXGuardedInitBranch(llvm::Value *NeedsInit,
329
                                               llvm::BasicBlock *InitBlock,
330
                                               llvm::BasicBlock *NoInitBlock,
331
                                               GuardKind Kind,
332
7.42k
                                               const VarDecl *D) {
333
7.42k
  assert((Kind == GuardKind::TlsGuard || D) && "no guarded variable");
334
7.42k
335
  // A guess at how many times we will enter the initialization of a
336
  // variable, depending on the kind of variable.
337
7.42k
  static const uint64_t InitsPerTLSVar = 1024;
338
7.42k
  static const uint64_t InitsPerLocalVar = 1024 * 1024;
339
7.42k
340
7.42k
  llvm::MDNode *Weights;
341
7.42k
  if (Kind == GuardKind::VariableGuard && 
!D->isLocalVarDecl()7.37k
) {
342
    // For non-local variables, don't apply any weighting for now. Due to our
343
    // use of COMDATs, we expect there to be at most one initialization of the
344
    // variable per DSO, but we have no way to know how many DSOs will try to
345
    // initialize the variable.
346
173
    Weights = nullptr;
347
7.25k
  } else {
348
7.25k
    uint64_t NumInits;
349
    // FIXME: For the TLS case, collect and use profiling information to
350
    // determine a more accurate brach weight.
351
7.25k
    if (Kind == GuardKind::TlsGuard || 
D->getTLSKind()7.20k
)
352
116
      NumInits = InitsPerTLSVar;
353
7.13k
    else
354
7.13k
      NumInits = InitsPerLocalVar;
355
7.25k
356
    // The probability of us entering the initializer is
357
    //   1 / (total number of times we attempt to initialize the variable).
358
7.25k
    llvm::MDBuilder MDHelper(CGM.getLLVMContext());
359
7.25k
    Weights = MDHelper.createBranchWeights(1, NumInits - 1);
360
7.25k
  }
361
7.42k
362
7.42k
  Builder.CreateCondBr(NeedsInit, InitBlock, NoInitBlock, Weights);
363
7.42k
}
364
365
llvm::Function *CodeGenModule::CreateGlobalInitOrCleanUpFunction(
366
    llvm::FunctionType *FTy, const Twine &Name, const CGFunctionInfo &FI,
367
10.3k
    SourceLocation Loc, bool TLS) {
368
10.3k
  llvm::Function *Fn = llvm::Function::Create(
369
10.3k
      FTy, llvm::GlobalValue::InternalLinkage, Name, &getModule());
370
10.3k
371
10.3k
  if (!getLangOpts().AppleKext && 
!TLS10.2k
) {
372
    // Set the section if needed.
373
10.2k
    if (const char *Section = getTarget().getStaticInitSectionSpecifier())
374
2.44k
      Fn->setSection(Section);
375
10.2k
  }
376
10.3k
377
10.3k
  SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
378
10.3k
379
10.3k
  Fn->setCallingConv(getRuntimeCC());
380
10.3k
381
10.3k
  if (!getLangOpts().Exceptions)
382
9.25k
    Fn->setDoesNotThrow();
383
10.3k
384
10.3k
  if (getLangOpts().Sanitize.has(SanitizerKind::Address) &&
385
91
      !isInSanitizerBlacklist(SanitizerKind::Address, Fn, Loc))
386
86
    Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
387
10.3k
388
10.3k
  if (getLangOpts().Sanitize.has(SanitizerKind::KernelAddress) &&
389
4
      !isInSanitizerBlacklist(SanitizerKind::KernelAddress, Fn, Loc))
390
2
    Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
391
10.3k
392
10.3k
  if (getLangOpts().Sanitize.has(SanitizerKind::HWAddress) &&
393
0
      !isInSanitizerBlacklist(SanitizerKind::HWAddress, Fn, Loc))
394
0
    Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
395
10.3k
396
10.3k
  if (getLangOpts().Sanitize.has(SanitizerKind::KernelHWAddress) &&
397
0
      !isInSanitizerBlacklist(SanitizerKind::KernelHWAddress, Fn, Loc))
398
0
    Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
399
10.3k
400
10.3k
  if (getLangOpts().Sanitize.has(SanitizerKind::MemTag) &&
401
0
      !isInSanitizerBlacklist(SanitizerKind::MemTag, Fn, Loc))
402
0
    Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
403
10.3k
404
10.3k
  if (getLangOpts().Sanitize.has(SanitizerKind::Thread) &&
405
6
      !isInSanitizerBlacklist(SanitizerKind::Thread, Fn, Loc))
406
3
    Fn->addFnAttr(llvm::Attribute::SanitizeThread);
407
10.3k
408
10.3k
  if (getLangOpts().Sanitize.has(SanitizerKind::Memory) &&
409
41
      !isInSanitizerBlacklist(SanitizerKind::Memory, Fn, Loc))
410
41
    Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
411
10.3k
412
10.3k
  if (getLangOpts().Sanitize.has(SanitizerKind::KernelMemory) &&
413
0
      !isInSanitizerBlacklist(SanitizerKind::KernelMemory, Fn, Loc))
414
0
    Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
415
10.3k
416
10.3k
  if (getLangOpts().Sanitize.has(SanitizerKind::SafeStack) &&
417
0
      !isInSanitizerBlacklist(SanitizerKind::SafeStack, Fn, Loc))
418
0
    Fn->addFnAttr(llvm::Attribute::SafeStack);
419
10.3k
420
10.3k
  if (getLangOpts().Sanitize.has(SanitizerKind::ShadowCallStack) &&
421
0
      !isInSanitizerBlacklist(SanitizerKind::ShadowCallStack, Fn, Loc))
422
0
    Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
423
10.3k
424
10.3k
  auto RASignKind = getLangOpts().getSignReturnAddressScope();
425
10.3k
  if (RASignKind != LangOptions::SignReturnAddressScopeKind::None) {
426
16
    Fn->addFnAttr("sign-return-address",
427
16
                  RASignKind == LangOptions::SignReturnAddressScopeKind::All
428
8
                      ? "all"
429
8
                      : "non-leaf");
430
16
    auto RASignKey = getLangOpts().getSignReturnAddressKey();
431
16
    Fn->addFnAttr("sign-return-address-key",
432
16
                  RASignKey == LangOptions::SignReturnAddressKeyKind::AKey
433
10
                      ? "a_key"
434
6
                      : "b_key");
435
16
  }
436
10.3k
437
10.3k
  if (getLangOpts().BranchTargetEnforcement)
438
6
    Fn->addFnAttr("branch-target-enforcement");
439
10.3k
440
10.3k
  return Fn;
441
10.3k
}
442
443
/// Create a global pointer to a function that will initialize a global
444
/// variable.  The user has requested that this pointer be emitted in a specific
445
/// section.
446
void CodeGenModule::EmitPointerToInitFunc(const VarDecl *D,
447
                                          llvm::GlobalVariable *GV,
448
                                          llvm::Function *InitFunc,
449
6
                                          InitSegAttr *ISA) {
450
6
  llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable(
451
6
      TheModule, InitFunc->getType(), /*isConstant=*/true,
452
6
      llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr");
453
6
  PtrArray->setSection(ISA->getSection());
454
6
  addUsedGlobal(PtrArray);
455
6
456
  // If the GV is already in a comdat group, then we have to join it.
457
6
  if (llvm::Comdat *C = GV->getComdat())
458
3
    PtrArray->setComdat(C);
459
6
}
460
461
void
462
CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
463
                                            llvm::GlobalVariable *Addr,
464
5.80k
                                            bool PerformInit) {
465
5.80k
466
  // According to E.2.3.1 in CUDA-7.5 Programming guide: __device__,
467
  // __constant__ and __shared__ variables defined in namespace scope,
468
  // that are of class type, cannot have a non-empty constructor. All
469
  // the checks have been done in Sema by now. Whatever initializers
470
  // are allowed are empty and we just need to ignore them here.
471
5.80k
  if (getLangOpts().CUDAIsDevice && 
!getLangOpts().GPUAllowDeviceInit25
&&
472
24
      (D->hasAttr<CUDADeviceAttr>() || 
D->hasAttr<CUDAConstantAttr>()14
||
473
4
       D->hasAttr<CUDASharedAttr>()))
474
24
    return;
475
5.78k
476
5.78k
  if (getLangOpts().OpenMP &&
477
3.89k
      getOpenMPRuntime().emitDeclareTargetVarDefinition(D, Addr, PerformInit))
478
77
    return;
479
5.70k
480
  // Check if we've already initialized this decl.
481
5.70k
  auto I = DelayedCXXInitPosition.find(D);
482
5.70k
  if (I != DelayedCXXInitPosition.end() && 
I->second == ~0U1.47k
)
483
22
    return;
484
5.68k
485
5.68k
  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
486
5.68k
  SmallString<256> FnName;
487
5.68k
  {
488
5.68k
    llvm::raw_svector_ostream Out(FnName);
489
5.68k
    getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
490
5.68k
  }
491
5.68k
492
  // Create a variable initialization function.
493
5.68k
  llvm::Function *Fn = CreateGlobalInitOrCleanUpFunction(
494
5.68k
      FTy, FnName.str(), getTypes().arrangeNullaryFunction(), D->getLocation());
495
5.68k
496
5.68k
  auto *ISA = D->getAttr<InitSegAttr>();
497
5.68k
  CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
498
5.68k
                                                          PerformInit);
499
5.68k
500
5.68k
  llvm::GlobalVariable *COMDATKey =
501
5.68k
      supportsCOMDAT() && 
D->isExternallyVisible()4.57k
?
Addr3.84k
:
nullptr1.83k
;
502
5.68k
503
5.68k
  if (D->getTLSKind()) {
504
    // FIXME: Should we support init_priority for thread_local?
505
    // FIXME: We only need to register one __cxa_thread_atexit function for the
506
    // entire TU.
507
177
    CXXThreadLocalInits.push_back(Fn);
508
177
    CXXThreadLocalInitVars.push_back(D);
509
5.50k
  } else if (PerformInit && 
ISA5.14k
) {
510
6
    EmitPointerToInitFunc(D, Addr, Fn, ISA);
511
5.50k
  } else if (auto *IPA = D->getAttr<InitPriorityAttr>()) {
512
921
    OrderGlobalInits Key(IPA->getPriority(), PrioritizedCXXGlobalInits.size());
513
921
    PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
514
4.58k
  } else if (isTemplateInstantiation(D->getTemplateSpecializationKind()) ||
515
4.47k
             getContext().GetGVALinkageForVariable(D) == GVA_DiscardableODR) {
516
    // C++ [basic.start.init]p2:
517
    //   Definitions of explicitly specialized class template static data
518
    //   members have ordered initialization. Other class template static data
519
    //   members (i.e., implicitly or explicitly instantiated specializations)
520
    //   have unordered initialization.
521
    //
522
    // As a consequence, we can put them into their own llvm.global_ctors entry.
523
    //
524
    // If the global is externally visible, put the initializer into a COMDAT
525
    // group with the global being initialized.  On most platforms, this is a
526
    // minor startup time optimization.  In the MS C++ ABI, there are no guard
527
    // variables, so this COMDAT key is required for correctness.
528
130
    AddGlobalCtor(Fn, 65535, COMDATKey);
529
130
    if (getTarget().getCXXABI().isMicrosoft() && 
COMDATKey35
) {
530
      // In The MS C++, MS add template static data member in the linker
531
      // drective.
532
31
      addUsedGlobal(COMDATKey);
533
31
    }
534
4.45k
  } else if (D->hasAttr<SelectAnyAttr>()) {
535
    // SelectAny globals will be comdat-folded. Put the initializer into a
536
    // COMDAT group associated with the global, so the initializers get folded
537
    // too.
538
6
    AddGlobalCtor(Fn, 65535, COMDATKey);
539
4.44k
  } else {
540
4.44k
    I = DelayedCXXInitPosition.find(D); // Re-do lookup in case of re-hash.
541
4.44k
    if (I == DelayedCXXInitPosition.end()) {
542
3.36k
      CXXGlobalInits.push_back(Fn);
543
1.08k
    } else if (I->second != ~0U) {
544
1.08k
      assert(I->second < CXXGlobalInits.size() &&
545
1.08k
             CXXGlobalInits[I->second] == nullptr);
546
1.08k
      CXXGlobalInits[I->second] = Fn;
547
1.08k
    }
548
4.44k
  }
549
5.68k
550
  // Remember that we already emitted the initializer for this global.
551
5.68k
  DelayedCXXInitPosition[D] = ~0U;
552
5.68k
}
553
554
28.8k
void CodeGenModule::EmitCXXThreadLocalInitFunc() {
555
28.8k
  getCXXABI().EmitThreadLocalInitFuncs(
556
28.8k
      *this, CXXThreadLocals, CXXThreadLocalInits, CXXThreadLocalInitVars);
557
28.8k
558
28.8k
  CXXThreadLocalInits.clear();
559
28.8k
  CXXThreadLocalInitVars.clear();
560
28.8k
  CXXThreadLocals.clear();
561
28.8k
}
562
563
1.33k
static SmallString<128> getTransformedFileName(llvm::Module &M) {
564
1.33k
  SmallString<128> FileName = llvm::sys::path::filename(M.getName());
565
1.33k
566
1.33k
  if (FileName.empty())
567
0
    FileName = "<null>";
568
1.33k
569
45.5k
  for (size_t i = 0; i < FileName.size(); 
++i44.2k
) {
570
    // Replace everything that's not [a-zA-Z0-9._] with a _. This set happens
571
    // to be the set of C preprocessing numbers.
572
44.2k
    if (!isPreprocessingNumberBody(FileName[i]))
573
916
      FileName[i] = '_';
574
44.2k
  }
575
1.33k
576
1.33k
  return FileName;
577
1.33k
}
578
579
void
580
28.8k
CodeGenModule::EmitCXXGlobalInitFunc() {
581
41.9k
  while (!CXXGlobalInits.empty() && 
!CXXGlobalInits.back()14.4k
)
582
13.1k
    CXXGlobalInits.pop_back();
583
28.8k
584
28.8k
  if (CXXGlobalInits.empty() && 
PrioritizedCXXGlobalInits.empty()27.5k
)
585
27.5k
    return;
586
1.33k
587
1.33k
  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
588
1.33k
  const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
589
1.33k
590
1.33k
  const bool UseSinitAndSterm = getCXXABI().useSinitAndSterm();
591
  // Create our global prioritized initialization function.
592
1.33k
  if (!PrioritizedCXXGlobalInits.empty()) {
593
307
    assert(!UseSinitAndSterm && "Prioritized sinit and sterm functions are not"
594
307
                                " supported yet.");
595
307
596
307
    SmallVector<llvm::Function *, 8> LocalCXXGlobalInits;
597
307
    llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
598
307
                         PrioritizedCXXGlobalInits.end());
599
    // Iterate over "chunks" of ctors with same priority and emit each chunk
600
    // into separate function. Note - everything is sorted first by priority,
601
    // second - by lex order, so we emit ctor functions in proper order.
602
307
    for (SmallVectorImpl<GlobalInitData >::iterator
603
307
           I = PrioritizedCXXGlobalInits.begin(),
604
921
           E = PrioritizedCXXGlobalInits.end(); I != E; ) {
605
614
      SmallVectorImpl<GlobalInitData >::iterator
606
614
        PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
607
614
608
614
      LocalCXXGlobalInits.clear();
609
614
      unsigned Priority = I->first.priority;
610
      // Compute the function suffix from priority. Prepend with zeroes to make
611
      // sure the function names are also ordered as priorities.
612
614
      std::string PrioritySuffix = llvm::utostr(Priority);
613
      // Priority is always <= 65535 (enforced by sema).
614
614
      PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
615
614
      llvm::Function *Fn = CreateGlobalInitOrCleanUpFunction(
616
614
          FTy, "_GLOBAL__I_" + PrioritySuffix, FI);
617
614
618
1.53k
      for (; I < PrioE; 
++I921
)
619
921
        LocalCXXGlobalInits.push_back(I->second);
620
614
621
614
      CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
622
614
      AddGlobalCtor(Fn, Priority);
623
614
    }
624
307
    PrioritizedCXXGlobalInits.clear();
625
307
  }
626
1.33k
627
1.33k
  if (UseSinitAndSterm && 
CXXGlobalInits.empty()8
)
628
0
    return;
629
1.33k
630
  // Include the filename in the symbol name. Including "sub_" matches gcc
631
  // and makes sure these symbols appear lexicographically behind the symbols
632
  // with priority emitted above.
633
1.33k
  llvm::Function *Fn = CreateGlobalInitOrCleanUpFunction(
634
1.33k
      FTy, llvm::Twine("_GLOBAL__sub_I_", getTransformedFileName(getModule())),
635
1.33k
      FI);
636
1.33k
637
1.33k
  CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
638
1.33k
  AddGlobalCtor(Fn);
639
1.33k
640
  // In OpenCL global init functions must be converted to kernels in order to
641
  // be able to launch them from the host.
642
  // FIXME: Some more work might be needed to handle destructors correctly.
643
  // Current initialization function makes use of function pointers callbacks.
644
  // We can't support function pointers especially between host and device.
645
  // However it seems global destruction has little meaning without any
646
  // dynamic resource allocation on the device and program scope variables are
647
  // destroyed by the runtime when program is released.
648
1.33k
  if (getLangOpts().OpenCL) {
649
6
    GenOpenCLArgMetadata(Fn);
650
6
    Fn->setCallingConv(llvm::CallingConv::SPIR_KERNEL);
651
6
  }
652
1.33k
653
1.33k
  if (getLangOpts().HIP) {
654
1
    Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
655
1
    Fn->addFnAttr("device-init");
656
1
  }
657
1.33k
658
1.33k
  CXXGlobalInits.clear();
659
1.33k
}
660
661
28.8k
void CodeGenModule::EmitCXXGlobalCleanUpFunc() {
662
28.8k
  if (CXXGlobalDtorsOrStermFinalizers.empty())
663
28.8k
    return;
664
11
665
11
  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
666
11
  const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
667
11
668
  // Create our global cleanup function.
669
11
  llvm::Function *Fn =
670
11
      CreateGlobalInitOrCleanUpFunction(FTy, "_GLOBAL__D_a", FI);
671
11
672
11
  CodeGenFunction(*this).GenerateCXXGlobalCleanUpFunc(
673
11
      Fn, CXXGlobalDtorsOrStermFinalizers);
674
11
  AddGlobalDtor(Fn);
675
11
  CXXGlobalDtorsOrStermFinalizers.clear();
676
11
}
677
678
/// Emit the code necessary to initialize the given global variable.
679
void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
680
                                                       const VarDecl *D,
681
                                                 llvm::GlobalVariable *Addr,
682
5.68k
                                                       bool PerformInit) {
683
  // Check if we need to emit debug info for variable initializer.
684
5.68k
  if (D->hasAttr<NoDebugAttr>())
685
1
    DebugInfo = nullptr; // disable debug info indefinitely for this function
686
5.68k
687
5.68k
  CurEHLocation = D->getBeginLoc();
688
5.68k
689
5.68k
  StartFunction(GlobalDecl(D, DynamicInitKind::Initializer),
690
5.68k
                getContext().VoidTy, Fn, getTypes().arrangeNullaryFunction(),
691
5.68k
                FunctionArgList(), D->getLocation(),
692
5.68k
                D->getInit()->getExprLoc());
693
5.68k
694
  // Use guarded initialization if the global variable is weak. This
695
  // occurs for, e.g., instantiated static data members and
696
  // definitions explicitly marked weak.
697
  //
698
  // Also use guarded initialization for a variable with dynamic TLS and
699
  // unordered initialization. (If the initialization is ordered, the ABI
700
  // layer will guard the whole-TU initialization for us.)
701
5.68k
  if (Addr->hasWeakLinkage() || 
Addr->hasLinkOnceLinkage()5.61k
||
702
5.46k
      (D->getTLSKind() == VarDecl::TLS_Dynamic &&
703
219
       
isTemplateInstantiation(D->getTemplateSpecializationKind())97
)) {
704
219
    EmitCXXGuardedInit(*D, Addr, PerformInit);
705
5.46k
  } else {
706
5.46k
    EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
707
5.46k
  }
708
5.68k
709
5.68k
  FinishFunction();
710
5.68k
}
711
712
void
713
CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
714
                                           ArrayRef<llvm::Function *> Decls,
715
2.00k
                                           ConstantAddress Guard) {
716
2.00k
  {
717
2.00k
    auto NL = ApplyDebugLocation::CreateEmpty(*this);
718
2.00k
    StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
719
2.00k
                  getTypes().arrangeNullaryFunction(), FunctionArgList());
720
    // Emit an artificial location for this function.
721
2.00k
    auto AL = ApplyDebugLocation::CreateArtificial(*this);
722
2.00k
723
2.00k
    llvm::BasicBlock *ExitBlock = nullptr;
724
2.00k
    if (Guard.isValid()) {
725
      // If we have a guard variable, check whether we've already performed
726
      // these initializations. This happens for TLS initialization functions.
727
49
      llvm::Value *GuardVal = Builder.CreateLoad(Guard);
728
49
      llvm::Value *Uninit = Builder.CreateIsNull(GuardVal,
729
49
                                                 "guard.uninitialized");
730
49
      llvm::BasicBlock *InitBlock = createBasicBlock("init");
731
49
      ExitBlock = createBasicBlock("exit");
732
49
      EmitCXXGuardedInitBranch(Uninit, InitBlock, ExitBlock,
733
49
                               GuardKind::TlsGuard, nullptr);
734
49
      EmitBlock(InitBlock);
735
      // Mark as initialized before initializing anything else. If the
736
      // initializers use previously-initialized thread_local vars, that's
737
      // probably supposed to be OK, but the standard doesn't say.
738
49
      Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard);
739
49
740
      // The guard variable can't ever change again.
741
49
      EmitInvariantStart(
742
49
          Guard.getPointer(),
743
49
          CharUnits::fromQuantity(
744
49
              CGM.getDataLayout().getTypeAllocSize(GuardVal->getType())));
745
49
    }
746
2.00k
747
2.00k
    RunCleanupsScope Scope(*this);
748
2.00k
749
    // When building in Objective-C++ ARC mode, create an autorelease pool
750
    // around the global initializers.
751
2.00k
    if (getLangOpts().ObjCAutoRefCount && 
getLangOpts().CPlusPlus4
) {
752
4
      llvm::Value *token = EmitObjCAutoreleasePoolPush();
753
4
      EmitObjCAutoreleasePoolCleanup(token);
754
4
    }
755
2.00k
756
10.9k
    for (unsigned i = 0, e = Decls.size(); i != e; 
++i8.97k
)
757
8.97k
      if (Decls[i])
758
5.46k
        EmitRuntimeCall(Decls[i]);
759
2.00k
760
2.00k
    Scope.ForceCleanup();
761
2.00k
762
2.00k
    if (ExitBlock) {
763
49
      Builder.CreateBr(ExitBlock);
764
49
      EmitBlock(ExitBlock);
765
49
    }
766
2.00k
  }
767
2.00k
768
2.00k
  FinishFunction();
769
2.00k
}
770
771
void CodeGenFunction::GenerateCXXGlobalCleanUpFunc(
772
    llvm::Function *Fn,
773
    const std::vector<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
774
11
                                 llvm::Constant *>> &DtorsOrStermFinalizers) {
775
11
  {
776
11
    auto NL = ApplyDebugLocation::CreateEmpty(*this);
777
11
    StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
778
11
                  getTypes().arrangeNullaryFunction(), FunctionArgList());
779
    // Emit an artificial location for this function.
780
11
    auto AL = ApplyDebugLocation::CreateArtificial(*this);
781
11
782
    // Emit the cleanups, in reverse order from construction.
783
33
    for (unsigned i = 0, e = DtorsOrStermFinalizers.size(); i != e; 
++i22
) {
784
22
      llvm::FunctionType *CalleeTy;
785
22
      llvm::Value *Callee;
786
22
      llvm::Constant *Arg;
787
22
      std::tie(CalleeTy, Callee, Arg) = DtorsOrStermFinalizers[e - i - 1];
788
22
789
22
      llvm::CallInst *CI = nullptr;
790
22
      if (Arg == nullptr) {
791
16
        assert(
792
16
            CGM.getCXXABI().useSinitAndSterm() &&
793
16
            "Arg could not be nullptr unless using sinit and sterm functions.");
794
16
        CI = Builder.CreateCall(CalleeTy, Callee);
795
16
      } else
796
6
        CI = Builder.CreateCall(CalleeTy, Callee, Arg);
797
22
798
      // Make sure the call and the callee agree on calling convention.
799
22
      if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
800
22
        CI->setCallingConv(F->getCallingConv());
801
22
    }
802
11
  }
803
11
804
11
  FinishFunction();
805
11
}
806
807
/// generateDestroyHelper - Generates a helper function which, when
808
/// invoked, destroys the given object.  The address of the object
809
/// should be in global memory.
810
llvm::Function *CodeGenFunction::generateDestroyHelper(
811
    Address addr, QualType type, Destroyer *destroyer,
812
340
    bool useEHCleanupForArray, const VarDecl *VD) {
813
340
  FunctionArgList args;
814
340
  ImplicitParamDecl Dst(getContext(), getContext().VoidPtrTy,
815
340
                        ImplicitParamDecl::Other);
816
340
  args.push_back(&Dst);
817
340
818
340
  const CGFunctionInfo &FI =
819
340
    CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, args);
820
340
  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
821
340
  llvm::Function *fn = CGM.CreateGlobalInitOrCleanUpFunction(
822
340
      FTy, "__cxx_global_array_dtor", FI, VD->getLocation());
823
340
824
340
  CurEHLocation = VD->getBeginLoc();
825
340
826
340
  StartFunction(VD, getContext().VoidTy, fn, FI, args);
827
340
828
340
  emitDestroy(addr, type, destroyer, useEHCleanupForArray);
829
340
830
340
  FinishFunction();
831
340
832
340
  return fn;
833
340
}