Coverage Report

Created: 2021-09-21 08:58

/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
15.2k
                         ConstantAddress DeclPtr) {
30
15.2k
  assert(
31
15.2k
      (D.hasGlobalStorage() ||
32
15.2k
       (D.hasLocalStorage() && CGF.getContext().getLangOpts().OpenCLCPlusPlus)) &&
33
15.2k
      "VarDecl must have global or local (in the case of OpenCL) storage!");
34
0
  assert(!D.getType()->isReferenceType() &&
35
15.2k
         "Should not call EmitDeclInit on a reference!");
36
37
0
  QualType type = D.getType();
38
15.2k
  LValue lv = CGF.MakeAddrLValue(DeclPtr, type);
39
40
15.2k
  const Expr *Init = D.getInit();
41
15.2k
  switch (CGF.getEvaluationKind(type)) {
42
10.3k
  case TEK_Scalar: {
43
10.3k
    CodeGenModule &CGM = CGF.CGM;
44
10.3k
    if (lv.isObjCStrong())
45
3
      CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
46
3
                                                DeclPtr, D.getTLSKind());
47
10.3k
    else if (lv.isObjCWeak())
48
2
      CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
49
2
                                              DeclPtr);
50
10.3k
    else
51
10.3k
      CGF.EmitScalarInit(Init, &D, lv, false);
52
10.3k
    return;
53
0
  }
54
3
  case TEK_Complex:
55
3
    CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true);
56
3
    return;
57
4.88k
  case TEK_Aggregate:
58
4.88k
    CGF.EmitAggExpr(Init,
59
4.88k
                    AggValueSlot::forLValue(lv, CGF, AggValueSlot::IsDestructed,
60
4.88k
                                            AggValueSlot::DoesNotNeedGCBarriers,
61
4.88k
                                            AggValueSlot::IsNotAliased,
62
4.88k
                                            AggValueSlot::DoesNotOverlap));
63
4.88k
    return;
64
15.2k
  }
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
15.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
15.6k
  QualType::DestructionKind DtorKind = D.needsDestruction(CGF.getContext());
79
80
  // FIXME:  __attribute__((cleanup)) ?
81
82
15.6k
  switch (DtorKind) {
83
10.9k
  case QualType::DK_none:
84
10.9k
    return;
85
86
4.75k
  case QualType::DK_cxx_destructor:
87
4.75k
    break;
88
89
7
  case QualType::DK_objc_strong_lifetime:
90
7
  case QualType::DK_objc_weak_lifetime:
91
7
  case QualType::DK_nontrivial_c_struct:
92
    // We don't care about releasing objects during process teardown.
93
7
    assert(!D.getTLSKind() && "should have rejected this");
94
0
    return;
95
15.6k
  }
96
97
4.75k
  llvm::FunctionCallee Func;
98
4.75k
  llvm::Constant *Argument;
99
100
4.75k
  CodeGenModule &CGM = CGF.CGM;
101
4.75k
  QualType Type = D.getType();
102
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.75k
  const CXXRecordDecl *Record = Type->getAsCXXRecordDecl();
108
4.75k
  bool CanRegisterDestructor =
109
4.75k
      Record && 
(4.41k
!CGM.getCXXABI().HasThisReturn(
110
4.41k
                     GlobalDecl(Record->getDestructor(), Dtor_Complete)) ||
111
4.41k
                 
CGM.getCXXABI().canCallMismatchedFunctionType()8
);
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.75k
  bool UsingExternalHelper = !CGM.getCodeGenOpts().CXAAtExit;
116
4.75k
  if (Record && 
(4.41k
CanRegisterDestructor4.41k
||
UsingExternalHelper1
)) {
117
4.41k
    assert(!Record->hasTrivialDestructor());
118
0
    CXXDestructorDecl *Dtor = Record->getDestructor();
119
120
4.41k
    Func = CGM.getAddrAndTypeOfCXXStructor(GlobalDecl(Dtor, Dtor_Complete));
121
4.41k
    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.40k
    } else {
134
4.40k
      Argument = llvm::ConstantExpr::getBitCast(
135
4.40k
          Addr.getPointer(), CGF.getTypes().ConvertType(Type)->getPointerTo());
136
4.40k
    }
137
  // Otherwise, the standard logic requires a helper function.
138
4.41k
  } else {
139
338
    Func = CodeGenFunction(CGM)
140
338
           .generateDestroyHelper(Addr, Type, CGF.getDestroyer(DtorKind),
141
338
                                  CGF.needsEHCleanup(DtorKind), &D);
142
338
    Argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
143
338
  }
144
145
0
  CGM.getCXXABI().registerGlobalDtor(CGF, D, Func, Argument);
