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