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