1//===--- CGDeclCXX.cpp - Emit LLVM Code for C++ declarations --------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This contains code dealing with code generation of C++ declarations 11// 12//===----------------------------------------------------------------------===// 13 14#include "CodeGenFunction.h" 15#include "CGCXXABI.h" 16#include "CGObjCRuntime.h" 17#include "CGOpenMPRuntime.h" 18#include "clang/Frontend/CodeGenOptions.h" 19#include "llvm/ADT/StringExtras.h" 20#include "llvm/IR/Intrinsics.h" 21#include "llvm/Support/Path.h" 22 23using namespace clang; 24using namespace CodeGen; 25 26static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D, 27 llvm::Constant *DeclPtr) { 28 assert(D.hasGlobalStorage() && "VarDecl must have global storage!"); 29 assert(!D.getType()->isReferenceType() && 30 "Should not call EmitDeclInit on a reference!"); 31 32 ASTContext &Context = CGF.getContext(); 33 34 CharUnits alignment = Context.getDeclAlign(&D); 35 QualType type = D.getType(); 36 LValue lv = CGF.MakeAddrLValue(DeclPtr, type, alignment); 37 38 const Expr *Init = D.getInit(); 39 switch (CGF.getEvaluationKind(type)) { 40 case TEK_Scalar: { 41 CodeGenModule &CGM = CGF.CGM; 42 if (lv.isObjCStrong()) 43 CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init), 44 DeclPtr, D.getTLSKind()); 45 else if (lv.isObjCWeak()) 46 CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init), 47 DeclPtr); 48 else 49 CGF.EmitScalarInit(Init, &D, lv, false); 50 return; 51 } 52 case TEK_Complex: 53 CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true); 54 return; 55 case TEK_Aggregate: 56 CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed, 57 AggValueSlot::DoesNotNeedGCBarriers, 58 AggValueSlot::IsNotAliased)); 59 return; 60 } 61 llvm_unreachable("bad evaluation kind"); 62} 63 64/// Emit code to cause the destruction of the given variable with 65/// static storage duration. 66static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D, 67 llvm::Constant *addr) { 68 CodeGenModule &CGM = CGF.CGM; 69 70 // FIXME: __attribute__((cleanup)) ? 71 72 QualType type = D.getType(); 73 QualType::DestructionKind dtorKind = type.isDestructedType(); 74 75 switch (dtorKind) { 76 case QualType::DK_none: 77 return; 78 79 case QualType::DK_cxx_destructor: 80 break; 81 82 case QualType::DK_objc_strong_lifetime: 83 case QualType::DK_objc_weak_lifetime: 84 // We don't care about releasing objects during process teardown. 85 assert(!D.getTLSKind() && "should have rejected this"); 86 return; 87 } 88 89 llvm::Constant *function; 90 llvm::Constant *argument; 91 92 // Special-case non-array C++ destructors, where there's a function 93 // with the right signature that we can just call. 94 const CXXRecordDecl *record = nullptr; 95 if (dtorKind == QualType::DK_cxx_destructor && 96 (record = type->getAsCXXRecordDecl())) { 97 assert(!record->hasTrivialDestructor()); 98 CXXDestructorDecl *dtor = record->getDestructor(); 99 100 function = CGM.getAddrOfCXXStructor(dtor, StructorType::Complete); 101 argument = llvm::ConstantExpr::getBitCast( 102 addr, CGF.getTypes().ConvertType(type)->getPointerTo()); 103 104 // Otherwise, the standard logic requires a helper function. 105 } else { 106 function = CodeGenFunction(CGM) 107 .generateDestroyHelper(addr, type, CGF.getDestroyer(dtorKind), 108 CGF.needsEHCleanup(dtorKind), &D); 109 argument = llvm::Constant::getNullValue(CGF.Int8PtrTy); 110 } 111 112 CGM.getCXXABI().registerGlobalDtor(CGF, D, function, argument); 113} 114 115/// Emit code to cause the variable at the given address to be considered as 116/// constant from this point onwards. 117static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D, 118 llvm::Constant *Addr) { 119 // Don't emit the intrinsic if we're not optimizing. 120 if (!CGF.CGM.getCodeGenOpts().OptimizationLevel) 121 return; 122 123 // Grab the llvm.invariant.start intrinsic. 124 llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start; 125 llvm::Constant *InvariantStart = CGF.CGM.getIntrinsic(InvStartID); 126 127 // Emit a call with the size in bytes of the object. 128 CharUnits WidthChars = CGF.getContext().getTypeSizeInChars(D.getType()); 129 uint64_t Width = WidthChars.getQuantity(); 130 llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(CGF.Int64Ty, Width), 131 llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)}; 132 CGF.Builder.CreateCall(InvariantStart, Args); 133} 134 135void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D, 136 llvm::Constant *DeclPtr, 137 bool PerformInit) { 138 139 const Expr *Init = D.getInit(); 140 QualType T = D.getType(); 141 142 // The address space of a static local variable (DeclPtr) may be different 143 // from the address space of the "this" argument of the constructor. In that 144 // case, we need an addrspacecast before calling the constructor. 145 // 146 // struct StructWithCtor { 147 // __device__ StructWithCtor() {...} 148 // }; 149 // __device__ void foo() { 150 // __shared__ StructWithCtor s; 151 // ... 152 // } 153 // 154 // For example, in the above CUDA code, the static local variable s has a 155 // "shared" address space qualifier, but the constructor of StructWithCtor 156 // expects "this" in the "generic" address space. 157 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(T); 158 unsigned ActualAddrSpace = DeclPtr->getType()->getPointerAddressSpace(); 159 if (ActualAddrSpace != ExpectedAddrSpace) { 160 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(T); 161 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace); 162 DeclPtr = llvm::ConstantExpr::getAddrSpaceCast(DeclPtr, PTy); 163 } 164 165 if (!T->isReferenceType()) { 166 if (getLangOpts().OpenMP && D.hasAttr<OMPThreadPrivateDeclAttr>()) 167 (void)CGM.getOpenMPRuntime().emitThreadPrivateVarDefinition( 168 &D, DeclPtr, D.getAttr<OMPThreadPrivateDeclAttr>()->getLocation(), 169 PerformInit, this); 170 if (PerformInit) 171 EmitDeclInit(*this, D, DeclPtr); 172 if (CGM.isTypeConstant(D.getType(), true)) 173 EmitDeclInvariant(*this, D, DeclPtr); 174 else 175 EmitDeclDestroy(*this, D, DeclPtr); 176 return; 177 } 178 179 assert(PerformInit && "cannot have constant initializer which needs " 180 "destruction for reference"); 181 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity(); 182 RValue RV = EmitReferenceBindingToExpr(Init); 183 EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T); 184} 185 186/// Create a stub function, suitable for being passed to atexit, 187/// which passes the given address to the given destructor function. 188llvm::Constant *CodeGenFunction::createAtExitStub(const VarDecl &VD, 189 llvm::Constant *dtor, 190 llvm::Constant *addr) { 191 // Get the destructor function type, void(*)(void). 192 llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false); 193 SmallString<256> FnName; 194 { 195 llvm::raw_svector_ostream Out(FnName); 196 CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out); 197 } 198 llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(ty, FnName.str(), 199 VD.getLocation()); 200 201 CodeGenFunction CGF(CGM); 202 203 CGF.StartFunction(&VD, CGM.getContext().VoidTy, fn, 204 CGM.getTypes().arrangeNullaryFunction(), FunctionArgList()); 205 206 llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr); 207 208 // Make sure the call and the callee agree on calling convention. 209 if (llvm::Function *dtorFn = 210 dyn_cast<llvm::Function>(dtor->stripPointerCasts())) 211 call->setCallingConv(dtorFn->getCallingConv()); 212 213 CGF.FinishFunction(); 214 215 return fn; 216} 217 218/// Register a global destructor using the C atexit runtime function. 219void CodeGenFunction::registerGlobalDtorWithAtExit(const VarDecl &VD, 220 llvm::Constant *dtor, 221 llvm::Constant *addr) { 222 // Create a function which calls the destructor. 223 llvm::Constant *dtorStub = createAtExitStub(VD, dtor, addr); 224 225 // extern "C" int atexit(void (*f)(void)); 226 llvm::FunctionType *atexitTy = 227 llvm::FunctionType::get(IntTy, dtorStub->getType(), false); 228 229 llvm::Constant *atexit = 230 CGM.CreateRuntimeFunction(atexitTy, "atexit"); 231 if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit)) 232 atexitFn->setDoesNotThrow(); 233 234 EmitNounwindRuntimeCall(atexit, dtorStub); 235} 236 237void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D, 238 llvm::GlobalVariable *DeclPtr, 239 bool PerformInit) { 240 // If we've been asked to forbid guard variables, emit an error now. 241 // This diagnostic is hard-coded for Darwin's use case; we can find 242 // better phrasing if someone else needs it. 243 if (CGM.getCodeGenOpts().ForbidGuardVariables) 244 CGM.Error(D.getLocation(), 245 "this initialization requires a guard variable, which " 246 "the kernel does not support"); 247 248 CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit); 249} 250 251llvm::Function *CodeGenModule::CreateGlobalInitOrDestructFunction( 252 llvm::FunctionType *FTy, const Twine &Name, SourceLocation Loc, bool TLS) { 253 llvm::Function *Fn = 254 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage, 255 Name, &getModule()); 256 if (!getLangOpts().AppleKext && !TLS) { 257 // Set the section if needed. 258 if (const char *Section = getTarget().getStaticInitSectionSpecifier()) 259 Fn->setSection(Section); 260 } 261 262 Fn->setCallingConv(getRuntimeCC()); 263 264 if (!getLangOpts().Exceptions) 265 Fn->setDoesNotThrow(); 266 267 if (!isInSanitizerBlacklist(Fn, Loc)) { 268 if (getLangOpts().Sanitize.has(SanitizerKind::Address)) 269 Fn->addFnAttr(llvm::Attribute::SanitizeAddress); 270 if (getLangOpts().Sanitize.has(SanitizerKind::Thread)) 271 Fn->addFnAttr(llvm::Attribute::SanitizeThread); 272 if (getLangOpts().Sanitize.has(SanitizerKind::Memory)) 273 Fn->addFnAttr(llvm::Attribute::SanitizeMemory); 274 } 275 276 return Fn; 277} 278 279/// Create a global pointer to a function that will initialize a global 280/// variable. The user has requested that this pointer be emitted in a specific 281/// section. 282void CodeGenModule::EmitPointerToInitFunc(const VarDecl *D, 283 llvm::GlobalVariable *GV, 284 llvm::Function *InitFunc, 285 InitSegAttr *ISA) { 286 llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable( 287 TheModule, InitFunc->getType(), /*isConstant=*/true, 288 llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr"); 289 PtrArray->setSection(ISA->getSection()); 290 addUsedGlobal(PtrArray); 291 292 // If the GV is already in a comdat group, then we have to join it. 293 if (llvm::Comdat *C = GV->getComdat()) 294 PtrArray->setComdat(C); 295} 296 297void 298CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D, 299 llvm::GlobalVariable *Addr, 300 bool PerformInit) { 301 // Check if we've already initialized this decl. 302 auto I = DelayedCXXInitPosition.find(D); 303 if (I != DelayedCXXInitPosition.end() && I->second == ~0U) 304 return; 305 306 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false); 307 SmallString<256> FnName; 308 { 309 llvm::raw_svector_ostream Out(FnName); 310 getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out); 311 } 312 313 // Create a variable initialization function. 314 llvm::Function *Fn = 315 CreateGlobalInitOrDestructFunction(FTy, FnName.str(), D->getLocation()); 316 317 auto *ISA = D->getAttr<InitSegAttr>(); 318 CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr, 319 PerformInit); 320 321 llvm::GlobalVariable *COMDATKey = 322 supportsCOMDAT() && D->isExternallyVisible() ? Addr : nullptr; 323 324 if (D->getTLSKind()) { 325 // FIXME: Should we support init_priority for thread_local? 326 // FIXME: Ideally, initialization of instantiated thread_local static data 327 // members of class templates should not trigger initialization of other 328 // entities in the TU. 329 // FIXME: We only need to register one __cxa_thread_atexit function for the 330 // entire TU. 331 CXXThreadLocalInits.push_back(Fn); 332 CXXThreadLocalInitVars.push_back(Addr); 333 } else if (PerformInit && ISA) { 334 EmitPointerToInitFunc(D, Addr, Fn, ISA); 335 } else if (auto *IPA = D->getAttr<InitPriorityAttr>()) { 336 OrderGlobalInits Key(IPA->getPriority(), PrioritizedCXXGlobalInits.size()); 337 PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn)); 338 } else if (isTemplateInstantiation(D->getTemplateSpecializationKind())) { 339 // C++ [basic.start.init]p2: 340 // Definitions of explicitly specialized class template static data 341 // members have ordered initialization. Other class template static data 342 // members (i.e., implicitly or explicitly instantiated specializations) 343 // have unordered initialization. 344 // 345 // As a consequence, we can put them into their own llvm.global_ctors entry. 346 // 347 // If the global is externally visible, put the initializer into a COMDAT 348 // group with the global being initialized. On most platforms, this is a 349 // minor startup time optimization. In the MS C++ ABI, there are no guard 350 // variables, so this COMDAT key is required for correctness. 351 AddGlobalCtor(Fn, 65535, COMDATKey); 352 } else if (D->hasAttr<SelectAnyAttr>()) { 353 // SelectAny globals will be comdat-folded. Put the initializer into a 354 // COMDAT group associated with the global, so the initializers get folded 355 // too. 356 AddGlobalCtor(Fn, 65535, COMDATKey); 357 } else { 358 I = DelayedCXXInitPosition.find(D); // Re-do lookup in case of re-hash. 359 if (I == DelayedCXXInitPosition.end()) { 360 CXXGlobalInits.push_back(Fn); 361 } else if (I->second != ~0U) { 362 assert(I->second < CXXGlobalInits.size() && 363 CXXGlobalInits[I->second] == nullptr); 364 CXXGlobalInits[I->second] = Fn; 365 } 366 } 367 368 // Remember that we already emitted the initializer for this global. 369 DelayedCXXInitPosition[D] = ~0U; 370} 371 372void CodeGenModule::EmitCXXThreadLocalInitFunc() { 373 getCXXABI().EmitThreadLocalInitFuncs( 374 *this, CXXThreadLocals, CXXThreadLocalInits, CXXThreadLocalInitVars); 375 376 CXXThreadLocalInits.clear(); 377 CXXThreadLocalInitVars.clear(); 378 CXXThreadLocals.clear(); 379} 380 381void 382CodeGenModule::EmitCXXGlobalInitFunc() { 383 while (!CXXGlobalInits.empty() && !CXXGlobalInits.back()) 384 CXXGlobalInits.pop_back(); 385 386 if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty()) 387 return; 388 389 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false); 390 391 392 // Create our global initialization function. 393 if (!PrioritizedCXXGlobalInits.empty()) { 394 SmallVector<llvm::Function *, 8> LocalCXXGlobalInits; 395 llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(), 396 PrioritizedCXXGlobalInits.end()); 397 // Iterate over "chunks" of ctors with same priority and emit each chunk 398 // into separate function. Note - everything is sorted first by priority, 399 // second - by lex order, so we emit ctor functions in proper order. 400 for (SmallVectorImpl<GlobalInitData >::iterator 401 I = PrioritizedCXXGlobalInits.begin(), 402 E = PrioritizedCXXGlobalInits.end(); I != E; ) { 403 SmallVectorImpl<GlobalInitData >::iterator 404 PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp()); 405 406 LocalCXXGlobalInits.clear(); 407 unsigned Priority = I->first.priority; 408 // Compute the function suffix from priority. Prepend with zeroes to make 409 // sure the function names are also ordered as priorities. 410 std::string PrioritySuffix = llvm::utostr(Priority); 411 // Priority is always <= 65535 (enforced by sema). 412 PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix; 413 llvm::Function *Fn = CreateGlobalInitOrDestructFunction( 414 FTy, "_GLOBAL__I_" + PrioritySuffix); 415 416 for (; I < PrioE; ++I) 417 LocalCXXGlobalInits.push_back(I->second); 418 419 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits); 420 AddGlobalCtor(Fn, Priority); 421 } 422 } 423 424 SmallString<128> FileName; 425 SourceManager &SM = Context.getSourceManager(); 426 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 427 // Include the filename in the symbol name. Including "sub_" matches gcc and 428 // makes sure these symbols appear lexicographically behind the symbols with 429 // priority emitted above. 430 FileName = llvm::sys::path::filename(MainFile->getName()); 431 } else { 432 FileName = SmallString<128>("<null>"); 433 } 434 435 for (size_t i = 0; i < FileName.size(); ++i) { 436 // Replace everything that's not [a-zA-Z0-9._] with a _. This set happens 437 // to be the set of C preprocessing numbers. 438 if (!isPreprocessingNumberBody(FileName[i])) 439 FileName[i] = '_'; 440 } 441 442 llvm::Function *Fn = CreateGlobalInitOrDestructFunction( 443 FTy, llvm::Twine("_GLOBAL__sub_I_", FileName)); 444 445 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits); 446 AddGlobalCtor(Fn); 447 448 CXXGlobalInits.clear(); 449 PrioritizedCXXGlobalInits.clear(); 450} 451 452void CodeGenModule::EmitCXXGlobalDtorFunc() { 453 if (CXXGlobalDtors.empty()) 454 return; 455 456 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false); 457 458 // Create our global destructor function. 459 llvm::Function *Fn = CreateGlobalInitOrDestructFunction(FTy, "_GLOBAL__D_a"); 460 461 CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors); 462 AddGlobalDtor(Fn); 463} 464 465/// Emit the code necessary to initialize the given global variable. 466void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn, 467 const VarDecl *D, 468 llvm::GlobalVariable *Addr, 469 bool PerformInit) { 470 // Check if we need to emit debug info for variable initializer. 471 if (D->hasAttr<NoDebugAttr>()) 472 DebugInfo = nullptr; // disable debug info indefinitely for this function 473 474 CurEHLocation = D->getLocStart(); 475 476 StartFunction(GlobalDecl(D), getContext().VoidTy, Fn, 477 getTypes().arrangeNullaryFunction(), 478 FunctionArgList(), D->getLocation(), 479 D->getInit()->getExprLoc()); 480 481 // Use guarded initialization if the global variable is weak. This 482 // occurs for, e.g., instantiated static data members and 483 // definitions explicitly marked weak. 484 if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage()) { 485 EmitCXXGuardedInit(*D, Addr, PerformInit); 486 } else { 487 EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit); 488 } 489 490 FinishFunction(); 491} 492 493void 494CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn, 495 ArrayRef<llvm::Function *> Decls, 496 llvm::GlobalVariable *Guard) { 497 { 498 auto NL = ApplyDebugLocation::CreateEmpty(*this); 499 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, 500 getTypes().arrangeNullaryFunction(), FunctionArgList()); 501 // Emit an artificial location for this function. 502 auto AL = ApplyDebugLocation::CreateArtificial(*this); 503 504 llvm::BasicBlock *ExitBlock = nullptr; 505 if (Guard) { 506 // If we have a guard variable, check whether we've already performed 507 // these initializations. This happens for TLS initialization functions. 508 llvm::Value *GuardVal = Builder.CreateLoad(Guard); 509 llvm::Value *Uninit = Builder.CreateIsNull(GuardVal, 510 "guard.uninitialized"); 511 // Mark as initialized before initializing anything else. If the 512 // initializers use previously-initialized thread_local vars, that's 513 // probably supposed to be OK, but the standard doesn't say. 514 Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard); 515 llvm::BasicBlock *InitBlock = createBasicBlock("init"); 516 ExitBlock = createBasicBlock("exit"); 517 Builder.CreateCondBr(Uninit, InitBlock, ExitBlock); 518 EmitBlock(InitBlock); 519 } 520 521 RunCleanupsScope Scope(*this); 522 523 // When building in Objective-C++ ARC mode, create an autorelease pool 524 // around the global initializers. 525 if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) { 526 llvm::Value *token = EmitObjCAutoreleasePoolPush(); 527 EmitObjCAutoreleasePoolCleanup(token); 528 } 529 530 for (unsigned i = 0, e = Decls.size(); i != e; ++i) 531 if (Decls[i]) 532 EmitRuntimeCall(Decls[i]); 533 534 Scope.ForceCleanup(); 535 536 if (ExitBlock) { 537 Builder.CreateBr(ExitBlock); 538 EmitBlock(ExitBlock); 539 } 540 } 541 542 FinishFunction(); 543} 544 545void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn, 546 const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> > 547 &DtorsAndObjects) { 548 { 549 auto NL = ApplyDebugLocation::CreateEmpty(*this); 550 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, 551 getTypes().arrangeNullaryFunction(), FunctionArgList()); 552 // Emit an artificial location for this function. 553 auto AL = ApplyDebugLocation::CreateArtificial(*this); 554 555 // Emit the dtors, in reverse order from construction. 556 for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) { 557 llvm::Value *Callee = DtorsAndObjects[e - i - 1].first; 558 llvm::CallInst *CI = Builder.CreateCall(Callee, 559 DtorsAndObjects[e - i - 1].second); 560 // Make sure the call and the callee agree on calling convention. 561 if (llvm::Function *F = dyn_cast<llvm::Function>(Callee)) 562 CI->setCallingConv(F->getCallingConv()); 563 } 564 } 565 566 FinishFunction(); 567} 568 569/// generateDestroyHelper - Generates a helper function which, when 570/// invoked, destroys the given object. 571llvm::Function *CodeGenFunction::generateDestroyHelper( 572 llvm::Constant *addr, QualType type, Destroyer *destroyer, 573 bool useEHCleanupForArray, const VarDecl *VD) { 574 FunctionArgList args; 575 ImplicitParamDecl dst(getContext(), nullptr, SourceLocation(), nullptr, 576 getContext().VoidPtrTy); 577 args.push_back(&dst); 578 579 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration( 580 getContext().VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false); 581 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); 582 llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction( 583 FTy, "__cxx_global_array_dtor", VD->getLocation()); 584 585 CurEHLocation = VD->getLocStart(); 586 587 StartFunction(VD, getContext().VoidTy, fn, FI, args); 588 589 emitDestroy(addr, type, destroyer, useEHCleanupForArray); 590 591 FinishFunction(); 592 593 return fn; 594} 595