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