146
4.75k
}
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
143
void CodeGenFunction::EmitInvariantStart(llvm::Constant *Addr, CharUnits Size) {
157
  // Do not emit the intrinsic if we're not optimizing.
158
143
  if (!CGM.getCodeGenOpts().OptimizationLevel)
159
133
    return;
160
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
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
15.8k
                                               bool PerformInit) {
177
178
15.8k
  const Expr *Init = D.getInit();
179
15.8k
  QualType T = D.getType();
180
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
15.8k
  unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(T);
197
15.8k
  unsigned ActualAddrSpace = DeclPtr->getType()->getPointerAddressSpace();
198
15.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
204
15.8k
  ConstantAddress DeclAddr(DeclPtr, getContext().getDeclAlign(&D));
205
206
15.8k
  if (!T->isReferenceType()) {
207
15.7k
    if (getLangOpts().OpenMP && 
!getLangOpts().OpenMPSimd3.87k
&&
208
15.7k
        
D.hasAttr<OMPThreadPrivateDeclAttr>()1.67k
) {
209
63
      (void)CGM.getOpenMPRuntime().emitThreadPrivateVarDefinition(
210
63
          &D, DeclAddr, D.getAttr<OMPThreadPrivateDeclAttr>()->getLocation(),
211
63
          PerformInit, this);
212
63
    }
213
15.7k
    if (PerformInit)
214
15.2k
      EmitDeclInit(*this, D, DeclAddr);
215
15.7k
    if (CGM.isTypeConstant(D.getType(), true))
216
92
      EmitDeclInvariant(*this, D, DeclPtr);
217
15.6k
    else
218
15.6k
      EmitDeclDestroy(*this, D, DeclAddr);
219
15.7k
    return;
220
15.7k
  }
221
222
99
  assert(PerformInit && "cannot have constant initializer which needs "
223
99
         "destruction for reference");
224
0
  RValue RV = EmitReferenceBindingToExpr(Init);
225
99
  EmitStoreOfScalar(RV.getScalarVal(), DeclAddr, false, T);
226
99
}
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
224
                                                  llvm::Constant *addr) {
233
  // Get the destructor function type, void(*)(void).
234
224
  llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
235
224
  SmallString<256> FnName;
236
224
  {
237
224
    llvm::raw_svector_ostream Out(FnName);
238
224
    CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out);
239
224
  }
240
241
224
  const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
242
224
  llvm::Function *fn = CGM.CreateGlobalInitOrCleanUpFunction(
243
224
      ty, FnName.str(), FI, VD.getLocation());
244
245
224
  CodeGenFunction CGF(CGM);
246
247
224
  CGF.StartFunction(GlobalDecl(&VD, DynamicInitKind::AtExit),
248
224
                    CGM.getContext().VoidTy, fn, FI, FunctionArgList(),
249
224
                    VD.getLocation(), VD.getInit()->getExprLoc());
250
  // Emit an artificial location for this function.
251
224
  auto AL = ApplyDebugLocation::CreateArtificial(CGF);
252
253
224
  llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
254
255
  // Make sure the call and the callee agree on calling convention.
256
224
  if (auto *dtorFn = dyn_cast<llvm::Function>(
257
224
          dtor.getCallee()->stripPointerCastsAndAliases()))
258
224
    call->setCallingConv(dtorFn->getCallingConv());
259
260
224
  CGF.FinishFunction();
261
262
224
  return fn;
263
224
}
264
265
/// Create a stub function, suitable for being passed to __pt_atexit_np,
266
/// which passes the given address to the given destructor function.
267
llvm::Function *CodeGenFunction::createTLSAtExitStub(
268
    const VarDecl &D, llvm::FunctionCallee Dtor, llvm::Constant *Addr,
269
5
    llvm::FunctionCallee &AtExit) {
270
5
  SmallString<256> FnName;
271
5
  {
272
5
    llvm::raw_svector_ostream Out(FnName);
273
5
    CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&D, Out);
274
5
  }
275
276
5
  const CGFunctionInfo &FI = CGM.getTypes().arrangeLLVMFunctionInfo(
277
5
      getContext().IntTy, /*instanceMethod=*/false, /*chainCall=*/false,
278
5
      {getContext().IntTy}, FunctionType::ExtInfo(), {}, RequiredArgs::All);
279
280
  // Get the stub function type, int(*)(int,...).
281
5
  llvm::FunctionType *StubTy =
282
5
      llvm::FunctionType::get(CGM.IntTy, {CGM.IntTy}, true);
283
284
5
  llvm::Function *DtorStub = CGM.CreateGlobalInitOrCleanUpFunction(
285
5
      StubTy, FnName.str(), FI, D.getLocation());
286
287
5
  CodeGenFunction CGF(CGM);
288
289
5
  FunctionArgList Args;
290
5
  ImplicitParamDecl IPD(CGM.getContext(), CGM.getContext().IntTy,
291
5
                        ImplicitParamDecl::Other);
292
5
  Args.push_back(&IPD);
293
5
  QualType ResTy = CGM.getContext().IntTy;
294
295
5
  CGF.StartFunction(GlobalDecl(&D, DynamicInitKind::AtExit), ResTy, DtorStub,
296
5
                    FI, Args, D.getLocation(), D.getInit()->getExprLoc());
297
298
  // Emit an artificial location for this function.
299
5
  auto AL = ApplyDebugLocation::CreateArtificial(CGF);
300
301
5
  llvm::CallInst *call = CGF.Builder.CreateCall(Dtor, Addr);
302
303
  // Make sure the call and the callee agree on calling convention.
304
5
  if (auto *DtorFn = dyn_cast<llvm::Function>(
305
5
          Dtor.getCallee()->stripPointerCastsAndAliases()))
306
5
    call->setCallingConv(DtorFn->getCallingConv());
307
308
  // Return 0 from function
309
5
  CGF.Builder.CreateStore(llvm::Constant::getNullValue(CGM.IntTy),
310
5
                          CGF.ReturnValue);
311
312
5
  CGF.FinishFunction();
313
314
5
  return DtorStub;
