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