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