315
5
}
316
317
/// Register a global destructor using the C atexit runtime function.
318
void CodeGenFunction::registerGlobalDtorWithAtExit(const VarDecl &VD,
319
                                                   llvm::FunctionCallee dtor,
320
178
                                                   llvm::Constant *addr) {
321
  // Create a function which calls the destructor.
322
178
  llvm::Constant *dtorStub = createAtExitStub(VD, dtor, addr);
323
178
  registerGlobalDtorWithAtExit(dtorStub);
324
178
}
325
326
231
void CodeGenFunction::registerGlobalDtorWithAtExit(llvm::Constant *dtorStub) {
327
  // extern "C" int atexit(void (*f)(void));
328
231
  assert(dtorStub->getType() ==
329
231
             llvm::PointerType::get(
330
231
                 llvm::FunctionType::get(CGM.VoidTy, false),
331
231
                 dtorStub->getType()->getPointerAddressSpace()) &&
332
231
         "Argument to atexit has a wrong type.");
333
334
0
  llvm::FunctionType *atexitTy =
335
231
      llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
336
337
231
  llvm::FunctionCallee atexit =
338
231
      CGM.CreateRuntimeFunction(atexitTy, "atexit", llvm::AttributeList(),
339
231
                                /*Local=*/true);
340
231
  if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit.getCallee()))
341
231
    atexitFn->setDoesNotThrow();
342
343
231
  EmitNounwindRuntimeCall(atexit, dtorStub);
344
231
}
345
346
llvm::Value *
347
48
CodeGenFunction::unregisterGlobalDtorWithUnAtExit(llvm::Constant *dtorStub) {
348
  // The unatexit subroutine unregisters __dtor functions that were previously
349
  // registered by the atexit subroutine. If the referenced function is found,
350
  // it is removed from the list of functions that are called at normal program
351
  // termination and the unatexit returns a value of 0, otherwise a non-zero
352
  // value is returned.
353
  //
354
  // extern "C" int unatexit(void (*f)(void));
355
48
  assert(dtorStub->getType() ==
356
48
             llvm::PointerType::get(
357
48
                 llvm::FunctionType::get(CGM.VoidTy, false),
358
48
                 dtorStub->getType()->getPointerAddressSpace()) &&
359
48
         "Argument to unatexit has a wrong type.");
360
361
0
  llvm::FunctionType *unatexitTy =
362
48
      llvm::FunctionType::get(IntTy, {dtorStub->getType()}, /*isVarArg=*/false);
363
364
48
  llvm::FunctionCallee unatexit =
365
48
      CGM.CreateRuntimeFunction(unatexitTy, "unatexit", llvm::AttributeList());
366
367
48
  cast<llvm::Function>(unatexit.getCallee())->setDoesNotThrow();
368
369
48
  return EmitNounwindRuntimeCall(unatexit, dtorStub);
370
48
}
371
372
void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
373
                                         llvm::GlobalVariable *DeclPtr,
