xref: /llvm-project/clang/lib/CodeGen/CGDeclCXX.cpp (revision 719f0d92538c917306004e541f38c79717d0c07d)
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 "CGHLSLRuntime.h"
15 #include "CGObjCRuntime.h"
16 #include "CGOpenMPRuntime.h"
17 #include "CodeGenFunction.h"
18 #include "TargetInfo.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/IR/Intrinsics.h"
23 #include "llvm/IR/MDBuilder.h"
24 #include "llvm/Support/Path.h"
25 
26 using namespace clang;
27 using namespace CodeGen;
28 
29 static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
30                          ConstantAddress DeclPtr) {
31   assert(
32       (D.hasGlobalStorage() ||
33        (D.hasLocalStorage() && CGF.getContext().getLangOpts().OpenCLCPlusPlus)) &&
34       "VarDecl must have global or local (in the case of OpenCL) storage!");
35   assert(!D.getType()->isReferenceType() &&
36          "Should not call EmitDeclInit on a reference!");
37 
38   QualType type = D.getType();
39   LValue lv = CGF.MakeAddrLValue(DeclPtr, type);
40 
41   const Expr *Init = D.getInit();
42   switch (CGF.getEvaluationKind(type)) {
43   case TEK_Scalar: {
44     CodeGenModule &CGM = CGF.CGM;
45     if (lv.isObjCStrong())
46       CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
47                                                 DeclPtr, D.getTLSKind());
48     else if (lv.isObjCWeak())
49       CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
50                                               DeclPtr);
51     else
52       CGF.EmitScalarInit(Init, &D, lv, false);
53     return;
54   }
55   case TEK_Complex:
56     CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true);
57     return;
58   case TEK_Aggregate:
59     CGF.EmitAggExpr(Init,
60                     AggValueSlot::forLValue(lv, AggValueSlot::IsDestructed,
61                                             AggValueSlot::DoesNotNeedGCBarriers,
62                                             AggValueSlot::IsNotAliased,
63                                             AggValueSlot::DoesNotOverlap));
64     return;
65   }
66   llvm_unreachable("bad evaluation kind");
67 }
68 
69 /// Emit code to cause the destruction of the given variable with
70 /// static storage duration.
71 static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
72                             ConstantAddress Addr) {
73   // Honor __attribute__((no_destroy)) and bail instead of attempting
74   // to emit a reference to a possibly nonexistent destructor, which
75   // in turn can cause a crash. This will result in a global constructor
76   // that isn't balanced out by a destructor call as intended by the
77   // attribute. This also checks for -fno-c++-static-destructors and
78   // bails even if the attribute is not present.
79   QualType::DestructionKind DtorKind = D.needsDestruction(CGF.getContext());
80 
81   // FIXME:  __attribute__((cleanup)) ?
82 
83   switch (DtorKind) {
84   case QualType::DK_none:
85     return;
86 
87   case QualType::DK_cxx_destructor:
88     break;
89 
90   case QualType::DK_objc_strong_lifetime:
91   case QualType::DK_objc_weak_lifetime:
92   case QualType::DK_nontrivial_c_struct:
93     // We don't care about releasing objects during process teardown.
94     assert(!D.getTLSKind() && "should have rejected this");
95     return;
96   }
97 
98   llvm::FunctionCallee Func;
99   llvm::Constant *Argument;
100 
101   CodeGenModule &CGM = CGF.CGM;
102   QualType Type = D.getType();
103 
104   // Special-case non-array C++ destructors, if they have the right signature.
105   // Under some ABIs, destructors return this instead of void, and cannot be
106   // passed directly to __cxa_atexit if the target does not allow this
107   // mismatch.
108   const CXXRecordDecl *Record = Type->getAsCXXRecordDecl();
109   bool CanRegisterDestructor =
110       Record && (!CGM.getCXXABI().HasThisReturn(
111                      GlobalDecl(Record->getDestructor(), Dtor_Complete)) ||
112                  CGM.getCXXABI().canCallMismatchedFunctionType());
113   // If __cxa_atexit is disabled via a flag, a different helper function is
114   // generated elsewhere which uses atexit instead, and it takes the destructor
115   // directly.
116   bool UsingExternalHelper = !CGM.getCodeGenOpts().CXAAtExit;
117   if (Record && (CanRegisterDestructor || UsingExternalHelper)) {
118     assert(!Record->hasTrivialDestructor());
119     CXXDestructorDecl *Dtor = Record->getDestructor();
120 
121     Func = CGM.getAddrAndTypeOfCXXStructor(GlobalDecl(Dtor, Dtor_Complete));
122     if (CGF.getContext().getLangOpts().OpenCL) {
123       auto DestAS =
124           CGM.getTargetCodeGenInfo().getAddrSpaceOfCxaAtexitPtrParam();
125       auto DestTy = llvm::PointerType::get(
126           CGM.getLLVMContext(), CGM.getContext().getTargetAddressSpace(DestAS));
127       auto SrcAS = D.getType().getQualifiers().getAddressSpace();
128       if (DestAS == SrcAS)
129         Argument = Addr.getPointer();
130       else
131         // FIXME: On addr space mismatch we are passing NULL. The generation
132         // of the global destructor function should be adjusted accordingly.
133         Argument = llvm::ConstantPointerNull::get(DestTy);
134     } else {
135       Argument = Addr.getPointer();
136     }
137   // Otherwise, the standard logic requires a helper function.
138   } else {
139     Addr = Addr.withElementType(CGF.ConvertTypeForMem(Type));
140     Func = CodeGenFunction(CGM)
141            .generateDestroyHelper(Addr, Type, CGF.getDestroyer(DtorKind),
142                                   CGF.needsEHCleanup(DtorKind), &D);
143     Argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
144   }
145 
146   CGM.getCXXABI().registerGlobalDtor(CGF, D, Func, Argument);
147 }
148 
149 /// Emit code to cause the variable at the given address to be considered as
150 /// constant from this point onwards.
151 static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
152                               llvm::Constant *Addr) {
153   return CGF.EmitInvariantStart(
154       Addr, CGF.getContext().getTypeSizeInChars(D.getType()));
155 }
156 
157 void CodeGenFunction::EmitInvariantStart(llvm::Constant *Addr, CharUnits Size) {
158   // Do not emit the intrinsic if we're not optimizing.
159   if (!CGM.getCodeGenOpts().OptimizationLevel)
160     return;
161 
162   // Grab the llvm.invariant.start intrinsic.
163   llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
164   // Overloaded address space type.
165   assert(Addr->getType()->isPointerTy() && "Address must be a pointer");
166   llvm::Type *ObjectPtr[1] = {Addr->getType()};
167   llvm::Function *InvariantStart = CGM.getIntrinsic(InvStartID, ObjectPtr);
168 
169   // Emit a call with the size in bytes of the object.
170   uint64_t Width = Size.getQuantity();
171   llvm::Value *Args[2] = {llvm::ConstantInt::getSigned(Int64Ty, Width), Addr};
172   Builder.CreateCall(InvariantStart, Args);
173 }
174 
175 void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
176                                                llvm::GlobalVariable *GV,
177                                                bool PerformInit) {
178 
179   const Expr *Init = D.getInit();
180   QualType T = D.getType();
181 
182   // The address space of a static local variable (DeclPtr) may be different
183   // from the address space of the "this" argument of the constructor. In that
184   // case, we need an addrspacecast before calling the constructor.
185   //
186   // struct StructWithCtor {
187   //   __device__ StructWithCtor() {...}
188   // };
189   // __device__ void foo() {
190   //   __shared__ StructWithCtor s;
191   //   ...
192   // }
193   //
194   // For example, in the above CUDA code, the static local variable s has a
195   // "shared" address space qualifier, but the constructor of StructWithCtor
196   // expects "this" in the "generic" address space.
197   unsigned ExpectedAddrSpace = getTypes().getTargetAddressSpace(T);
198   unsigned ActualAddrSpace = GV->getAddressSpace();
199   llvm::Constant *DeclPtr = GV;
200   if (ActualAddrSpace != ExpectedAddrSpace) {
201     llvm::PointerType *PTy =
202         llvm::PointerType::get(getLLVMContext(), ExpectedAddrSpace);
203     DeclPtr = llvm::ConstantExpr::getAddrSpaceCast(DeclPtr, PTy);
204   }
205 
206   ConstantAddress DeclAddr(
207       DeclPtr, GV->getValueType(), getContext().getDeclAlign(&D));
208 
209   if (!T->isReferenceType()) {
210     if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
211         D.hasAttr<OMPThreadPrivateDeclAttr>()) {
212       (void)CGM.getOpenMPRuntime().emitThreadPrivateVarDefinition(
213           &D, DeclAddr, D.getAttr<OMPThreadPrivateDeclAttr>()->getLocation(),
214           PerformInit, this);
215     }
216     bool NeedsDtor =
217         D.needsDestruction(getContext()) == QualType::DK_cxx_destructor;
218     if (PerformInit)
219       EmitDeclInit(*this, D, DeclAddr);
220     if (D.getType().isConstantStorage(getContext(), true, !NeedsDtor))
221       EmitDeclInvariant(*this, D, DeclPtr);
222     else
223       EmitDeclDestroy(*this, D, DeclAddr);
224     return;
225   }
226 
227   assert(PerformInit && "cannot have constant initializer which needs "
228          "destruction for reference");
229   RValue RV = EmitReferenceBindingToExpr(Init);
230   EmitStoreOfScalar(RV.getScalarVal(), DeclAddr, false, T);
231 }
232 
233 /// Create a stub function, suitable for being passed to atexit,
234 /// which passes the given address to the given destructor function.
235 llvm::Constant *CodeGenFunction::createAtExitStub(const VarDecl &VD,
236                                                   llvm::FunctionCallee dtor,
237                                                   llvm::Constant *addr) {
238   // Get the destructor function type, void(*)(void).
239   llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
240   SmallString<256> FnName;
241   {
242     llvm::raw_svector_ostream Out(FnName);
243     CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out);
244   }
245 
246   const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
247   llvm::Function *fn = CGM.CreateGlobalInitOrCleanUpFunction(
248       ty, FnName.str(), FI, VD.getLocation());
249 
250   CodeGenFunction CGF(CGM);
251 
252   CGF.StartFunction(GlobalDecl(&VD, DynamicInitKind::AtExit),
253                     CGM.getContext().VoidTy, fn, FI, FunctionArgList(),
254                     VD.getLocation(), VD.getInit()->getExprLoc());
255   // Emit an artificial location for this function.
256   auto AL = ApplyDebugLocation::CreateArtificial(CGF);
257 
258   llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
259 
260   // Make sure the call and the callee agree on calling convention.
261   if (auto *dtorFn = dyn_cast<llvm::Function>(
262           dtor.getCallee()->stripPointerCastsAndAliases()))
263     call->setCallingConv(dtorFn->getCallingConv());
264 
265   CGF.FinishFunction();
266 
267   // Get a proper function pointer.
268   FunctionProtoType::ExtProtoInfo EPI(getContext().getDefaultCallingConvention(
269       /*IsVariadic=*/false, /*IsCXXMethod=*/false));
270   QualType fnType = getContext().getFunctionType(getContext().VoidTy,
271                                                  {getContext().VoidPtrTy}, EPI);
272   return CGM.getFunctionPointer(fn, fnType);
273 }
274 
275 /// Create a stub function, suitable for being passed to __pt_atexit_np,
276 /// which passes the given address to the given destructor function.
277 llvm::Function *CodeGenFunction::createTLSAtExitStub(
278     const VarDecl &D, llvm::FunctionCallee Dtor, llvm::Constant *Addr,
279     llvm::FunctionCallee &AtExit) {
280   SmallString<256> FnName;
281   {
282     llvm::raw_svector_ostream Out(FnName);
283     CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&D, Out);
284   }
285 
286   const CGFunctionInfo &FI = CGM.getTypes().arrangeLLVMFunctionInfo(
287       getContext().IntTy, FnInfoOpts::None, {getContext().IntTy},
288       FunctionType::ExtInfo(), {}, RequiredArgs::All);
289 
290   // Get the stub function type, int(*)(int,...).
291   llvm::FunctionType *StubTy =
292       llvm::FunctionType::get(CGM.IntTy, {CGM.IntTy}, true);
293 
294   llvm::Function *DtorStub = CGM.CreateGlobalInitOrCleanUpFunction(
295       StubTy, FnName.str(), FI, D.getLocation());
296 
297   CodeGenFunction CGF(CGM);
298 
299   FunctionArgList Args;
300   ImplicitParamDecl IPD(CGM.getContext(), CGM.getContext().IntTy,
301                         ImplicitParamKind::Other);
302   Args.push_back(&IPD);
303   QualType ResTy = CGM.getContext().IntTy;
304 
305   CGF.StartFunction(GlobalDecl(&D, DynamicInitKind::AtExit), ResTy, DtorStub,
306                     FI, Args, D.getLocation(), D.getInit()->getExprLoc());
307 
308   // Emit an artificial location for this function.
309   auto AL = ApplyDebugLocation::CreateArtificial(CGF);
310 
311   llvm::CallInst *call = CGF.Builder.CreateCall(Dtor, Addr);
312 
313   // Make sure the call and the callee agree on calling convention.
314   if (auto *DtorFn = dyn_cast<llvm::Function>(
315           Dtor.getCallee()->stripPointerCastsAndAliases()))
316     call->setCallingConv(DtorFn->getCallingConv());
317 
318   // Return 0 from function
319   CGF.Builder.CreateStore(llvm::Constant::getNullValue(CGM.IntTy),
320                           CGF.ReturnValue);
321 
322   CGF.FinishFunction();
323 
324   return DtorStub;
325 }
326 
327 /// Register a global destructor using the C atexit runtime function.
328 void CodeGenFunction::registerGlobalDtorWithAtExit(const VarDecl &VD,
329                                                    llvm::FunctionCallee dtor,
330                                                    llvm::Constant *addr) {
331   // Create a function which calls the destructor.
332   llvm::Constant *dtorStub = createAtExitStub(VD, dtor, addr);
333   registerGlobalDtorWithAtExit(dtorStub);
334 }
335 
336 /// Register a global destructor using the LLVM 'llvm.global_dtors' global.
337 void CodeGenFunction::registerGlobalDtorWithLLVM(const VarDecl &VD,
338                                                  llvm::FunctionCallee Dtor,
339                                                  llvm::Constant *Addr) {
340   // Create a function which calls the destructor.
341   llvm::Function *dtorStub =
342       cast<llvm::Function>(createAtExitStub(VD, Dtor, Addr));
343   CGM.AddGlobalDtor(dtorStub);
344 }
345 
346 void CodeGenFunction::registerGlobalDtorWithAtExit(llvm::Constant *dtorStub) {
347   // extern "C" int atexit(void (*f)(void));
348   assert(dtorStub->getType() ==
349              llvm::PointerType::get(
350                  llvm::FunctionType::get(CGM.VoidTy, false),
351                  dtorStub->getType()->getPointerAddressSpace()) &&
352          "Argument to atexit has a wrong type.");
353 
354   llvm::FunctionType *atexitTy =
355       llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
356 
357   llvm::FunctionCallee atexit =
358       CGM.CreateRuntimeFunction(atexitTy, "atexit", llvm::AttributeList(),
359                                 /*Local=*/true);
360   if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit.getCallee()))
361     atexitFn->setDoesNotThrow();
362 
363   EmitNounwindRuntimeCall(atexit, dtorStub);
364 }
365 
366 llvm::Value *
367 CodeGenFunction::unregisterGlobalDtorWithUnAtExit(llvm::Constant *dtorStub) {
368   // The unatexit subroutine unregisters __dtor functions that were previously
369   // registered by the atexit subroutine. If the referenced function is found,
370   // it is removed from the list of functions that are called at normal program
371   // termination and the unatexit returns a value of 0, otherwise a non-zero
372   // value is returned.
373   //
374   // extern "C" int unatexit(void (*f)(void));
375   assert(dtorStub->getType() ==
376              llvm::PointerType::get(
377                  llvm::FunctionType::get(CGM.VoidTy, false),
378                  dtorStub->getType()->getPointerAddressSpace()) &&
379          "Argument to unatexit has a wrong type.");
380 
381   llvm::FunctionType *unatexitTy =
382       llvm::FunctionType::get(IntTy, {dtorStub->getType()}, /*isVarArg=*/false);
383 
384   llvm::FunctionCallee unatexit =
385       CGM.CreateRuntimeFunction(unatexitTy, "unatexit", llvm::AttributeList());
386 
387   cast<llvm::Function>(unatexit.getCallee())->setDoesNotThrow();
388 
389   return EmitNounwindRuntimeCall(unatexit, dtorStub);
390 }
391 
392 void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
393                                          llvm::GlobalVariable *DeclPtr,
394                                          bool PerformInit) {
395   // If we've been asked to forbid guard variables, emit an error now.
396   // This diagnostic is hard-coded for Darwin's use case;  we can find
397   // better phrasing if someone else needs it.
398   if (CGM.getCodeGenOpts().ForbidGuardVariables)
399     CGM.Error(D.getLocation(),
400               "this initialization requires a guard variable, which "
401               "the kernel does not support");
402 
403   CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
404 }
405 
406 void CodeGenFunction::EmitCXXGuardedInitBranch(llvm::Value *NeedsInit,
407                                                llvm::BasicBlock *InitBlock,
408                                                llvm::BasicBlock *NoInitBlock,
409                                                GuardKind Kind,
410                                                const VarDecl *D) {
411   assert((Kind == GuardKind::TlsGuard || D) && "no guarded variable");
412 
413   // A guess at how many times we will enter the initialization of a
414   // variable, depending on the kind of variable.
415   static const uint64_t InitsPerTLSVar = 1024;
416   static const uint64_t InitsPerLocalVar = 1024 * 1024;
417 
418   llvm::MDNode *Weights;
419   if (Kind == GuardKind::VariableGuard && !D->isLocalVarDecl()) {
420     // For non-local variables, don't apply any weighting for now. Due to our
421     // use of COMDATs, we expect there to be at most one initialization of the
422     // variable per DSO, but we have no way to know how many DSOs will try to
423     // initialize the variable.
424     Weights = nullptr;
425   } else {
426     uint64_t NumInits;
427     // FIXME: For the TLS case, collect and use profiling information to
428     // determine a more accurate brach weight.
429     if (Kind == GuardKind::TlsGuard || D->getTLSKind())
430       NumInits = InitsPerTLSVar;
431     else
432       NumInits = InitsPerLocalVar;
433 
434     // The probability of us entering the initializer is
435     //   1 / (total number of times we attempt to initialize the variable).
436     llvm::MDBuilder MDHelper(CGM.getLLVMContext());
437     Weights = MDHelper.createBranchWeights(1, NumInits - 1);
438   }
439 
440   Builder.CreateCondBr(NeedsInit, InitBlock, NoInitBlock, Weights);
441 }
442 
443 llvm::Function *CodeGenModule::CreateGlobalInitOrCleanUpFunction(
444     llvm::FunctionType *FTy, const Twine &Name, const CGFunctionInfo &FI,
445     SourceLocation Loc, bool TLS, llvm::GlobalVariable::LinkageTypes Linkage) {
446   llvm::Function *Fn = llvm::Function::Create(FTy, Linkage, Name, &getModule());
447 
448   if (!getLangOpts().AppleKext && !TLS) {
449     // Set the section if needed.
450     if (const char *Section = getTarget().getStaticInitSectionSpecifier())
451       Fn->setSection(Section);
452   }
453 
454   if (Linkage == llvm::GlobalVariable::InternalLinkage)
455     SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
456 
457   Fn->setCallingConv(getRuntimeCC());
458 
459   if (!getLangOpts().Exceptions)
460     Fn->setDoesNotThrow();
461 
462   if (getLangOpts().Sanitize.has(SanitizerKind::Address) &&
463       !isInNoSanitizeList(SanitizerKind::Address, Fn, Loc))
464     Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
465 
466   if (getLangOpts().Sanitize.has(SanitizerKind::KernelAddress) &&
467       !isInNoSanitizeList(SanitizerKind::KernelAddress, Fn, Loc))
468     Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
469 
470   if (getLangOpts().Sanitize.has(SanitizerKind::HWAddress) &&
471       !isInNoSanitizeList(SanitizerKind::HWAddress, Fn, Loc))
472     Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
473 
474   if (getLangOpts().Sanitize.has(SanitizerKind::KernelHWAddress) &&
475       !isInNoSanitizeList(SanitizerKind::KernelHWAddress, Fn, Loc))
476     Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
477 
478   if (getLangOpts().Sanitize.has(SanitizerKind::MemtagStack) &&
479       !isInNoSanitizeList(SanitizerKind::MemtagStack, Fn, Loc))
480     Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
481 
482   if (getLangOpts().Sanitize.has(SanitizerKind::Type) &&
483       !isInNoSanitizeList(SanitizerKind::Type, Fn, Loc))
484     Fn->addFnAttr(llvm::Attribute::SanitizeType);
485 
486   if (getLangOpts().Sanitize.has(SanitizerKind::Thread) &&
487       !isInNoSanitizeList(SanitizerKind::Thread, Fn, Loc))
488     Fn->addFnAttr(llvm::Attribute::SanitizeThread);
489 
490   if (getLangOpts().Sanitize.has(SanitizerKind::NumericalStability) &&
491       !isInNoSanitizeList(SanitizerKind::NumericalStability, Fn, Loc))
492     Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
493 
494   if (getLangOpts().Sanitize.has(SanitizerKind::Memory) &&
495       !isInNoSanitizeList(SanitizerKind::Memory, Fn, Loc))
496     Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
497 
498   if (getLangOpts().Sanitize.has(SanitizerKind::KernelMemory) &&
499       !isInNoSanitizeList(SanitizerKind::KernelMemory, Fn, Loc))
500     Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
501 
502   if (getLangOpts().Sanitize.has(SanitizerKind::SafeStack) &&
503       !isInNoSanitizeList(SanitizerKind::SafeStack, Fn, Loc))
504     Fn->addFnAttr(llvm::Attribute::SafeStack);
505 
506   if (getLangOpts().Sanitize.has(SanitizerKind::ShadowCallStack) &&
507       !isInNoSanitizeList(SanitizerKind::ShadowCallStack, Fn, Loc))
508     Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
509 
510   return Fn;
511 }
512 
513 /// Create a global pointer to a function that will initialize a global
514 /// variable.  The user has requested that this pointer be emitted in a specific
515 /// section.
516 void CodeGenModule::EmitPointerToInitFunc(const VarDecl *D,
517                                           llvm::GlobalVariable *GV,
518                                           llvm::Function *InitFunc,
519                                           InitSegAttr *ISA) {
520   llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable(
521       TheModule, InitFunc->getType(), /*isConstant=*/true,
522       llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr");
523   PtrArray->setSection(ISA->getSection());
524   addUsedGlobal(PtrArray);
525 
526   // If the GV is already in a comdat group, then we have to join it.
527   if (llvm::Comdat *C = GV->getComdat())
528     PtrArray->setComdat(C);
529 }
530 
531 void
532 CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
533                                             llvm::GlobalVariable *Addr,
534                                             bool PerformInit) {
535 
536   // According to E.2.3.1 in CUDA-7.5 Programming guide: __device__,
537   // __constant__ and __shared__ variables defined in namespace scope,
538   // that are of class type, cannot have a non-empty constructor. All
539   // the checks have been done in Sema by now. Whatever initializers
540   // are allowed are empty and we just need to ignore them here.
541   if (getLangOpts().CUDAIsDevice && !getLangOpts().GPUAllowDeviceInit &&
542       (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
543        D->hasAttr<CUDASharedAttr>()))
544     return;
545 
546   // Check if we've already initialized this decl.
547   auto I = DelayedCXXInitPosition.find(D);
548   if (I != DelayedCXXInitPosition.end() && I->second == ~0U)
549     return;
550 
551   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
552   SmallString<256> FnName;
553   {
554     llvm::raw_svector_ostream Out(FnName);
555     getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
556   }
557 
558   // Create a variable initialization function.
559   llvm::Function *Fn = CreateGlobalInitOrCleanUpFunction(
560       FTy, FnName.str(), getTypes().arrangeNullaryFunction(), D->getLocation());
561 
562   auto *ISA = D->getAttr<InitSegAttr>();
563   CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
564                                                           PerformInit);
565 
566   llvm::GlobalVariable *COMDATKey =
567       supportsCOMDAT() && D->isExternallyVisible() ? Addr : nullptr;
568 
569   if (D->getTLSKind()) {
570     // FIXME: Should we support init_priority for thread_local?
571     // FIXME: We only need to register one __cxa_thread_atexit function for the
572     // entire TU.
573     CXXThreadLocalInits.push_back(Fn);
574     CXXThreadLocalInitVars.push_back(D);
575   } else if (PerformInit && ISA) {
576     // Contract with backend that "init_seg(compiler)" corresponds to priority
577     // 200 and "init_seg(lib)" corresponds to priority 400.
578     int Priority = -1;
579     if (ISA->getSection() == ".CRT$XCC")
580       Priority = 200;
581     else if (ISA->getSection() == ".CRT$XCL")
582       Priority = 400;
583 
584     if (Priority != -1)
585       AddGlobalCtor(Fn, Priority, ~0U, COMDATKey);
586     else
587       EmitPointerToInitFunc(D, Addr, Fn, ISA);
588   } else if (auto *IPA = D->getAttr<InitPriorityAttr>()) {
589     OrderGlobalInitsOrStermFinalizers Key(IPA->getPriority(),
590                                           PrioritizedCXXGlobalInits.size());
591     PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
592   } else if (isTemplateInstantiation(D->getTemplateSpecializationKind()) ||
593              !isUniqueGVALinkage(getContext().GetGVALinkageForVariable(D)) ||
594              D->hasAttr<SelectAnyAttr>()) {
595     // For vague linkage globals, put the initializer into its own global_ctors
596     // entry with the global as a comdat key. This ensures at most one
597     // initializer per DSO runs during DSO dynamic initialization.
598     //
599     // For ELF platforms, this is an important code size and startup time
600     // optimization. For dynamic, non-hidden symbols, the weak guard variable
601     // remains to ensure that other DSOs do not re-initialize the global.
602     //
603     // For PE-COFF platforms, there is no guard variable, and COMDAT
604     // associativity is the only way to ensure vauge linkage globals are
605     // initialized exactly once.
606     //
607     // MachO is the only remaining platform with no comdats that doesn't
608     // benefit from this optimization. The rest are mainly modeled on ELF
609     // behavior.
610     //
611     // C++ requires that inline global variables are initialized in source
612     // order, but this requirement does not exist for templated entities.
613     // llvm.global_ctors does not guarantee initialization order, so in
614     // general, Clang does not fully conform to the ordering requirement.
615     // However, in practice, LLVM emits global_ctors in the provided order, and
616     // users typically don't rely on ordering between inline globals in
617     // different headers which are then transitively included in varying order.
618     // Clang's current behavior is a practical tradeoff, since dropping the
619     // comdat would lead to unacceptable impact on code size and startup time.
620     //
621     // FIXME: Find a solution to guarantee source-order initialization of
622     // inline variables.
623     //
624     // C++ [basic.start.init]p2:
625     //   Definitions of explicitly specialized class template static data
626     //   members have ordered initialization. Other class template static data
627     //   members (i.e., implicitly or explicitly instantiated specializations)
628     //   have unordered initialization.
629     //
630     // CXXGlobalInits.size() is the lex order number for the next deferred
631     // VarDecl. Use it when the current VarDecl is non-deferred. Although this
632     // lex order number is shared between current VarDecl and some following
633     // VarDecls, their order of insertion into `llvm.global_ctors` is the same
634     // as the lexing order and the following stable sort would preserve such
635     // order.
636     I = DelayedCXXInitPosition.find(D);
637     unsigned LexOrder =
638         I == DelayedCXXInitPosition.end() ? CXXGlobalInits.size() : I->second;
639     AddGlobalCtor(Fn, 65535, LexOrder, COMDATKey);
640     if (COMDATKey && (getTriple().isOSBinFormatELF() ||
641                       getTarget().getCXXABI().isMicrosoft())) {
642       // When COMDAT is used on ELF or in the MS C++ ABI, the key must be in
643       // llvm.used to prevent linker GC.
644       addUsedGlobal(COMDATKey);
645     }
646 
647     // If we used a COMDAT key for the global ctor, the init function can be
648     // discarded if the global ctor entry is discarded.
649     // FIXME: Do we need to restrict this to ELF and Wasm?
650     llvm::Comdat *C = Addr->getComdat();
651     if (COMDATKey && C &&
652         (getTarget().getTriple().isOSBinFormatELF() ||
653          getTarget().getTriple().isOSBinFormatWasm())) {
654       Fn->setComdat(C);
655     }
656   } else {
657     I = DelayedCXXInitPosition.find(D); // Re-do lookup in case of re-hash.
658     if (I == DelayedCXXInitPosition.end()) {
659       CXXGlobalInits.push_back(Fn);
660     } else if (I->second != ~0U) {
661       assert(I->second < CXXGlobalInits.size() &&
662              CXXGlobalInits[I->second] == nullptr);
663       CXXGlobalInits[I->second] = Fn;
664     }
665   }
666 
667   // Remember that we already emitted the initializer for this global.
668   DelayedCXXInitPosition[D] = ~0U;
669 }
670 
671 void CodeGenModule::EmitCXXThreadLocalInitFunc() {
672   getCXXABI().EmitThreadLocalInitFuncs(
673       *this, CXXThreadLocals, CXXThreadLocalInits, CXXThreadLocalInitVars);
674 
675   CXXThreadLocalInits.clear();
676   CXXThreadLocalInitVars.clear();
677   CXXThreadLocals.clear();
678 }
679 
680 /* Build the initializer for a C++20 module:
681    This is arranged to be run only once regardless of how many times the module
682    might be included transitively.  This arranged by using a guard variable.
683 
684    If there are no initializers at all (and also no imported modules) we reduce
685    this to an empty function (since the Itanium ABI requires that this function
686    be available to a caller, which might be produced by a different
687    implementation).
688 
689    First we call any initializers for imported modules.
690    We then call initializers for the Global Module Fragment (if present)
691    We then call initializers for the current module.
692    We then call initializers for the Private Module Fragment (if present)
693 */
694 
695 void CodeGenModule::EmitCXXModuleInitFunc(Module *Primary) {
696   assert(Primary->isInterfaceOrPartition() &&
697          "The function should only be called for C++20 named module interface"
698          " or partition.");
699 
700   while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
701     CXXGlobalInits.pop_back();
702 
703   // As noted above, we create the function, even if it is empty.
704   // Module initializers for imported modules are emitted first.
705 
706   // Collect all the modules that we import
707   llvm::SmallSetVector<Module *, 8> AllImports;
708   // Ones that we export
709   for (auto I : Primary->Exports)
710     AllImports.insert(I.getPointer());
711   // Ones that we only import.
712   for (Module *M : Primary->Imports)
713     AllImports.insert(M);
714   // Ones that we import in the global module fragment or the private module
715   // fragment.
716   for (Module *SubM : Primary->submodules()) {
717     assert((SubM->isGlobalModule() || SubM->isPrivateModule()) &&
718            "The sub modules of C++20 module unit should only be global module "
719            "fragments or private module framents.");
720     assert(SubM->Exports.empty() &&
721            "The global mdoule fragments and the private module fragments are "
722            "not allowed to export import modules.");
723     for (Module *M : SubM->Imports)
724       AllImports.insert(M);
725   }
726 
727   SmallVector<llvm::Function *, 8> ModuleInits;
728   for (Module *M : AllImports) {
729     // No Itanium initializer in header like modules.
730     if (M->isHeaderLikeModule())
731       continue; // TODO: warn of mixed use of module map modules and C++20?
732     // We're allowed to skip the initialization if we are sure it doesn't
733     // do any thing.
734     if (!M->isNamedModuleInterfaceHasInit())
735       continue;
736     llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
737     SmallString<256> FnName;
738     {
739       llvm::raw_svector_ostream Out(FnName);
740       cast<ItaniumMangleContext>(getCXXABI().getMangleContext())
741           .mangleModuleInitializer(M, Out);
742     }
743     assert(!GetGlobalValue(FnName.str()) &&
744            "We should only have one use of the initializer call");
745     llvm::Function *Fn = llvm::Function::Create(
746         FTy, llvm::Function::ExternalLinkage, FnName.str(), &getModule());
747     ModuleInits.push_back(Fn);
748   }
749 
750   // Add any initializers with specified priority; this uses the same  approach
751   // as EmitCXXGlobalInitFunc().
752   if (!PrioritizedCXXGlobalInits.empty()) {
753     SmallVector<llvm::Function *, 8> LocalCXXGlobalInits;
754     llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
755                          PrioritizedCXXGlobalInits.end());
756     for (SmallVectorImpl<GlobalInitData>::iterator
757              I = PrioritizedCXXGlobalInits.begin(),
758              E = PrioritizedCXXGlobalInits.end();
759          I != E;) {
760       SmallVectorImpl<GlobalInitData>::iterator PrioE =
761           std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
762 
763       for (; I < PrioE; ++I)
764         ModuleInits.push_back(I->second);
765     }
766   }
767 
768   // Now append the ones without specified priority.
769   for (auto *F : CXXGlobalInits)
770     ModuleInits.push_back(F);
771 
772   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
773   const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
774 
775   // We now build the initializer for this module, which has a mangled name
776   // as per the Itanium ABI .  The action of the initializer is guarded so that
777   // each init is run just once (even though a module might be imported
778   // multiple times via nested use).
779   llvm::Function *Fn;
780   {
781     SmallString<256> InitFnName;
782     llvm::raw_svector_ostream Out(InitFnName);
783     cast<ItaniumMangleContext>(getCXXABI().getMangleContext())
784         .mangleModuleInitializer(Primary, Out);
785     Fn = CreateGlobalInitOrCleanUpFunction(
786         FTy, llvm::Twine(InitFnName), FI, SourceLocation(), false,
787         llvm::GlobalVariable::ExternalLinkage);
788 
789     // If we have a completely empty initializer then we do not want to create
790     // the guard variable.
791     ConstantAddress GuardAddr = ConstantAddress::invalid();
792     if (!ModuleInits.empty()) {
793       // Create the guard var.
794       llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
795           getModule(), Int8Ty, /*isConstant=*/false,
796           llvm::GlobalVariable::InternalLinkage,
797           llvm::ConstantInt::get(Int8Ty, 0), InitFnName.str() + "__in_chrg");
798       CharUnits GuardAlign = CharUnits::One();
799       Guard->setAlignment(GuardAlign.getAsAlign());
800       GuardAddr = ConstantAddress(Guard, Int8Ty, GuardAlign);
801     }
802     CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, ModuleInits,
803                                                      GuardAddr);
804   }
805 
806   // We allow for the case that a module object is added to a linked binary
807   // without a specific call to the the initializer.  This also ensures that
808   // implementation partition initializers are called when the partition
809   // is not imported as an interface.
810   AddGlobalCtor(Fn);
811 
812   // See the comment in EmitCXXGlobalInitFunc about OpenCL global init
813   // functions.
814   if (getLangOpts().OpenCL) {
815     GenKernelArgMetadata(Fn);
816     Fn->setCallingConv(llvm::CallingConv::SPIR_KERNEL);
817   }
818 
819   assert(!getLangOpts().CUDA || !getLangOpts().CUDAIsDevice ||
820          getLangOpts().GPUAllowDeviceInit);
821   if (getLangOpts().HIP && getLangOpts().CUDAIsDevice) {
822     if (getTriple().isSPIRV())
823       Fn->setCallingConv(llvm::CallingConv::SPIR_KERNEL);
824     else
825       Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
826     Fn->addFnAttr("device-init");
827   }
828 
829   // We are done with the inits.
830   AllImports.clear();
831   PrioritizedCXXGlobalInits.clear();
832   CXXGlobalInits.clear();
833   ModuleInits.clear();
834 }
835 
836 static SmallString<128> getTransformedFileName(llvm::Module &M) {
837   SmallString<128> FileName = llvm::sys::path::filename(M.getName());
838 
839   if (FileName.empty())
840     FileName = "<null>";
841 
842   for (size_t i = 0; i < FileName.size(); ++i) {
843     // Replace everything that's not [a-zA-Z0-9._] with a _. This set happens
844     // to be the set of C preprocessing numbers.
845     if (!isPreprocessingNumberBody(FileName[i]))
846       FileName[i] = '_';
847   }
848 
849   return FileName;
850 }
851 
852 static std::string getPrioritySuffix(unsigned int Priority) {
853   assert(Priority <= 65535 && "Priority should always be <= 65535.");
854 
855   // Compute the function suffix from priority. Prepend with zeroes to make
856   // sure the function names are also ordered as priorities.
857   std::string PrioritySuffix = llvm::utostr(Priority);
858   PrioritySuffix = std::string(6 - PrioritySuffix.size(), '0') + PrioritySuffix;
859 
860   return PrioritySuffix;
861 }
862 
863 void
864 CodeGenModule::EmitCXXGlobalInitFunc() {
865   while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
866     CXXGlobalInits.pop_back();
867 
868   // When we import C++20 modules, we must run their initializers first.
869   SmallVector<llvm::Function *, 8> ModuleInits;
870   if (CXX20ModuleInits)
871     for (Module *M : ImportedModules) {
872       // No Itanium initializer in header like modules.
873       if (M->isHeaderLikeModule())
874         continue;
875       // We're allowed to skip the initialization if we are sure it doesn't
876       // do any thing.
877       if (!M->isNamedModuleInterfaceHasInit())
878         continue;
879       llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
880       SmallString<256> FnName;
881       {
882         llvm::raw_svector_ostream Out(FnName);
883         cast<ItaniumMangleContext>(getCXXABI().getMangleContext())
884             .mangleModuleInitializer(M, Out);
885       }
886       assert(!GetGlobalValue(FnName.str()) &&
887              "We should only have one use of the initializer call");
888       llvm::Function *Fn = llvm::Function::Create(
889           FTy, llvm::Function::ExternalLinkage, FnName.str(), &getModule());
890       ModuleInits.push_back(Fn);
891     }
892 
893   if (ModuleInits.empty() && CXXGlobalInits.empty() &&
894       PrioritizedCXXGlobalInits.empty())
895     return;
896 
897   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
898   const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
899 
900   // Create our global prioritized initialization function.
901   if (!PrioritizedCXXGlobalInits.empty()) {
902     SmallVector<llvm::Function *, 8> LocalCXXGlobalInits;
903     llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
904                          PrioritizedCXXGlobalInits.end());
905     // Iterate over "chunks" of ctors with same priority and emit each chunk
906     // into separate function. Note - everything is sorted first by priority,
907     // second - by lex order, so we emit ctor functions in proper order.
908     for (SmallVectorImpl<GlobalInitData >::iterator
909            I = PrioritizedCXXGlobalInits.begin(),
910            E = PrioritizedCXXGlobalInits.end(); I != E; ) {
911       SmallVectorImpl<GlobalInitData >::iterator
912         PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
913 
914       LocalCXXGlobalInits.clear();
915 
916       unsigned int Priority = I->first.priority;
917       llvm::Function *Fn = CreateGlobalInitOrCleanUpFunction(
918           FTy, "_GLOBAL__I_" + getPrioritySuffix(Priority), FI);
919 
920       // Prepend the module inits to the highest priority set.
921       if (!ModuleInits.empty()) {
922         for (auto *F : ModuleInits)
923           LocalCXXGlobalInits.push_back(F);
924         ModuleInits.clear();
925       }
926 
927       for (; I < PrioE; ++I)
928         LocalCXXGlobalInits.push_back(I->second);
929 
930       CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
931       AddGlobalCtor(Fn, Priority);
932     }
933     PrioritizedCXXGlobalInits.clear();
934   }
935 
936   if (getCXXABI().useSinitAndSterm() && ModuleInits.empty() &&
937       CXXGlobalInits.empty())
938     return;
939 
940   for (auto *F : CXXGlobalInits)
941     ModuleInits.push_back(F);
942   CXXGlobalInits.clear();
943 
944   // Include the filename in the symbol name. Including "sub_" matches gcc
945   // and makes sure these symbols appear lexicographically behind the symbols
946   // with priority emitted above.  Module implementation units behave the same
947   // way as a non-modular TU with imports.
948   llvm::Function *Fn;
949   if (CXX20ModuleInits && getContext().getCurrentNamedModule() &&
950       !getContext().getCurrentNamedModule()->isModuleImplementation()) {
951     SmallString<256> InitFnName;
952     llvm::raw_svector_ostream Out(InitFnName);
953     cast<ItaniumMangleContext>(getCXXABI().getMangleContext())
954         .mangleModuleInitializer(getContext().getCurrentNamedModule(), Out);
955     Fn = CreateGlobalInitOrCleanUpFunction(
956         FTy, llvm::Twine(InitFnName), FI, SourceLocation(), false,
957         llvm::GlobalVariable::ExternalLinkage);
958   } else
959     Fn = CreateGlobalInitOrCleanUpFunction(
960         FTy,
961         llvm::Twine("_GLOBAL__sub_I_", getTransformedFileName(getModule())),
962         FI);
963 
964   CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, ModuleInits);
965   AddGlobalCtor(Fn);
966 
967   // In OpenCL global init functions must be converted to kernels in order to
968   // be able to launch them from the host.
969   // FIXME: Some more work might be needed to handle destructors correctly.
970   // Current initialization function makes use of function pointers callbacks.
971   // We can't support function pointers especially between host and device.
972   // However it seems global destruction has little meaning without any
973   // dynamic resource allocation on the device and program scope variables are
974   // destroyed by the runtime when program is released.
975   if (getLangOpts().OpenCL) {
976     GenKernelArgMetadata(Fn);
977     Fn->setCallingConv(llvm::CallingConv::SPIR_KERNEL);
978   }
979 
980   assert(!getLangOpts().CUDA || !getLangOpts().CUDAIsDevice ||
981          getLangOpts().GPUAllowDeviceInit);
982   if (getLangOpts().HIP && getLangOpts().CUDAIsDevice) {
983     if (getTriple().isSPIRV())
984       Fn->setCallingConv(llvm::CallingConv::SPIR_KERNEL);
985     else
986       Fn->setCallingConv(llvm::CallingConv::AMDGPU_KERNEL);
987     Fn->addFnAttr("device-init");
988   }
989 
990   ModuleInits.clear();
991 }
992 
993 void CodeGenModule::EmitCXXGlobalCleanUpFunc() {
994   if (CXXGlobalDtorsOrStermFinalizers.empty() &&
995       PrioritizedCXXStermFinalizers.empty())
996     return;
997 
998   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
999   const CGFunctionInfo &FI = getTypes().arrangeNullaryFunction();
1000 
1001   // Create our global prioritized cleanup function.
1002   if (!PrioritizedCXXStermFinalizers.empty()) {
1003     SmallVector<CXXGlobalDtorsOrStermFinalizer_t, 8> LocalCXXStermFinalizers;
1004     llvm::array_pod_sort(PrioritizedCXXStermFinalizers.begin(),
1005                          PrioritizedCXXStermFinalizers.end());
1006     // Iterate over "chunks" of dtors with same priority and emit each chunk
1007     // into separate function. Note - everything is sorted first by priority,
1008     // second - by lex order, so we emit dtor functions in proper order.
1009     for (SmallVectorImpl<StermFinalizerData>::iterator
1010              I = PrioritizedCXXStermFinalizers.begin(),
1011              E = PrioritizedCXXStermFinalizers.end();
1012          I != E;) {
1013       SmallVectorImpl<StermFinalizerData>::iterator PrioE =
1014           std::upper_bound(I + 1, E, *I, StermFinalizerPriorityCmp());
1015 
1016       LocalCXXStermFinalizers.clear();
1017 
1018       unsigned int Priority = I->first.priority;
1019       llvm::Function *Fn = CreateGlobalInitOrCleanUpFunction(
1020           FTy, "_GLOBAL__a_" + getPrioritySuffix(Priority), FI);
1021 
1022       for (; I < PrioE; ++I) {
1023         llvm::FunctionCallee DtorFn = I->second;
1024         LocalCXXStermFinalizers.emplace_back(DtorFn.getFunctionType(),
1025                                              DtorFn.getCallee(), nullptr);
1026       }
1027 
1028       CodeGenFunction(*this).GenerateCXXGlobalCleanUpFunc(
1029           Fn, LocalCXXStermFinalizers);
1030       AddGlobalDtor(Fn, Priority);
1031     }
1032     PrioritizedCXXStermFinalizers.clear();
1033   }
1034 
1035   if (CXXGlobalDtorsOrStermFinalizers.empty())
1036     return;
1037 
1038   // Create our global cleanup function.
1039   llvm::Function *Fn =
1040       CreateGlobalInitOrCleanUpFunction(FTy, "_GLOBAL__D_a", FI);
1041 
1042   CodeGenFunction(*this).GenerateCXXGlobalCleanUpFunc(
1043       Fn, CXXGlobalDtorsOrStermFinalizers);
1044   AddGlobalDtor(Fn);
1045   CXXGlobalDtorsOrStermFinalizers.clear();
1046 }
1047 
1048 /// Emit the code necessary to initialize the given global variable.
1049 void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
1050                                                        const VarDecl *D,
1051                                                  llvm::GlobalVariable *Addr,
1052                                                        bool PerformInit) {
1053   // Check if we need to emit debug info for variable initializer.
1054   if (D->hasAttr<NoDebugAttr>())
1055     DebugInfo = nullptr; // disable debug info indefinitely for this function
1056 
1057   CurEHLocation = D->getBeginLoc();
1058 
1059   StartFunction(GlobalDecl(D, DynamicInitKind::Initializer),
1060                 getContext().VoidTy, Fn, getTypes().arrangeNullaryFunction(),
1061                 FunctionArgList());
1062   // Emit an artificial location for this function.
1063   auto AL = ApplyDebugLocation::CreateArtificial(*this);
1064 
1065   // Use guarded initialization if the global variable is weak. This
1066   // occurs for, e.g., instantiated static data members and
1067   // definitions explicitly marked weak.
1068   //
1069   // Also use guarded initialization for a variable with dynamic TLS and
1070   // unordered initialization. (If the initialization is ordered, the ABI
1071   // layer will guard the whole-TU initialization for us.)
1072   if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage() ||
1073       (D->getTLSKind() == VarDecl::TLS_Dynamic &&
1074        isTemplateInstantiation(D->getTemplateSpecializationKind()))) {
1075     EmitCXXGuardedInit(*D, Addr, PerformInit);
1076   } else {
1077     EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
1078   }
1079 
1080   if (getLangOpts().HLSL)
1081     CGM.getHLSLRuntime().annotateHLSLResource(D, Addr);
1082 
1083   FinishFunction();
1084 }
1085 
1086 void
1087 CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
1088                                            ArrayRef<llvm::Function *> Decls,
1089                                            ConstantAddress Guard) {
1090   {
1091     auto NL = ApplyDebugLocation::CreateEmpty(*this);
1092     StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
1093                   getTypes().arrangeNullaryFunction(), FunctionArgList());
1094     // Emit an artificial location for this function.
1095     auto AL = ApplyDebugLocation::CreateArtificial(*this);
1096 
1097     llvm::BasicBlock *ExitBlock = nullptr;
1098     if (Guard.isValid()) {
1099       // If we have a guard variable, check whether we've already performed
1100       // these initializations. This happens for TLS initialization functions.
1101       llvm::Value *GuardVal = Builder.CreateLoad(Guard);
1102       llvm::Value *Uninit = Builder.CreateIsNull(GuardVal,
1103                                                  "guard.uninitialized");
1104       llvm::BasicBlock *InitBlock = createBasicBlock("init");
1105       ExitBlock = createBasicBlock("exit");
1106       EmitCXXGuardedInitBranch(Uninit, InitBlock, ExitBlock,
1107                                GuardKind::TlsGuard, nullptr);
1108       EmitBlock(InitBlock);
1109       // Mark as initialized before initializing anything else. If the
1110       // initializers use previously-initialized thread_local vars, that's
1111       // probably supposed to be OK, but the standard doesn't say.
1112       Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard);
1113 
1114       // The guard variable can't ever change again.
1115       EmitInvariantStart(
1116           Guard.getPointer(),
1117           CharUnits::fromQuantity(
1118               CGM.getDataLayout().getTypeAllocSize(GuardVal->getType())));
1119     }
1120 
1121     RunCleanupsScope Scope(*this);
1122 
1123     // When building in Objective-C++ ARC mode, create an autorelease pool
1124     // around the global initializers.
1125     if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
1126       llvm::Value *token = EmitObjCAutoreleasePoolPush();
1127       EmitObjCAutoreleasePoolCleanup(token);
1128     }
1129 
1130     for (unsigned i = 0, e = Decls.size(); i != e; ++i)
1131       if (Decls[i])
1132         EmitRuntimeCall(Decls[i]);
1133 
1134     Scope.ForceCleanup();
1135 
1136     if (ExitBlock) {
1137       Builder.CreateBr(ExitBlock);
1138       EmitBlock(ExitBlock);
1139     }
1140   }
1141 
1142   FinishFunction();
1143 }
1144 
1145 void CodeGenFunction::GenerateCXXGlobalCleanUpFunc(
1146     llvm::Function *Fn,
1147     ArrayRef<std::tuple<llvm::FunctionType *, llvm::WeakTrackingVH,
1148                         llvm::Constant *>>
1149         DtorsOrStermFinalizers) {
1150   {
1151     auto NL = ApplyDebugLocation::CreateEmpty(*this);
1152     StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
1153                   getTypes().arrangeNullaryFunction(), FunctionArgList());
1154     // Emit an artificial location for this function.
1155     auto AL = ApplyDebugLocation::CreateArtificial(*this);
1156 
1157     // Emit the cleanups, in reverse order from construction.
1158     for (unsigned i = 0, e = DtorsOrStermFinalizers.size(); i != e; ++i) {
1159       llvm::FunctionType *CalleeTy;
1160       llvm::Value *Callee;
1161       llvm::Constant *Arg;
1162       std::tie(CalleeTy, Callee, Arg) = DtorsOrStermFinalizers[e - i - 1];
1163 
1164       llvm::CallInst *CI = nullptr;
1165       if (Arg == nullptr) {
1166         assert(
1167             CGM.getCXXABI().useSinitAndSterm() &&
1168             "Arg could not be nullptr unless using sinit and sterm functions.");
1169         CI = Builder.CreateCall(CalleeTy, Callee);
1170       } else
1171         CI = Builder.CreateCall(CalleeTy, Callee, Arg);
1172 
1173       // Make sure the call and the callee agree on calling convention.
1174       if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
1175         CI->setCallingConv(F->getCallingConv());
1176     }
1177   }
1178 
1179   FinishFunction();
1180 }
1181 
1182 /// generateDestroyHelper - Generates a helper function which, when
1183 /// invoked, destroys the given object.  The address of the object
1184 /// should be in global memory.
1185 llvm::Function *CodeGenFunction::generateDestroyHelper(
1186     Address addr, QualType type, Destroyer *destroyer,
1187     bool useEHCleanupForArray, const VarDecl *VD) {
1188   FunctionArgList args;
1189   ImplicitParamDecl Dst(getContext(), getContext().VoidPtrTy,
1190                         ImplicitParamKind::Other);
1191   args.push_back(&Dst);
1192 
1193   const CGFunctionInfo &FI =
1194     CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, args);
1195   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
1196   llvm::Function *fn = CGM.CreateGlobalInitOrCleanUpFunction(
1197       FTy, "__cxx_global_array_dtor", FI, VD->getLocation());
1198 
1199   CurEHLocation = VD->getBeginLoc();
1200 
1201   StartFunction(GlobalDecl(VD, DynamicInitKind::GlobalArrayDestructor),
1202                 getContext().VoidTy, fn, FI, args);
1203   // Emit an artificial location for this function.
1204   auto AL = ApplyDebugLocation::CreateArtificial(*this);
1205 
1206   emitDestroy(addr, type, destroyer, useEHCleanupForArray);
1207 
1208   FinishFunction();
1209 
1210   return fn;
1211 }
1212