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