374
10.3k
                                         bool PerformInit) {
375
  // If we've been asked to forbid guard variables, emit an error now.
376
  // This diagnostic is hard-coded for Darwin's use case;  we can find
377
  // better phrasing if someone else needs it.
378
10.3k
  if (CGM.getCodeGenOpts().ForbidGuardVariables)
379
1
    CGM.Error(D.getLocation(),
380
1
              "this initialization requires a guard variable, which "
381
1
              "the kernel does not support");
382
383
10.3k
  CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
384
10.3k
}
385
386
void CodeGenFunction::EmitCXXGuardedInitBranch(llvm::Value *NeedsInit,
387
                                               llvm::BasicBlock *InitBlock,
388
                                               llvm::BasicBlock *NoInitBlock,
389
                                               GuardKind Kind,
390
10.3k
                                               const VarDecl *D) {
391
10.3k
  assert((Kind == GuardKind::TlsGuard || D) && "no guarded variable");
392
393
  // A guess at how many times we will enter the initialization of a
394
  // variable, depending on the kind of variable.
395
0
  static const uint64_t InitsPerTLSVar = 1024;
396
10.3k
  static const uint64_t InitsPerLocalVar = 1024 * 1024;
397
398
10.3k
  llvm::MDNode *Weights;
399
10.3k
  if (Kind == GuardKind::VariableGuard && 
!D->isLocalVarDecl()10.2k
) {
400
    // For non-local variables, don't apply any weighting for now. Due to our
401
    // use of COMDATs, we expect there to be at most one initialization of the
402
    // variable per DSO, but we have no way to know how many DSOs will try to
403
    // initialize the variable.
404
182
    Weights = nullptr;
405
10.1k
  } else {
406
10.1k
    uint64_t NumInits;
407
    // FIXME: For the TLS case, collect and use profiling information to
408
    // determine a more accurate brach weight.
409
10.1k
    if (Kind == GuardKind::TlsGuard || 
D->getTLSKind()10.0k
)
410
122
      NumInits = InitsPerTLSVar;
411
10.0k
    else
412
10.0k
      NumInits = InitsPerLocalVar;
413
414
    // The probability of us entering the initializer is
415
    //   1 / (total number of times we attempt to initialize the variable).
416
10.1k
    llvm::MDBuilder MDHelper(CGM.getLLVMContext());
417
10.1k
    Weights = MDHelper.createBranchWeights(1, NumInits - 1);
418
10.1k
  }
419
420
10.3k
  Builder.CreateCondBr(NeedsInit, InitBlock, NoInitBlock, Weights);
421
10.3k
}
422
423
llvm::Function *CodeGenModule::CreateGlobalInitOrCleanUpFunction(
424
    llvm::FunctionType *FTy, const Twine &Name, const CGFunctionInfo &FI,
425
10.6k
    SourceLocation Loc, bool TLS) {
426
10.6k
  llvm::Function *Fn = llvm::Function::Create(
427
10.6k
      FTy, llvm::GlobalValue::InternalLinkage, Name, &getModule());
428
429
10.6k
  if (!getLangOpts().AppleKext && 
!TLS10.6k
) {
430
    // Set the section if needed.
431
10.6k
    if (const char *Section = getTarget().getStaticInitSectionSpecifier())
432
2.52k
      Fn->setSection(Section);
433
10.6k
  }
434
435
10.6k
  SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
436
437
10.6k
  Fn->setCallingConv(getRuntimeCC());
438
439
10.6k
  if (!getLangOpts().Exceptions)
440
9.57k
    Fn->setDoesNotThrow();
441
442
10.6k
  if (getLangOpts().Sanitize.has(SanitizerKind::Address) &&
443
10.6k
      
!isInNoSanitizeList(SanitizerKind::Address, Fn, Loc)93
)
444
88
    Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
445
446
10.6k
  if (getLangOpts().Sanitize.has(SanitizerKind::KernelAddress) &&
447
10.6k
      
!isInNoSanitizeList(SanitizerKind::KernelAddress, Fn, Loc)4
)
448
2
    Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
449
450
10.6k
  if (getLangOpts().Sanitize.has(SanitizerKind::HWAddress) &&
451
10.6k
      
!isInNoSanitizeList(SanitizerKind::HWAddress, Fn, Loc)0
)
452
0
    Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
453
454
10.6k
  if (getLangOpts().Sanitize.has(SanitizerKind::KernelHWAddress) &&
455
10.6k
      
!isInNoSanitizeList(SanitizerKind::KernelHWAddress, Fn, Loc)0
)
456
0
    Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
457
458
10.6k
  if (getLangOpts().Sanitize.has(SanitizerKind::MemTag) &&
459
10.6k
      
!isInNoSanitizeList(SanitizerKind::MemTag, Fn, Loc)0
)
460
0
    Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
461
462
10.6k
  if (getLangOpts().Sanitize.has(SanitizerKind::Thread) &&
463
10.6k
      
!isInNoSanitizeList(SanitizerKind::Thread, Fn, Loc)6
)
464
3
    Fn->addFnAttr(llvm::Attribute::SanitizeThread);
465
466
10.6k
  if (getLangOpts().Sanitize.has(SanitizerKind::Memory) &&
467
10.6k
      
!isInNoSanitizeList(SanitizerKind::Memory, Fn, Loc)93
)
468
93
    Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
469
470
10.6k
  if (getLangOpts().Sanitize.has(SanitizerKind::KernelMemory) &&
471
10.6k
      
!isInNoSanitizeList(SanitizerKind::KernelMemory, Fn, Loc)0
)
472
0
    Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
473
474
10.6k
  if (getLangOpts().Sanitize.has(SanitizerKind::SafeStack) &&
475
10.6k
      
!isInNoSanitizeList(SanitizerKind::SafeStack, Fn, Loc)0
)
476
0
    Fn->addFnAttr(llvm::Attribute::SafeStack);
477
478
10.6k
  if (getLangOpts().Sanitize.has(SanitizerKind::ShadowCallStack) &&
479
10.6k
      
!isInNoSanitizeList(SanitizerKind::ShadowCallStack, Fn, Loc)0
)
480
0
    Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
481
482
10.6k
  return Fn;
483
10.6k
}
484
485
/// Create a global pointer to a function that will initialize a global
486
/// variable.  The user has requested that this pointer be emitted in a specific
487
/// section.
488
void CodeGenModule::EmitPointerToInitFunc(const VarDecl *D,
489
                                          llvm::GlobalVariable *GV,
490
                                          llvm::Function *InitFunc,
491
6
                                          InitSegAttr *ISA) {
492
6
  llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable(
493
6
      TheModule, InitFunc->getType(), /*isConstant=*/true,
494
6
      llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr");
495
6
  PtrArray->setSection(ISA->getSection());
496
6
  addUsedGlobal(PtrArray);
497
498
  // If the GV is already in a comdat group, then we have to join it.
499
6
  if (llvm::Comdat *C = GV->getComdat())
500
3
    PtrArray->setComdat(C);
501
6
}
502
503
void
504
CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
505
                                            llvm::GlobalVariable *Addr,
506
5.92k
                                            bool PerformInit) {
507
508
  // According to E.2.3.1 in CUDA-7.5 Programming guide: __device__,
509
  // __constant__ and __shared__ variables defined in namespace scope,
510
  // that are of class type, cannot have a non-empty constructor. All
511
  // the checks have been done in Sema by now. Whatever initializers
512
  // are allowed are empty and we just need to ignore them here.
513
5.92k
  if (getLangOpts().CUDAIsDevice && 
!getLangOpts().GPUAllowDeviceInit25
&&
514
5.92k
      
(24
D->hasAttr<CUDADeviceAttr>()24
||
D->hasAttr<CUDAConstantAttr>()14
||
515
24
       
D->hasAttr<CUDASharedAttr>()4
))
516
24
    return;
517
518
5.89k
  if (getLangOpts().OpenMP &&
519
5.89k
      
getOpenMPRuntime().emitDeclareTargetVarDefinition(D, Addr, PerformInit)3.89k
)
520
78
    return;
521
522
  // Check if we've already initialized this decl.
523
5.81k
  auto I = DelayedCXXInitPosition.find(D);
524
5.81k
  if (I != DelayedCXXInitPosition.end() && 
I->second == ~0U1.62k
)
525
22
    return;
526
527
5.79k
  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
528
5.79k
  SmallString<256> FnName;
529
5.79k
  {
530
5.79k
    llvm::raw_svector_ostream Out(FnName);
531
5.79k
    getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
532
5.79k
  }
533
534
  // Create a variable initialization function.
535
5.79k
  llvm::Function *Fn = CreateGlobalInitOrCleanUpFunction(
536
5.79k
      FTy, FnName.str(), getTypes().arrangeNullaryFunction(), D->getLocation());
537
538
5.79k
  auto *ISA = D->getAttr<InitSegAttr>();
539
5.79k
  CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
540
5.79k
                                                          PerformInit);
