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