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