541
542
5.79k
  llvm::GlobalVariable *COMDATKey =
543
5.79k
      supportsCOMDAT() && 
D->isExternallyVisible()4.63k
?
Addr3.91k
:
nullptr1.88k
;
544
545
5.79k
  if (D->getTLSKind()) {
546
    // FIXME: Should we support init_priority for thread_local?
547
    // FIXME: We only need to register one __cxa_thread_atexit function for the
548
    // entire TU.
549
187
    CXXThreadLocalInits.push_back(Fn);
550
187
    CXXThreadLocalInitVars.push_back(D);
551
5.60k
  } else if (PerformInit && 
ISA5.18k
) {
552
6
    EmitPointerToInitFunc(D, Addr, Fn, ISA);
553
5.60k
  } else if (auto *IPA = D->getAttr<InitPriorityAttr>()) {
554
929
    OrderGlobalInitsOrStermFinalizers Key(IPA->getPriority(),
555
929
                                          PrioritizedCXXGlobalInits.size());
556
929
    PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
557
4.67k
  } else if (isTemplateInstantiation(D->getTemplateSpecializationKind()) ||
558
4.67k
             
getContext().GetGVALinkageForVariable(D) == GVA_DiscardableODR4.56k
||
559
4.67k
             
D->hasAttr<SelectAnyAttr>()4.54k
) {
560
    // C++ [basic.start.init]p2:
561
    //   Definitions of explicitly specialized class template static data
562
    //   members have ordered initialization. Other class template static data
563
    //   members (i.e., implicitly or explicitly instantiated specializations)
564
    //   have unordered initialization.
565
    //
566
    // As a consequence, we can put them into their own llvm.global_ctors entry.
567
    //
568
    // If the global is externally visible, put the initializer into a COMDAT
569
    // group with the global being initialized.  On most platforms, this is a
570
    // minor startup time optimization.  In the MS C++ ABI, there are no guard
571
    // variables, so this COMDAT key is required for correctness.
572
    //
573
    // SelectAny globals will be comdat-folded. Put the initializer into a
574
    // COMDAT group associated with the global, so the initializers get folded
575
    // too.
576
577
140
    AddGlobalCtor(Fn, 65535, COMDATKey);
578
140
    if (COMDATKey && 
(105
getTriple().isOSBinFormatELF()105
||
579
105
                      
getTarget().getCXXABI().isMicrosoft()37
)) {
580
      // When COMDAT is used on ELF or in the MS C++ ABI, the key must be in
581
      // llvm.used to prevent linker GC.
582
105
      addUsedGlobal(COMDATKey);
583
105
    }
584
585
    // If we used a COMDAT key for the global ctor, the init function can be
586
    // discarded if the global ctor entry is discarded.
587
    // FIXME: Do we need to restrict this to ELF and Wasm?
588
140
    llvm::Comdat *C = Addr->getComdat();
589
140
    if (COMDATKey && 
C105
&&
590
140
        
(105
getTarget().getTriple().isOSBinFormatELF()105
||
591
105
         
getTarget().getTriple().isOSBinFormatWasm()37
)) {
592
68
      Fn->setComdat(C);
593
68
    }
594
4.53k
  } else {
595
4.53k
    I = DelayedCXXInitPosition.find(D); // Re-do lookup in case of re-hash.
596
4.53k
    if (I == DelayedCXXInitPosition.end()) {
597
3.30k
      CXXGlobalInits.push_back(Fn);
598
3.30k
    } else 
if (1.22k
I->second != ~0U1.22k
) {
599
1.22k
      assert(I->second < CXXGlobalInits.size() &&
600
1.22k
             CXXGlobalInits[I->second] == nullptr);
601
0
      CXXGlobalInits[I->second] = Fn;
602
1.22k
    }
603
4.53k
  }
604
605
  // Remember that we already emitted the initializer for this global.
606
0
  DelayedCXXInitPosition[D] = ~0U;
