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