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