607
5.79k
}
608
609
36.7k
void CodeGenModule::EmitCXXThreadLocalInitFunc() {
610
36.7k
  getCXXABI().EmitThreadLocalInitFuncs(
611
36.7k
      *this, CXXThreadLocals, CXXThreadLocalInits, CXXThreadLocalInitVars);
612
613
36.7k
  CXXThreadLocalInits.clear();
614
36.7k
  CXXThreadLocalInitVars.clear();
615
36.7k
  CXXThreadLocals.clear();
616
36.7k
}
617
618
1.36k
static SmallString<128> getTransformedFileName(llvm::Module &M) {
619
1.36k
  SmallString<128> FileName = llvm::sys::path::filename(M.getName());
620
621
1.36k
  if (FileName.empty())
622
0
    FileName = "<null>";
623
624
45.7k
  for (size_t i = 0; i < FileName.size(); 
++i44.3k
) {
625
    // Replace everything that's not [a-zA-Z0-9._] with a _. This set happens
626
    // to be the set of C preprocessing numbers.
627
44.3k
    if (!isPreprocessingNumberBody(FileName[i]))
628
910
      FileName[i] = '_';
629
44.3k
  }
630
631
1.36k
  return FileName;
632
1.36k
}
633
634
626
static std::string getPrioritySuffix(unsigned int Priority) {
635
626
  assert(Priority <= 65535 && "Priority should always be <= 65535.");
636
637
  // Compute the function suffix from priority. Prepend with zeroes to make
638
  // sure the function names are also ordered as priorities.
639
0
  std::string PrioritySuffix = llvm::utostr(Priority);
640
626
  PrioritySuffix = std::string(6 - PrioritySuffix.size(), '0') + PrioritySuffix;
641
642
626
  return PrioritySuffix;
643
626
}
644
645
void
646
36.7k
CodeGenModule::EmitCXXGlobalInitFunc() {
647
50.7k
  while (!CXXGlobalInits.empty() && 
!CXXGlobalInits.back()15.3k
)
648
13.9k
    CXXGlobalInits.pop_back();
649
650
36.7k
  if (CXXGlobalInits.empty() && 
PrioritizedCXXGlobalInits.empty()35.4k
)
651
35.4k
    return;
652
653
1.36k
  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
654
1.36k
  const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
655
656
  // Create our global prioritized initialization function.
657
1.36k
  if (!PrioritizedCXXGlobalInits.empty()) {
658
309
    SmallVector<llvm::Function *, 8> LocalCXXGlobalInits;
659
309
    llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
660
309
                         PrioritizedCXXGlobalInits.end());
661
    // Iterate over "chunks" of ctors with same priority and emit each chunk
662
    // into separate function. Note - everything is sorted first by priority,
663
    // second - by lex order, so we emit ctor functions in proper order.
664
309
    for (SmallVectorImpl<GlobalInitData >::iterator
665
309
           I = PrioritizedCXXGlobalInits.begin(),
666
929
           E = PrioritizedCXXGlobalInits.end(); I != E; ) {
667
620
      SmallVectorImpl<GlobalInitData >::iterator
668
620
        PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
669
670
620
      LocalCXXGlobalInits.clear();
671
672
620
      unsigned int Priority = I->first.priority;
673
620
      llvm::Function *Fn = CreateGlobalInitOrCleanUpFunction(
674
620
          FTy, "_GLOBAL__I_" + getPrioritySuffix(Priority), FI);
675
676
1.54k
      for (; I < PrioE; 
++I929
)
677
929
        LocalCXXGlobalInits.push_back(I->second);
678
679
620
      CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
680
620
      AddGlobalCtor(Fn, Priority);
681
620
    }
682
309
    PrioritizedCXXGlobalInits.clear();
683
309
  }
684
685
1.36k
  if (getCXXABI().useSinitAndSterm() && 
CXXGlobalInits.empty()15
)
686
0
    return;
687
688
  // Include the filename in the symbol name. Including "sub_" matches gcc
689
  // and makes sure these symbols appear lexicographically behind the symbols
690
  // with priority emitted above.
691
1.36k
  llvm::Function *Fn = CreateGlobalInitOrCleanUpFunction(
692
1.36k
      FTy, llvm::Twine("_GLOBAL__sub_I_", getTransformedFileName(getModule())),
693
1.36k
      FI);
694
695
1.36k
  CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
696
1.36k
  AddGlobalCtor(Fn);
697
698
  // In OpenCL global init functions must be converted to kernels in order to
699
  // be able to launch them from the host.
700
  // FIXME: Some more work might be needed to handle destructors correctly.
701
  // Current initialization function makes use of function pointers callbacks.
702
  // We can't support function pointers especially between host and device.
703
  // However it seems global destruction has little meaning without any
704
  // dynamic resource allocation on the device and program scope variables are
705
  // destroyed by the runtime when program is released.
706
1.36k
  if (getLangOpts().OpenCL) {
707
7
    GenOpenCLArgMetadata(Fn);
708
7
    Fn->setCallingConv(llvm::CallingConv::SPIR_KERNEL);
709
7
  }
710
711
1.36k
  assert(!getLangOpts().CUDA || !getLangOpts().CUDAIsDevice ||
712
1.36k
         getLangOpts().GPUAllowDeviceInit);
713
1.36k
  if (getLangOpts().HIP && 
getLangOpts().CUDAIsDevice1
) {
714
1
    Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
715
1
    Fn->addFnAttr("device-init");
716
1
  }
717
718
1.36k
  CXXGlobalInits.clear();
