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