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