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