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