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