719
1.36k
}
720
721
36.7k
void CodeGenModule::EmitCXXGlobalCleanUpFunc() {
722
36.7k
  if (CXXGlobalDtorsOrStermFinalizers.empty() &&
723
36.7k
      
PrioritizedCXXStermFinalizers.empty()36.7k
)
724
36.7k
    return;
725
726
17
  llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
727
17
  const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
728
729
  // Create our global prioritized cleanup function.
730
17
  if (!PrioritizedCXXStermFinalizers.empty()) {
731
2
    SmallVector<CXXGlobalDtorsOrStermFinalizer_t, 8> LocalCXXStermFinalizers;
732
2
    llvm::array_pod_sort(PrioritizedCXXStermFinalizers.begin(),
733
2
                         PrioritizedCXXStermFinalizers.end());
734
    // Iterate over "chunks" of dtors with same priority and emit each chunk
735
    // into separate function. Note - everything is sorted first by priority,
736
    // second - by lex order, so we emit dtor functions in proper order.
737
2
    for (SmallVectorImpl<StermFinalizerData>::iterator
738
2
             I = PrioritizedCXXStermFinalizers.begin(),
739
2
             E = PrioritizedCXXStermFinalizers.end();
740
8
         I != E;) {
741
6
      SmallVectorImpl<StermFinalizerData>::iterator PrioE =
742
6
          std::upper_bound(I + 1, E, *I, StermFinalizerPriorityCmp());
743
744
6
      LocalCXXStermFinalizers.clear();
745
746
6
      unsigned int Priority = I->first.priority;
747
6
      llvm::Function *Fn = CreateGlobalInitOrCleanUpFunction(
748
6
          FTy, "_GLOBAL__a_" + getPrioritySuffix(Priority), FI);
749
750
14
      for (; I < PrioE; 
++I8
) {
751
8
        llvm::FunctionCallee DtorFn = I->second;
752
8
        LocalCXXStermFinalizers.emplace_back(DtorFn.getFunctionType(),
753
8
                                             DtorFn.getCallee(), nullptr);
754
8
      }
755
756
6
      CodeGenFunction(*this).GenerateCXXGlobalCleanUpFunc(
757
6
          Fn, LocalCXXStermFinalizers);
758
6
      AddGlobalDtor(Fn, Priority);
759
6
    }
760
2
    PrioritizedCXXStermFinalizers.clear();
761
2
  }
762
763
17
  if (CXXGlobalDtorsOrStermFinalizers.empty())
764
0
    return;
765
766
  // Create our global cleanup function.
767
17
  llvm::Function *Fn =
768
17
      CreateGlobalInitOrCleanUpFunction(FTy, "_GLOBAL__D_a", FI);
769
770
17
  CodeGenFunction(*this).GenerateCXXGlobalCleanUpFunc(
771
17
      Fn, CXXGlobalDtorsOrStermFinalizers);
772
17
  AddGlobalDtor(Fn);
773
17
  CXXGlobalDtorsOrStermFinalizers.clear();
774
17
}
775
776
/// Emit the code necessary to initialize the given global variable.
777
void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
778
                                                       const VarDecl *D,
779
                                                 llvm::GlobalVariable *Addr,
780
5.79k
                                                       bool PerformInit) {
781
  // Check if we need to emit debug info for variable initializer.
782
5.79k
  if (D->hasAttr<NoDebugAttr>())
783
1
    DebugInfo = nullptr; // disable debug info indefinitely for this function
784
785
5.79k
  CurEHLocation = D->getBeginLoc();
786
787
5.79k
  StartFunction(GlobalDecl(D, DynamicInitKind::Initializer),
788
5.79k
                getContext().VoidTy, Fn, getTypes().arrangeNullaryFunction(),
789
5.79k
                FunctionArgList());
790
  // Emit an artificial location for this function.
791
5.79k
  auto AL = ApplyDebugLocation::CreateArtificial(*this);
792
793
  // Use guarded initialization if the global variable is weak. This
794
  // occurs for, e.g., instantiated static data members and
795
  // definitions explicitly marked weak.
796
  //
797
  // Also use guarded initialization for a variable with dynamic TLS and
798
  // unordered initialization. (If the initialization is ordered, the ABI
799
  // layer will guard the whole-TU initialization for us.)
800
5.79k
  if (Addr->hasWeakLinkage() || 
Addr->hasLinkOnceLinkage()5.72k
||
801
5.79k
      
(5.56k
D->getTLSKind() == VarDecl::TLS_Dynamic5.56k
&&
802
5.56k
       
isTemplateInstantiation(D->getTemplateSpecializationKind())102
)) {
803
228
    EmitCXXGuardedInit(*D, Addr, PerformInit);
804
5.56k
  } else {
805
5.56k
    EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
806
5.56k
  }
807
808
5.79k
  FinishFunction();
809
5.79k
}
810
811
void
812
CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
813
                                           ArrayRef<llvm::Function *> Decls,
