1 //===--- CGDecl.cpp - Emit LLVM Code for 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 to emit Decl nodes as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CGBlocks.h" 16 #include "CGCXXABI.h" 17 #include "CGCleanup.h" 18 #include "CGDebugInfo.h" 19 #include "CGOpenCLRuntime.h" 20 #include "CGOpenMPRuntime.h" 21 #include "CodeGenModule.h" 22 #include "clang/AST/ASTContext.h" 23 #include "clang/AST/CharUnits.h" 24 #include "clang/AST/Decl.h" 25 #include "clang/AST/DeclObjC.h" 26 #include "clang/AST/DeclOpenMP.h" 27 #include "clang/Basic/SourceManager.h" 28 #include "clang/Basic/TargetInfo.h" 29 #include "clang/CodeGen/CGFunctionInfo.h" 30 #include "clang/Frontend/CodeGenOptions.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/GlobalVariable.h" 33 #include "llvm/IR/Intrinsics.h" 34 #include "llvm/IR/Type.h" 35 36 using namespace clang; 37 using namespace CodeGen; 38 39 void CodeGenFunction::EmitDecl(const Decl &D) { 40 switch (D.getKind()) { 41 case Decl::BuiltinTemplate: 42 case Decl::TranslationUnit: 43 case Decl::ExternCContext: 44 case Decl::Namespace: 45 case Decl::UnresolvedUsingTypename: 46 case Decl::ClassTemplateSpecialization: 47 case Decl::ClassTemplatePartialSpecialization: 48 case Decl::VarTemplateSpecialization: 49 case Decl::VarTemplatePartialSpecialization: 50 case Decl::TemplateTypeParm: 51 case Decl::UnresolvedUsingValue: 52 case Decl::NonTypeTemplateParm: 53 case Decl::CXXDeductionGuide: 54 case Decl::CXXMethod: 55 case Decl::CXXConstructor: 56 case Decl::CXXDestructor: 57 case Decl::CXXConversion: 58 case Decl::Field: 59 case Decl::MSProperty: 60 case Decl::IndirectField: 61 case Decl::ObjCIvar: 62 case Decl::ObjCAtDefsField: 63 case Decl::ParmVar: 64 case Decl::ImplicitParam: 65 case Decl::ClassTemplate: 66 case Decl::VarTemplate: 67 case Decl::FunctionTemplate: 68 case Decl::TypeAliasTemplate: 69 case Decl::TemplateTemplateParm: 70 case Decl::ObjCMethod: 71 case Decl::ObjCCategory: 72 case Decl::ObjCProtocol: 73 case Decl::ObjCInterface: 74 case Decl::ObjCCategoryImpl: 75 case Decl::ObjCImplementation: 76 case Decl::ObjCProperty: 77 case Decl::ObjCCompatibleAlias: 78 case Decl::PragmaComment: 79 case Decl::PragmaDetectMismatch: 80 case Decl::AccessSpec: 81 case Decl::LinkageSpec: 82 case Decl::Export: 83 case Decl::ObjCPropertyImpl: 84 case Decl::FileScopeAsm: 85 case Decl::Friend: 86 case Decl::FriendTemplate: 87 case Decl::Block: 88 case Decl::Captured: 89 case Decl::ClassScopeFunctionSpecialization: 90 case Decl::UsingShadow: 91 case Decl::ConstructorUsingShadow: 92 case Decl::ObjCTypeParam: 93 case Decl::Binding: 94 llvm_unreachable("Declaration should not be in declstmts!"); 95 case Decl::Function: // void X(); 96 case Decl::Record: // struct/union/class X; 97 case Decl::Enum: // enum X; 98 case Decl::EnumConstant: // enum ? { X = ? } 99 case Decl::CXXRecord: // struct/union/class X; [C++] 100 case Decl::StaticAssert: // static_assert(X, ""); [C++0x] 101 case Decl::Label: // __label__ x; 102 case Decl::Import: 103 case Decl::OMPThreadPrivate: 104 case Decl::OMPCapturedExpr: 105 case Decl::Empty: 106 // None of these decls require codegen support. 107 return; 108 109 case Decl::NamespaceAlias: 110 if (CGDebugInfo *DI = getDebugInfo()) 111 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D)); 112 return; 113 case Decl::Using: // using X; [C++] 114 if (CGDebugInfo *DI = getDebugInfo()) 115 DI->EmitUsingDecl(cast<UsingDecl>(D)); 116 return; 117 case Decl::UsingPack: 118 for (auto *Using : cast<UsingPackDecl>(D).expansions()) 119 EmitDecl(*Using); 120 return; 121 case Decl::UsingDirective: // using namespace X; [C++] 122 if (CGDebugInfo *DI = getDebugInfo()) 123 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D)); 124 return; 125 case Decl::Var: 126 case Decl::Decomposition: { 127 const VarDecl &VD = cast<VarDecl>(D); 128 assert(VD.isLocalVarDecl() && 129 "Should not see file-scope variables inside a function!"); 130 EmitVarDecl(VD); 131 if (auto *DD = dyn_cast<DecompositionDecl>(&VD)) 132 for (auto *B : DD->bindings()) 133 if (auto *HD = B->getHoldingVar()) 134 EmitVarDecl(*HD); 135 return; 136 } 137 138 case Decl::OMPDeclareReduction: 139 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this); 140 141 case Decl::Typedef: // typedef int X; 142 case Decl::TypeAlias: { // using X = int; [C++0x] 143 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D); 144 QualType Ty = TD.getUnderlyingType(); 145 146 if (Ty->isVariablyModifiedType()) 147 EmitVariablyModifiedType(Ty); 148 } 149 } 150 } 151 152 /// EmitVarDecl - This method handles emission of any variable declaration 153 /// inside a function, including static vars etc. 154 void CodeGenFunction::EmitVarDecl(const VarDecl &D) { 155 if (D.isStaticLocal()) { 156 llvm::GlobalValue::LinkageTypes Linkage = 157 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false); 158 159 // FIXME: We need to force the emission/use of a guard variable for 160 // some variables even if we can constant-evaluate them because 161 // we can't guarantee every translation unit will constant-evaluate them. 162 163 return EmitStaticVarDecl(D, Linkage); 164 } 165 166 if (D.hasExternalStorage()) 167 // Don't emit it now, allow it to be emitted lazily on its first use. 168 return; 169 170 if (D.getType().getAddressSpace() == LangAS::opencl_local) 171 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D); 172 173 assert(D.hasLocalStorage()); 174 return EmitAutoVarDecl(D); 175 } 176 177 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) { 178 if (CGM.getLangOpts().CPlusPlus) 179 return CGM.getMangledName(&D).str(); 180 181 // If this isn't C++, we don't need a mangled name, just a pretty one. 182 assert(!D.isExternallyVisible() && "name shouldn't matter"); 183 std::string ContextName; 184 const DeclContext *DC = D.getDeclContext(); 185 if (auto *CD = dyn_cast<CapturedDecl>(DC)) 186 DC = cast<DeclContext>(CD->getNonClosureContext()); 187 if (const auto *FD = dyn_cast<FunctionDecl>(DC)) 188 ContextName = CGM.getMangledName(FD); 189 else if (const auto *BD = dyn_cast<BlockDecl>(DC)) 190 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD); 191 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC)) 192 ContextName = OMD->getSelector().getAsString(); 193 else 194 llvm_unreachable("Unknown context for static var decl"); 195 196 ContextName += "." + D.getNameAsString(); 197 return ContextName; 198 } 199 200 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl( 201 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) { 202 // In general, we don't always emit static var decls once before we reference 203 // them. It is possible to reference them before emitting the function that 204 // contains them, and it is possible to emit the containing function multiple 205 // times. 206 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D]) 207 return ExistingGV; 208 209 QualType Ty = D.getType(); 210 assert(Ty->isConstantSizeType() && "VLAs can't be static"); 211 212 // Use the label if the variable is renamed with the asm-label extension. 213 std::string Name; 214 if (D.hasAttr<AsmLabelAttr>()) 215 Name = getMangledName(&D); 216 else 217 Name = getStaticDeclName(*this, D); 218 219 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty); 220 unsigned AddrSpace = 221 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty)); 222 223 // Local address space cannot have an initializer. 224 llvm::Constant *Init = nullptr; 225 if (Ty.getAddressSpace() != LangAS::opencl_local) 226 Init = EmitNullConstant(Ty); 227 else 228 Init = llvm::UndefValue::get(LTy); 229 230 llvm::GlobalVariable *GV = 231 new llvm::GlobalVariable(getModule(), LTy, 232 Ty.isConstant(getContext()), Linkage, 233 Init, Name, nullptr, 234 llvm::GlobalVariable::NotThreadLocal, 235 AddrSpace); 236 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity()); 237 setGlobalVisibility(GV, &D); 238 239 if (supportsCOMDAT() && GV->isWeakForLinker()) 240 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 241 242 if (D.getTLSKind()) 243 setTLSMode(GV, D); 244 245 if (D.isExternallyVisible()) { 246 if (D.hasAttr<DLLImportAttr>()) 247 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 248 else if (D.hasAttr<DLLExportAttr>()) 249 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 250 } 251 252 // Make sure the result is of the correct type. 253 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty); 254 llvm::Constant *Addr = GV; 255 if (AddrSpace != ExpectedAddrSpace) { 256 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace); 257 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy); 258 } 259 260 setStaticLocalDeclAddress(&D, Addr); 261 262 // Ensure that the static local gets initialized by making sure the parent 263 // function gets emitted eventually. 264 const Decl *DC = cast<Decl>(D.getDeclContext()); 265 266 // We can't name blocks or captured statements directly, so try to emit their 267 // parents. 268 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) { 269 DC = DC->getNonClosureContext(); 270 // FIXME: Ensure that global blocks get emitted. 271 if (!DC) 272 return Addr; 273 } 274 275 GlobalDecl GD; 276 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC)) 277 GD = GlobalDecl(CD, Ctor_Base); 278 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC)) 279 GD = GlobalDecl(DD, Dtor_Base); 280 else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) 281 GD = GlobalDecl(FD); 282 else { 283 // Don't do anything for Obj-C method decls or global closures. We should 284 // never defer them. 285 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl"); 286 } 287 if (GD.getDecl()) 288 (void)GetAddrOfGlobal(GD); 289 290 return Addr; 291 } 292 293 /// hasNontrivialDestruction - Determine whether a type's destruction is 294 /// non-trivial. If so, and the variable uses static initialization, we must 295 /// register its destructor to run on exit. 296 static bool hasNontrivialDestruction(QualType T) { 297 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 298 return RD && !RD->hasTrivialDestructor(); 299 } 300 301 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 302 /// global variable that has already been created for it. If the initializer 303 /// has a different type than GV does, this may free GV and return a different 304 /// one. Otherwise it just returns GV. 305 llvm::GlobalVariable * 306 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D, 307 llvm::GlobalVariable *GV) { 308 llvm::Constant *Init = CGM.EmitConstantInit(D, this); 309 310 // If constant emission failed, then this should be a C++ static 311 // initializer. 312 if (!Init) { 313 if (!getLangOpts().CPlusPlus) 314 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression"); 315 else if (HaveInsertPoint()) { 316 // Since we have a static initializer, this global variable can't 317 // be constant. 318 GV->setConstant(false); 319 320 EmitCXXGuardedInit(D, GV, /*PerformInit*/true); 321 } 322 return GV; 323 } 324 325 // The initializer may differ in type from the global. Rewrite 326 // the global to match the initializer. (We have to do this 327 // because some types, like unions, can't be completely represented 328 // in the LLVM type system.) 329 if (GV->getType()->getElementType() != Init->getType()) { 330 llvm::GlobalVariable *OldGV = GV; 331 332 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), 333 OldGV->isConstant(), 334 OldGV->getLinkage(), Init, "", 335 /*InsertBefore*/ OldGV, 336 OldGV->getThreadLocalMode(), 337 CGM.getContext().getTargetAddressSpace(D.getType())); 338 GV->setVisibility(OldGV->getVisibility()); 339 GV->setComdat(OldGV->getComdat()); 340 341 // Steal the name of the old global 342 GV->takeName(OldGV); 343 344 // Replace all uses of the old global with the new global 345 llvm::Constant *NewPtrForOldDecl = 346 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 347 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 348 349 // Erase the old global, since it is no longer used. 350 OldGV->eraseFromParent(); 351 } 352 353 GV->setConstant(CGM.isTypeConstant(D.getType(), true)); 354 GV->setInitializer(Init); 355 356 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) { 357 // We have a constant initializer, but a nontrivial destructor. We still 358 // need to perform a guarded "initialization" in order to register the 359 // destructor. 360 EmitCXXGuardedInit(D, GV, /*PerformInit*/false); 361 } 362 363 return GV; 364 } 365 366 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D, 367 llvm::GlobalValue::LinkageTypes Linkage) { 368 // Check to see if we already have a global variable for this 369 // declaration. This can happen when double-emitting function 370 // bodies, e.g. with complete and base constructors. 371 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage); 372 CharUnits alignment = getContext().getDeclAlign(&D); 373 374 // Store into LocalDeclMap before generating initializer to handle 375 // circular references. 376 setAddrOfLocalVar(&D, Address(addr, alignment)); 377 378 // We can't have a VLA here, but we can have a pointer to a VLA, 379 // even though that doesn't really make any sense. 380 // Make sure to evaluate VLA bounds now so that we have them for later. 381 if (D.getType()->isVariablyModifiedType()) 382 EmitVariablyModifiedType(D.getType()); 383 384 // Save the type in case adding the initializer forces a type change. 385 llvm::Type *expectedType = addr->getType(); 386 387 llvm::GlobalVariable *var = 388 cast<llvm::GlobalVariable>(addr->stripPointerCasts()); 389 390 // CUDA's local and local static __shared__ variables should not 391 // have any non-empty initializers. This is ensured by Sema. 392 // Whatever initializer such variable may have when it gets here is 393 // a no-op and should not be emitted. 394 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 395 D.hasAttr<CUDASharedAttr>(); 396 // If this value has an initializer, emit it. 397 if (D.getInit() && !isCudaSharedVar) 398 var = AddInitializerToStaticVarDecl(D, var); 399 400 var->setAlignment(alignment.getQuantity()); 401 402 if (D.hasAttr<AnnotateAttr>()) 403 CGM.AddGlobalAnnotations(&D, var); 404 405 if (const SectionAttr *SA = D.getAttr<SectionAttr>()) 406 var->setSection(SA->getName()); 407 408 if (D.hasAttr<UsedAttr>()) 409 CGM.addUsedGlobal(var); 410 411 // We may have to cast the constant because of the initializer 412 // mismatch above. 413 // 414 // FIXME: It is really dangerous to store this in the map; if anyone 415 // RAUW's the GV uses of this constant will be invalid. 416 llvm::Constant *castedAddr = 417 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType); 418 if (var != castedAddr) 419 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment); 420 CGM.setStaticLocalDeclAddress(&D, castedAddr); 421 422 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D); 423 424 // Emit global variable debug descriptor for static vars. 425 CGDebugInfo *DI = getDebugInfo(); 426 if (DI && 427 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) { 428 DI->setLocation(D.getLocation()); 429 DI->EmitGlobalVariable(var, &D); 430 } 431 } 432 433 namespace { 434 struct DestroyObject final : EHScopeStack::Cleanup { 435 DestroyObject(Address addr, QualType type, 436 CodeGenFunction::Destroyer *destroyer, 437 bool useEHCleanupForArray) 438 : addr(addr), type(type), destroyer(destroyer), 439 useEHCleanupForArray(useEHCleanupForArray) {} 440 441 Address addr; 442 QualType type; 443 CodeGenFunction::Destroyer *destroyer; 444 bool useEHCleanupForArray; 445 446 void Emit(CodeGenFunction &CGF, Flags flags) override { 447 // Don't use an EH cleanup recursively from an EH cleanup. 448 bool useEHCleanupForArray = 449 flags.isForNormalCleanup() && this->useEHCleanupForArray; 450 451 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray); 452 } 453 }; 454 455 struct DestroyNRVOVariable final : EHScopeStack::Cleanup { 456 DestroyNRVOVariable(Address addr, 457 const CXXDestructorDecl *Dtor, 458 llvm::Value *NRVOFlag) 459 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {} 460 461 const CXXDestructorDecl *Dtor; 462 llvm::Value *NRVOFlag; 463 Address Loc; 464 465 void Emit(CodeGenFunction &CGF, Flags flags) override { 466 // Along the exceptions path we always execute the dtor. 467 bool NRVO = flags.isForNormalCleanup() && NRVOFlag; 468 469 llvm::BasicBlock *SkipDtorBB = nullptr; 470 if (NRVO) { 471 // If we exited via NRVO, we skip the destructor call. 472 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused"); 473 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor"); 474 llvm::Value *DidNRVO = 475 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val"); 476 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB); 477 CGF.EmitBlock(RunDtorBB); 478 } 479 480 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 481 /*ForVirtualBase=*/false, 482 /*Delegating=*/false, 483 Loc); 484 485 if (NRVO) CGF.EmitBlock(SkipDtorBB); 486 } 487 }; 488 489 struct CallStackRestore final : EHScopeStack::Cleanup { 490 Address Stack; 491 CallStackRestore(Address Stack) : Stack(Stack) {} 492 void Emit(CodeGenFunction &CGF, Flags flags) override { 493 llvm::Value *V = CGF.Builder.CreateLoad(Stack); 494 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 495 CGF.Builder.CreateCall(F, V); 496 } 497 }; 498 499 struct ExtendGCLifetime final : EHScopeStack::Cleanup { 500 const VarDecl &Var; 501 ExtendGCLifetime(const VarDecl *var) : Var(*var) {} 502 503 void Emit(CodeGenFunction &CGF, Flags flags) override { 504 // Compute the address of the local variable, in case it's a 505 // byref or something. 506 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false, 507 Var.getType(), VK_LValue, SourceLocation()); 508 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE), 509 SourceLocation()); 510 CGF.EmitExtendGCLifetime(value); 511 } 512 }; 513 514 struct CallCleanupFunction final : EHScopeStack::Cleanup { 515 llvm::Constant *CleanupFn; 516 const CGFunctionInfo &FnInfo; 517 const VarDecl &Var; 518 519 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info, 520 const VarDecl *Var) 521 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {} 522 523 void Emit(CodeGenFunction &CGF, Flags flags) override { 524 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false, 525 Var.getType(), VK_LValue, SourceLocation()); 526 // Compute the address of the local variable, in case it's a byref 527 // or something. 528 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(); 529 530 // In some cases, the type of the function argument will be different from 531 // the type of the pointer. An example of this is 532 // void f(void* arg); 533 // __attribute__((cleanup(f))) void *g; 534 // 535 // To fix this we insert a bitcast here. 536 QualType ArgTy = FnInfo.arg_begin()->type; 537 llvm::Value *Arg = 538 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy)); 539 540 CallArgList Args; 541 Args.add(RValue::get(Arg), 542 CGF.getContext().getPointerType(Var.getType())); 543 auto Callee = CGCallee::forDirect(CleanupFn); 544 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args); 545 } 546 }; 547 } // end anonymous namespace 548 549 /// EmitAutoVarWithLifetime - Does the setup required for an automatic 550 /// variable with lifetime. 551 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var, 552 Address addr, 553 Qualifiers::ObjCLifetime lifetime) { 554 switch (lifetime) { 555 case Qualifiers::OCL_None: 556 llvm_unreachable("present but none"); 557 558 case Qualifiers::OCL_ExplicitNone: 559 // nothing to do 560 break; 561 562 case Qualifiers::OCL_Strong: { 563 CodeGenFunction::Destroyer *destroyer = 564 (var.hasAttr<ObjCPreciseLifetimeAttr>() 565 ? CodeGenFunction::destroyARCStrongPrecise 566 : CodeGenFunction::destroyARCStrongImprecise); 567 568 CleanupKind cleanupKind = CGF.getARCCleanupKind(); 569 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer, 570 cleanupKind & EHCleanup); 571 break; 572 } 573 case Qualifiers::OCL_Autoreleasing: 574 // nothing to do 575 break; 576 577 case Qualifiers::OCL_Weak: 578 // __weak objects always get EH cleanups; otherwise, exceptions 579 // could cause really nasty crashes instead of mere leaks. 580 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(), 581 CodeGenFunction::destroyARCWeak, 582 /*useEHCleanup*/ true); 583 break; 584 } 585 } 586 587 static bool isAccessedBy(const VarDecl &var, const Stmt *s) { 588 if (const Expr *e = dyn_cast<Expr>(s)) { 589 // Skip the most common kinds of expressions that make 590 // hierarchy-walking expensive. 591 s = e = e->IgnoreParenCasts(); 592 593 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) 594 return (ref->getDecl() == &var); 595 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) { 596 const BlockDecl *block = be->getBlockDecl(); 597 for (const auto &I : block->captures()) { 598 if (I.getVariable() == &var) 599 return true; 600 } 601 } 602 } 603 604 for (const Stmt *SubStmt : s->children()) 605 // SubStmt might be null; as in missing decl or conditional of an if-stmt. 606 if (SubStmt && isAccessedBy(var, SubStmt)) 607 return true; 608 609 return false; 610 } 611 612 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) { 613 if (!decl) return false; 614 if (!isa<VarDecl>(decl)) return false; 615 const VarDecl *var = cast<VarDecl>(decl); 616 return isAccessedBy(*var, e); 617 } 618 619 static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF, 620 const LValue &destLV, const Expr *init) { 621 bool needsCast = false; 622 623 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) { 624 switch (castExpr->getCastKind()) { 625 // Look through casts that don't require representation changes. 626 case CK_NoOp: 627 case CK_BitCast: 628 case CK_BlockPointerToObjCPointerCast: 629 needsCast = true; 630 break; 631 632 // If we find an l-value to r-value cast from a __weak variable, 633 // emit this operation as a copy or move. 634 case CK_LValueToRValue: { 635 const Expr *srcExpr = castExpr->getSubExpr(); 636 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak) 637 return false; 638 639 // Emit the source l-value. 640 LValue srcLV = CGF.EmitLValue(srcExpr); 641 642 // Handle a formal type change to avoid asserting. 643 auto srcAddr = srcLV.getAddress(); 644 if (needsCast) { 645 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr, 646 destLV.getAddress().getElementType()); 647 } 648 649 // If it was an l-value, use objc_copyWeak. 650 if (srcExpr->getValueKind() == VK_LValue) { 651 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr); 652 } else { 653 assert(srcExpr->getValueKind() == VK_XValue); 654 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr); 655 } 656 return true; 657 } 658 659 // Stop at anything else. 660 default: 661 return false; 662 } 663 664 init = castExpr->getSubExpr(); 665 } 666 return false; 667 } 668 669 static void drillIntoBlockVariable(CodeGenFunction &CGF, 670 LValue &lvalue, 671 const VarDecl *var) { 672 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var)); 673 } 674 675 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D, 676 LValue lvalue, bool capturedByInit) { 677 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime(); 678 if (!lifetime) { 679 llvm::Value *value = EmitScalarExpr(init); 680 if (capturedByInit) 681 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 682 EmitStoreThroughLValue(RValue::get(value), lvalue, true); 683 return; 684 } 685 686 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init)) 687 init = DIE->getExpr(); 688 689 // If we're emitting a value with lifetime, we have to do the 690 // initialization *before* we leave the cleanup scopes. 691 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) { 692 enterFullExpression(ewc); 693 init = ewc->getSubExpr(); 694 } 695 CodeGenFunction::RunCleanupsScope Scope(*this); 696 697 // We have to maintain the illusion that the variable is 698 // zero-initialized. If the variable might be accessed in its 699 // initializer, zero-initialize before running the initializer, then 700 // actually perform the initialization with an assign. 701 bool accessedByInit = false; 702 if (lifetime != Qualifiers::OCL_ExplicitNone) 703 accessedByInit = (capturedByInit || isAccessedBy(D, init)); 704 if (accessedByInit) { 705 LValue tempLV = lvalue; 706 // Drill down to the __block object if necessary. 707 if (capturedByInit) { 708 // We can use a simple GEP for this because it can't have been 709 // moved yet. 710 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(), 711 cast<VarDecl>(D), 712 /*follow*/ false)); 713 } 714 715 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType()); 716 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType()); 717 718 // If __weak, we want to use a barrier under certain conditions. 719 if (lifetime == Qualifiers::OCL_Weak) 720 EmitARCInitWeak(tempLV.getAddress(), zero); 721 722 // Otherwise just do a simple store. 723 else 724 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true); 725 } 726 727 // Emit the initializer. 728 llvm::Value *value = nullptr; 729 730 switch (lifetime) { 731 case Qualifiers::OCL_None: 732 llvm_unreachable("present but none"); 733 734 case Qualifiers::OCL_ExplicitNone: 735 value = EmitARCUnsafeUnretainedScalarExpr(init); 736 break; 737 738 case Qualifiers::OCL_Strong: { 739 value = EmitARCRetainScalarExpr(init); 740 break; 741 } 742 743 case Qualifiers::OCL_Weak: { 744 // If it's not accessed by the initializer, try to emit the 745 // initialization with a copy or move. 746 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) { 747 return; 748 } 749 750 // No way to optimize a producing initializer into this. It's not 751 // worth optimizing for, because the value will immediately 752 // disappear in the common case. 753 value = EmitScalarExpr(init); 754 755 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 756 if (accessedByInit) 757 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true); 758 else 759 EmitARCInitWeak(lvalue.getAddress(), value); 760 return; 761 } 762 763 case Qualifiers::OCL_Autoreleasing: 764 value = EmitARCRetainAutoreleaseScalarExpr(init); 765 break; 766 } 767 768 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 769 770 // If the variable might have been accessed by its initializer, we 771 // might have to initialize with a barrier. We have to do this for 772 // both __weak and __strong, but __weak got filtered out above. 773 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) { 774 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc()); 775 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true); 776 EmitARCRelease(oldValue, ARCImpreciseLifetime); 777 return; 778 } 779 780 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true); 781 } 782 783 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the 784 /// non-zero parts of the specified initializer with equal or fewer than 785 /// NumStores scalar stores. 786 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init, 787 unsigned &NumStores) { 788 // Zero and Undef never requires any extra stores. 789 if (isa<llvm::ConstantAggregateZero>(Init) || 790 isa<llvm::ConstantPointerNull>(Init) || 791 isa<llvm::UndefValue>(Init)) 792 return true; 793 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) || 794 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) || 795 isa<llvm::ConstantExpr>(Init)) 796 return Init->isNullValue() || NumStores--; 797 798 // See if we can emit each element. 799 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) { 800 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 801 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i)); 802 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores)) 803 return false; 804 } 805 return true; 806 } 807 808 if (llvm::ConstantDataSequential *CDS = 809 dyn_cast<llvm::ConstantDataSequential>(Init)) { 810 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 811 llvm::Constant *Elt = CDS->getElementAsConstant(i); 812 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores)) 813 return false; 814 } 815 return true; 816 } 817 818 // Anything else is hard and scary. 819 return false; 820 } 821 822 /// emitStoresForInitAfterMemset - For inits that 823 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar 824 /// stores that would be required. 825 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc, 826 bool isVolatile, CGBuilderTy &Builder) { 827 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) && 828 "called emitStoresForInitAfterMemset for zero or undef value."); 829 830 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) || 831 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) || 832 isa<llvm::ConstantExpr>(Init)) { 833 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile); 834 return; 835 } 836 837 if (llvm::ConstantDataSequential *CDS = 838 dyn_cast<llvm::ConstantDataSequential>(Init)) { 839 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 840 llvm::Constant *Elt = CDS->getElementAsConstant(i); 841 842 // If necessary, get a pointer to the element and emit it. 843 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt)) 844 emitStoresForInitAfterMemset( 845 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i), 846 isVolatile, Builder); 847 } 848 return; 849 } 850 851 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) && 852 "Unknown value type!"); 853 854 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 855 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i)); 856 857 // If necessary, get a pointer to the element and emit it. 858 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt)) 859 emitStoresForInitAfterMemset( 860 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i), 861 isVolatile, Builder); 862 } 863 } 864 865 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset 866 /// plus some stores to initialize a local variable instead of using a memcpy 867 /// from a constant global. It is beneficial to use memset if the global is all 868 /// zeros, or mostly zeros and large. 869 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init, 870 uint64_t GlobalSize) { 871 // If a global is all zeros, always use a memset. 872 if (isa<llvm::ConstantAggregateZero>(Init)) return true; 873 874 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large, 875 // do it if it will require 6 or fewer scalar stores. 876 // TODO: Should budget depends on the size? Avoiding a large global warrants 877 // plopping in more stores. 878 unsigned StoreBudget = 6; 879 uint64_t SizeLimit = 32; 880 881 return GlobalSize > SizeLimit && 882 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget); 883 } 884 885 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a 886 /// variable declaration with auto, register, or no storage class specifier. 887 /// These turn into simple stack objects, or GlobalValues depending on target. 888 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) { 889 AutoVarEmission emission = EmitAutoVarAlloca(D); 890 EmitAutoVarInit(emission); 891 EmitAutoVarCleanups(emission); 892 } 893 894 /// Emit a lifetime.begin marker if some criteria are satisfied. 895 /// \return a pointer to the temporary size Value if a marker was emitted, null 896 /// otherwise 897 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size, 898 llvm::Value *Addr) { 899 if (!ShouldEmitLifetimeMarkers) 900 return nullptr; 901 902 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size); 903 Addr = Builder.CreateBitCast(Addr, Int8PtrTy); 904 llvm::CallInst *C = 905 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr}); 906 C->setDoesNotThrow(); 907 return SizeV; 908 } 909 910 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) { 911 Addr = Builder.CreateBitCast(Addr, Int8PtrTy); 912 llvm::CallInst *C = 913 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr}); 914 C->setDoesNotThrow(); 915 } 916 917 /// EmitAutoVarAlloca - Emit the alloca and debug information for a 918 /// local variable. Does not emit initialization or destruction. 919 CodeGenFunction::AutoVarEmission 920 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) { 921 QualType Ty = D.getType(); 922 923 AutoVarEmission emission(D); 924 925 bool isByRef = D.hasAttr<BlocksAttr>(); 926 emission.IsByRef = isByRef; 927 928 CharUnits alignment = getContext().getDeclAlign(&D); 929 930 // If the type is variably-modified, emit all the VLA sizes for it. 931 if (Ty->isVariablyModifiedType()) 932 EmitVariablyModifiedType(Ty); 933 934 Address address = Address::invalid(); 935 if (Ty->isConstantSizeType()) { 936 bool NRVO = getLangOpts().ElideConstructors && 937 D.isNRVOVariable(); 938 939 // If this value is an array or struct with a statically determinable 940 // constant initializer, there are optimizations we can do. 941 // 942 // TODO: We should constant-evaluate the initializer of any variable, 943 // as long as it is initialized by a constant expression. Currently, 944 // isConstantInitializer produces wrong answers for structs with 945 // reference or bitfield members, and a few other cases, and checking 946 // for POD-ness protects us from some of these. 947 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) && 948 (D.isConstexpr() || 949 ((Ty.isPODType(getContext()) || 950 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) && 951 D.getInit()->isConstantInitializer(getContext(), false)))) { 952 953 // If the variable's a const type, and it's neither an NRVO 954 // candidate nor a __block variable and has no mutable members, 955 // emit it as a global instead. 956 // Exception is if a variable is located in non-constant address space 957 // in OpenCL. 958 if ((!getLangOpts().OpenCL || 959 Ty.getAddressSpace() == LangAS::opencl_constant) && 960 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef && 961 CGM.isTypeConstant(Ty, true))) { 962 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage); 963 964 // Signal this condition to later callbacks. 965 emission.Addr = Address::invalid(); 966 assert(emission.wasEmittedAsGlobal()); 967 return emission; 968 } 969 970 // Otherwise, tell the initialization code that we're in this case. 971 emission.IsConstantAggregate = true; 972 } 973 974 // A normal fixed sized variable becomes an alloca in the entry block, 975 // unless it's an NRVO variable. 976 977 if (NRVO) { 978 // The named return value optimization: allocate this variable in the 979 // return slot, so that we can elide the copy when returning this 980 // variable (C++0x [class.copy]p34). 981 address = ReturnValue; 982 983 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) { 984 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) { 985 // Create a flag that is used to indicate when the NRVO was applied 986 // to this variable. Set it to zero to indicate that NRVO was not 987 // applied. 988 llvm::Value *Zero = Builder.getFalse(); 989 Address NRVOFlag = 990 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo"); 991 EnsureInsertPoint(); 992 Builder.CreateStore(Zero, NRVOFlag); 993 994 // Record the NRVO flag for this variable. 995 NRVOFlags[&D] = NRVOFlag.getPointer(); 996 emission.NRVOFlag = NRVOFlag.getPointer(); 997 } 998 } 999 } else { 1000 CharUnits allocaAlignment; 1001 llvm::Type *allocaTy; 1002 if (isByRef) { 1003 auto &byrefInfo = getBlockByrefInfo(&D); 1004 allocaTy = byrefInfo.Type; 1005 allocaAlignment = byrefInfo.ByrefAlignment; 1006 } else { 1007 allocaTy = ConvertTypeForMem(Ty); 1008 allocaAlignment = alignment; 1009 } 1010 1011 // Create the alloca. Note that we set the name separately from 1012 // building the instruction so that it's there even in no-asserts 1013 // builds. 1014 address = CreateTempAlloca(allocaTy, allocaAlignment); 1015 address.getPointer()->setName(D.getName()); 1016 1017 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of 1018 // the catch parameter starts in the catchpad instruction, and we can't 1019 // insert code in those basic blocks. 1020 bool IsMSCatchParam = 1021 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft(); 1022 1023 // Emit a lifetime intrinsic if meaningful. There's no point in doing this 1024 // if we don't have a valid insertion point (?). 1025 if (HaveInsertPoint() && !IsMSCatchParam) { 1026 // If there's a jump into the lifetime of this variable, its lifetime 1027 // gets broken up into several regions in IR, which requires more work 1028 // to handle correctly. For now, just omit the intrinsics; this is a 1029 // rare case, and it's better to just be conservatively correct. 1030 // PR28267. 1031 // 1032 // We have to do this in all language modes if there's a jump past the 1033 // declaration. We also have to do it in C if there's a jump to an 1034 // earlier point in the current block because non-VLA lifetimes begin as 1035 // soon as the containing block is entered, not when its variables 1036 // actually come into scope; suppressing the lifetime annotations 1037 // completely in this case is unnecessarily pessimistic, but again, this 1038 // is rare. 1039 if (!Bypasses.IsBypassed(&D) && 1040 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) { 1041 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy); 1042 emission.SizeForLifetimeMarkers = 1043 EmitLifetimeStart(size, address.getPointer()); 1044 } 1045 } else { 1046 assert(!emission.useLifetimeMarkers()); 1047 } 1048 } 1049 } else { 1050 EnsureInsertPoint(); 1051 1052 if (!DidCallStackSave) { 1053 // Save the stack. 1054 Address Stack = 1055 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack"); 1056 1057 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave); 1058 llvm::Value *V = Builder.CreateCall(F); 1059 Builder.CreateStore(V, Stack); 1060 1061 DidCallStackSave = true; 1062 1063 // Push a cleanup block and restore the stack there. 1064 // FIXME: in general circumstances, this should be an EH cleanup. 1065 pushStackRestore(NormalCleanup, Stack); 1066 } 1067 1068 llvm::Value *elementCount; 1069 QualType elementType; 1070 std::tie(elementCount, elementType) = getVLASize(Ty); 1071 1072 llvm::Type *llvmTy = ConvertTypeForMem(elementType); 1073 1074 // Allocate memory for the array. 1075 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla"); 1076 vla->setAlignment(alignment.getQuantity()); 1077 1078 address = Address(vla, alignment); 1079 } 1080 1081 setAddrOfLocalVar(&D, address); 1082 emission.Addr = address; 1083 1084 // Emit debug info for local var declaration. 1085 if (HaveInsertPoint()) 1086 if (CGDebugInfo *DI = getDebugInfo()) { 1087 if (CGM.getCodeGenOpts().getDebugInfo() >= 1088 codegenoptions::LimitedDebugInfo) { 1089 DI->setLocation(D.getLocation()); 1090 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder); 1091 } 1092 } 1093 1094 if (D.hasAttr<AnnotateAttr>()) 1095 EmitVarAnnotations(&D, address.getPointer()); 1096 1097 return emission; 1098 } 1099 1100 /// Determines whether the given __block variable is potentially 1101 /// captured by the given expression. 1102 static bool isCapturedBy(const VarDecl &var, const Expr *e) { 1103 // Skip the most common kinds of expressions that make 1104 // hierarchy-walking expensive. 1105 e = e->IgnoreParenCasts(); 1106 1107 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) { 1108 const BlockDecl *block = be->getBlockDecl(); 1109 for (const auto &I : block->captures()) { 1110 if (I.getVariable() == &var) 1111 return true; 1112 } 1113 1114 // No need to walk into the subexpressions. 1115 return false; 1116 } 1117 1118 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) { 1119 const CompoundStmt *CS = SE->getSubStmt(); 1120 for (const auto *BI : CS->body()) 1121 if (const auto *E = dyn_cast<Expr>(BI)) { 1122 if (isCapturedBy(var, E)) 1123 return true; 1124 } 1125 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) { 1126 // special case declarations 1127 for (const auto *I : DS->decls()) { 1128 if (const auto *VD = dyn_cast<VarDecl>((I))) { 1129 const Expr *Init = VD->getInit(); 1130 if (Init && isCapturedBy(var, Init)) 1131 return true; 1132 } 1133 } 1134 } 1135 else 1136 // FIXME. Make safe assumption assuming arbitrary statements cause capturing. 1137 // Later, provide code to poke into statements for capture analysis. 1138 return true; 1139 return false; 1140 } 1141 1142 for (const Stmt *SubStmt : e->children()) 1143 if (isCapturedBy(var, cast<Expr>(SubStmt))) 1144 return true; 1145 1146 return false; 1147 } 1148 1149 /// \brief Determine whether the given initializer is trivial in the sense 1150 /// that it requires no code to be generated. 1151 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) { 1152 if (!Init) 1153 return true; 1154 1155 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) 1156 if (CXXConstructorDecl *Constructor = Construct->getConstructor()) 1157 if (Constructor->isTrivial() && 1158 Constructor->isDefaultConstructor() && 1159 !Construct->requiresZeroInitialization()) 1160 return true; 1161 1162 return false; 1163 } 1164 1165 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) { 1166 assert(emission.Variable && "emission was not valid!"); 1167 1168 // If this was emitted as a global constant, we're done. 1169 if (emission.wasEmittedAsGlobal()) return; 1170 1171 const VarDecl &D = *emission.Variable; 1172 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation()); 1173 QualType type = D.getType(); 1174 1175 // If this local has an initializer, emit it now. 1176 const Expr *Init = D.getInit(); 1177 1178 // If we are at an unreachable point, we don't need to emit the initializer 1179 // unless it contains a label. 1180 if (!HaveInsertPoint()) { 1181 if (!Init || !ContainsLabel(Init)) return; 1182 EnsureInsertPoint(); 1183 } 1184 1185 // Initialize the structure of a __block variable. 1186 if (emission.IsByRef) 1187 emitByrefStructureInit(emission); 1188 1189 if (isTrivialInitializer(Init)) 1190 return; 1191 1192 // Check whether this is a byref variable that's potentially 1193 // captured and moved by its own initializer. If so, we'll need to 1194 // emit the initializer first, then copy into the variable. 1195 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init); 1196 1197 Address Loc = 1198 capturedByInit ? emission.Addr : emission.getObjectAddress(*this); 1199 1200 llvm::Constant *constant = nullptr; 1201 if (emission.IsConstantAggregate || D.isConstexpr()) { 1202 assert(!capturedByInit && "constant init contains a capturing block?"); 1203 constant = CGM.EmitConstantInit(D, this); 1204 } 1205 1206 if (!constant) { 1207 LValue lv = MakeAddrLValue(Loc, type); 1208 lv.setNonGC(true); 1209 return EmitExprAsInit(Init, &D, lv, capturedByInit); 1210 } 1211 1212 if (!emission.IsConstantAggregate) { 1213 // For simple scalar/complex initialization, store the value directly. 1214 LValue lv = MakeAddrLValue(Loc, type); 1215 lv.setNonGC(true); 1216 return EmitStoreThroughLValue(RValue::get(constant), lv, true); 1217 } 1218 1219 // If this is a simple aggregate initialization, we can optimize it 1220 // in various ways. 1221 bool isVolatile = type.isVolatileQualified(); 1222 1223 llvm::Value *SizeVal = 1224 llvm::ConstantInt::get(IntPtrTy, 1225 getContext().getTypeSizeInChars(type).getQuantity()); 1226 1227 llvm::Type *BP = Int8PtrTy; 1228 if (Loc.getType() != BP) 1229 Loc = Builder.CreateBitCast(Loc, BP); 1230 1231 // If the initializer is all or mostly zeros, codegen with memset then do 1232 // a few stores afterward. 1233 if (shouldUseMemSetPlusStoresToInitialize(constant, 1234 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) { 1235 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal, 1236 isVolatile); 1237 // Zero and undef don't require a stores. 1238 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) { 1239 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo()); 1240 emitStoresForInitAfterMemset(constant, Loc.getPointer(), 1241 isVolatile, Builder); 1242 } 1243 } else { 1244 // Otherwise, create a temporary global with the initializer then 1245 // memcpy from the global to the alloca. 1246 std::string Name = getStaticDeclName(CGM, D); 1247 unsigned AS = 0; 1248 if (getLangOpts().OpenCL) { 1249 AS = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 1250 BP = llvm::PointerType::getInt8PtrTy(getLLVMContext(), AS); 1251 } 1252 llvm::GlobalVariable *GV = 1253 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true, 1254 llvm::GlobalValue::PrivateLinkage, 1255 constant, Name, nullptr, 1256 llvm::GlobalValue::NotThreadLocal, AS); 1257 GV->setAlignment(Loc.getAlignment().getQuantity()); 1258 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1259 1260 Address SrcPtr = Address(GV, Loc.getAlignment()); 1261 if (SrcPtr.getType() != BP) 1262 SrcPtr = Builder.CreateBitCast(SrcPtr, BP); 1263 1264 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile); 1265 } 1266 } 1267 1268 /// Emit an expression as an initializer for a variable at the given 1269 /// location. The expression is not necessarily the normal 1270 /// initializer for the variable, and the address is not necessarily 1271 /// its normal location. 1272 /// 1273 /// \param init the initializing expression 1274 /// \param var the variable to act as if we're initializing 1275 /// \param loc the address to initialize; its type is a pointer 1276 /// to the LLVM mapping of the variable's type 1277 /// \param alignment the alignment of the address 1278 /// \param capturedByInit true if the variable is a __block variable 1279 /// whose address is potentially changed by the initializer 1280 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D, 1281 LValue lvalue, bool capturedByInit) { 1282 QualType type = D->getType(); 1283 1284 if (type->isReferenceType()) { 1285 RValue rvalue = EmitReferenceBindingToExpr(init); 1286 if (capturedByInit) 1287 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 1288 EmitStoreThroughLValue(rvalue, lvalue, true); 1289 return; 1290 } 1291 switch (getEvaluationKind(type)) { 1292 case TEK_Scalar: 1293 EmitScalarInit(init, D, lvalue, capturedByInit); 1294 return; 1295 case TEK_Complex: { 1296 ComplexPairTy complex = EmitComplexExpr(init); 1297 if (capturedByInit) 1298 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 1299 EmitStoreOfComplex(complex, lvalue, /*init*/ true); 1300 return; 1301 } 1302 case TEK_Aggregate: 1303 if (type->isAtomicType()) { 1304 EmitAtomicInit(const_cast<Expr*>(init), lvalue); 1305 } else { 1306 // TODO: how can we delay here if D is captured by its initializer? 1307 EmitAggExpr(init, AggValueSlot::forLValue(lvalue, 1308 AggValueSlot::IsDestructed, 1309 AggValueSlot::DoesNotNeedGCBarriers, 1310 AggValueSlot::IsNotAliased)); 1311 } 1312 return; 1313 } 1314 llvm_unreachable("bad evaluation kind"); 1315 } 1316 1317 /// Enter a destroy cleanup for the given local variable. 1318 void CodeGenFunction::emitAutoVarTypeCleanup( 1319 const CodeGenFunction::AutoVarEmission &emission, 1320 QualType::DestructionKind dtorKind) { 1321 assert(dtorKind != QualType::DK_none); 1322 1323 // Note that for __block variables, we want to destroy the 1324 // original stack object, not the possibly forwarded object. 1325 Address addr = emission.getObjectAddress(*this); 1326 1327 const VarDecl *var = emission.Variable; 1328 QualType type = var->getType(); 1329 1330 CleanupKind cleanupKind = NormalAndEHCleanup; 1331 CodeGenFunction::Destroyer *destroyer = nullptr; 1332 1333 switch (dtorKind) { 1334 case QualType::DK_none: 1335 llvm_unreachable("no cleanup for trivially-destructible variable"); 1336 1337 case QualType::DK_cxx_destructor: 1338 // If there's an NRVO flag on the emission, we need a different 1339 // cleanup. 1340 if (emission.NRVOFlag) { 1341 assert(!type->isArrayType()); 1342 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor(); 1343 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, 1344 dtor, emission.NRVOFlag); 1345 return; 1346 } 1347 break; 1348 1349 case QualType::DK_objc_strong_lifetime: 1350 // Suppress cleanups for pseudo-strong variables. 1351 if (var->isARCPseudoStrong()) return; 1352 1353 // Otherwise, consider whether to use an EH cleanup or not. 1354 cleanupKind = getARCCleanupKind(); 1355 1356 // Use the imprecise destroyer by default. 1357 if (!var->hasAttr<ObjCPreciseLifetimeAttr>()) 1358 destroyer = CodeGenFunction::destroyARCStrongImprecise; 1359 break; 1360 1361 case QualType::DK_objc_weak_lifetime: 1362 break; 1363 } 1364 1365 // If we haven't chosen a more specific destroyer, use the default. 1366 if (!destroyer) destroyer = getDestroyer(dtorKind); 1367 1368 // Use an EH cleanup in array destructors iff the destructor itself 1369 // is being pushed as an EH cleanup. 1370 bool useEHCleanup = (cleanupKind & EHCleanup); 1371 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer, 1372 useEHCleanup); 1373 } 1374 1375 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) { 1376 assert(emission.Variable && "emission was not valid!"); 1377 1378 // If this was emitted as a global constant, we're done. 1379 if (emission.wasEmittedAsGlobal()) return; 1380 1381 // If we don't have an insertion point, we're done. Sema prevents 1382 // us from jumping into any of these scopes anyway. 1383 if (!HaveInsertPoint()) return; 1384 1385 const VarDecl &D = *emission.Variable; 1386 1387 // Make sure we call @llvm.lifetime.end. This needs to happen 1388 // *last*, so the cleanup needs to be pushed *first*. 1389 if (emission.useLifetimeMarkers()) 1390 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, 1391 emission.getAllocatedAddress(), 1392 emission.getSizeForLifetimeMarkers()); 1393 1394 // Check the type for a cleanup. 1395 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType()) 1396 emitAutoVarTypeCleanup(emission, dtorKind); 1397 1398 // In GC mode, honor objc_precise_lifetime. 1399 if (getLangOpts().getGC() != LangOptions::NonGC && 1400 D.hasAttr<ObjCPreciseLifetimeAttr>()) { 1401 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D); 1402 } 1403 1404 // Handle the cleanup attribute. 1405 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) { 1406 const FunctionDecl *FD = CA->getFunctionDecl(); 1407 1408 llvm::Constant *F = CGM.GetAddrOfFunction(FD); 1409 assert(F && "Could not find function!"); 1410 1411 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD); 1412 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D); 1413 } 1414 1415 // If this is a block variable, call _Block_object_destroy 1416 // (on the unforwarded address). 1417 if (emission.IsByRef) 1418 enterByrefCleanup(emission); 1419 } 1420 1421 CodeGenFunction::Destroyer * 1422 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) { 1423 switch (kind) { 1424 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor"); 1425 case QualType::DK_cxx_destructor: 1426 return destroyCXXObject; 1427 case QualType::DK_objc_strong_lifetime: 1428 return destroyARCStrongPrecise; 1429 case QualType::DK_objc_weak_lifetime: 1430 return destroyARCWeak; 1431 } 1432 llvm_unreachable("Unknown DestructionKind"); 1433 } 1434 1435 /// pushEHDestroy - Push the standard destructor for the given type as 1436 /// an EH-only cleanup. 1437 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind, 1438 Address addr, QualType type) { 1439 assert(dtorKind && "cannot push destructor for trivial type"); 1440 assert(needsEHCleanup(dtorKind)); 1441 1442 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true); 1443 } 1444 1445 /// pushDestroy - Push the standard destructor for the given type as 1446 /// at least a normal cleanup. 1447 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind, 1448 Address addr, QualType type) { 1449 assert(dtorKind && "cannot push destructor for trivial type"); 1450 1451 CleanupKind cleanupKind = getCleanupKind(dtorKind); 1452 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind), 1453 cleanupKind & EHCleanup); 1454 } 1455 1456 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr, 1457 QualType type, Destroyer *destroyer, 1458 bool useEHCleanupForArray) { 1459 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type, 1460 destroyer, useEHCleanupForArray); 1461 } 1462 1463 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) { 1464 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem); 1465 } 1466 1467 void CodeGenFunction::pushLifetimeExtendedDestroy( 1468 CleanupKind cleanupKind, Address addr, QualType type, 1469 Destroyer *destroyer, bool useEHCleanupForArray) { 1470 assert(!isInConditionalBranch() && 1471 "performing lifetime extension from within conditional"); 1472 1473 // Push an EH-only cleanup for the object now. 1474 // FIXME: When popping normal cleanups, we need to keep this EH cleanup 1475 // around in case a temporary's destructor throws an exception. 1476 if (cleanupKind & EHCleanup) 1477 EHStack.pushCleanup<DestroyObject>( 1478 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type, 1479 destroyer, useEHCleanupForArray); 1480 1481 // Remember that we need to push a full cleanup for the object at the 1482 // end of the full-expression. 1483 pushCleanupAfterFullExpr<DestroyObject>( 1484 cleanupKind, addr, type, destroyer, useEHCleanupForArray); 1485 } 1486 1487 /// emitDestroy - Immediately perform the destruction of the given 1488 /// object. 1489 /// 1490 /// \param addr - the address of the object; a type* 1491 /// \param type - the type of the object; if an array type, all 1492 /// objects are destroyed in reverse order 1493 /// \param destroyer - the function to call to destroy individual 1494 /// elements 1495 /// \param useEHCleanupForArray - whether an EH cleanup should be 1496 /// used when destroying array elements, in case one of the 1497 /// destructions throws an exception 1498 void CodeGenFunction::emitDestroy(Address addr, QualType type, 1499 Destroyer *destroyer, 1500 bool useEHCleanupForArray) { 1501 const ArrayType *arrayType = getContext().getAsArrayType(type); 1502 if (!arrayType) 1503 return destroyer(*this, addr, type); 1504 1505 llvm::Value *length = emitArrayLength(arrayType, type, addr); 1506 1507 CharUnits elementAlign = 1508 addr.getAlignment() 1509 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type)); 1510 1511 // Normally we have to check whether the array is zero-length. 1512 bool checkZeroLength = true; 1513 1514 // But if the array length is constant, we can suppress that. 1515 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) { 1516 // ...and if it's constant zero, we can just skip the entire thing. 1517 if (constLength->isZero()) return; 1518 checkZeroLength = false; 1519 } 1520 1521 llvm::Value *begin = addr.getPointer(); 1522 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length); 1523 emitArrayDestroy(begin, end, type, elementAlign, destroyer, 1524 checkZeroLength, useEHCleanupForArray); 1525 } 1526 1527 /// emitArrayDestroy - Destroys all the elements of the given array, 1528 /// beginning from last to first. The array cannot be zero-length. 1529 /// 1530 /// \param begin - a type* denoting the first element of the array 1531 /// \param end - a type* denoting one past the end of the array 1532 /// \param elementType - the element type of the array 1533 /// \param destroyer - the function to call to destroy elements 1534 /// \param useEHCleanup - whether to push an EH cleanup to destroy 1535 /// the remaining elements in case the destruction of a single 1536 /// element throws 1537 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin, 1538 llvm::Value *end, 1539 QualType elementType, 1540 CharUnits elementAlign, 1541 Destroyer *destroyer, 1542 bool checkZeroLength, 1543 bool useEHCleanup) { 1544 assert(!elementType->isArrayType()); 1545 1546 // The basic structure here is a do-while loop, because we don't 1547 // need to check for the zero-element case. 1548 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body"); 1549 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done"); 1550 1551 if (checkZeroLength) { 1552 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end, 1553 "arraydestroy.isempty"); 1554 Builder.CreateCondBr(isEmpty, doneBB, bodyBB); 1555 } 1556 1557 // Enter the loop body, making that address the current address. 1558 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 1559 EmitBlock(bodyBB); 1560 llvm::PHINode *elementPast = 1561 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast"); 1562 elementPast->addIncoming(end, entryBB); 1563 1564 // Shift the address back by one element. 1565 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true); 1566 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne, 1567 "arraydestroy.element"); 1568 1569 if (useEHCleanup) 1570 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign, 1571 destroyer); 1572 1573 // Perform the actual destruction there. 1574 destroyer(*this, Address(element, elementAlign), elementType); 1575 1576 if (useEHCleanup) 1577 PopCleanupBlock(); 1578 1579 // Check whether we've reached the end. 1580 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done"); 1581 Builder.CreateCondBr(done, doneBB, bodyBB); 1582 elementPast->addIncoming(element, Builder.GetInsertBlock()); 1583 1584 // Done. 1585 EmitBlock(doneBB); 1586 } 1587 1588 /// Perform partial array destruction as if in an EH cleanup. Unlike 1589 /// emitArrayDestroy, the element type here may still be an array type. 1590 static void emitPartialArrayDestroy(CodeGenFunction &CGF, 1591 llvm::Value *begin, llvm::Value *end, 1592 QualType type, CharUnits elementAlign, 1593 CodeGenFunction::Destroyer *destroyer) { 1594 // If the element type is itself an array, drill down. 1595 unsigned arrayDepth = 0; 1596 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) { 1597 // VLAs don't require a GEP index to walk into. 1598 if (!isa<VariableArrayType>(arrayType)) 1599 arrayDepth++; 1600 type = arrayType->getElementType(); 1601 } 1602 1603 if (arrayDepth) { 1604 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0); 1605 1606 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero); 1607 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin"); 1608 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend"); 1609 } 1610 1611 // Destroy the array. We don't ever need an EH cleanup because we 1612 // assume that we're in an EH cleanup ourselves, so a throwing 1613 // destructor causes an immediate terminate. 1614 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer, 1615 /*checkZeroLength*/ true, /*useEHCleanup*/ false); 1616 } 1617 1618 namespace { 1619 /// RegularPartialArrayDestroy - a cleanup which performs a partial 1620 /// array destroy where the end pointer is regularly determined and 1621 /// does not need to be loaded from a local. 1622 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup { 1623 llvm::Value *ArrayBegin; 1624 llvm::Value *ArrayEnd; 1625 QualType ElementType; 1626 CodeGenFunction::Destroyer *Destroyer; 1627 CharUnits ElementAlign; 1628 public: 1629 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd, 1630 QualType elementType, CharUnits elementAlign, 1631 CodeGenFunction::Destroyer *destroyer) 1632 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd), 1633 ElementType(elementType), Destroyer(destroyer), 1634 ElementAlign(elementAlign) {} 1635 1636 void Emit(CodeGenFunction &CGF, Flags flags) override { 1637 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd, 1638 ElementType, ElementAlign, Destroyer); 1639 } 1640 }; 1641 1642 /// IrregularPartialArrayDestroy - a cleanup which performs a 1643 /// partial array destroy where the end pointer is irregularly 1644 /// determined and must be loaded from a local. 1645 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup { 1646 llvm::Value *ArrayBegin; 1647 Address ArrayEndPointer; 1648 QualType ElementType; 1649 CodeGenFunction::Destroyer *Destroyer; 1650 CharUnits ElementAlign; 1651 public: 1652 IrregularPartialArrayDestroy(llvm::Value *arrayBegin, 1653 Address arrayEndPointer, 1654 QualType elementType, 1655 CharUnits elementAlign, 1656 CodeGenFunction::Destroyer *destroyer) 1657 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer), 1658 ElementType(elementType), Destroyer(destroyer), 1659 ElementAlign(elementAlign) {} 1660 1661 void Emit(CodeGenFunction &CGF, Flags flags) override { 1662 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer); 1663 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd, 1664 ElementType, ElementAlign, Destroyer); 1665 } 1666 }; 1667 } // end anonymous namespace 1668 1669 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy 1670 /// already-constructed elements of the given array. The cleanup 1671 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock. 1672 /// 1673 /// \param elementType - the immediate element type of the array; 1674 /// possibly still an array type 1675 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 1676 Address arrayEndPointer, 1677 QualType elementType, 1678 CharUnits elementAlign, 1679 Destroyer *destroyer) { 1680 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup, 1681 arrayBegin, arrayEndPointer, 1682 elementType, elementAlign, 1683 destroyer); 1684 } 1685 1686 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy 1687 /// already-constructed elements of the given array. The cleanup 1688 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock. 1689 /// 1690 /// \param elementType - the immediate element type of the array; 1691 /// possibly still an array type 1692 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 1693 llvm::Value *arrayEnd, 1694 QualType elementType, 1695 CharUnits elementAlign, 1696 Destroyer *destroyer) { 1697 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup, 1698 arrayBegin, arrayEnd, 1699 elementType, elementAlign, 1700 destroyer); 1701 } 1702 1703 /// Lazily declare the @llvm.lifetime.start intrinsic. 1704 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() { 1705 if (LifetimeStartFn) return LifetimeStartFn; 1706 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(), 1707 llvm::Intrinsic::lifetime_start); 1708 return LifetimeStartFn; 1709 } 1710 1711 /// Lazily declare the @llvm.lifetime.end intrinsic. 1712 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() { 1713 if (LifetimeEndFn) return LifetimeEndFn; 1714 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(), 1715 llvm::Intrinsic::lifetime_end); 1716 return LifetimeEndFn; 1717 } 1718 1719 namespace { 1720 /// A cleanup to perform a release of an object at the end of a 1721 /// function. This is used to balance out the incoming +1 of a 1722 /// ns_consumed argument when we can't reasonably do that just by 1723 /// not doing the initial retain for a __block argument. 1724 struct ConsumeARCParameter final : EHScopeStack::Cleanup { 1725 ConsumeARCParameter(llvm::Value *param, 1726 ARCPreciseLifetime_t precise) 1727 : Param(param), Precise(precise) {} 1728 1729 llvm::Value *Param; 1730 ARCPreciseLifetime_t Precise; 1731 1732 void Emit(CodeGenFunction &CGF, Flags flags) override { 1733 CGF.EmitARCRelease(Param, Precise); 1734 } 1735 }; 1736 } // end anonymous namespace 1737 1738 /// Emit an alloca (or GlobalValue depending on target) 1739 /// for the specified parameter and set up LocalDeclMap. 1740 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg, 1741 unsigned ArgNo) { 1742 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl? 1743 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) && 1744 "Invalid argument to EmitParmDecl"); 1745 1746 Arg.getAnyValue()->setName(D.getName()); 1747 1748 QualType Ty = D.getType(); 1749 1750 // Use better IR generation for certain implicit parameters. 1751 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) { 1752 // The only implicit argument a block has is its literal. 1753 // We assume this is always passed directly. 1754 if (BlockInfo) { 1755 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue()); 1756 return; 1757 } 1758 1759 // Apply any prologue 'this' adjustments required by the ABI. Be careful to 1760 // handle the case where 'this' is passed indirectly as part of an inalloca 1761 // struct. 1762 if (const CXXMethodDecl *MD = 1763 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) { 1764 if (MD->isVirtual() && IPD == CXXABIThisDecl) { 1765 llvm::Value *This = Arg.isIndirect() 1766 ? Builder.CreateLoad(Arg.getIndirectAddress()) 1767 : Arg.getDirectValue(); 1768 This = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue( 1769 *this, CurGD, This); 1770 if (Arg.isIndirect()) 1771 Builder.CreateStore(This, Arg.getIndirectAddress()); 1772 else 1773 Arg = ParamValue::forDirect(This); 1774 } 1775 } 1776 } 1777 1778 Address DeclPtr = Address::invalid(); 1779 bool DoStore = false; 1780 bool IsScalar = hasScalarEvaluationKind(Ty); 1781 // If we already have a pointer to the argument, reuse the input pointer. 1782 if (Arg.isIndirect()) { 1783 DeclPtr = Arg.getIndirectAddress(); 1784 // If we have a prettier pointer type at this point, bitcast to that. 1785 unsigned AS = DeclPtr.getType()->getAddressSpace(); 1786 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS); 1787 if (DeclPtr.getType() != IRTy) 1788 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName()); 1789 1790 // Push a destructor cleanup for this parameter if the ABI requires it. 1791 // Don't push a cleanup in a thunk for a method that will also emit a 1792 // cleanup. 1793 if (!IsScalar && !CurFuncIsThunk && 1794 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) { 1795 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 1796 if (RD && RD->hasNonTrivialDestructor()) 1797 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty); 1798 } 1799 } else { 1800 // Otherwise, create a temporary to hold the value. 1801 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D), 1802 D.getName() + ".addr"); 1803 DoStore = true; 1804 } 1805 1806 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr); 1807 1808 LValue lv = MakeAddrLValue(DeclPtr, Ty); 1809 if (IsScalar) { 1810 Qualifiers qs = Ty.getQualifiers(); 1811 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) { 1812 // We honor __attribute__((ns_consumed)) for types with lifetime. 1813 // For __strong, it's handled by just skipping the initial retain; 1814 // otherwise we have to balance out the initial +1 with an extra 1815 // cleanup to do the release at the end of the function. 1816 bool isConsumed = D.hasAttr<NSConsumedAttr>(); 1817 1818 // 'self' is always formally __strong, but if this is not an 1819 // init method then we don't want to retain it. 1820 if (D.isARCPseudoStrong()) { 1821 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl); 1822 assert(&D == method->getSelfDecl()); 1823 assert(lt == Qualifiers::OCL_Strong); 1824 assert(qs.hasConst()); 1825 assert(method->getMethodFamily() != OMF_init); 1826 (void) method; 1827 lt = Qualifiers::OCL_ExplicitNone; 1828 } 1829 1830 if (lt == Qualifiers::OCL_Strong) { 1831 if (!isConsumed) { 1832 if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 1833 // use objc_storeStrong(&dest, value) for retaining the 1834 // object. But first, store a null into 'dest' because 1835 // objc_storeStrong attempts to release its old value. 1836 llvm::Value *Null = CGM.EmitNullConstant(D.getType()); 1837 EmitStoreOfScalar(Null, lv, /* isInitialization */ true); 1838 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true); 1839 DoStore = false; 1840 } 1841 else 1842 // Don't use objc_retainBlock for block pointers, because we 1843 // don't want to Block_copy something just because we got it 1844 // as a parameter. 1845 ArgVal = EmitARCRetainNonBlock(ArgVal); 1846 } 1847 } else { 1848 // Push the cleanup for a consumed parameter. 1849 if (isConsumed) { 1850 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>() 1851 ? ARCPreciseLifetime : ARCImpreciseLifetime); 1852 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal, 1853 precise); 1854 } 1855 1856 if (lt == Qualifiers::OCL_Weak) { 1857 EmitARCInitWeak(DeclPtr, ArgVal); 1858 DoStore = false; // The weak init is a store, no need to do two. 1859 } 1860 } 1861 1862 // Enter the cleanup scope. 1863 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt); 1864 } 1865 } 1866 1867 // Store the initial value into the alloca. 1868 if (DoStore) 1869 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true); 1870 1871 setAddrOfLocalVar(&D, DeclPtr); 1872 1873 // Emit debug info for param declaration. 1874 if (CGDebugInfo *DI = getDebugInfo()) { 1875 if (CGM.getCodeGenOpts().getDebugInfo() >= 1876 codegenoptions::LimitedDebugInfo) { 1877 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder); 1878 } 1879 } 1880 1881 if (D.hasAttr<AnnotateAttr>()) 1882 EmitVarAnnotations(&D, DeclPtr.getPointer()); 1883 } 1884 1885 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, 1886 CodeGenFunction *CGF) { 1887 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed())) 1888 return; 1889 getOpenMPRuntime().emitUserDefinedReduction(CGF, D); 1890 } 1891