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