814
2.04k
                                           ConstantAddress Guard) {
815
2.04k
  {
816
2.04k
    auto NL = ApplyDebugLocation::CreateEmpty(*this);
817
2.04k
    StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
818
2.04k
                  getTypes().arrangeNullaryFunction(), FunctionArgList());
819
    // Emit an artificial location for this function.
820
2.04k
    auto AL = ApplyDebugLocation::CreateArtificial(*this);
821
822
2.04k
    llvm::BasicBlock *ExitBlock = nullptr;
823
2.04k
    if (Guard.isValid()) {
824
      // If we have a guard variable, check whether we've already performed
825
      // these initializations. This happens for TLS initialization functions.
826
51
      llvm::Value *GuardVal = Builder.CreateLoad(Guard);
827
51
      llvm::Value *Uninit = Builder.CreateIsNull(GuardVal,
828
51
                                                 "guard.uninitialized");
829
51
      llvm::BasicBlock *InitBlock = createBasicBlock("init");
830
51
      ExitBlock = createBasicBlock("exit");
831
51
      EmitCXXGuardedInitBranch(Uninit, InitBlock, ExitBlock,
832
51
                               GuardKind::TlsGuard, nullptr);
833
51
      EmitBlock(InitBlock);
834
      // Mark as initialized before initializing anything else. If the
835
      // initializers use previously-initialized thread_local vars, that's
836
      // probably supposed to be OK, but the standard doesn't say.
837
51
      Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard);
838
839
      // The guard variable can't ever change again.
840
51
      EmitInvariantStart(
841
51
          Guard.getPointer(),
842
51
          CharUnits::fromQuantity(
843
51
              CGM.getDataLayout().getTypeAllocSize(GuardVal->getType())));
844
51
    }
845
846
2.04k
    RunCleanupsScope Scope(*this);
847
848
    // When building in Objective-C++ ARC mode, create an autorelease pool
849
    // around the global initializers.
850
2.04k
    if (getLangOpts().ObjCAutoRefCount && 
getLangOpts().CPlusPlus4
) {
851
4
      llvm::Value *token = EmitObjCAutoreleasePoolPush();
852
4
      EmitObjCAutoreleasePoolCleanup(token);
853
4
    }
854
855
10.4k
    for (unsigned i = 0, e = Decls.size(); i != e; 
++i8.38k
)
856
8.38k
      if (Decls[i])
857
5.56k
        EmitRuntimeCall(Decls[i]);
858
859
2.04k
    Scope.ForceCleanup();
860
861
2.04k
    if (ExitBlock) {
862
51
      Builder.CreateBr(ExitBlock);
863
51
      EmitBlock(ExitBlock);
864
51
    }
865
2.04k
  }
866
867
2.04k
  FinishFunction();
868
2.04k
}
869
870
void CodeGenFunction::GenerateCXXGlobalCleanUpFunc(
871
    llvm::Function *Fn,
872
    ArrayRef<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
873
                        llvm::Constant *>>
874
23
        DtorsOrStermFinalizers) {
875
23
  {
876
23
    auto NL = ApplyDebugLocation::CreateEmpty(*this);
877
23
    StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
878
23
                  getTypes().arrangeNullaryFunction(), FunctionArgList());
879
    // Emit an artificial location for this function.
880
23
    auto AL = ApplyDebugLocation::CreateArtificial(*this);
881
882
    // Emit the cleanups, in reverse order from construction.
883
59
    for (unsigned i = 0, e = DtorsOrStermFinalizers.size(); i != e; 
++i36
) {
884
36
      llvm::FunctionType *CalleeTy;
885
36
      llvm::Value *Callee;
886
36
      llvm::Constant *Arg;
887
36
      std::tie(CalleeTy, Callee, Arg) = DtorsOrStermFinalizers[e - i - 1];
888
889
36
      llvm::CallInst *CI = nullptr;
890
36
      if (Arg == nullptr) {
891
30
        assert(
892
30
            CGM.getCXXABI().useSinitAndSterm() &&
893
30
            "Arg could not be nullptr unless using sinit and sterm functions.");
894
0
        CI = Builder.CreateCall(CalleeTy, Callee);
895
30
      } else
896
6
        CI = Builder.CreateCall(CalleeTy, Callee, Arg);
897
898
      // Make sure the call and the callee agree on calling convention.
899
36
      if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
900
36
        CI->setCallingConv(F->getCallingConv());
901
36
    }
902
23
  }
903
904
23
  FinishFunction();
905
23
}
906
907
/// generateDestroyHelper - Generates a helper function which, when
908
/// invoked, destroys the given object.  The address of the object
909
/// should be in global memory.
910
llvm::Function *CodeGenFunction::generateDestroyHelper(
911
    Address addr, QualType type, Destroyer *destroyer,
912
342
    bool useEHCleanupForArray, const VarDecl *VD) {
913
342
  FunctionArgList args;
914
342
  ImplicitParamDecl Dst(getContext(), getContext().VoidPtrTy,
915
342
                        ImplicitParamDecl::Other);
916
342
  args.push_back(&Dst);
917
918
342
  const CGFunctionInfo &FI =
919
342
    CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, args);
920
342
  llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
921
342
  llvm::Function *fn = CGM.CreateGlobalInitOrCleanUpFunction(
922
342
      FTy, "__cxx_global_array_dtor", FI, VD->getLocation());
923
924
342
  CurEHLocation = VD->getBeginLoc();
925
926
342
  StartFunction(GlobalDecl(VD, DynamicInitKind::GlobalArrayDestructor),
927
342
                getContext().VoidTy, fn, FI, args);
928
  // Emit an artificial location for this function.
929
342
  auto AL = ApplyDebugLocation::CreateArtificial(*this);
930
931
342
  emitDestroy(addr, type, destroyer, useEHCleanupForArray);
932
933
342
  FinishFunction();
934
935
342
  return fn;
936
342
}