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