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