1 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This contains code to emit Decl nodes as LLVM code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CGBlocks.h" 14 #include "CGCXXABI.h" 15 #include "CGCleanup.h" 16 #include "CGDebugInfo.h" 17 #include "CGOpenCLRuntime.h" 18 #include "CGOpenMPRuntime.h" 19 #include "CodeGenFunction.h" 20 #include "CodeGenModule.h" 21 #include "ConstantEmitter.h" 22 #include "PatternInit.h" 23 #include "TargetInfo.h" 24 #include "clang/AST/ASTContext.h" 25 #include "clang/AST/Attr.h" 26 #include "clang/AST/CharUnits.h" 27 #include "clang/AST/Decl.h" 28 #include "clang/AST/DeclObjC.h" 29 #include "clang/AST/DeclOpenMP.h" 30 #include "clang/Basic/CodeGenOptions.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/CodeGen/CGFunctionInfo.h" 34 #include "clang/Sema/Sema.h" 35 #include "llvm/Analysis/ValueTracking.h" 36 #include "llvm/IR/DataLayout.h" 37 #include "llvm/IR/GlobalVariable.h" 38 #include "llvm/IR/Intrinsics.h" 39 #include "llvm/IR/Type.h" 40 41 using namespace clang; 42 using namespace CodeGen; 43 44 static_assert(clang::Sema::MaximumAlignment <= llvm::Value::MaximumAlignment, 45 "Clang max alignment greater than what LLVM supports?"); 46 47 void CodeGenFunction::EmitDecl(const Decl &D) { 48 switch (D.getKind()) { 49 case Decl::BuiltinTemplate: 50 case Decl::TranslationUnit: 51 case Decl::ExternCContext: 52 case Decl::Namespace: 53 case Decl::UnresolvedUsingTypename: 54 case Decl::ClassTemplateSpecialization: 55 case Decl::ClassTemplatePartialSpecialization: 56 case Decl::VarTemplateSpecialization: 57 case Decl::VarTemplatePartialSpecialization: 58 case Decl::TemplateTypeParm: 59 case Decl::UnresolvedUsingValue: 60 case Decl::NonTypeTemplateParm: 61 case Decl::CXXDeductionGuide: 62 case Decl::CXXMethod: 63 case Decl::CXXConstructor: 64 case Decl::CXXDestructor: 65 case Decl::CXXConversion: 66 case Decl::Field: 67 case Decl::MSProperty: 68 case Decl::IndirectField: 69 case Decl::ObjCIvar: 70 case Decl::ObjCAtDefsField: 71 case Decl::ParmVar: 72 case Decl::ImplicitParam: 73 case Decl::ClassTemplate: 74 case Decl::VarTemplate: 75 case Decl::FunctionTemplate: 76 case Decl::TypeAliasTemplate: 77 case Decl::TemplateTemplateParm: 78 case Decl::ObjCMethod: 79 case Decl::ObjCCategory: 80 case Decl::ObjCProtocol: 81 case Decl::ObjCInterface: 82 case Decl::ObjCCategoryImpl: 83 case Decl::ObjCImplementation: 84 case Decl::ObjCProperty: 85 case Decl::ObjCCompatibleAlias: 86 case Decl::PragmaComment: 87 case Decl::PragmaDetectMismatch: 88 case Decl::AccessSpec: 89 case Decl::LinkageSpec: 90 case Decl::Export: 91 case Decl::ObjCPropertyImpl: 92 case Decl::FileScopeAsm: 93 case Decl::Friend: 94 case Decl::FriendTemplate: 95 case Decl::Block: 96 case Decl::Captured: 97 case Decl::ClassScopeFunctionSpecialization: 98 case Decl::UsingShadow: 99 case Decl::ConstructorUsingShadow: 100 case Decl::ObjCTypeParam: 101 case Decl::Binding: 102 llvm_unreachable("Declaration should not be in declstmts!"); 103 case Decl::Record: // struct/union/class X; 104 case Decl::CXXRecord: // struct/union/class X; [C++] 105 if (CGDebugInfo *DI = getDebugInfo()) 106 if (cast<RecordDecl>(D).getDefinition()) 107 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(&D))); 108 return; 109 case Decl::Enum: // enum X; 110 if (CGDebugInfo *DI = getDebugInfo()) 111 if (cast<EnumDecl>(D).getDefinition()) 112 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(&D))); 113 return; 114 case Decl::Function: // void X(); 115 case Decl::EnumConstant: // enum ? { X = ? } 116 case Decl::StaticAssert: // static_assert(X, ""); [C++0x] 117 case Decl::Label: // __label__ x; 118 case Decl::Import: 119 case Decl::MSGuid: // __declspec(uuid("...")) 120 case Decl::TemplateParamObject: 121 case Decl::OMPThreadPrivate: 122 case Decl::OMPAllocate: 123 case Decl::OMPCapturedExpr: 124 case Decl::OMPRequires: 125 case Decl::Empty: 126 case Decl::Concept: 127 case Decl::LifetimeExtendedTemporary: 128 case Decl::RequiresExprBody: 129 // None of these decls require codegen support. 130 return; 131 132 case Decl::NamespaceAlias: 133 if (CGDebugInfo *DI = getDebugInfo()) 134 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D)); 135 return; 136 case Decl::Using: // using X; [C++] 137 if (CGDebugInfo *DI = getDebugInfo()) 138 DI->EmitUsingDecl(cast<UsingDecl>(D)); 139 return; 140 case Decl::UsingPack: 141 for (auto *Using : cast<UsingPackDecl>(D).expansions()) 142 EmitDecl(*Using); 143 return; 144 case Decl::UsingDirective: // using namespace X; [C++] 145 if (CGDebugInfo *DI = getDebugInfo()) 146 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D)); 147 return; 148 case Decl::Var: 149 case Decl::Decomposition: { 150 const VarDecl &VD = cast<VarDecl>(D); 151 assert(VD.isLocalVarDecl() && 152 "Should not see file-scope variables inside a function!"); 153 EmitVarDecl(VD); 154 if (auto *DD = dyn_cast<DecompositionDecl>(&VD)) 155 for (auto *B : DD->bindings()) 156 if (auto *HD = B->getHoldingVar()) 157 EmitVarDecl(*HD); 158 return; 159 } 160 161 case Decl::OMPDeclareReduction: 162 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this); 163 164 case Decl::OMPDeclareMapper: 165 return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this); 166 167 case Decl::Typedef: // typedef int X; 168 case Decl::TypeAlias: { // using X = int; [C++0x] 169 QualType Ty = cast<TypedefNameDecl>(D).getUnderlyingType(); 170 if (CGDebugInfo *DI = getDebugInfo()) 171 DI->EmitAndRetainType(Ty); 172 if (Ty->isVariablyModifiedType()) 173 EmitVariablyModifiedType(Ty); 174 return; 175 } 176 } 177 } 178 179 /// EmitVarDecl - This method handles emission of any variable declaration 180 /// inside a function, including static vars etc. 181 void CodeGenFunction::EmitVarDecl(const VarDecl &D) { 182 if (D.hasExternalStorage()) 183 // Don't emit it now, allow it to be emitted lazily on its first use. 184 return; 185 186 // Some function-scope variable does not have static storage but still 187 // needs to be emitted like a static variable, e.g. a function-scope 188 // variable in constant address space in OpenCL. 189 if (D.getStorageDuration() != SD_Automatic) { 190 // Static sampler variables translated to function calls. 191 if (D.getType()->isSamplerT()) 192 return; 193 194 llvm::GlobalValue::LinkageTypes Linkage = 195 CGM.getLLVMLinkageVarDefinition(&D, /*IsConstant=*/false); 196 197 // FIXME: We need to force the emission/use of a guard variable for 198 // some variables even if we can constant-evaluate them because 199 // we can't guarantee every translation unit will constant-evaluate them. 200 201 return EmitStaticVarDecl(D, Linkage); 202 } 203 204 if (D.getType().getAddressSpace() == LangAS::opencl_local) 205 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D); 206 207 assert(D.hasLocalStorage()); 208 return EmitAutoVarDecl(D); 209 } 210 211 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) { 212 if (CGM.getLangOpts().CPlusPlus) 213 return CGM.getMangledName(&D).str(); 214 215 // If this isn't C++, we don't need a mangled name, just a pretty one. 216 assert(!D.isExternallyVisible() && "name shouldn't matter"); 217 std::string ContextName; 218 const DeclContext *DC = D.getDeclContext(); 219 if (auto *CD = dyn_cast<CapturedDecl>(DC)) 220 DC = cast<DeclContext>(CD->getNonClosureContext()); 221 if (const auto *FD = dyn_cast<FunctionDecl>(DC)) 222 ContextName = std::string(CGM.getMangledName(FD)); 223 else if (const auto *BD = dyn_cast<BlockDecl>(DC)) 224 ContextName = std::string(CGM.getBlockMangledName(GlobalDecl(), BD)); 225 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC)) 226 ContextName = OMD->getSelector().getAsString(); 227 else 228 llvm_unreachable("Unknown context for static var decl"); 229 230 ContextName += "." + D.getNameAsString(); 231 return ContextName; 232 } 233 234 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl( 235 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) { 236 // In general, we don't always emit static var decls once before we reference 237 // them. It is possible to reference them before emitting the function that 238 // contains them, and it is possible to emit the containing function multiple 239 // times. 240 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D]) 241 return ExistingGV; 242 243 QualType Ty = D.getType(); 244 assert(Ty->isConstantSizeType() && "VLAs can't be static"); 245 246 // Use the label if the variable is renamed with the asm-label extension. 247 std::string Name; 248 if (D.hasAttr<AsmLabelAttr>()) 249 Name = std::string(getMangledName(&D)); 250 else 251 Name = getStaticDeclName(*this, D); 252 253 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty); 254 LangAS AS = GetGlobalVarAddressSpace(&D); 255 unsigned TargetAS = getContext().getTargetAddressSpace(AS); 256 257 // OpenCL variables in local address space and CUDA shared 258 // variables cannot have an initializer. 259 llvm::Constant *Init = nullptr; 260 if (Ty.getAddressSpace() == LangAS::opencl_local || 261 D.hasAttr<CUDASharedAttr>() || D.hasAttr<LoaderUninitializedAttr>()) 262 Init = llvm::UndefValue::get(LTy); 263 else 264 Init = EmitNullConstant(Ty); 265 266 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 267 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name, 268 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 269 GV->setAlignment(getContext().getDeclAlign(&D).getAsAlign()); 270 271 if (supportsCOMDAT() && GV->isWeakForLinker()) 272 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 273 274 if (D.getTLSKind()) 275 setTLSMode(GV, D); 276 277 setGVProperties(GV, &D); 278 279 // Make sure the result is of the correct type. 280 LangAS ExpectedAS = Ty.getAddressSpace(); 281 llvm::Constant *Addr = GV; 282 if (AS != ExpectedAS) { 283 Addr = getTargetCodeGenInfo().performAddrSpaceCast( 284 *this, GV, AS, ExpectedAS, 285 LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS))); 286 } 287 288 setStaticLocalDeclAddress(&D, Addr); 289 290 // Ensure that the static local gets initialized by making sure the parent 291 // function gets emitted eventually. 292 const Decl *DC = cast<Decl>(D.getDeclContext()); 293 294 // We can't name blocks or captured statements directly, so try to emit their 295 // parents. 296 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) { 297 DC = DC->getNonClosureContext(); 298 // FIXME: Ensure that global blocks get emitted. 299 if (!DC) 300 return Addr; 301 } 302 303 GlobalDecl GD; 304 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC)) 305 GD = GlobalDecl(CD, Ctor_Base); 306 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC)) 307 GD = GlobalDecl(DD, Dtor_Base); 308 else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) 309 GD = GlobalDecl(FD); 310 else { 311 // Don't do anything for Obj-C method decls or global closures. We should 312 // never defer them. 313 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl"); 314 } 315 if (GD.getDecl()) { 316 // Disable emission of the parent function for the OpenMP device codegen. 317 CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this); 318 (void)GetAddrOfGlobal(GD); 319 } 320 321 return Addr; 322 } 323 324 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 325 /// global variable that has already been created for it. If the initializer 326 /// has a different type than GV does, this may free GV and return a different 327 /// one. Otherwise it just returns GV. 328 llvm::GlobalVariable * 329 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D, 330 llvm::GlobalVariable *GV) { 331 ConstantEmitter emitter(*this); 332 llvm::Constant *Init = emitter.tryEmitForInitializer(D); 333 334 // If constant emission failed, then this should be a C++ static 335 // initializer. 336 if (!Init) { 337 if (!getLangOpts().CPlusPlus) 338 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression"); 339 else if (HaveInsertPoint()) { 340 // Since we have a static initializer, this global variable can't 341 // be constant. 342 GV->setConstant(false); 343 344 EmitCXXGuardedInit(D, GV, /*PerformInit*/true); 345 } 346 return GV; 347 } 348 349 // The initializer may differ in type from the global. Rewrite 350 // the global to match the initializer. (We have to do this 351 // because some types, like unions, can't be completely represented 352 // in the LLVM type system.) 353 if (GV->getValueType() != Init->getType()) { 354 llvm::GlobalVariable *OldGV = GV; 355 356 GV = new llvm::GlobalVariable( 357 CGM.getModule(), Init->getType(), OldGV->isConstant(), 358 OldGV->getLinkage(), Init, "", 359 /*InsertBefore*/ OldGV, OldGV->getThreadLocalMode(), 360 OldGV->getType()->getPointerAddressSpace()); 361 GV->setVisibility(OldGV->getVisibility()); 362 GV->setDSOLocal(OldGV->isDSOLocal()); 363 GV->setComdat(OldGV->getComdat()); 364 365 // Steal the name of the old global 366 GV->takeName(OldGV); 367 368 // Replace all uses of the old global with the new global 369 llvm::Constant *NewPtrForOldDecl = 370 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 371 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 372 373 // Erase the old global, since it is no longer used. 374 OldGV->eraseFromParent(); 375 } 376 377 GV->setConstant(CGM.isTypeConstant(D.getType(), true)); 378 GV->setInitializer(Init); 379 380 emitter.finalize(GV); 381 382 if (D.needsDestruction(getContext()) == QualType::DK_cxx_destructor && 383 HaveInsertPoint()) { 384 // We have a constant initializer, but a nontrivial destructor. We still 385 // need to perform a guarded "initialization" in order to register the 386 // destructor. 387 EmitCXXGuardedInit(D, GV, /*PerformInit*/false); 388 } 389 390 return GV; 391 } 392 393 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D, 394 llvm::GlobalValue::LinkageTypes Linkage) { 395 // Check to see if we already have a global variable for this 396 // declaration. This can happen when double-emitting function 397 // bodies, e.g. with complete and base constructors. 398 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage); 399 CharUnits alignment = getContext().getDeclAlign(&D); 400 401 // Store into LocalDeclMap before generating initializer to handle 402 // circular references. 403 setAddrOfLocalVar(&D, Address(addr, alignment)); 404 405 // We can't have a VLA here, but we can have a pointer to a VLA, 406 // even though that doesn't really make any sense. 407 // Make sure to evaluate VLA bounds now so that we have them for later. 408 if (D.getType()->isVariablyModifiedType()) 409 EmitVariablyModifiedType(D.getType()); 410 411 // Save the type in case adding the initializer forces a type change. 412 llvm::Type *expectedType = addr->getType(); 413 414 llvm::GlobalVariable *var = 415 cast<llvm::GlobalVariable>(addr->stripPointerCasts()); 416 417 // CUDA's local and local static __shared__ variables should not 418 // have any non-empty initializers. This is ensured by Sema. 419 // Whatever initializer such variable may have when it gets here is 420 // a no-op and should not be emitted. 421 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 422 D.hasAttr<CUDASharedAttr>(); 423 // If this value has an initializer, emit it. 424 if (D.getInit() && !isCudaSharedVar) 425 var = AddInitializerToStaticVarDecl(D, var); 426 427 var->setAlignment(alignment.getAsAlign()); 428 429 if (D.hasAttr<AnnotateAttr>()) 430 CGM.AddGlobalAnnotations(&D, var); 431 432 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>()) 433 var->addAttribute("bss-section", SA->getName()); 434 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>()) 435 var->addAttribute("data-section", SA->getName()); 436 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>()) 437 var->addAttribute("rodata-section", SA->getName()); 438 if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>()) 439 var->addAttribute("relro-section", SA->getName()); 440 441 if (const SectionAttr *SA = D.getAttr<SectionAttr>()) 442 var->setSection(SA->getName()); 443 444 if (D.hasAttr<RetainAttr>()) 445 CGM.addUsedGlobal(var); 446 else if (D.hasAttr<UsedAttr>()) 447 CGM.addUsedOrCompilerUsedGlobal(var); 448 449 // We may have to cast the constant because of the initializer 450 // mismatch above. 451 // 452 // FIXME: It is really dangerous to store this in the map; if anyone 453 // RAUW's the GV uses of this constant will be invalid. 454 llvm::Constant *castedAddr = 455 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType); 456 if (var != castedAddr) 457 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment); 458 CGM.setStaticLocalDeclAddress(&D, castedAddr); 459 460 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D); 461 462 // Emit global variable debug descriptor for static vars. 463 CGDebugInfo *DI = getDebugInfo(); 464 if (DI && CGM.getCodeGenOpts().hasReducedDebugInfo()) { 465 DI->setLocation(D.getLocation()); 466 DI->EmitGlobalVariable(var, &D); 467 } 468 } 469 470 namespace { 471 struct DestroyObject final : EHScopeStack::Cleanup { 472 DestroyObject(Address addr, QualType type, 473 CodeGenFunction::Destroyer *destroyer, 474 bool useEHCleanupForArray) 475 : addr(addr), type(type), destroyer(destroyer), 476 useEHCleanupForArray(useEHCleanupForArray) {} 477 478 Address addr; 479 QualType type; 480 CodeGenFunction::Destroyer *destroyer; 481 bool useEHCleanupForArray; 482 483 void Emit(CodeGenFunction &CGF, Flags flags) override { 484 // Don't use an EH cleanup recursively from an EH cleanup. 485 bool useEHCleanupForArray = 486 flags.isForNormalCleanup() && this->useEHCleanupForArray; 487 488 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray); 489 } 490 }; 491 492 template <class Derived> 493 struct DestroyNRVOVariable : EHScopeStack::Cleanup { 494 DestroyNRVOVariable(Address addr, QualType type, llvm::Value *NRVOFlag) 495 : NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {} 496 497 llvm::Value *NRVOFlag; 498 Address Loc; 499 QualType Ty; 500 501 void Emit(CodeGenFunction &CGF, Flags flags) override { 502 // Along the exceptions path we always execute the dtor. 503 bool NRVO = flags.isForNormalCleanup() && NRVOFlag; 504 505 llvm::BasicBlock *SkipDtorBB = nullptr; 506 if (NRVO) { 507 // If we exited via NRVO, we skip the destructor call. 508 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused"); 509 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor"); 510 llvm::Value *DidNRVO = 511 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val"); 512 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB); 513 CGF.EmitBlock(RunDtorBB); 514 } 515 516 static_cast<Derived *>(this)->emitDestructorCall(CGF); 517 518 if (NRVO) CGF.EmitBlock(SkipDtorBB); 519 } 520 521 virtual ~DestroyNRVOVariable() = default; 522 }; 523 524 struct DestroyNRVOVariableCXX final 525 : DestroyNRVOVariable<DestroyNRVOVariableCXX> { 526 DestroyNRVOVariableCXX(Address addr, QualType type, 527 const CXXDestructorDecl *Dtor, llvm::Value *NRVOFlag) 528 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, NRVOFlag), 529 Dtor(Dtor) {} 530 531 const CXXDestructorDecl *Dtor; 532 533 void emitDestructorCall(CodeGenFunction &CGF) { 534 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 535 /*ForVirtualBase=*/false, 536 /*Delegating=*/false, Loc, Ty); 537 } 538 }; 539 540 struct DestroyNRVOVariableC final 541 : DestroyNRVOVariable<DestroyNRVOVariableC> { 542 DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty) 543 : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, Ty, NRVOFlag) {} 544 545 void emitDestructorCall(CodeGenFunction &CGF) { 546 CGF.destroyNonTrivialCStruct(CGF, Loc, Ty); 547 } 548 }; 549 550 struct CallStackRestore final : EHScopeStack::Cleanup { 551 Address Stack; 552 CallStackRestore(Address Stack) : Stack(Stack) {} 553 bool isRedundantBeforeReturn() override { return true; } 554 void Emit(CodeGenFunction &CGF, Flags flags) override { 555 llvm::Value *V = CGF.Builder.CreateLoad(Stack); 556 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 557 CGF.Builder.CreateCall(F, V); 558 } 559 }; 560 561 struct ExtendGCLifetime final : EHScopeStack::Cleanup { 562 const VarDecl &Var; 563 ExtendGCLifetime(const VarDecl *var) : Var(*var) {} 564 565 void Emit(CodeGenFunction &CGF, Flags flags) override { 566 // Compute the address of the local variable, in case it's a 567 // byref or something. 568 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false, 569 Var.getType(), VK_LValue, SourceLocation()); 570 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE), 571 SourceLocation()); 572 CGF.EmitExtendGCLifetime(value); 573 } 574 }; 575 576 struct CallCleanupFunction final : EHScopeStack::Cleanup { 577 llvm::Constant *CleanupFn; 578 const CGFunctionInfo &FnInfo; 579 const VarDecl &Var; 580 581 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info, 582 const VarDecl *Var) 583 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {} 584 585 void Emit(CodeGenFunction &CGF, Flags flags) override { 586 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false, 587 Var.getType(), VK_LValue, SourceLocation()); 588 // Compute the address of the local variable, in case it's a byref 589 // or something. 590 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(CGF); 591 592 // In some cases, the type of the function argument will be different from 593 // the type of the pointer. An example of this is 594 // void f(void* arg); 595 // __attribute__((cleanup(f))) void *g; 596 // 597 // To fix this we insert a bitcast here. 598 QualType ArgTy = FnInfo.arg_begin()->type; 599 llvm::Value *Arg = 600 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy)); 601 602 CallArgList Args; 603 Args.add(RValue::get(Arg), 604 CGF.getContext().getPointerType(Var.getType())); 605 auto Callee = CGCallee::forDirect(CleanupFn); 606 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args); 607 } 608 }; 609 } // end anonymous namespace 610 611 /// EmitAutoVarWithLifetime - Does the setup required for an automatic 612 /// variable with lifetime. 613 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var, 614 Address addr, 615 Qualifiers::ObjCLifetime lifetime) { 616 switch (lifetime) { 617 case Qualifiers::OCL_None: 618 llvm_unreachable("present but none"); 619 620 case Qualifiers::OCL_ExplicitNone: 621 // nothing to do 622 break; 623 624 case Qualifiers::OCL_Strong: { 625 CodeGenFunction::Destroyer *destroyer = 626 (var.hasAttr<ObjCPreciseLifetimeAttr>() 627 ? CodeGenFunction::destroyARCStrongPrecise 628 : CodeGenFunction::destroyARCStrongImprecise); 629 630 CleanupKind cleanupKind = CGF.getARCCleanupKind(); 631 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer, 632 cleanupKind & EHCleanup); 633 break; 634 } 635 case Qualifiers::OCL_Autoreleasing: 636 // nothing to do 637 break; 638 639 case Qualifiers::OCL_Weak: 640 // __weak objects always get EH cleanups; otherwise, exceptions 641 // could cause really nasty crashes instead of mere leaks. 642 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(), 643 CodeGenFunction::destroyARCWeak, 644 /*useEHCleanup*/ true); 645 break; 646 } 647 } 648 649 static bool isAccessedBy(const VarDecl &var, const Stmt *s) { 650 if (const Expr *e = dyn_cast<Expr>(s)) { 651 // Skip the most common kinds of expressions that make 652 // hierarchy-walking expensive. 653 s = e = e->IgnoreParenCasts(); 654 655 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) 656 return (ref->getDecl() == &var); 657 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) { 658 const BlockDecl *block = be->getBlockDecl(); 659 for (const auto &I : block->captures()) { 660 if (I.getVariable() == &var) 661 return true; 662 } 663 } 664 } 665 666 for (const Stmt *SubStmt : s->children()) 667 // SubStmt might be null; as in missing decl or conditional of an if-stmt. 668 if (SubStmt && isAccessedBy(var, SubStmt)) 669 return true; 670 671 return false; 672 } 673 674 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) { 675 if (!decl) return false; 676 if (!isa<VarDecl>(decl)) return false; 677 const VarDecl *var = cast<VarDecl>(decl); 678 return isAccessedBy(*var, e); 679 } 680 681 static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF, 682 const LValue &destLV, const Expr *init) { 683 bool needsCast = false; 684 685 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) { 686 switch (castExpr->getCastKind()) { 687 // Look through casts that don't require representation changes. 688 case CK_NoOp: 689 case CK_BitCast: 690 case CK_BlockPointerToObjCPointerCast: 691 needsCast = true; 692 break; 693 694 // If we find an l-value to r-value cast from a __weak variable, 695 // emit this operation as a copy or move. 696 case CK_LValueToRValue: { 697 const Expr *srcExpr = castExpr->getSubExpr(); 698 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak) 699 return false; 700 701 // Emit the source l-value. 702 LValue srcLV = CGF.EmitLValue(srcExpr); 703 704 // Handle a formal type change to avoid asserting. 705 auto srcAddr = srcLV.getAddress(CGF); 706 if (needsCast) { 707 srcAddr = CGF.Builder.CreateElementBitCast( 708 srcAddr, destLV.getAddress(CGF).getElementType()); 709 } 710 711 // If it was an l-value, use objc_copyWeak. 712 if (srcExpr->getValueKind() == VK_LValue) { 713 CGF.EmitARCCopyWeak(destLV.getAddress(CGF), srcAddr); 714 } else { 715 assert(srcExpr->getValueKind() == VK_XValue); 716 CGF.EmitARCMoveWeak(destLV.getAddress(CGF), srcAddr); 717 } 718 return true; 719 } 720 721 // Stop at anything else. 722 default: 723 return false; 724 } 725 726 init = castExpr->getSubExpr(); 727 } 728 return false; 729 } 730 731 static void drillIntoBlockVariable(CodeGenFunction &CGF, 732 LValue &lvalue, 733 const VarDecl *var) { 734 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(CGF), var)); 735 } 736 737 void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, 738 SourceLocation Loc) { 739 if (!SanOpts.has(SanitizerKind::NullabilityAssign)) 740 return; 741 742 auto Nullability = LHS.getType()->getNullability(getContext()); 743 if (!Nullability || *Nullability != NullabilityKind::NonNull) 744 return; 745 746 // Check if the right hand side of the assignment is nonnull, if the left 747 // hand side must be nonnull. 748 SanitizerScope SanScope(this); 749 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS); 750 llvm::Constant *StaticData[] = { 751 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()), 752 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused. 753 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)}; 754 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}}, 755 SanitizerHandler::TypeMismatch, StaticData, RHS); 756 } 757 758 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D, 759 LValue lvalue, bool capturedByInit) { 760 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime(); 761 if (!lifetime) { 762 llvm::Value *value = EmitScalarExpr(init); 763 if (capturedByInit) 764 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 765 EmitNullabilityCheck(lvalue, value, init->getExprLoc()); 766 EmitStoreThroughLValue(RValue::get(value), lvalue, true); 767 return; 768 } 769 770 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init)) 771 init = DIE->getExpr(); 772 773 // If we're emitting a value with lifetime, we have to do the 774 // initialization *before* we leave the cleanup scopes. 775 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(init)) 776 init = EWC->getSubExpr(); 777 CodeGenFunction::RunCleanupsScope Scope(*this); 778 779 // We have to maintain the illusion that the variable is 780 // zero-initialized. If the variable might be accessed in its 781 // initializer, zero-initialize before running the initializer, then 782 // actually perform the initialization with an assign. 783 bool accessedByInit = false; 784 if (lifetime != Qualifiers::OCL_ExplicitNone) 785 accessedByInit = (capturedByInit || isAccessedBy(D, init)); 786 if (accessedByInit) { 787 LValue tempLV = lvalue; 788 // Drill down to the __block object if necessary. 789 if (capturedByInit) { 790 // We can use a simple GEP for this because it can't have been 791 // moved yet. 792 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(*this), 793 cast<VarDecl>(D), 794 /*follow*/ false)); 795 } 796 797 auto ty = 798 cast<llvm::PointerType>(tempLV.getAddress(*this).getElementType()); 799 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType()); 800 801 // If __weak, we want to use a barrier under certain conditions. 802 if (lifetime == Qualifiers::OCL_Weak) 803 EmitARCInitWeak(tempLV.getAddress(*this), zero); 804 805 // Otherwise just do a simple store. 806 else 807 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true); 808 } 809 810 // Emit the initializer. 811 llvm::Value *value = nullptr; 812 813 switch (lifetime) { 814 case Qualifiers::OCL_None: 815 llvm_unreachable("present but none"); 816 817 case Qualifiers::OCL_Strong: { 818 if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) { 819 value = EmitARCRetainScalarExpr(init); 820 break; 821 } 822 // If D is pseudo-strong, treat it like __unsafe_unretained here. This means 823 // that we omit the retain, and causes non-autoreleased return values to be 824 // immediately released. 825 LLVM_FALLTHROUGH; 826 } 827 828 case Qualifiers::OCL_ExplicitNone: 829 value = EmitARCUnsafeUnretainedScalarExpr(init); 830 break; 831 832 case Qualifiers::OCL_Weak: { 833 // If it's not accessed by the initializer, try to emit the 834 // initialization with a copy or move. 835 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) { 836 return; 837 } 838 839 // No way to optimize a producing initializer into this. It's not 840 // worth optimizing for, because the value will immediately 841 // disappear in the common case. 842 value = EmitScalarExpr(init); 843 844 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 845 if (accessedByInit) 846 EmitARCStoreWeak(lvalue.getAddress(*this), value, /*ignored*/ true); 847 else 848 EmitARCInitWeak(lvalue.getAddress(*this), value); 849 return; 850 } 851 852 case Qualifiers::OCL_Autoreleasing: 853 value = EmitARCRetainAutoreleaseScalarExpr(init); 854 break; 855 } 856 857 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 858 859 EmitNullabilityCheck(lvalue, value, init->getExprLoc()); 860 861 // If the variable might have been accessed by its initializer, we 862 // might have to initialize with a barrier. We have to do this for 863 // both __weak and __strong, but __weak got filtered out above. 864 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) { 865 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc()); 866 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true); 867 EmitARCRelease(oldValue, ARCImpreciseLifetime); 868 return; 869 } 870 871 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true); 872 } 873 874 /// Decide whether we can emit the non-zero parts of the specified initializer 875 /// with equal or fewer than NumStores scalar stores. 876 static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init, 877 unsigned &NumStores) { 878 // Zero and Undef never requires any extra stores. 879 if (isa<llvm::ConstantAggregateZero>(Init) || 880 isa<llvm::ConstantPointerNull>(Init) || 881 isa<llvm::UndefValue>(Init)) 882 return true; 883 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) || 884 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) || 885 isa<llvm::ConstantExpr>(Init)) 886 return Init->isNullValue() || NumStores--; 887 888 // See if we can emit each element. 889 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) { 890 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 891 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i)); 892 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores)) 893 return false; 894 } 895 return true; 896 } 897 898 if (llvm::ConstantDataSequential *CDS = 899 dyn_cast<llvm::ConstantDataSequential>(Init)) { 900 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 901 llvm::Constant *Elt = CDS->getElementAsConstant(i); 902 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores)) 903 return false; 904 } 905 return true; 906 } 907 908 // Anything else is hard and scary. 909 return false; 910 } 911 912 /// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit 913 /// the scalar stores that would be required. 914 static void emitStoresForInitAfterBZero(CodeGenModule &CGM, 915 llvm::Constant *Init, Address Loc, 916 bool isVolatile, CGBuilderTy &Builder, 917 bool IsAutoInit) { 918 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) && 919 "called emitStoresForInitAfterBZero for zero or undef value."); 920 921 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) || 922 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) || 923 isa<llvm::ConstantExpr>(Init)) { 924 auto *I = Builder.CreateStore(Init, Loc, isVolatile); 925 if (IsAutoInit) 926 I->addAnnotationMetadata("auto-init"); 927 return; 928 } 929 930 if (llvm::ConstantDataSequential *CDS = 931 dyn_cast<llvm::ConstantDataSequential>(Init)) { 932 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 933 llvm::Constant *Elt = CDS->getElementAsConstant(i); 934 935 // If necessary, get a pointer to the element and emit it. 936 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt)) 937 emitStoresForInitAfterBZero( 938 CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile, 939 Builder, IsAutoInit); 940 } 941 return; 942 } 943 944 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) && 945 "Unknown value type!"); 946 947 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 948 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i)); 949 950 // If necessary, get a pointer to the element and emit it. 951 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt)) 952 emitStoresForInitAfterBZero(CGM, Elt, 953 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), 954 isVolatile, Builder, IsAutoInit); 955 } 956 } 957 958 /// Decide whether we should use bzero plus some stores to initialize a local 959 /// variable instead of using a memcpy from a constant global. It is beneficial 960 /// to use bzero if the global is all zeros, or mostly zeros and large. 961 static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init, 962 uint64_t GlobalSize) { 963 // If a global is all zeros, always use a bzero. 964 if (isa<llvm::ConstantAggregateZero>(Init)) return true; 965 966 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large, 967 // do it if it will require 6 or fewer scalar stores. 968 // TODO: Should budget depends on the size? Avoiding a large global warrants 969 // plopping in more stores. 970 unsigned StoreBudget = 6; 971 uint64_t SizeLimit = 32; 972 973 return GlobalSize > SizeLimit && 974 canEmitInitWithFewStoresAfterBZero(Init, StoreBudget); 975 } 976 977 /// Decide whether we should use memset to initialize a local variable instead 978 /// of using a memcpy from a constant global. Assumes we've already decided to 979 /// not user bzero. 980 /// FIXME We could be more clever, as we are for bzero above, and generate 981 /// memset followed by stores. It's unclear that's worth the effort. 982 static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init, 983 uint64_t GlobalSize, 984 const llvm::DataLayout &DL) { 985 uint64_t SizeLimit = 32; 986 if (GlobalSize <= SizeLimit) 987 return nullptr; 988 return llvm::isBytewiseValue(Init, DL); 989 } 990 991 /// Decide whether we want to split a constant structure or array store into a 992 /// sequence of its fields' stores. This may cost us code size and compilation 993 /// speed, but plays better with store optimizations. 994 static bool shouldSplitConstantStore(CodeGenModule &CGM, 995 uint64_t GlobalByteSize) { 996 // Don't break things that occupy more than one cacheline. 997 uint64_t ByteSizeLimit = 64; 998 if (CGM.getCodeGenOpts().OptimizationLevel == 0) 999 return false; 1000 if (GlobalByteSize <= ByteSizeLimit) 1001 return true; 1002 return false; 1003 } 1004 1005 enum class IsPattern { No, Yes }; 1006 1007 /// Generate a constant filled with either a pattern or zeroes. 1008 static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern, 1009 llvm::Type *Ty) { 1010 if (isPattern == IsPattern::Yes) 1011 return initializationPatternFor(CGM, Ty); 1012 else 1013 return llvm::Constant::getNullValue(Ty); 1014 } 1015 1016 static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern, 1017 llvm::Constant *constant); 1018 1019 /// Helper function for constWithPadding() to deal with padding in structures. 1020 static llvm::Constant *constStructWithPadding(CodeGenModule &CGM, 1021 IsPattern isPattern, 1022 llvm::StructType *STy, 1023 llvm::Constant *constant) { 1024 const llvm::DataLayout &DL = CGM.getDataLayout(); 1025 const llvm::StructLayout *Layout = DL.getStructLayout(STy); 1026 llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext()); 1027 unsigned SizeSoFar = 0; 1028 SmallVector<llvm::Constant *, 8> Values; 1029 bool NestedIntact = true; 1030 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) { 1031 unsigned CurOff = Layout->getElementOffset(i); 1032 if (SizeSoFar < CurOff) { 1033 assert(!STy->isPacked()); 1034 auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar); 1035 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy)); 1036 } 1037 llvm::Constant *CurOp; 1038 if (constant->isZeroValue()) 1039 CurOp = llvm::Constant::getNullValue(STy->getElementType(i)); 1040 else 1041 CurOp = cast<llvm::Constant>(constant->getAggregateElement(i)); 1042 auto *NewOp = constWithPadding(CGM, isPattern, CurOp); 1043 if (CurOp != NewOp) 1044 NestedIntact = false; 1045 Values.push_back(NewOp); 1046 SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType()); 1047 } 1048 unsigned TotalSize = Layout->getSizeInBytes(); 1049 if (SizeSoFar < TotalSize) { 1050 auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar); 1051 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy)); 1052 } 1053 if (NestedIntact && Values.size() == STy->getNumElements()) 1054 return constant; 1055 return llvm::ConstantStruct::getAnon(Values, STy->isPacked()); 1056 } 1057 1058 /// Replace all padding bytes in a given constant with either a pattern byte or 1059 /// 0x00. 1060 static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern, 1061 llvm::Constant *constant) { 1062 llvm::Type *OrigTy = constant->getType(); 1063 if (const auto STy = dyn_cast<llvm::StructType>(OrigTy)) 1064 return constStructWithPadding(CGM, isPattern, STy, constant); 1065 if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(OrigTy)) { 1066 llvm::SmallVector<llvm::Constant *, 8> Values; 1067 uint64_t Size = ArrayTy->getNumElements(); 1068 if (!Size) 1069 return constant; 1070 llvm::Type *ElemTy = ArrayTy->getElementType(); 1071 bool ZeroInitializer = constant->isNullValue(); 1072 llvm::Constant *OpValue, *PaddedOp; 1073 if (ZeroInitializer) { 1074 OpValue = llvm::Constant::getNullValue(ElemTy); 1075 PaddedOp = constWithPadding(CGM, isPattern, OpValue); 1076 } 1077 for (unsigned Op = 0; Op != Size; ++Op) { 1078 if (!ZeroInitializer) { 1079 OpValue = constant->getAggregateElement(Op); 1080 PaddedOp = constWithPadding(CGM, isPattern, OpValue); 1081 } 1082 Values.push_back(PaddedOp); 1083 } 1084 auto *NewElemTy = Values[0]->getType(); 1085 if (NewElemTy == ElemTy) 1086 return constant; 1087 auto *NewArrayTy = llvm::ArrayType::get(NewElemTy, Size); 1088 return llvm::ConstantArray::get(NewArrayTy, Values); 1089 } 1090 // FIXME: Add handling for tail padding in vectors. Vectors don't 1091 // have padding between or inside elements, but the total amount of 1092 // data can be less than the allocated size. 1093 return constant; 1094 } 1095 1096 Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D, 1097 llvm::Constant *Constant, 1098 CharUnits Align) { 1099 auto FunctionName = [&](const DeclContext *DC) -> std::string { 1100 if (const auto *FD = dyn_cast<FunctionDecl>(DC)) { 1101 if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD)) 1102 return CC->getNameAsString(); 1103 if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD)) 1104 return CD->getNameAsString(); 1105 return std::string(getMangledName(FD)); 1106 } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) { 1107 return OM->getNameAsString(); 1108 } else if (isa<BlockDecl>(DC)) { 1109 return "<block>"; 1110 } else if (isa<CapturedDecl>(DC)) { 1111 return "<captured>"; 1112 } else { 1113 llvm_unreachable("expected a function or method"); 1114 } 1115 }; 1116 1117 // Form a simple per-variable cache of these values in case we find we 1118 // want to reuse them. 1119 llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D]; 1120 if (!CacheEntry || CacheEntry->getInitializer() != Constant) { 1121 auto *Ty = Constant->getType(); 1122 bool isConstant = true; 1123 llvm::GlobalVariable *InsertBefore = nullptr; 1124 unsigned AS = 1125 getContext().getTargetAddressSpace(getStringLiteralAddressSpace()); 1126 std::string Name; 1127 if (D.hasGlobalStorage()) 1128 Name = getMangledName(&D).str() + ".const"; 1129 else if (const DeclContext *DC = D.getParentFunctionOrMethod()) 1130 Name = ("__const." + FunctionName(DC) + "." + D.getName()).str(); 1131 else 1132 llvm_unreachable("local variable has no parent function or method"); 1133 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 1134 getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage, 1135 Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS); 1136 GV->setAlignment(Align.getAsAlign()); 1137 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1138 CacheEntry = GV; 1139 } else if (CacheEntry->getAlignment() < Align.getQuantity()) { 1140 CacheEntry->setAlignment(Align.getAsAlign()); 1141 } 1142 1143 return Address(CacheEntry, Align); 1144 } 1145 1146 static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM, 1147 const VarDecl &D, 1148 CGBuilderTy &Builder, 1149 llvm::Constant *Constant, 1150 CharUnits Align) { 1151 Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align); 1152 llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(), 1153 SrcPtr.getAddressSpace()); 1154 if (SrcPtr.getType() != BP) 1155 SrcPtr = Builder.CreateBitCast(SrcPtr, BP); 1156 return SrcPtr; 1157 } 1158 1159 static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D, 1160 Address Loc, bool isVolatile, 1161 CGBuilderTy &Builder, 1162 llvm::Constant *constant, bool IsAutoInit) { 1163 auto *Ty = constant->getType(); 1164 uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty); 1165 if (!ConstantSize) 1166 return; 1167 1168 bool canDoSingleStore = Ty->isIntOrIntVectorTy() || 1169 Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy(); 1170 if (canDoSingleStore) { 1171 auto *I = Builder.CreateStore(constant, Loc, isVolatile); 1172 if (IsAutoInit) 1173 I->addAnnotationMetadata("auto-init"); 1174 return; 1175 } 1176 1177 auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize); 1178 1179 // If the initializer is all or mostly the same, codegen with bzero / memset 1180 // then do a few stores afterward. 1181 if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) { 1182 auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0), 1183 SizeVal, isVolatile); 1184 if (IsAutoInit) 1185 I->addAnnotationMetadata("auto-init"); 1186 1187 bool valueAlreadyCorrect = 1188 constant->isNullValue() || isa<llvm::UndefValue>(constant); 1189 if (!valueAlreadyCorrect) { 1190 Loc = Builder.CreateBitCast(Loc, Ty->getPointerTo(Loc.getAddressSpace())); 1191 emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder, 1192 IsAutoInit); 1193 } 1194 return; 1195 } 1196 1197 // If the initializer is a repeated byte pattern, use memset. 1198 llvm::Value *Pattern = 1199 shouldUseMemSetToInitialize(constant, ConstantSize, CGM.getDataLayout()); 1200 if (Pattern) { 1201 uint64_t Value = 0x00; 1202 if (!isa<llvm::UndefValue>(Pattern)) { 1203 const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue(); 1204 assert(AP.getBitWidth() <= 8); 1205 Value = AP.getLimitedValue(); 1206 } 1207 auto *I = Builder.CreateMemSet( 1208 Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal, isVolatile); 1209 if (IsAutoInit) 1210 I->addAnnotationMetadata("auto-init"); 1211 return; 1212 } 1213 1214 // If the initializer is small, use a handful of stores. 1215 if (shouldSplitConstantStore(CGM, ConstantSize)) { 1216 if (auto *STy = dyn_cast<llvm::StructType>(Ty)) { 1217 // FIXME: handle the case when STy != Loc.getElementType(). 1218 if (STy == Loc.getElementType()) { 1219 for (unsigned i = 0; i != constant->getNumOperands(); i++) { 1220 Address EltPtr = Builder.CreateStructGEP(Loc, i); 1221 emitStoresForConstant( 1222 CGM, D, EltPtr, isVolatile, Builder, 1223 cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)), 1224 IsAutoInit); 1225 } 1226 return; 1227 } 1228 } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) { 1229 // FIXME: handle the case when ATy != Loc.getElementType(). 1230 if (ATy == Loc.getElementType()) { 1231 for (unsigned i = 0; i != ATy->getNumElements(); i++) { 1232 Address EltPtr = Builder.CreateConstArrayGEP(Loc, i); 1233 emitStoresForConstant( 1234 CGM, D, EltPtr, isVolatile, Builder, 1235 cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)), 1236 IsAutoInit); 1237 } 1238 return; 1239 } 1240 } 1241 } 1242 1243 // Copy from a global. 1244 auto *I = 1245 Builder.CreateMemCpy(Loc, 1246 createUnnamedGlobalForMemcpyFrom( 1247 CGM, D, Builder, constant, Loc.getAlignment()), 1248 SizeVal, isVolatile); 1249 if (IsAutoInit) 1250 I->addAnnotationMetadata("auto-init"); 1251 } 1252 1253 static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D, 1254 Address Loc, bool isVolatile, 1255 CGBuilderTy &Builder) { 1256 llvm::Type *ElTy = Loc.getElementType(); 1257 llvm::Constant *constant = 1258 constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy)); 1259 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant, 1260 /*IsAutoInit=*/true); 1261 } 1262 1263 static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D, 1264 Address Loc, bool isVolatile, 1265 CGBuilderTy &Builder) { 1266 llvm::Type *ElTy = Loc.getElementType(); 1267 llvm::Constant *constant = constWithPadding( 1268 CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy)); 1269 assert(!isa<llvm::UndefValue>(constant)); 1270 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant, 1271 /*IsAutoInit=*/true); 1272 } 1273 1274 static bool containsUndef(llvm::Constant *constant) { 1275 auto *Ty = constant->getType(); 1276 if (isa<llvm::UndefValue>(constant)) 1277 return true; 1278 if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) 1279 for (llvm::Use &Op : constant->operands()) 1280 if (containsUndef(cast<llvm::Constant>(Op))) 1281 return true; 1282 return false; 1283 } 1284 1285 static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern, 1286 llvm::Constant *constant) { 1287 auto *Ty = constant->getType(); 1288 if (isa<llvm::UndefValue>(constant)) 1289 return patternOrZeroFor(CGM, isPattern, Ty); 1290 if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())) 1291 return constant; 1292 if (!containsUndef(constant)) 1293 return constant; 1294 llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands()); 1295 for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) { 1296 auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op)); 1297 Values[Op] = replaceUndef(CGM, isPattern, OpValue); 1298 } 1299 if (Ty->isStructTy()) 1300 return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values); 1301 if (Ty->isArrayTy()) 1302 return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values); 1303 assert(Ty->isVectorTy()); 1304 return llvm::ConstantVector::get(Values); 1305 } 1306 1307 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a 1308 /// variable declaration with auto, register, or no storage class specifier. 1309 /// These turn into simple stack objects, or GlobalValues depending on target. 1310 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) { 1311 AutoVarEmission emission = EmitAutoVarAlloca(D); 1312 EmitAutoVarInit(emission); 1313 EmitAutoVarCleanups(emission); 1314 } 1315 1316 /// Emit a lifetime.begin marker if some criteria are satisfied. 1317 /// \return a pointer to the temporary size Value if a marker was emitted, null 1318 /// otherwise 1319 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size, 1320 llvm::Value *Addr) { 1321 if (!ShouldEmitLifetimeMarkers) 1322 return nullptr; 1323 1324 assert(Addr->getType()->getPointerAddressSpace() == 1325 CGM.getDataLayout().getAllocaAddrSpace() && 1326 "Pointer should be in alloca address space"); 1327 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size); 1328 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy); 1329 llvm::CallInst *C = 1330 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr}); 1331 C->setDoesNotThrow(); 1332 return SizeV; 1333 } 1334 1335 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) { 1336 assert(Addr->getType()->getPointerAddressSpace() == 1337 CGM.getDataLayout().getAllocaAddrSpace() && 1338 "Pointer should be in alloca address space"); 1339 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy); 1340 llvm::CallInst *C = 1341 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr}); 1342 C->setDoesNotThrow(); 1343 } 1344 1345 void CodeGenFunction::EmitAndRegisterVariableArrayDimensions( 1346 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) { 1347 // For each dimension stores its QualType and corresponding 1348 // size-expression Value. 1349 SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions; 1350 SmallVector<IdentifierInfo *, 4> VLAExprNames; 1351 1352 // Break down the array into individual dimensions. 1353 QualType Type1D = D.getType(); 1354 while (getContext().getAsVariableArrayType(Type1D)) { 1355 auto VlaSize = getVLAElements1D(Type1D); 1356 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts)) 1357 Dimensions.emplace_back(C, Type1D.getUnqualifiedType()); 1358 else { 1359 // Generate a locally unique name for the size expression. 1360 Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++); 1361 SmallString<12> Buffer; 1362 StringRef NameRef = Name.toStringRef(Buffer); 1363 auto &Ident = getContext().Idents.getOwn(NameRef); 1364 VLAExprNames.push_back(&Ident); 1365 auto SizeExprAddr = 1366 CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef); 1367 Builder.CreateStore(VlaSize.NumElts, SizeExprAddr); 1368 Dimensions.emplace_back(SizeExprAddr.getPointer(), 1369 Type1D.getUnqualifiedType()); 1370 } 1371 Type1D = VlaSize.Type; 1372 } 1373 1374 if (!EmitDebugInfo) 1375 return; 1376 1377 // Register each dimension's size-expression with a DILocalVariable, 1378 // so that it can be used by CGDebugInfo when instantiating a DISubrange 1379 // to describe this array. 1380 unsigned NameIdx = 0; 1381 for (auto &VlaSize : Dimensions) { 1382 llvm::Metadata *MD; 1383 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts)) 1384 MD = llvm::ConstantAsMetadata::get(C); 1385 else { 1386 // Create an artificial VarDecl to generate debug info for. 1387 IdentifierInfo *NameIdent = VLAExprNames[NameIdx++]; 1388 auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType(); 1389 auto QT = getContext().getIntTypeForBitwidth( 1390 VlaExprTy->getScalarSizeInBits(), false); 1391 auto *ArtificialDecl = VarDecl::Create( 1392 getContext(), const_cast<DeclContext *>(D.getDeclContext()), 1393 D.getLocation(), D.getLocation(), NameIdent, QT, 1394 getContext().CreateTypeSourceInfo(QT), SC_Auto); 1395 ArtificialDecl->setImplicit(); 1396 1397 MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts, 1398 Builder); 1399 } 1400 assert(MD && "No Size expression debug node created"); 1401 DI->registerVLASizeExpression(VlaSize.Type, MD); 1402 } 1403 } 1404 1405 /// EmitAutoVarAlloca - Emit the alloca and debug information for a 1406 /// local variable. Does not emit initialization or destruction. 1407 CodeGenFunction::AutoVarEmission 1408 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) { 1409 QualType Ty = D.getType(); 1410 assert( 1411 Ty.getAddressSpace() == LangAS::Default || 1412 (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL)); 1413 1414 AutoVarEmission emission(D); 1415 1416 bool isEscapingByRef = D.isEscapingByref(); 1417 emission.IsEscapingByRef = isEscapingByRef; 1418 1419 CharUnits alignment = getContext().getDeclAlign(&D); 1420 1421 // If the type is variably-modified, emit all the VLA sizes for it. 1422 if (Ty->isVariablyModifiedType()) 1423 EmitVariablyModifiedType(Ty); 1424 1425 auto *DI = getDebugInfo(); 1426 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo(); 1427 1428 Address address = Address::invalid(); 1429 Address AllocaAddr = Address::invalid(); 1430 Address OpenMPLocalAddr = Address::invalid(); 1431 if (CGM.getLangOpts().OpenMPIRBuilder) 1432 OpenMPLocalAddr = OMPBuilderCBHelpers::getAddressOfLocalVariable(*this, &D); 1433 else 1434 OpenMPLocalAddr = 1435 getLangOpts().OpenMP 1436 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D) 1437 : Address::invalid(); 1438 1439 bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable(); 1440 1441 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) { 1442 address = OpenMPLocalAddr; 1443 } else if (Ty->isConstantSizeType()) { 1444 // If this value is an array or struct with a statically determinable 1445 // constant initializer, there are optimizations we can do. 1446 // 1447 // TODO: We should constant-evaluate the initializer of any variable, 1448 // as long as it is initialized by a constant expression. Currently, 1449 // isConstantInitializer produces wrong answers for structs with 1450 // reference or bitfield members, and a few other cases, and checking 1451 // for POD-ness protects us from some of these. 1452 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) && 1453 (D.isConstexpr() || 1454 ((Ty.isPODType(getContext()) || 1455 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) && 1456 D.getInit()->isConstantInitializer(getContext(), false)))) { 1457 1458 // If the variable's a const type, and it's neither an NRVO 1459 // candidate nor a __block variable and has no mutable members, 1460 // emit it as a global instead. 1461 // Exception is if a variable is located in non-constant address space 1462 // in OpenCL. 1463 if ((!getLangOpts().OpenCL || 1464 Ty.getAddressSpace() == LangAS::opencl_constant) && 1465 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && 1466 !isEscapingByRef && CGM.isTypeConstant(Ty, true))) { 1467 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage); 1468 1469 // Signal this condition to later callbacks. 1470 emission.Addr = Address::invalid(); 1471 assert(emission.wasEmittedAsGlobal()); 1472 return emission; 1473 } 1474 1475 // Otherwise, tell the initialization code that we're in this case. 1476 emission.IsConstantAggregate = true; 1477 } 1478 1479 // A normal fixed sized variable becomes an alloca in the entry block, 1480 // unless: 1481 // - it's an NRVO variable. 1482 // - we are compiling OpenMP and it's an OpenMP local variable. 1483 if (NRVO) { 1484 // The named return value optimization: allocate this variable in the 1485 // return slot, so that we can elide the copy when returning this 1486 // variable (C++0x [class.copy]p34). 1487 address = ReturnValue; 1488 1489 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) { 1490 const auto *RD = RecordTy->getDecl(); 1491 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 1492 if ((CXXRD && !CXXRD->hasTrivialDestructor()) || 1493 RD->isNonTrivialToPrimitiveDestroy()) { 1494 // Create a flag that is used to indicate when the NRVO was applied 1495 // to this variable. Set it to zero to indicate that NRVO was not 1496 // applied. 1497 llvm::Value *Zero = Builder.getFalse(); 1498 Address NRVOFlag = 1499 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo"); 1500 EnsureInsertPoint(); 1501 Builder.CreateStore(Zero, NRVOFlag); 1502 1503 // Record the NRVO flag for this variable. 1504 NRVOFlags[&D] = NRVOFlag.getPointer(); 1505 emission.NRVOFlag = NRVOFlag.getPointer(); 1506 } 1507 } 1508 } else { 1509 CharUnits allocaAlignment; 1510 llvm::Type *allocaTy; 1511 if (isEscapingByRef) { 1512 auto &byrefInfo = getBlockByrefInfo(&D); 1513 allocaTy = byrefInfo.Type; 1514 allocaAlignment = byrefInfo.ByrefAlignment; 1515 } else { 1516 allocaTy = ConvertTypeForMem(Ty); 1517 allocaAlignment = alignment; 1518 } 1519 1520 // Create the alloca. Note that we set the name separately from 1521 // building the instruction so that it's there even in no-asserts 1522 // builds. 1523 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(), 1524 /*ArraySize=*/nullptr, &AllocaAddr); 1525 1526 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of 1527 // the catch parameter starts in the catchpad instruction, and we can't 1528 // insert code in those basic blocks. 1529 bool IsMSCatchParam = 1530 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft(); 1531 1532 // Emit a lifetime intrinsic if meaningful. There's no point in doing this 1533 // if we don't have a valid insertion point (?). 1534 if (HaveInsertPoint() && !IsMSCatchParam) { 1535 // If there's a jump into the lifetime of this variable, its lifetime 1536 // gets broken up into several regions in IR, which requires more work 1537 // to handle correctly. For now, just omit the intrinsics; this is a 1538 // rare case, and it's better to just be conservatively correct. 1539 // PR28267. 1540 // 1541 // We have to do this in all language modes if there's a jump past the 1542 // declaration. We also have to do it in C if there's a jump to an 1543 // earlier point in the current block because non-VLA lifetimes begin as 1544 // soon as the containing block is entered, not when its variables 1545 // actually come into scope; suppressing the lifetime annotations 1546 // completely in this case is unnecessarily pessimistic, but again, this 1547 // is rare. 1548 if (!Bypasses.IsBypassed(&D) && 1549 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) { 1550 llvm::TypeSize size = 1551 CGM.getDataLayout().getTypeAllocSize(allocaTy); 1552 emission.SizeForLifetimeMarkers = 1553 size.isScalable() ? EmitLifetimeStart(-1, AllocaAddr.getPointer()) 1554 : EmitLifetimeStart(size.getFixedSize(), 1555 AllocaAddr.getPointer()); 1556 } 1557 } else { 1558 assert(!emission.useLifetimeMarkers()); 1559 } 1560 } 1561 } else { 1562 EnsureInsertPoint(); 1563 1564 if (!DidCallStackSave) { 1565 // Save the stack. 1566 Address Stack = 1567 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack"); 1568 1569 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave); 1570 llvm::Value *V = Builder.CreateCall(F); 1571 Builder.CreateStore(V, Stack); 1572 1573 DidCallStackSave = true; 1574 1575 // Push a cleanup block and restore the stack there. 1576 // FIXME: in general circumstances, this should be an EH cleanup. 1577 pushStackRestore(NormalCleanup, Stack); 1578 } 1579 1580 auto VlaSize = getVLASize(Ty); 1581 llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type); 1582 1583 // Allocate memory for the array. 1584 address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts, 1585 &AllocaAddr); 1586 1587 // If we have debug info enabled, properly describe the VLA dimensions for 1588 // this type by registering the vla size expression for each of the 1589 // dimensions. 1590 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo); 1591 } 1592 1593 setAddrOfLocalVar(&D, address); 1594 emission.Addr = address; 1595 emission.AllocaAddr = AllocaAddr; 1596 1597 // Emit debug info for local var declaration. 1598 if (EmitDebugInfo && HaveInsertPoint()) { 1599 Address DebugAddr = address; 1600 bool UsePointerValue = NRVO && ReturnValuePointer.isValid(); 1601 DI->setLocation(D.getLocation()); 1602 1603 // If NRVO, use a pointer to the return address. 1604 if (UsePointerValue) 1605 DebugAddr = ReturnValuePointer; 1606 1607 (void)DI->EmitDeclareOfAutoVariable(&D, DebugAddr.getPointer(), Builder, 1608 UsePointerValue); 1609 } 1610 1611 if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint()) 1612 EmitVarAnnotations(&D, address.getPointer()); 1613 1614 // Make sure we call @llvm.lifetime.end. 1615 if (emission.useLifetimeMarkers()) 1616 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, 1617 emission.getOriginalAllocatedAddress(), 1618 emission.getSizeForLifetimeMarkers()); 1619 1620 return emission; 1621 } 1622 1623 static bool isCapturedBy(const VarDecl &, const Expr *); 1624 1625 /// Determines whether the given __block variable is potentially 1626 /// captured by the given statement. 1627 static bool isCapturedBy(const VarDecl &Var, const Stmt *S) { 1628 if (const Expr *E = dyn_cast<Expr>(S)) 1629 return isCapturedBy(Var, E); 1630 for (const Stmt *SubStmt : S->children()) 1631 if (isCapturedBy(Var, SubStmt)) 1632 return true; 1633 return false; 1634 } 1635 1636 /// Determines whether the given __block variable is potentially 1637 /// captured by the given expression. 1638 static bool isCapturedBy(const VarDecl &Var, const Expr *E) { 1639 // Skip the most common kinds of expressions that make 1640 // hierarchy-walking expensive. 1641 E = E->IgnoreParenCasts(); 1642 1643 if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) { 1644 const BlockDecl *Block = BE->getBlockDecl(); 1645 for (const auto &I : Block->captures()) { 1646 if (I.getVariable() == &Var) 1647 return true; 1648 } 1649 1650 // No need to walk into the subexpressions. 1651 return false; 1652 } 1653 1654 if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) { 1655 const CompoundStmt *CS = SE->getSubStmt(); 1656 for (const auto *BI : CS->body()) 1657 if (const auto *BIE = dyn_cast<Expr>(BI)) { 1658 if (isCapturedBy(Var, BIE)) 1659 return true; 1660 } 1661 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) { 1662 // special case declarations 1663 for (const auto *I : DS->decls()) { 1664 if (const auto *VD = dyn_cast<VarDecl>((I))) { 1665 const Expr *Init = VD->getInit(); 1666 if (Init && isCapturedBy(Var, Init)) 1667 return true; 1668 } 1669 } 1670 } 1671 else 1672 // FIXME. Make safe assumption assuming arbitrary statements cause capturing. 1673 // Later, provide code to poke into statements for capture analysis. 1674 return true; 1675 return false; 1676 } 1677 1678 for (const Stmt *SubStmt : E->children()) 1679 if (isCapturedBy(Var, SubStmt)) 1680 return true; 1681 1682 return false; 1683 } 1684 1685 /// Determine whether the given initializer is trivial in the sense 1686 /// that it requires no code to be generated. 1687 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) { 1688 if (!Init) 1689 return true; 1690 1691 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) 1692 if (CXXConstructorDecl *Constructor = Construct->getConstructor()) 1693 if (Constructor->isTrivial() && 1694 Constructor->isDefaultConstructor() && 1695 !Construct->requiresZeroInitialization()) 1696 return true; 1697 1698 return false; 1699 } 1700 1701 void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type, 1702 const VarDecl &D, 1703 Address Loc) { 1704 auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit(); 1705 CharUnits Size = getContext().getTypeSizeInChars(type); 1706 bool isVolatile = type.isVolatileQualified(); 1707 if (!Size.isZero()) { 1708 switch (trivialAutoVarInit) { 1709 case LangOptions::TrivialAutoVarInitKind::Uninitialized: 1710 llvm_unreachable("Uninitialized handled by caller"); 1711 case LangOptions::TrivialAutoVarInitKind::Zero: 1712 if (CGM.stopAutoInit()) 1713 return; 1714 emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder); 1715 break; 1716 case LangOptions::TrivialAutoVarInitKind::Pattern: 1717 if (CGM.stopAutoInit()) 1718 return; 1719 emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder); 1720 break; 1721 } 1722 return; 1723 } 1724 1725 // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to 1726 // them, so emit a memcpy with the VLA size to initialize each element. 1727 // Technically zero-sized or negative-sized VLAs are undefined, and UBSan 1728 // will catch that code, but there exists code which generates zero-sized 1729 // VLAs. Be nice and initialize whatever they requested. 1730 const auto *VlaType = getContext().getAsVariableArrayType(type); 1731 if (!VlaType) 1732 return; 1733 auto VlaSize = getVLASize(VlaType); 1734 auto SizeVal = VlaSize.NumElts; 1735 CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type); 1736 switch (trivialAutoVarInit) { 1737 case LangOptions::TrivialAutoVarInitKind::Uninitialized: 1738 llvm_unreachable("Uninitialized handled by caller"); 1739 1740 case LangOptions::TrivialAutoVarInitKind::Zero: { 1741 if (CGM.stopAutoInit()) 1742 return; 1743 if (!EltSize.isOne()) 1744 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize)); 1745 auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), 1746 SizeVal, isVolatile); 1747 I->addAnnotationMetadata("auto-init"); 1748 break; 1749 } 1750 1751 case LangOptions::TrivialAutoVarInitKind::Pattern: { 1752 if (CGM.stopAutoInit()) 1753 return; 1754 llvm::Type *ElTy = Loc.getElementType(); 1755 llvm::Constant *Constant = constWithPadding( 1756 CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy)); 1757 CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type); 1758 llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop"); 1759 llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop"); 1760 llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont"); 1761 llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ( 1762 SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0), 1763 "vla.iszerosized"); 1764 Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB); 1765 EmitBlock(SetupBB); 1766 if (!EltSize.isOne()) 1767 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize)); 1768 llvm::Value *BaseSizeInChars = 1769 llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity()); 1770 Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin"); 1771 llvm::Value *End = Builder.CreateInBoundsGEP( 1772 Begin.getElementType(), Begin.getPointer(), SizeVal, "vla.end"); 1773 llvm::BasicBlock *OriginBB = Builder.GetInsertBlock(); 1774 EmitBlock(LoopBB); 1775 llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur"); 1776 Cur->addIncoming(Begin.getPointer(), OriginBB); 1777 CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize); 1778 auto *I = 1779 Builder.CreateMemCpy(Address(Cur, CurAlign), 1780 createUnnamedGlobalForMemcpyFrom( 1781 CGM, D, Builder, Constant, ConstantAlign), 1782 BaseSizeInChars, isVolatile); 1783 I->addAnnotationMetadata("auto-init"); 1784 llvm::Value *Next = 1785 Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next"); 1786 llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone"); 1787 Builder.CreateCondBr(Done, ContBB, LoopBB); 1788 Cur->addIncoming(Next, LoopBB); 1789 EmitBlock(ContBB); 1790 } break; 1791 } 1792 } 1793 1794 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) { 1795 assert(emission.Variable && "emission was not valid!"); 1796 1797 // If this was emitted as a global constant, we're done. 1798 if (emission.wasEmittedAsGlobal()) return; 1799 1800 const VarDecl &D = *emission.Variable; 1801 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation()); 1802 QualType type = D.getType(); 1803 1804 // If this local has an initializer, emit it now. 1805 const Expr *Init = D.getInit(); 1806 1807 // If we are at an unreachable point, we don't need to emit the initializer 1808 // unless it contains a label. 1809 if (!HaveInsertPoint()) { 1810 if (!Init || !ContainsLabel(Init)) return; 1811 EnsureInsertPoint(); 1812 } 1813 1814 // Initialize the structure of a __block variable. 1815 if (emission.IsEscapingByRef) 1816 emitByrefStructureInit(emission); 1817 1818 // Initialize the variable here if it doesn't have a initializer and it is a 1819 // C struct that is non-trivial to initialize or an array containing such a 1820 // struct. 1821 if (!Init && 1822 type.isNonTrivialToPrimitiveDefaultInitialize() == 1823 QualType::PDIK_Struct) { 1824 LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type); 1825 if (emission.IsEscapingByRef) 1826 drillIntoBlockVariable(*this, Dst, &D); 1827 defaultInitNonTrivialCStructVar(Dst); 1828 return; 1829 } 1830 1831 // Check whether this is a byref variable that's potentially 1832 // captured and moved by its own initializer. If so, we'll need to 1833 // emit the initializer first, then copy into the variable. 1834 bool capturedByInit = 1835 Init && emission.IsEscapingByRef && isCapturedBy(D, Init); 1836 1837 bool locIsByrefHeader = !capturedByInit; 1838 const Address Loc = 1839 locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr; 1840 1841 // Note: constexpr already initializes everything correctly. 1842 LangOptions::TrivialAutoVarInitKind trivialAutoVarInit = 1843 (D.isConstexpr() 1844 ? LangOptions::TrivialAutoVarInitKind::Uninitialized 1845 : (D.getAttr<UninitializedAttr>() 1846 ? LangOptions::TrivialAutoVarInitKind::Uninitialized 1847 : getContext().getLangOpts().getTrivialAutoVarInit())); 1848 1849 auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) { 1850 if (trivialAutoVarInit == 1851 LangOptions::TrivialAutoVarInitKind::Uninitialized) 1852 return; 1853 1854 // Only initialize a __block's storage: we always initialize the header. 1855 if (emission.IsEscapingByRef && !locIsByrefHeader) 1856 Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false); 1857 1858 return emitZeroOrPatternForAutoVarInit(type, D, Loc); 1859 }; 1860 1861 if (isTrivialInitializer(Init)) 1862 return initializeWhatIsTechnicallyUninitialized(Loc); 1863 1864 llvm::Constant *constant = nullptr; 1865 if (emission.IsConstantAggregate || 1866 D.mightBeUsableInConstantExpressions(getContext())) { 1867 assert(!capturedByInit && "constant init contains a capturing block?"); 1868 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D); 1869 if (constant && !constant->isZeroValue() && 1870 (trivialAutoVarInit != 1871 LangOptions::TrivialAutoVarInitKind::Uninitialized)) { 1872 IsPattern isPattern = 1873 (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern) 1874 ? IsPattern::Yes 1875 : IsPattern::No; 1876 // C guarantees that brace-init with fewer initializers than members in 1877 // the aggregate will initialize the rest of the aggregate as-if it were 1878 // static initialization. In turn static initialization guarantees that 1879 // padding is initialized to zero bits. We could instead pattern-init if D 1880 // has any ImplicitValueInitExpr, but that seems to be unintuitive 1881 // behavior. 1882 constant = constWithPadding(CGM, IsPattern::No, 1883 replaceUndef(CGM, isPattern, constant)); 1884 } 1885 } 1886 1887 if (!constant) { 1888 initializeWhatIsTechnicallyUninitialized(Loc); 1889 LValue lv = MakeAddrLValue(Loc, type); 1890 lv.setNonGC(true); 1891 return EmitExprAsInit(Init, &D, lv, capturedByInit); 1892 } 1893 1894 if (!emission.IsConstantAggregate) { 1895 // For simple scalar/complex initialization, store the value directly. 1896 LValue lv = MakeAddrLValue(Loc, type); 1897 lv.setNonGC(true); 1898 return EmitStoreThroughLValue(RValue::get(constant), lv, true); 1899 } 1900 1901 llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace()); 1902 emitStoresForConstant( 1903 CGM, D, (Loc.getType() == BP) ? Loc : Builder.CreateBitCast(Loc, BP), 1904 type.isVolatileQualified(), Builder, constant, /*IsAutoInit=*/false); 1905 } 1906 1907 /// Emit an expression as an initializer for an object (variable, field, etc.) 1908 /// at the given location. The expression is not necessarily the normal 1909 /// initializer for the object, and the address is not necessarily 1910 /// its normal location. 1911 /// 1912 /// \param init the initializing expression 1913 /// \param D the object to act as if we're initializing 1914 /// \param lvalue the lvalue to initialize 1915 /// \param capturedByInit true if \p D is a __block variable 1916 /// whose address is potentially changed by the initializer 1917 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D, 1918 LValue lvalue, bool capturedByInit) { 1919 QualType type = D->getType(); 1920 1921 if (type->isReferenceType()) { 1922 RValue rvalue = EmitReferenceBindingToExpr(init); 1923 if (capturedByInit) 1924 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 1925 EmitStoreThroughLValue(rvalue, lvalue, true); 1926 return; 1927 } 1928 switch (getEvaluationKind(type)) { 1929 case TEK_Scalar: 1930 EmitScalarInit(init, D, lvalue, capturedByInit); 1931 return; 1932 case TEK_Complex: { 1933 ComplexPairTy complex = EmitComplexExpr(init); 1934 if (capturedByInit) 1935 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 1936 EmitStoreOfComplex(complex, lvalue, /*init*/ true); 1937 return; 1938 } 1939 case TEK_Aggregate: 1940 if (type->isAtomicType()) { 1941 EmitAtomicInit(const_cast<Expr*>(init), lvalue); 1942 } else { 1943 AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap; 1944 if (isa<VarDecl>(D)) 1945 Overlap = AggValueSlot::DoesNotOverlap; 1946 else if (auto *FD = dyn_cast<FieldDecl>(D)) 1947 Overlap = getOverlapForFieldInit(FD); 1948 // TODO: how can we delay here if D is captured by its initializer? 1949 EmitAggExpr(init, AggValueSlot::forLValue( 1950 lvalue, *this, AggValueSlot::IsDestructed, 1951 AggValueSlot::DoesNotNeedGCBarriers, 1952 AggValueSlot::IsNotAliased, Overlap)); 1953 } 1954 return; 1955 } 1956 llvm_unreachable("bad evaluation kind"); 1957 } 1958 1959 /// Enter a destroy cleanup for the given local variable. 1960 void CodeGenFunction::emitAutoVarTypeCleanup( 1961 const CodeGenFunction::AutoVarEmission &emission, 1962 QualType::DestructionKind dtorKind) { 1963 assert(dtorKind != QualType::DK_none); 1964 1965 // Note that for __block variables, we want to destroy the 1966 // original stack object, not the possibly forwarded object. 1967 Address addr = emission.getObjectAddress(*this); 1968 1969 const VarDecl *var = emission.Variable; 1970 QualType type = var->getType(); 1971 1972 CleanupKind cleanupKind = NormalAndEHCleanup; 1973 CodeGenFunction::Destroyer *destroyer = nullptr; 1974 1975 switch (dtorKind) { 1976 case QualType::DK_none: 1977 llvm_unreachable("no cleanup for trivially-destructible variable"); 1978 1979 case QualType::DK_cxx_destructor: 1980 // If there's an NRVO flag on the emission, we need a different 1981 // cleanup. 1982 if (emission.NRVOFlag) { 1983 assert(!type->isArrayType()); 1984 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor(); 1985 EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor, 1986 emission.NRVOFlag); 1987 return; 1988 } 1989 break; 1990 1991 case QualType::DK_objc_strong_lifetime: 1992 // Suppress cleanups for pseudo-strong variables. 1993 if (var->isARCPseudoStrong()) return; 1994 1995 // Otherwise, consider whether to use an EH cleanup or not. 1996 cleanupKind = getARCCleanupKind(); 1997 1998 // Use the imprecise destroyer by default. 1999 if (!var->hasAttr<ObjCPreciseLifetimeAttr>()) 2000 destroyer = CodeGenFunction::destroyARCStrongImprecise; 2001 break; 2002 2003 case QualType::DK_objc_weak_lifetime: 2004 break; 2005 2006 case QualType::DK_nontrivial_c_struct: 2007 destroyer = CodeGenFunction::destroyNonTrivialCStruct; 2008 if (emission.NRVOFlag) { 2009 assert(!type->isArrayType()); 2010 EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr, 2011 emission.NRVOFlag, type); 2012 return; 2013 } 2014 break; 2015 } 2016 2017 // If we haven't chosen a more specific destroyer, use the default. 2018 if (!destroyer) destroyer = getDestroyer(dtorKind); 2019 2020 // Use an EH cleanup in array destructors iff the destructor itself 2021 // is being pushed as an EH cleanup. 2022 bool useEHCleanup = (cleanupKind & EHCleanup); 2023 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer, 2024 useEHCleanup); 2025 } 2026 2027 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) { 2028 assert(emission.Variable && "emission was not valid!"); 2029 2030 // If this was emitted as a global constant, we're done. 2031 if (emission.wasEmittedAsGlobal()) return; 2032 2033 // If we don't have an insertion point, we're done. Sema prevents 2034 // us from jumping into any of these scopes anyway. 2035 if (!HaveInsertPoint()) return; 2036 2037 const VarDecl &D = *emission.Variable; 2038 2039 // Check the type for a cleanup. 2040 if (QualType::DestructionKind dtorKind = D.needsDestruction(getContext())) 2041 emitAutoVarTypeCleanup(emission, dtorKind); 2042 2043 // In GC mode, honor objc_precise_lifetime. 2044 if (getLangOpts().getGC() != LangOptions::NonGC && 2045 D.hasAttr<ObjCPreciseLifetimeAttr>()) { 2046 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D); 2047 } 2048 2049 // Handle the cleanup attribute. 2050 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) { 2051 const FunctionDecl *FD = CA->getFunctionDecl(); 2052 2053 llvm::Constant *F = CGM.GetAddrOfFunction(FD); 2054 assert(F && "Could not find function!"); 2055 2056 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD); 2057 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D); 2058 } 2059 2060 // If this is a block variable, call _Block_object_destroy 2061 // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC 2062 // mode. 2063 if (emission.IsEscapingByRef && 2064 CGM.getLangOpts().getGC() != LangOptions::GCOnly) { 2065 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF; 2066 if (emission.Variable->getType().isObjCGCWeak()) 2067 Flags |= BLOCK_FIELD_IS_WEAK; 2068 enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags, 2069 /*LoadBlockVarAddr*/ false, 2070 cxxDestructorCanThrow(emission.Variable->getType())); 2071 } 2072 } 2073 2074 CodeGenFunction::Destroyer * 2075 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) { 2076 switch (kind) { 2077 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor"); 2078 case QualType::DK_cxx_destructor: 2079 return destroyCXXObject; 2080 case QualType::DK_objc_strong_lifetime: 2081 return destroyARCStrongPrecise; 2082 case QualType::DK_objc_weak_lifetime: 2083 return destroyARCWeak; 2084 case QualType::DK_nontrivial_c_struct: 2085 return destroyNonTrivialCStruct; 2086 } 2087 llvm_unreachable("Unknown DestructionKind"); 2088 } 2089 2090 /// pushEHDestroy - Push the standard destructor for the given type as 2091 /// an EH-only cleanup. 2092 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind, 2093 Address addr, QualType type) { 2094 assert(dtorKind && "cannot push destructor for trivial type"); 2095 assert(needsEHCleanup(dtorKind)); 2096 2097 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true); 2098 } 2099 2100 /// pushDestroy - Push the standard destructor for the given type as 2101 /// at least a normal cleanup. 2102 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind, 2103 Address addr, QualType type) { 2104 assert(dtorKind && "cannot push destructor for trivial type"); 2105 2106 CleanupKind cleanupKind = getCleanupKind(dtorKind); 2107 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind), 2108 cleanupKind & EHCleanup); 2109 } 2110 2111 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr, 2112 QualType type, Destroyer *destroyer, 2113 bool useEHCleanupForArray) { 2114 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type, 2115 destroyer, useEHCleanupForArray); 2116 } 2117 2118 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) { 2119 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem); 2120 } 2121 2122 void CodeGenFunction::pushLifetimeExtendedDestroy(CleanupKind cleanupKind, 2123 Address addr, QualType type, 2124 Destroyer *destroyer, 2125 bool useEHCleanupForArray) { 2126 // If we're not in a conditional branch, we don't need to bother generating a 2127 // conditional cleanup. 2128 if (!isInConditionalBranch()) { 2129 // Push an EH-only cleanup for the object now. 2130 // FIXME: When popping normal cleanups, we need to keep this EH cleanup 2131 // around in case a temporary's destructor throws an exception. 2132 if (cleanupKind & EHCleanup) 2133 EHStack.pushCleanup<DestroyObject>( 2134 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type, 2135 destroyer, useEHCleanupForArray); 2136 2137 return pushCleanupAfterFullExprWithActiveFlag<DestroyObject>( 2138 cleanupKind, Address::invalid(), addr, type, destroyer, useEHCleanupForArray); 2139 } 2140 2141 // Otherwise, we should only destroy the object if it's been initialized. 2142 // Re-use the active flag and saved address across both the EH and end of 2143 // scope cleanups. 2144 2145 using SavedType = typename DominatingValue<Address>::saved_type; 2146 using ConditionalCleanupType = 2147 EHScopeStack::ConditionalCleanup<DestroyObject, Address, QualType, 2148 Destroyer *, bool>; 2149 2150 Address ActiveFlag = createCleanupActiveFlag(); 2151 SavedType SavedAddr = saveValueInCond(addr); 2152 2153 if (cleanupKind & EHCleanup) { 2154 EHStack.pushCleanup<ConditionalCleanupType>( 2155 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), SavedAddr, type, 2156 destroyer, useEHCleanupForArray); 2157 initFullExprCleanupWithFlag(ActiveFlag); 2158 } 2159 2160 pushCleanupAfterFullExprWithActiveFlag<ConditionalCleanupType>( 2161 cleanupKind, ActiveFlag, SavedAddr, type, destroyer, 2162 useEHCleanupForArray); 2163 } 2164 2165 /// emitDestroy - Immediately perform the destruction of the given 2166 /// object. 2167 /// 2168 /// \param addr - the address of the object; a type* 2169 /// \param type - the type of the object; if an array type, all 2170 /// objects are destroyed in reverse order 2171 /// \param destroyer - the function to call to destroy individual 2172 /// elements 2173 /// \param useEHCleanupForArray - whether an EH cleanup should be 2174 /// used when destroying array elements, in case one of the 2175 /// destructions throws an exception 2176 void CodeGenFunction::emitDestroy(Address addr, QualType type, 2177 Destroyer *destroyer, 2178 bool useEHCleanupForArray) { 2179 const ArrayType *arrayType = getContext().getAsArrayType(type); 2180 if (!arrayType) 2181 return destroyer(*this, addr, type); 2182 2183 llvm::Value *length = emitArrayLength(arrayType, type, addr); 2184 2185 CharUnits elementAlign = 2186 addr.getAlignment() 2187 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type)); 2188 2189 // Normally we have to check whether the array is zero-length. 2190 bool checkZeroLength = true; 2191 2192 // But if the array length is constant, we can suppress that. 2193 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) { 2194 // ...and if it's constant zero, we can just skip the entire thing. 2195 if (constLength->isZero()) return; 2196 checkZeroLength = false; 2197 } 2198 2199 llvm::Value *begin = addr.getPointer(); 2200 llvm::Value *end = 2201 Builder.CreateInBoundsGEP(addr.getElementType(), begin, length); 2202 emitArrayDestroy(begin, end, type, elementAlign, destroyer, 2203 checkZeroLength, useEHCleanupForArray); 2204 } 2205 2206 /// emitArrayDestroy - Destroys all the elements of the given array, 2207 /// beginning from last to first. The array cannot be zero-length. 2208 /// 2209 /// \param begin - a type* denoting the first element of the array 2210 /// \param end - a type* denoting one past the end of the array 2211 /// \param elementType - the element type of the array 2212 /// \param destroyer - the function to call to destroy elements 2213 /// \param useEHCleanup - whether to push an EH cleanup to destroy 2214 /// the remaining elements in case the destruction of a single 2215 /// element throws 2216 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin, 2217 llvm::Value *end, 2218 QualType elementType, 2219 CharUnits elementAlign, 2220 Destroyer *destroyer, 2221 bool checkZeroLength, 2222 bool useEHCleanup) { 2223 assert(!elementType->isArrayType()); 2224 2225 // The basic structure here is a do-while loop, because we don't 2226 // need to check for the zero-element case. 2227 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body"); 2228 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done"); 2229 2230 if (checkZeroLength) { 2231 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end, 2232 "arraydestroy.isempty"); 2233 Builder.CreateCondBr(isEmpty, doneBB, bodyBB); 2234 } 2235 2236 // Enter the loop body, making that address the current address. 2237 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 2238 EmitBlock(bodyBB); 2239 llvm::PHINode *elementPast = 2240 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast"); 2241 elementPast->addIncoming(end, entryBB); 2242 2243 // Shift the address back by one element. 2244 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true); 2245 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne, 2246 "arraydestroy.element"); 2247 2248 if (useEHCleanup) 2249 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign, 2250 destroyer); 2251 2252 // Perform the actual destruction there. 2253 destroyer(*this, Address(element, elementAlign), elementType); 2254 2255 if (useEHCleanup) 2256 PopCleanupBlock(); 2257 2258 // Check whether we've reached the end. 2259 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done"); 2260 Builder.CreateCondBr(done, doneBB, bodyBB); 2261 elementPast->addIncoming(element, Builder.GetInsertBlock()); 2262 2263 // Done. 2264 EmitBlock(doneBB); 2265 } 2266 2267 /// Perform partial array destruction as if in an EH cleanup. Unlike 2268 /// emitArrayDestroy, the element type here may still be an array type. 2269 static void emitPartialArrayDestroy(CodeGenFunction &CGF, 2270 llvm::Value *begin, llvm::Value *end, 2271 QualType type, CharUnits elementAlign, 2272 CodeGenFunction::Destroyer *destroyer) { 2273 // If the element type is itself an array, drill down. 2274 unsigned arrayDepth = 0; 2275 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) { 2276 // VLAs don't require a GEP index to walk into. 2277 if (!isa<VariableArrayType>(arrayType)) 2278 arrayDepth++; 2279 type = arrayType->getElementType(); 2280 } 2281 2282 if (arrayDepth) { 2283 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0); 2284 2285 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero); 2286 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin"); 2287 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend"); 2288 } 2289 2290 // Destroy the array. We don't ever need an EH cleanup because we 2291 // assume that we're in an EH cleanup ourselves, so a throwing 2292 // destructor causes an immediate terminate. 2293 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer, 2294 /*checkZeroLength*/ true, /*useEHCleanup*/ false); 2295 } 2296 2297 namespace { 2298 /// RegularPartialArrayDestroy - a cleanup which performs a partial 2299 /// array destroy where the end pointer is regularly determined and 2300 /// does not need to be loaded from a local. 2301 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup { 2302 llvm::Value *ArrayBegin; 2303 llvm::Value *ArrayEnd; 2304 QualType ElementType; 2305 CodeGenFunction::Destroyer *Destroyer; 2306 CharUnits ElementAlign; 2307 public: 2308 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd, 2309 QualType elementType, CharUnits elementAlign, 2310 CodeGenFunction::Destroyer *destroyer) 2311 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd), 2312 ElementType(elementType), Destroyer(destroyer), 2313 ElementAlign(elementAlign) {} 2314 2315 void Emit(CodeGenFunction &CGF, Flags flags) override { 2316 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd, 2317 ElementType, ElementAlign, Destroyer); 2318 } 2319 }; 2320 2321 /// IrregularPartialArrayDestroy - a cleanup which performs a 2322 /// partial array destroy where the end pointer is irregularly 2323 /// determined and must be loaded from a local. 2324 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup { 2325 llvm::Value *ArrayBegin; 2326 Address ArrayEndPointer; 2327 QualType ElementType; 2328 CodeGenFunction::Destroyer *Destroyer; 2329 CharUnits ElementAlign; 2330 public: 2331 IrregularPartialArrayDestroy(llvm::Value *arrayBegin, 2332 Address arrayEndPointer, 2333 QualType elementType, 2334 CharUnits elementAlign, 2335 CodeGenFunction::Destroyer *destroyer) 2336 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer), 2337 ElementType(elementType), Destroyer(destroyer), 2338 ElementAlign(elementAlign) {} 2339 2340 void Emit(CodeGenFunction &CGF, Flags flags) override { 2341 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer); 2342 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd, 2343 ElementType, ElementAlign, Destroyer); 2344 } 2345 }; 2346 } // end anonymous namespace 2347 2348 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy 2349 /// already-constructed elements of the given array. The cleanup 2350 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock. 2351 /// 2352 /// \param elementType - the immediate element type of the array; 2353 /// possibly still an array type 2354 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 2355 Address arrayEndPointer, 2356 QualType elementType, 2357 CharUnits elementAlign, 2358 Destroyer *destroyer) { 2359 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup, 2360 arrayBegin, arrayEndPointer, 2361 elementType, elementAlign, 2362 destroyer); 2363 } 2364 2365 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy 2366 /// already-constructed elements of the given array. The cleanup 2367 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock. 2368 /// 2369 /// \param elementType - the immediate element type of the array; 2370 /// possibly still an array type 2371 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 2372 llvm::Value *arrayEnd, 2373 QualType elementType, 2374 CharUnits elementAlign, 2375 Destroyer *destroyer) { 2376 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup, 2377 arrayBegin, arrayEnd, 2378 elementType, elementAlign, 2379 destroyer); 2380 } 2381 2382 /// Lazily declare the @llvm.lifetime.start intrinsic. 2383 llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() { 2384 if (LifetimeStartFn) 2385 return LifetimeStartFn; 2386 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(), 2387 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy); 2388 return LifetimeStartFn; 2389 } 2390 2391 /// Lazily declare the @llvm.lifetime.end intrinsic. 2392 llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() { 2393 if (LifetimeEndFn) 2394 return LifetimeEndFn; 2395 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(), 2396 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy); 2397 return LifetimeEndFn; 2398 } 2399 2400 namespace { 2401 /// A cleanup to perform a release of an object at the end of a 2402 /// function. This is used to balance out the incoming +1 of a 2403 /// ns_consumed argument when we can't reasonably do that just by 2404 /// not doing the initial retain for a __block argument. 2405 struct ConsumeARCParameter final : EHScopeStack::Cleanup { 2406 ConsumeARCParameter(llvm::Value *param, 2407 ARCPreciseLifetime_t precise) 2408 : Param(param), Precise(precise) {} 2409 2410 llvm::Value *Param; 2411 ARCPreciseLifetime_t Precise; 2412 2413 void Emit(CodeGenFunction &CGF, Flags flags) override { 2414 CGF.EmitARCRelease(Param, Precise); 2415 } 2416 }; 2417 } // end anonymous namespace 2418 2419 /// Emit an alloca (or GlobalValue depending on target) 2420 /// for the specified parameter and set up LocalDeclMap. 2421 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg, 2422 unsigned ArgNo) { 2423 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl? 2424 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) && 2425 "Invalid argument to EmitParmDecl"); 2426 2427 Arg.getAnyValue()->setName(D.getName()); 2428 2429 QualType Ty = D.getType(); 2430 2431 // Use better IR generation for certain implicit parameters. 2432 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) { 2433 // The only implicit argument a block has is its literal. 2434 // This may be passed as an inalloca'ed value on Windows x86. 2435 if (BlockInfo) { 2436 llvm::Value *V = Arg.isIndirect() 2437 ? Builder.CreateLoad(Arg.getIndirectAddress()) 2438 : Arg.getDirectValue(); 2439 setBlockContextParameter(IPD, ArgNo, V); 2440 return; 2441 } 2442 } 2443 2444 Address DeclPtr = Address::invalid(); 2445 bool DoStore = false; 2446 bool IsScalar = hasScalarEvaluationKind(Ty); 2447 // If we already have a pointer to the argument, reuse the input pointer. 2448 if (Arg.isIndirect()) { 2449 DeclPtr = Arg.getIndirectAddress(); 2450 // If we have a prettier pointer type at this point, bitcast to that. 2451 unsigned AS = DeclPtr.getType()->getAddressSpace(); 2452 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS); 2453 if (DeclPtr.getType() != IRTy) 2454 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName()); 2455 // Indirect argument is in alloca address space, which may be different 2456 // from the default address space. 2457 auto AllocaAS = CGM.getASTAllocaAddressSpace(); 2458 auto *V = DeclPtr.getPointer(); 2459 auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS; 2460 auto DestLangAS = 2461 getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default; 2462 if (SrcLangAS != DestLangAS) { 2463 assert(getContext().getTargetAddressSpace(SrcLangAS) == 2464 CGM.getDataLayout().getAllocaAddrSpace()); 2465 auto DestAS = getContext().getTargetAddressSpace(DestLangAS); 2466 auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS); 2467 DeclPtr = Address(getTargetHooks().performAddrSpaceCast( 2468 *this, V, SrcLangAS, DestLangAS, T, true), 2469 DeclPtr.getAlignment()); 2470 } 2471 2472 // Push a destructor cleanup for this parameter if the ABI requires it. 2473 // Don't push a cleanup in a thunk for a method that will also emit a 2474 // cleanup. 2475 if (hasAggregateEvaluationKind(Ty) && !CurFuncIsThunk && 2476 Ty->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) { 2477 if (QualType::DestructionKind DtorKind = 2478 D.needsDestruction(getContext())) { 2479 assert((DtorKind == QualType::DK_cxx_destructor || 2480 DtorKind == QualType::DK_nontrivial_c_struct) && 2481 "unexpected destructor type"); 2482 pushDestroy(DtorKind, DeclPtr, Ty); 2483 CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] = 2484 EHStack.stable_begin(); 2485 } 2486 } 2487 } else { 2488 // Check if the parameter address is controlled by OpenMP runtime. 2489 Address OpenMPLocalAddr = 2490 getLangOpts().OpenMP 2491 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D) 2492 : Address::invalid(); 2493 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) { 2494 DeclPtr = OpenMPLocalAddr; 2495 } else { 2496 // Otherwise, create a temporary to hold the value. 2497 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D), 2498 D.getName() + ".addr"); 2499 } 2500 DoStore = true; 2501 } 2502 2503 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr); 2504 2505 LValue lv = MakeAddrLValue(DeclPtr, Ty); 2506 if (IsScalar) { 2507 Qualifiers qs = Ty.getQualifiers(); 2508 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) { 2509 // We honor __attribute__((ns_consumed)) for types with lifetime. 2510 // For __strong, it's handled by just skipping the initial retain; 2511 // otherwise we have to balance out the initial +1 with an extra 2512 // cleanup to do the release at the end of the function. 2513 bool isConsumed = D.hasAttr<NSConsumedAttr>(); 2514 2515 // If a parameter is pseudo-strong then we can omit the implicit retain. 2516 if (D.isARCPseudoStrong()) { 2517 assert(lt == Qualifiers::OCL_Strong && 2518 "pseudo-strong variable isn't strong?"); 2519 assert(qs.hasConst() && "pseudo-strong variable should be const!"); 2520 lt = Qualifiers::OCL_ExplicitNone; 2521 } 2522 2523 // Load objects passed indirectly. 2524 if (Arg.isIndirect() && !ArgVal) 2525 ArgVal = Builder.CreateLoad(DeclPtr); 2526 2527 if (lt == Qualifiers::OCL_Strong) { 2528 if (!isConsumed) { 2529 if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 2530 // use objc_storeStrong(&dest, value) for retaining the 2531 // object. But first, store a null into 'dest' because 2532 // objc_storeStrong attempts to release its old value. 2533 llvm::Value *Null = CGM.EmitNullConstant(D.getType()); 2534 EmitStoreOfScalar(Null, lv, /* isInitialization */ true); 2535 EmitARCStoreStrongCall(lv.getAddress(*this), ArgVal, true); 2536 DoStore = false; 2537 } 2538 else 2539 // Don't use objc_retainBlock for block pointers, because we 2540 // don't want to Block_copy something just because we got it 2541 // as a parameter. 2542 ArgVal = EmitARCRetainNonBlock(ArgVal); 2543 } 2544 } else { 2545 // Push the cleanup for a consumed parameter. 2546 if (isConsumed) { 2547 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>() 2548 ? ARCPreciseLifetime : ARCImpreciseLifetime); 2549 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal, 2550 precise); 2551 } 2552 2553 if (lt == Qualifiers::OCL_Weak) { 2554 EmitARCInitWeak(DeclPtr, ArgVal); 2555 DoStore = false; // The weak init is a store, no need to do two. 2556 } 2557 } 2558 2559 // Enter the cleanup scope. 2560 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt); 2561 } 2562 } 2563 2564 // Store the initial value into the alloca. 2565 if (DoStore) 2566 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true); 2567 2568 setAddrOfLocalVar(&D, DeclPtr); 2569 2570 // Emit debug info for param declarations in non-thunk functions. 2571 if (CGDebugInfo *DI = getDebugInfo()) { 2572 if (CGM.getCodeGenOpts().hasReducedDebugInfo() && !CurFuncIsThunk) { 2573 llvm::DILocalVariable *DILocalVar = DI->EmitDeclareOfArgVariable( 2574 &D, DeclPtr.getPointer(), ArgNo, Builder); 2575 if (const auto *Var = dyn_cast_or_null<ParmVarDecl>(&D)) 2576 DI->getParamDbgMappings().insert({Var, DILocalVar}); 2577 } 2578 } 2579 2580 if (D.hasAttr<AnnotateAttr>()) 2581 EmitVarAnnotations(&D, DeclPtr.getPointer()); 2582 2583 // We can only check return value nullability if all arguments to the 2584 // function satisfy their nullability preconditions. This makes it necessary 2585 // to emit null checks for args in the function body itself. 2586 if (requiresReturnValueNullabilityCheck()) { 2587 auto Nullability = Ty->getNullability(getContext()); 2588 if (Nullability && *Nullability == NullabilityKind::NonNull) { 2589 SanitizerScope SanScope(this); 2590 RetValNullabilityPrecondition = 2591 Builder.CreateAnd(RetValNullabilityPrecondition, 2592 Builder.CreateIsNotNull(Arg.getAnyValue())); 2593 } 2594 } 2595 } 2596 2597 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, 2598 CodeGenFunction *CGF) { 2599 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed())) 2600 return; 2601 getOpenMPRuntime().emitUserDefinedReduction(CGF, D); 2602 } 2603 2604 void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D, 2605 CodeGenFunction *CGF) { 2606 if (!LangOpts.OpenMP || LangOpts.OpenMPSimd || 2607 (!LangOpts.EmitAllDecls && !D->isUsed())) 2608 return; 2609 getOpenMPRuntime().emitUserDefinedMapper(D, CGF); 2610 } 2611 2612 void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) { 2613 getOpenMPRuntime().processRequiresDirective(D); 2614 } 2615