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