1 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code to emit Decl nodes as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CGBlocks.h" 15 #include "CGCXXABI.h" 16 #include "CGCleanup.h" 17 #include "CGDebugInfo.h" 18 #include "CGOpenCLRuntime.h" 19 #include "CGOpenMPRuntime.h" 20 #include "CodeGenFunction.h" 21 #include "CodeGenModule.h" 22 #include "ConstantEmitter.h" 23 #include "TargetInfo.h" 24 #include "clang/AST/ASTContext.h" 25 #include "clang/AST/CharUnits.h" 26 #include "clang/AST/Decl.h" 27 #include "clang/AST/DeclObjC.h" 28 #include "clang/AST/DeclOpenMP.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/CodeGen/CGFunctionInfo.h" 32 #include "clang/Frontend/CodeGenOptions.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::Empty: 108 // None of these decls require codegen support. 109 return; 110 111 case Decl::NamespaceAlias: 112 if (CGDebugInfo *DI = getDebugInfo()) 113 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D)); 114 return; 115 case Decl::Using: // using X; [C++] 116 if (CGDebugInfo *DI = getDebugInfo()) 117 DI->EmitUsingDecl(cast<UsingDecl>(D)); 118 return; 119 case Decl::UsingPack: 120 for (auto *Using : cast<UsingPackDecl>(D).expansions()) 121 EmitDecl(*Using); 122 return; 123 case Decl::UsingDirective: // using namespace X; [C++] 124 if (CGDebugInfo *DI = getDebugInfo()) 125 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D)); 126 return; 127 case Decl::Var: 128 case Decl::Decomposition: { 129 const VarDecl &VD = cast<VarDecl>(D); 130 assert(VD.isLocalVarDecl() && 131 "Should not see file-scope variables inside a function!"); 132 EmitVarDecl(VD); 133 if (auto *DD = dyn_cast<DecompositionDecl>(&VD)) 134 for (auto *B : DD->bindings()) 135 if (auto *HD = B->getHoldingVar()) 136 EmitVarDecl(*HD); 137 return; 138 } 139 140 case Decl::OMPDeclareReduction: 141 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this); 142 143 case Decl::Typedef: // typedef int X; 144 case Decl::TypeAlias: { // using X = int; [C++0x] 145 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D); 146 QualType Ty = TD.getUnderlyingType(); 147 148 if (Ty->isVariablyModifiedType()) 149 EmitVariablyModifiedType(Ty); 150 } 151 } 152 } 153 154 /// EmitVarDecl - This method handles emission of any variable declaration 155 /// inside a function, including static vars etc. 156 void CodeGenFunction::EmitVarDecl(const VarDecl &D) { 157 if (D.hasExternalStorage()) 158 // Don't emit it now, allow it to be emitted lazily on its first use. 159 return; 160 161 // Some function-scope variable does not have static storage but still 162 // needs to be emitted like a static variable, e.g. a function-scope 163 // variable in constant address space in OpenCL. 164 if (D.getStorageDuration() != SD_Automatic) { 165 // Static sampler variables translated to function calls. 166 if (D.getType()->isSamplerT()) 167 return; 168 169 llvm::GlobalValue::LinkageTypes Linkage = 170 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false); 171 172 // FIXME: We need to force the emission/use of a guard variable for 173 // some variables even if we can constant-evaluate them because 174 // we can't guarantee every translation unit will constant-evaluate them. 175 176 return EmitStaticVarDecl(D, Linkage); 177 } 178 179 if (D.getType().getAddressSpace() == LangAS::opencl_local) 180 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D); 181 182 assert(D.hasLocalStorage()); 183 return EmitAutoVarDecl(D); 184 } 185 186 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) { 187 if (CGM.getLangOpts().CPlusPlus) 188 return CGM.getMangledName(&D).str(); 189 190 // If this isn't C++, we don't need a mangled name, just a pretty one. 191 assert(!D.isExternallyVisible() && "name shouldn't matter"); 192 std::string ContextName; 193 const DeclContext *DC = D.getDeclContext(); 194 if (auto *CD = dyn_cast<CapturedDecl>(DC)) 195 DC = cast<DeclContext>(CD->getNonClosureContext()); 196 if (const auto *FD = dyn_cast<FunctionDecl>(DC)) 197 ContextName = CGM.getMangledName(FD); 198 else if (const auto *BD = dyn_cast<BlockDecl>(DC)) 199 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD); 200 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC)) 201 ContextName = OMD->getSelector().getAsString(); 202 else 203 llvm_unreachable("Unknown context for static var decl"); 204 205 ContextName += "." + D.getNameAsString(); 206 return ContextName; 207 } 208 209 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl( 210 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) { 211 // In general, we don't always emit static var decls once before we reference 212 // them. It is possible to reference them before emitting the function that 213 // contains them, and it is possible to emit the containing function multiple 214 // times. 215 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D]) 216 return ExistingGV; 217 218 QualType Ty = D.getType(); 219 assert(Ty->isConstantSizeType() && "VLAs can't be static"); 220 221 // Use the label if the variable is renamed with the asm-label extension. 222 std::string Name; 223 if (D.hasAttr<AsmLabelAttr>()) 224 Name = getMangledName(&D); 225 else 226 Name = getStaticDeclName(*this, D); 227 228 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty); 229 LangAS AS = GetGlobalVarAddressSpace(&D); 230 unsigned TargetAS = getContext().getTargetAddressSpace(AS); 231 232 // Local address space cannot have an initializer. 233 llvm::Constant *Init = nullptr; 234 if (Ty.getAddressSpace() != LangAS::opencl_local) 235 Init = EmitNullConstant(Ty); 236 else 237 Init = llvm::UndefValue::get(LTy); 238 239 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 240 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name, 241 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 242 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity()); 243 244 if (supportsCOMDAT() && GV->isWeakForLinker()) 245 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 246 247 if (D.getTLSKind()) 248 setTLSMode(GV, D); 249 250 setGVProperties(GV, &D); 251 252 // Make sure the result is of the correct type. 253 LangAS ExpectedAS = Ty.getAddressSpace(); 254 llvm::Constant *Addr = GV; 255 if (AS != ExpectedAS) { 256 Addr = getTargetCodeGenInfo().performAddrSpaceCast( 257 *this, GV, AS, ExpectedAS, 258 LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS))); 259 } 260 261 setStaticLocalDeclAddress(&D, Addr); 262 263 // Ensure that the static local gets initialized by making sure the parent 264 // function gets emitted eventually. 265 const Decl *DC = cast<Decl>(D.getDeclContext()); 266 267 // We can't name blocks or captured statements directly, so try to emit their 268 // parents. 269 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) { 270 DC = DC->getNonClosureContext(); 271 // FIXME: Ensure that global blocks get emitted. 272 if (!DC) 273 return Addr; 274 } 275 276 GlobalDecl GD; 277 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC)) 278 GD = GlobalDecl(CD, Ctor_Base); 279 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC)) 280 GD = GlobalDecl(DD, Dtor_Base); 281 else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) 282 GD = GlobalDecl(FD); 283 else { 284 // Don't do anything for Obj-C method decls or global closures. We should 285 // never defer them. 286 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl"); 287 } 288 if (GD.getDecl()) { 289 // Disable emission of the parent function for the OpenMP device codegen. 290 CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this); 291 (void)GetAddrOfGlobal(GD); 292 } 293 294 return Addr; 295 } 296 297 /// hasNontrivialDestruction - Determine whether a type's destruction is 298 /// non-trivial. If so, and the variable uses static initialization, we must 299 /// register its destructor to run on exit. 300 static bool hasNontrivialDestruction(QualType T) { 301 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 302 return RD && !RD->hasTrivialDestructor(); 303 } 304 305 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 306 /// global variable that has already been created for it. If the initializer 307 /// has a different type than GV does, this may free GV and return a different 308 /// one. Otherwise it just returns GV. 309 llvm::GlobalVariable * 310 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D, 311 llvm::GlobalVariable *GV) { 312 ConstantEmitter emitter(*this); 313 llvm::Constant *Init = emitter.tryEmitForInitializer(D); 314 315 // If constant emission failed, then this should be a C++ static 316 // initializer. 317 if (!Init) { 318 if (!getLangOpts().CPlusPlus) 319 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression"); 320 else if (HaveInsertPoint()) { 321 // Since we have a static initializer, this global variable can't 322 // be constant. 323 GV->setConstant(false); 324 325 EmitCXXGuardedInit(D, GV, /*PerformInit*/true); 326 } 327 return GV; 328 } 329 330 // The initializer may differ in type from the global. Rewrite 331 // the global to match the initializer. (We have to do this 332 // because some types, like unions, can't be completely represented 333 // in the LLVM type system.) 334 if (GV->getType()->getElementType() != Init->getType()) { 335 llvm::GlobalVariable *OldGV = GV; 336 337 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), 338 OldGV->isConstant(), 339 OldGV->getLinkage(), Init, "", 340 /*InsertBefore*/ OldGV, 341 OldGV->getThreadLocalMode(), 342 CGM.getContext().getTargetAddressSpace(D.getType())); 343 GV->setVisibility(OldGV->getVisibility()); 344 GV->setDSOLocal(OldGV->isDSOLocal()); 345 GV->setComdat(OldGV->getComdat()); 346 347 // Steal the name of the old global 348 GV->takeName(OldGV); 349 350 // Replace all uses of the old global with the new global 351 llvm::Constant *NewPtrForOldDecl = 352 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 353 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 354 355 // Erase the old global, since it is no longer used. 356 OldGV->eraseFromParent(); 357 } 358 359 GV->setConstant(CGM.isTypeConstant(D.getType(), true)); 360 GV->setInitializer(Init); 361 362 emitter.finalize(GV); 363 364 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) { 365 // We have a constant initializer, but a nontrivial destructor. We still 366 // need to perform a guarded "initialization" in order to register the 367 // destructor. 368 EmitCXXGuardedInit(D, GV, /*PerformInit*/false); 369 } 370 371 return GV; 372 } 373 374 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D, 375 llvm::GlobalValue::LinkageTypes Linkage) { 376 // Check to see if we already have a global variable for this 377 // declaration. This can happen when double-emitting function 378 // bodies, e.g. with complete and base constructors. 379 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage); 380 CharUnits alignment = getContext().getDeclAlign(&D); 381 382 // Store into LocalDeclMap before generating initializer to handle 383 // circular references. 384 setAddrOfLocalVar(&D, Address(addr, alignment)); 385 386 // We can't have a VLA here, but we can have a pointer to a VLA, 387 // even though that doesn't really make any sense. 388 // Make sure to evaluate VLA bounds now so that we have them for later. 389 if (D.getType()->isVariablyModifiedType()) 390 EmitVariablyModifiedType(D.getType()); 391 392 // Save the type in case adding the initializer forces a type change. 393 llvm::Type *expectedType = addr->getType(); 394 395 llvm::GlobalVariable *var = 396 cast<llvm::GlobalVariable>(addr->stripPointerCasts()); 397 398 // CUDA's local and local static __shared__ variables should not 399 // have any non-empty initializers. This is ensured by Sema. 400 // Whatever initializer such variable may have when it gets here is 401 // a no-op and should not be emitted. 402 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 403 D.hasAttr<CUDASharedAttr>(); 404 // If this value has an initializer, emit it. 405 if (D.getInit() && !isCudaSharedVar) 406 var = AddInitializerToStaticVarDecl(D, var); 407 408 var->setAlignment(alignment.getQuantity()); 409 410 if (D.hasAttr<AnnotateAttr>()) 411 CGM.AddGlobalAnnotations(&D, var); 412 413 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>()) 414 var->addAttribute("bss-section", SA->getName()); 415 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>()) 416 var->addAttribute("data-section", SA->getName()); 417 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>()) 418 var->addAttribute("rodata-section", SA->getName()); 419 420 if (const SectionAttr *SA = D.getAttr<SectionAttr>()) 421 var->setSection(SA->getName()); 422 423 if (D.hasAttr<UsedAttr>()) 424 CGM.addUsedGlobal(var); 425 426 // We may have to cast the constant because of the initializer 427 // mismatch above. 428 // 429 // FIXME: It is really dangerous to store this in the map; if anyone 430 // RAUW's the GV uses of this constant will be invalid. 431 llvm::Constant *castedAddr = 432 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType); 433 if (var != castedAddr) 434 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment); 435 CGM.setStaticLocalDeclAddress(&D, castedAddr); 436 437 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D); 438 439 // Emit global variable debug descriptor for static vars. 440 CGDebugInfo *DI = getDebugInfo(); 441 if (DI && 442 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) { 443 DI->setLocation(D.getLocation()); 444 DI->EmitGlobalVariable(var, &D); 445 } 446 } 447 448 namespace { 449 struct DestroyObject final : EHScopeStack::Cleanup { 450 DestroyObject(Address addr, QualType type, 451 CodeGenFunction::Destroyer *destroyer, 452 bool useEHCleanupForArray) 453 : addr(addr), type(type), destroyer(destroyer), 454 useEHCleanupForArray(useEHCleanupForArray) {} 455 456 Address addr; 457 QualType type; 458 CodeGenFunction::Destroyer *destroyer; 459 bool useEHCleanupForArray; 460 461 void Emit(CodeGenFunction &CGF, Flags flags) override { 462 // Don't use an EH cleanup recursively from an EH cleanup. 463 bool useEHCleanupForArray = 464 flags.isForNormalCleanup() && this->useEHCleanupForArray; 465 466 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray); 467 } 468 }; 469 470 struct DestroyNRVOVariable final : EHScopeStack::Cleanup { 471 DestroyNRVOVariable(Address addr, 472 const CXXDestructorDecl *Dtor, 473 llvm::Value *NRVOFlag) 474 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {} 475 476 const CXXDestructorDecl *Dtor; 477 llvm::Value *NRVOFlag; 478 Address Loc; 479 480 void Emit(CodeGenFunction &CGF, Flags flags) override { 481 // Along the exceptions path we always execute the dtor. 482 bool NRVO = flags.isForNormalCleanup() && NRVOFlag; 483 484 llvm::BasicBlock *SkipDtorBB = nullptr; 485 if (NRVO) { 486 // If we exited via NRVO, we skip the destructor call. 487 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused"); 488 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor"); 489 llvm::Value *DidNRVO = 490 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val"); 491 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB); 492 CGF.EmitBlock(RunDtorBB); 493 } 494 495 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 496 /*ForVirtualBase=*/false, 497 /*Delegating=*/false, 498 Loc); 499 500 if (NRVO) CGF.EmitBlock(SkipDtorBB); 501 } 502 }; 503 504 struct CallStackRestore final : EHScopeStack::Cleanup { 505 Address Stack; 506 CallStackRestore(Address Stack) : Stack(Stack) {} 507 void Emit(CodeGenFunction &CGF, Flags flags) override { 508 llvm::Value *V = CGF.Builder.CreateLoad(Stack); 509 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 510 CGF.Builder.CreateCall(F, V); 511 } 512 }; 513 514 struct ExtendGCLifetime final : EHScopeStack::Cleanup { 515 const VarDecl &Var; 516 ExtendGCLifetime(const VarDecl *var) : Var(*var) {} 517 518 void Emit(CodeGenFunction &CGF, Flags flags) override { 519 // Compute the address of the local variable, in case it's a 520 // byref or something. 521 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false, 522 Var.getType(), VK_LValue, SourceLocation()); 523 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE), 524 SourceLocation()); 525 CGF.EmitExtendGCLifetime(value); 526 } 527 }; 528 529 struct CallCleanupFunction final : EHScopeStack::Cleanup { 530 llvm::Constant *CleanupFn; 531 const CGFunctionInfo &FnInfo; 532 const VarDecl &Var; 533 534 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info, 535 const VarDecl *Var) 536 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {} 537 538 void Emit(CodeGenFunction &CGF, Flags flags) override { 539 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false, 540 Var.getType(), VK_LValue, SourceLocation()); 541 // Compute the address of the local variable, in case it's a byref 542 // or something. 543 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(); 544 545 // In some cases, the type of the function argument will be different from 546 // the type of the pointer. An example of this is 547 // void f(void* arg); 548 // __attribute__((cleanup(f))) void *g; 549 // 550 // To fix this we insert a bitcast here. 551 QualType ArgTy = FnInfo.arg_begin()->type; 552 llvm::Value *Arg = 553 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy)); 554 555 CallArgList Args; 556 Args.add(RValue::get(Arg), 557 CGF.getContext().getPointerType(Var.getType())); 558 auto Callee = CGCallee::forDirect(CleanupFn); 559 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args); 560 } 561 }; 562 } // end anonymous namespace 563 564 /// EmitAutoVarWithLifetime - Does the setup required for an automatic 565 /// variable with lifetime. 566 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var, 567 Address addr, 568 Qualifiers::ObjCLifetime lifetime) { 569 switch (lifetime) { 570 case Qualifiers::OCL_None: 571 llvm_unreachable("present but none"); 572 573 case Qualifiers::OCL_ExplicitNone: 574 // nothing to do 575 break; 576 577 case Qualifiers::OCL_Strong: { 578 CodeGenFunction::Destroyer *destroyer = 579 (var.hasAttr<ObjCPreciseLifetimeAttr>() 580 ? CodeGenFunction::destroyARCStrongPrecise 581 : CodeGenFunction::destroyARCStrongImprecise); 582 583 CleanupKind cleanupKind = CGF.getARCCleanupKind(); 584 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer, 585 cleanupKind & EHCleanup); 586 break; 587 } 588 case Qualifiers::OCL_Autoreleasing: 589 // nothing to do 590 break; 591 592 case Qualifiers::OCL_Weak: 593 // __weak objects always get EH cleanups; otherwise, exceptions 594 // could cause really nasty crashes instead of mere leaks. 595 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(), 596 CodeGenFunction::destroyARCWeak, 597 /*useEHCleanup*/ true); 598 break; 599 } 600 } 601 602 static bool isAccessedBy(const VarDecl &var, const Stmt *s) { 603 if (const Expr *e = dyn_cast<Expr>(s)) { 604 // Skip the most common kinds of expressions that make 605 // hierarchy-walking expensive. 606 s = e = e->IgnoreParenCasts(); 607 608 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) 609 return (ref->getDecl() == &var); 610 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) { 611 const BlockDecl *block = be->getBlockDecl(); 612 for (const auto &I : block->captures()) { 613 if (I.getVariable() == &var) 614 return true; 615 } 616 } 617 } 618 619 for (const Stmt *SubStmt : s->children()) 620 // SubStmt might be null; as in missing decl or conditional of an if-stmt. 621 if (SubStmt && isAccessedBy(var, SubStmt)) 622 return true; 623 624 return false; 625 } 626 627 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) { 628 if (!decl) return false; 629 if (!isa<VarDecl>(decl)) return false; 630 const VarDecl *var = cast<VarDecl>(decl); 631 return isAccessedBy(*var, e); 632 } 633 634 static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF, 635 const LValue &destLV, const Expr *init) { 636 bool needsCast = false; 637 638 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) { 639 switch (castExpr->getCastKind()) { 640 // Look through casts that don't require representation changes. 641 case CK_NoOp: 642 case CK_BitCast: 643 case CK_BlockPointerToObjCPointerCast: 644 needsCast = true; 645 break; 646 647 // If we find an l-value to r-value cast from a __weak variable, 648 // emit this operation as a copy or move. 649 case CK_LValueToRValue: { 650 const Expr *srcExpr = castExpr->getSubExpr(); 651 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak) 652 return false; 653 654 // Emit the source l-value. 655 LValue srcLV = CGF.EmitLValue(srcExpr); 656 657 // Handle a formal type change to avoid asserting. 658 auto srcAddr = srcLV.getAddress(); 659 if (needsCast) { 660 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr, 661 destLV.getAddress().getElementType()); 662 } 663 664 // If it was an l-value, use objc_copyWeak. 665 if (srcExpr->getValueKind() == VK_LValue) { 666 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr); 667 } else { 668 assert(srcExpr->getValueKind() == VK_XValue); 669 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr); 670 } 671 return true; 672 } 673 674 // Stop at anything else. 675 default: 676 return false; 677 } 678 679 init = castExpr->getSubExpr(); 680 } 681 return false; 682 } 683 684 static void drillIntoBlockVariable(CodeGenFunction &CGF, 685 LValue &lvalue, 686 const VarDecl *var) { 687 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var)); 688 } 689 690 void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, 691 SourceLocation Loc) { 692 if (!SanOpts.has(SanitizerKind::NullabilityAssign)) 693 return; 694 695 auto Nullability = LHS.getType()->getNullability(getContext()); 696 if (!Nullability || *Nullability != NullabilityKind::NonNull) 697 return; 698 699 // Check if the right hand side of the assignment is nonnull, if the left 700 // hand side must be nonnull. 701 SanitizerScope SanScope(this); 702 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS); 703 llvm::Constant *StaticData[] = { 704 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()), 705 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused. 706 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)}; 707 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}}, 708 SanitizerHandler::TypeMismatch, StaticData, RHS); 709 } 710 711 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D, 712 LValue lvalue, bool capturedByInit) { 713 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime(); 714 if (!lifetime) { 715 llvm::Value *value = EmitScalarExpr(init); 716 if (capturedByInit) 717 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 718 EmitNullabilityCheck(lvalue, value, init->getExprLoc()); 719 EmitStoreThroughLValue(RValue::get(value), lvalue, true); 720 return; 721 } 722 723 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init)) 724 init = DIE->getExpr(); 725 726 // If we're emitting a value with lifetime, we have to do the 727 // initialization *before* we leave the cleanup scopes. 728 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) { 729 enterFullExpression(ewc); 730 init = ewc->getSubExpr(); 731 } 732 CodeGenFunction::RunCleanupsScope Scope(*this); 733 734 // We have to maintain the illusion that the variable is 735 // zero-initialized. If the variable might be accessed in its 736 // initializer, zero-initialize before running the initializer, then 737 // actually perform the initialization with an assign. 738 bool accessedByInit = false; 739 if (lifetime != Qualifiers::OCL_ExplicitNone) 740 accessedByInit = (capturedByInit || isAccessedBy(D, init)); 741 if (accessedByInit) { 742 LValue tempLV = lvalue; 743 // Drill down to the __block object if necessary. 744 if (capturedByInit) { 745 // We can use a simple GEP for this because it can't have been 746 // moved yet. 747 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(), 748 cast<VarDecl>(D), 749 /*follow*/ false)); 750 } 751 752 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType()); 753 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType()); 754 755 // If __weak, we want to use a barrier under certain conditions. 756 if (lifetime == Qualifiers::OCL_Weak) 757 EmitARCInitWeak(tempLV.getAddress(), zero); 758 759 // Otherwise just do a simple store. 760 else 761 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true); 762 } 763 764 // Emit the initializer. 765 llvm::Value *value = nullptr; 766 767 switch (lifetime) { 768 case Qualifiers::OCL_None: 769 llvm_unreachable("present but none"); 770 771 case Qualifiers::OCL_ExplicitNone: 772 value = EmitARCUnsafeUnretainedScalarExpr(init); 773 break; 774 775 case Qualifiers::OCL_Strong: { 776 value = EmitARCRetainScalarExpr(init); 777 break; 778 } 779 780 case Qualifiers::OCL_Weak: { 781 // If it's not accessed by the initializer, try to emit the 782 // initialization with a copy or move. 783 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) { 784 return; 785 } 786 787 // No way to optimize a producing initializer into this. It's not 788 // worth optimizing for, because the value will immediately 789 // disappear in the common case. 790 value = EmitScalarExpr(init); 791 792 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 793 if (accessedByInit) 794 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true); 795 else 796 EmitARCInitWeak(lvalue.getAddress(), value); 797 return; 798 } 799 800 case Qualifiers::OCL_Autoreleasing: 801 value = EmitARCRetainAutoreleaseScalarExpr(init); 802 break; 803 } 804 805 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 806 807 EmitNullabilityCheck(lvalue, value, init->getExprLoc()); 808 809 // If the variable might have been accessed by its initializer, we 810 // might have to initialize with a barrier. We have to do this for 811 // both __weak and __strong, but __weak got filtered out above. 812 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) { 813 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc()); 814 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true); 815 EmitARCRelease(oldValue, ARCImpreciseLifetime); 816 return; 817 } 818 819 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true); 820 } 821 822 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the 823 /// non-zero parts of the specified initializer with equal or fewer than 824 /// NumStores scalar stores. 825 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init, 826 unsigned &NumStores) { 827 // Zero and Undef never requires any extra stores. 828 if (isa<llvm::ConstantAggregateZero>(Init) || 829 isa<llvm::ConstantPointerNull>(Init) || 830 isa<llvm::UndefValue>(Init)) 831 return true; 832 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) || 833 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) || 834 isa<llvm::ConstantExpr>(Init)) 835 return Init->isNullValue() || NumStores--; 836 837 // See if we can emit each element. 838 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) { 839 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 840 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i)); 841 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores)) 842 return false; 843 } 844 return true; 845 } 846 847 if (llvm::ConstantDataSequential *CDS = 848 dyn_cast<llvm::ConstantDataSequential>(Init)) { 849 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 850 llvm::Constant *Elt = CDS->getElementAsConstant(i); 851 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores)) 852 return false; 853 } 854 return true; 855 } 856 857 // Anything else is hard and scary. 858 return false; 859 } 860 861 /// emitStoresForInitAfterMemset - For inits that 862 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar 863 /// stores that would be required. 864 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc, 865 bool isVolatile, CGBuilderTy &Builder) { 866 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) && 867 "called emitStoresForInitAfterMemset for zero or undef value."); 868 869 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) || 870 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) || 871 isa<llvm::ConstantExpr>(Init)) { 872 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile); 873 return; 874 } 875 876 if (llvm::ConstantDataSequential *CDS = 877 dyn_cast<llvm::ConstantDataSequential>(Init)) { 878 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 879 llvm::Constant *Elt = CDS->getElementAsConstant(i); 880 881 // If necessary, get a pointer to the element and emit it. 882 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt)) 883 emitStoresForInitAfterMemset( 884 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i), 885 isVolatile, Builder); 886 } 887 return; 888 } 889 890 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) && 891 "Unknown value type!"); 892 893 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 894 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i)); 895 896 // If necessary, get a pointer to the element and emit it. 897 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt)) 898 emitStoresForInitAfterMemset( 899 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i), 900 isVolatile, Builder); 901 } 902 } 903 904 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset 905 /// plus some stores to initialize a local variable instead of using a memcpy 906 /// from a constant global. It is beneficial to use memset if the global is all 907 /// zeros, or mostly zeros and large. 908 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init, 909 uint64_t GlobalSize) { 910 // If a global is all zeros, always use a memset. 911 if (isa<llvm::ConstantAggregateZero>(Init)) return true; 912 913 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large, 914 // do it if it will require 6 or fewer scalar stores. 915 // TODO: Should budget depends on the size? Avoiding a large global warrants 916 // plopping in more stores. 917 unsigned StoreBudget = 6; 918 uint64_t SizeLimit = 32; 919 920 return GlobalSize > SizeLimit && 921 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget); 922 } 923 924 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a 925 /// variable declaration with auto, register, or no storage class specifier. 926 /// These turn into simple stack objects, or GlobalValues depending on target. 927 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) { 928 AutoVarEmission emission = EmitAutoVarAlloca(D); 929 EmitAutoVarInit(emission); 930 EmitAutoVarCleanups(emission); 931 } 932 933 /// Emit a lifetime.begin marker if some criteria are satisfied. 934 /// \return a pointer to the temporary size Value if a marker was emitted, null 935 /// otherwise 936 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size, 937 llvm::Value *Addr) { 938 if (!ShouldEmitLifetimeMarkers) 939 return nullptr; 940 941 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size); 942 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy); 943 llvm::CallInst *C = 944 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr}); 945 C->setDoesNotThrow(); 946 return SizeV; 947 } 948 949 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) { 950 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy); 951 llvm::CallInst *C = 952 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr}); 953 C->setDoesNotThrow(); 954 } 955 956 void CodeGenFunction::EmitAndRegisterVariableArrayDimensions( 957 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) { 958 // For each dimension stores its QualType and corresponding 959 // size-expression Value. 960 SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions; 961 962 // Break down the array into individual dimensions. 963 QualType Type1D = D.getType(); 964 while (getContext().getAsVariableArrayType(Type1D)) { 965 auto VlaSize = getVLAElements1D(Type1D); 966 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts)) 967 Dimensions.emplace_back(C, Type1D.getUnqualifiedType()); 968 else { 969 auto SizeExprAddr = CreateDefaultAlignTempAlloca( 970 VlaSize.NumElts->getType(), "__vla_expr"); 971 Builder.CreateStore(VlaSize.NumElts, SizeExprAddr); 972 Dimensions.emplace_back(SizeExprAddr.getPointer(), 973 Type1D.getUnqualifiedType()); 974 } 975 Type1D = VlaSize.Type; 976 } 977 978 if (!EmitDebugInfo) 979 return; 980 981 // Register each dimension's size-expression with a DILocalVariable, 982 // so that it can be used by CGDebugInfo when instantiating a DISubrange 983 // to describe this array. 984 for (auto &VlaSize : Dimensions) { 985 llvm::Metadata *MD; 986 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts)) 987 MD = llvm::ConstantAsMetadata::get(C); 988 else { 989 // Create an artificial VarDecl to generate debug info for. 990 IdentifierInfo &NameIdent = getContext().Idents.getOwn( 991 cast<llvm::AllocaInst>(VlaSize.NumElts)->getName()); 992 auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType(); 993 auto QT = getContext().getIntTypeForBitwidth( 994 VlaExprTy->getScalarSizeInBits(), false); 995 auto *ArtificialDecl = VarDecl::Create( 996 getContext(), const_cast<DeclContext *>(D.getDeclContext()), 997 D.getLocation(), D.getLocation(), &NameIdent, QT, 998 getContext().CreateTypeSourceInfo(QT), SC_Auto); 999 ArtificialDecl->setImplicit(); 1000 1001 MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts, 1002 Builder); 1003 } 1004 assert(MD && "No Size expression debug node created"); 1005 DI->registerVLASizeExpression(VlaSize.Type, MD); 1006 } 1007 } 1008 1009 /// EmitAutoVarAlloca - Emit the alloca and debug information for a 1010 /// local variable. Does not emit initialization or destruction. 1011 CodeGenFunction::AutoVarEmission 1012 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) { 1013 QualType Ty = D.getType(); 1014 assert( 1015 Ty.getAddressSpace() == LangAS::Default || 1016 (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL)); 1017 1018 AutoVarEmission emission(D); 1019 1020 bool isByRef = D.hasAttr<BlocksAttr>(); 1021 emission.IsByRef = isByRef; 1022 1023 CharUnits alignment = getContext().getDeclAlign(&D); 1024 1025 // If the type is variably-modified, emit all the VLA sizes for it. 1026 if (Ty->isVariablyModifiedType()) 1027 EmitVariablyModifiedType(Ty); 1028 1029 auto *DI = getDebugInfo(); 1030 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().getDebugInfo() >= 1031 codegenoptions::LimitedDebugInfo; 1032 1033 Address address = Address::invalid(); 1034 if (Ty->isConstantSizeType()) { 1035 bool NRVO = getLangOpts().ElideConstructors && 1036 D.isNRVOVariable(); 1037 1038 // If this value is an array or struct with a statically determinable 1039 // constant initializer, there are optimizations we can do. 1040 // 1041 // TODO: We should constant-evaluate the initializer of any variable, 1042 // as long as it is initialized by a constant expression. Currently, 1043 // isConstantInitializer produces wrong answers for structs with 1044 // reference or bitfield members, and a few other cases, and checking 1045 // for POD-ness protects us from some of these. 1046 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) && 1047 (D.isConstexpr() || 1048 ((Ty.isPODType(getContext()) || 1049 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) && 1050 D.getInit()->isConstantInitializer(getContext(), false)))) { 1051 1052 // If the variable's a const type, and it's neither an NRVO 1053 // candidate nor a __block variable and has no mutable members, 1054 // emit it as a global instead. 1055 // Exception is if a variable is located in non-constant address space 1056 // in OpenCL. 1057 if ((!getLangOpts().OpenCL || 1058 Ty.getAddressSpace() == LangAS::opencl_constant) && 1059 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef && 1060 CGM.isTypeConstant(Ty, true))) { 1061 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage); 1062 1063 // Signal this condition to later callbacks. 1064 emission.Addr = Address::invalid(); 1065 assert(emission.wasEmittedAsGlobal()); 1066 return emission; 1067 } 1068 1069 // Otherwise, tell the initialization code that we're in this case. 1070 emission.IsConstantAggregate = true; 1071 } 1072 1073 // A normal fixed sized variable becomes an alloca in the entry block, 1074 // unless: 1075 // - it's an NRVO variable. 1076 // - we are compiling OpenMP and it's an OpenMP local variable. 1077 1078 Address OpenMPLocalAddr = 1079 getLangOpts().OpenMP 1080 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D) 1081 : Address::invalid(); 1082 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) { 1083 address = OpenMPLocalAddr; 1084 } else if (NRVO) { 1085 // The named return value optimization: allocate this variable in the 1086 // return slot, so that we can elide the copy when returning this 1087 // variable (C++0x [class.copy]p34). 1088 address = ReturnValue; 1089 1090 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) { 1091 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) { 1092 // Create a flag that is used to indicate when the NRVO was applied 1093 // to this variable. Set it to zero to indicate that NRVO was not 1094 // applied. 1095 llvm::Value *Zero = Builder.getFalse(); 1096 Address NRVOFlag = 1097 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo"); 1098 EnsureInsertPoint(); 1099 Builder.CreateStore(Zero, NRVOFlag); 1100 1101 // Record the NRVO flag for this variable. 1102 NRVOFlags[&D] = NRVOFlag.getPointer(); 1103 emission.NRVOFlag = NRVOFlag.getPointer(); 1104 } 1105 } 1106 } else { 1107 CharUnits allocaAlignment; 1108 llvm::Type *allocaTy; 1109 if (isByRef) { 1110 auto &byrefInfo = getBlockByrefInfo(&D); 1111 allocaTy = byrefInfo.Type; 1112 allocaAlignment = byrefInfo.ByrefAlignment; 1113 } else { 1114 allocaTy = ConvertTypeForMem(Ty); 1115 allocaAlignment = alignment; 1116 } 1117 1118 // Create the alloca. Note that we set the name separately from 1119 // building the instruction so that it's there even in no-asserts 1120 // builds. 1121 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName()); 1122 1123 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of 1124 // the catch parameter starts in the catchpad instruction, and we can't 1125 // insert code in those basic blocks. 1126 bool IsMSCatchParam = 1127 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft(); 1128 1129 // Emit a lifetime intrinsic if meaningful. There's no point in doing this 1130 // if we don't have a valid insertion point (?). 1131 if (HaveInsertPoint() && !IsMSCatchParam) { 1132 // If there's a jump into the lifetime of this variable, its lifetime 1133 // gets broken up into several regions in IR, which requires more work 1134 // to handle correctly. For now, just omit the intrinsics; this is a 1135 // rare case, and it's better to just be conservatively correct. 1136 // PR28267. 1137 // 1138 // We have to do this in all language modes if there's a jump past the 1139 // declaration. We also have to do it in C if there's a jump to an 1140 // earlier point in the current block because non-VLA lifetimes begin as 1141 // soon as the containing block is entered, not when its variables 1142 // actually come into scope; suppressing the lifetime annotations 1143 // completely in this case is unnecessarily pessimistic, but again, this 1144 // is rare. 1145 if (!Bypasses.IsBypassed(&D) && 1146 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) { 1147 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy); 1148 emission.SizeForLifetimeMarkers = 1149 EmitLifetimeStart(size, address.getPointer()); 1150 } 1151 } else { 1152 assert(!emission.useLifetimeMarkers()); 1153 } 1154 } 1155 } else { 1156 EnsureInsertPoint(); 1157 1158 if (!DidCallStackSave) { 1159 // Save the stack. 1160 Address Stack = 1161 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack"); 1162 1163 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave); 1164 llvm::Value *V = Builder.CreateCall(F); 1165 Builder.CreateStore(V, Stack); 1166 1167 DidCallStackSave = true; 1168 1169 // Push a cleanup block and restore the stack there. 1170 // FIXME: in general circumstances, this should be an EH cleanup. 1171 pushStackRestore(NormalCleanup, Stack); 1172 } 1173 1174 auto VlaSize = getVLASize(Ty); 1175 llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type); 1176 1177 // Allocate memory for the array. 1178 address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts); 1179 1180 // If we have debug info enabled, properly describe the VLA dimensions for 1181 // this type by registering the vla size expression for each of the 1182 // dimensions. 1183 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo); 1184 } 1185 1186 setAddrOfLocalVar(&D, address); 1187 emission.Addr = address; 1188 1189 // Emit debug info for local var declaration. 1190 if (EmitDebugInfo && HaveInsertPoint()) { 1191 DI->setLocation(D.getLocation()); 1192 (void)DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder); 1193 } 1194 1195 if (D.hasAttr<AnnotateAttr>()) 1196 EmitVarAnnotations(&D, address.getPointer()); 1197 1198 // Make sure we call @llvm.lifetime.end. 1199 if (emission.useLifetimeMarkers()) 1200 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, 1201 emission.getAllocatedAddress(), 1202 emission.getSizeForLifetimeMarkers()); 1203 1204 return emission; 1205 } 1206 1207 /// Determines whether the given __block variable is potentially 1208 /// captured by the given expression. 1209 static bool isCapturedBy(const VarDecl &var, const Expr *e) { 1210 // Skip the most common kinds of expressions that make 1211 // hierarchy-walking expensive. 1212 e = e->IgnoreParenCasts(); 1213 1214 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) { 1215 const BlockDecl *block = be->getBlockDecl(); 1216 for (const auto &I : block->captures()) { 1217 if (I.getVariable() == &var) 1218 return true; 1219 } 1220 1221 // No need to walk into the subexpressions. 1222 return false; 1223 } 1224 1225 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) { 1226 const CompoundStmt *CS = SE->getSubStmt(); 1227 for (const auto *BI : CS->body()) 1228 if (const auto *E = dyn_cast<Expr>(BI)) { 1229 if (isCapturedBy(var, E)) 1230 return true; 1231 } 1232 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) { 1233 // special case declarations 1234 for (const auto *I : DS->decls()) { 1235 if (const auto *VD = dyn_cast<VarDecl>((I))) { 1236 const Expr *Init = VD->getInit(); 1237 if (Init && isCapturedBy(var, Init)) 1238 return true; 1239 } 1240 } 1241 } 1242 else 1243 // FIXME. Make safe assumption assuming arbitrary statements cause capturing. 1244 // Later, provide code to poke into statements for capture analysis. 1245 return true; 1246 return false; 1247 } 1248 1249 for (const Stmt *SubStmt : e->children()) 1250 if (isCapturedBy(var, cast<Expr>(SubStmt))) 1251 return true; 1252 1253 return false; 1254 } 1255 1256 /// \brief Determine whether the given initializer is trivial in the sense 1257 /// that it requires no code to be generated. 1258 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) { 1259 if (!Init) 1260 return true; 1261 1262 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) 1263 if (CXXConstructorDecl *Constructor = Construct->getConstructor()) 1264 if (Constructor->isTrivial() && 1265 Constructor->isDefaultConstructor() && 1266 !Construct->requiresZeroInitialization()) 1267 return true; 1268 1269 return false; 1270 } 1271 1272 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) { 1273 assert(emission.Variable && "emission was not valid!"); 1274 1275 // If this was emitted as a global constant, we're done. 1276 if (emission.wasEmittedAsGlobal()) return; 1277 1278 const VarDecl &D = *emission.Variable; 1279 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation()); 1280 QualType type = D.getType(); 1281 1282 // If this local has an initializer, emit it now. 1283 const Expr *Init = D.getInit(); 1284 1285 // If we are at an unreachable point, we don't need to emit the initializer 1286 // unless it contains a label. 1287 if (!HaveInsertPoint()) { 1288 if (!Init || !ContainsLabel(Init)) return; 1289 EnsureInsertPoint(); 1290 } 1291 1292 // Initialize the structure of a __block variable. 1293 if (emission.IsByRef) 1294 emitByrefStructureInit(emission); 1295 1296 // Initialize the variable here if it doesn't have a initializer and it is a 1297 // C struct that is non-trivial to initialize or an array containing such a 1298 // struct. 1299 if (!Init && 1300 type.isNonTrivialToPrimitiveDefaultInitialize() == 1301 QualType::PDIK_Struct) { 1302 LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type); 1303 if (emission.IsByRef) 1304 drillIntoBlockVariable(*this, Dst, &D); 1305 defaultInitNonTrivialCStructVar(Dst); 1306 return; 1307 } 1308 1309 if (isTrivialInitializer(Init)) 1310 return; 1311 1312 // Check whether this is a byref variable that's potentially 1313 // captured and moved by its own initializer. If so, we'll need to 1314 // emit the initializer first, then copy into the variable. 1315 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init); 1316 1317 Address Loc = 1318 capturedByInit ? emission.Addr : emission.getObjectAddress(*this); 1319 1320 llvm::Constant *constant = nullptr; 1321 if (emission.IsConstantAggregate || D.isConstexpr()) { 1322 assert(!capturedByInit && "constant init contains a capturing block?"); 1323 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D); 1324 } 1325 1326 if (!constant) { 1327 LValue lv = MakeAddrLValue(Loc, type); 1328 lv.setNonGC(true); 1329 return EmitExprAsInit(Init, &D, lv, capturedByInit); 1330 } 1331 1332 if (!emission.IsConstantAggregate) { 1333 // For simple scalar/complex initialization, store the value directly. 1334 LValue lv = MakeAddrLValue(Loc, type); 1335 lv.setNonGC(true); 1336 return EmitStoreThroughLValue(RValue::get(constant), lv, true); 1337 } 1338 1339 // If this is a simple aggregate initialization, we can optimize it 1340 // in various ways. 1341 bool isVolatile = type.isVolatileQualified(); 1342 1343 llvm::Value *SizeVal = 1344 llvm::ConstantInt::get(IntPtrTy, 1345 getContext().getTypeSizeInChars(type).getQuantity()); 1346 1347 llvm::Type *BP = AllocaInt8PtrTy; 1348 if (Loc.getType() != BP) 1349 Loc = Builder.CreateBitCast(Loc, BP); 1350 1351 // If the initializer is all or mostly zeros, codegen with memset then do 1352 // a few stores afterward. 1353 if (shouldUseMemSetPlusStoresToInitialize(constant, 1354 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) { 1355 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal, 1356 isVolatile); 1357 // Zero and undef don't require a stores. 1358 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) { 1359 Loc = Builder.CreateBitCast(Loc, 1360 constant->getType()->getPointerTo(Loc.getAddressSpace())); 1361 emitStoresForInitAfterMemset(constant, Loc.getPointer(), 1362 isVolatile, Builder); 1363 } 1364 } else { 1365 // Otherwise, create a temporary global with the initializer then 1366 // memcpy from the global to the alloca. 1367 std::string Name = getStaticDeclName(CGM, D); 1368 unsigned AS = 0; 1369 if (getLangOpts().OpenCL) { 1370 AS = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 1371 BP = llvm::PointerType::getInt8PtrTy(getLLVMContext(), AS); 1372 } 1373 llvm::GlobalVariable *GV = 1374 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true, 1375 llvm::GlobalValue::PrivateLinkage, 1376 constant, Name, nullptr, 1377 llvm::GlobalValue::NotThreadLocal, AS); 1378 GV->setAlignment(Loc.getAlignment().getQuantity()); 1379 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1380 1381 Address SrcPtr = Address(GV, Loc.getAlignment()); 1382 if (SrcPtr.getType() != BP) 1383 SrcPtr = Builder.CreateBitCast(SrcPtr, BP); 1384 1385 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile); 1386 } 1387 } 1388 1389 /// Emit an expression as an initializer for a variable at the given 1390 /// location. The expression is not necessarily the normal 1391 /// initializer for the variable, and the address is not necessarily 1392 /// its normal location. 1393 /// 1394 /// \param init the initializing expression 1395 /// \param var the variable to act as if we're initializing 1396 /// \param loc the address to initialize; its type is a pointer 1397 /// to the LLVM mapping of the variable's type 1398 /// \param alignment the alignment of the address 1399 /// \param capturedByInit true if the variable is a __block variable 1400 /// whose address is potentially changed by the initializer 1401 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D, 1402 LValue lvalue, bool capturedByInit) { 1403 QualType type = D->getType(); 1404 1405 if (type->isReferenceType()) { 1406 RValue rvalue = EmitReferenceBindingToExpr(init); 1407 if (capturedByInit) 1408 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 1409 EmitStoreThroughLValue(rvalue, lvalue, true); 1410 return; 1411 } 1412 switch (getEvaluationKind(type)) { 1413 case TEK_Scalar: 1414 EmitScalarInit(init, D, lvalue, capturedByInit); 1415 return; 1416 case TEK_Complex: { 1417 ComplexPairTy complex = EmitComplexExpr(init); 1418 if (capturedByInit) 1419 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 1420 EmitStoreOfComplex(complex, lvalue, /*init*/ true); 1421 return; 1422 } 1423 case TEK_Aggregate: 1424 if (type->isAtomicType()) { 1425 EmitAtomicInit(const_cast<Expr*>(init), lvalue); 1426 } else { 1427 // TODO: how can we delay here if D is captured by its initializer? 1428 EmitAggExpr(init, AggValueSlot::forLValue(lvalue, 1429 AggValueSlot::IsDestructed, 1430 AggValueSlot::DoesNotNeedGCBarriers, 1431 AggValueSlot::IsNotAliased)); 1432 } 1433 return; 1434 } 1435 llvm_unreachable("bad evaluation kind"); 1436 } 1437 1438 /// Enter a destroy cleanup for the given local variable. 1439 void CodeGenFunction::emitAutoVarTypeCleanup( 1440 const CodeGenFunction::AutoVarEmission &emission, 1441 QualType::DestructionKind dtorKind) { 1442 assert(dtorKind != QualType::DK_none); 1443 1444 // Note that for __block variables, we want to destroy the 1445 // original stack object, not the possibly forwarded object. 1446 Address addr = emission.getObjectAddress(*this); 1447 1448 const VarDecl *var = emission.Variable; 1449 QualType type = var->getType(); 1450 1451 CleanupKind cleanupKind = NormalAndEHCleanup; 1452 CodeGenFunction::Destroyer *destroyer = nullptr; 1453 1454 switch (dtorKind) { 1455 case QualType::DK_none: 1456 llvm_unreachable("no cleanup for trivially-destructible variable"); 1457 1458 case QualType::DK_cxx_destructor: 1459 // If there's an NRVO flag on the emission, we need a different 1460 // cleanup. 1461 if (emission.NRVOFlag) { 1462 assert(!type->isArrayType()); 1463 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor(); 1464 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, 1465 dtor, emission.NRVOFlag); 1466 return; 1467 } 1468 break; 1469 1470 case QualType::DK_objc_strong_lifetime: 1471 // Suppress cleanups for pseudo-strong variables. 1472 if (var->isARCPseudoStrong()) return; 1473 1474 // Otherwise, consider whether to use an EH cleanup or not. 1475 cleanupKind = getARCCleanupKind(); 1476 1477 // Use the imprecise destroyer by default. 1478 if (!var->hasAttr<ObjCPreciseLifetimeAttr>()) 1479 destroyer = CodeGenFunction::destroyARCStrongImprecise; 1480 break; 1481 1482 case QualType::DK_objc_weak_lifetime: 1483 break; 1484 1485 case QualType::DK_nontrivial_c_struct: 1486 destroyer = CodeGenFunction::destroyNonTrivialCStruct; 1487 break; 1488 } 1489 1490 // If we haven't chosen a more specific destroyer, use the default. 1491 if (!destroyer) destroyer = getDestroyer(dtorKind); 1492 1493 // Use an EH cleanup in array destructors iff the destructor itself 1494 // is being pushed as an EH cleanup. 1495 bool useEHCleanup = (cleanupKind & EHCleanup); 1496 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer, 1497 useEHCleanup); 1498 } 1499 1500 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) { 1501 assert(emission.Variable && "emission was not valid!"); 1502 1503 // If this was emitted as a global constant, we're done. 1504 if (emission.wasEmittedAsGlobal()) return; 1505 1506 // If we don't have an insertion point, we're done. Sema prevents 1507 // us from jumping into any of these scopes anyway. 1508 if (!HaveInsertPoint()) return; 1509 1510 const VarDecl &D = *emission.Variable; 1511 1512 // Check the type for a cleanup. 1513 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType()) 1514 emitAutoVarTypeCleanup(emission, dtorKind); 1515 1516 // In GC mode, honor objc_precise_lifetime. 1517 if (getLangOpts().getGC() != LangOptions::NonGC && 1518 D.hasAttr<ObjCPreciseLifetimeAttr>()) { 1519 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D); 1520 } 1521 1522 // Handle the cleanup attribute. 1523 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) { 1524 const FunctionDecl *FD = CA->getFunctionDecl(); 1525 1526 llvm::Constant *F = CGM.GetAddrOfFunction(FD); 1527 assert(F && "Could not find function!"); 1528 1529 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD); 1530 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D); 1531 } 1532 1533 // If this is a block variable, call _Block_object_destroy 1534 // (on the unforwarded address). 1535 if (emission.IsByRef) 1536 enterByrefCleanup(emission); 1537 } 1538 1539 CodeGenFunction::Destroyer * 1540 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) { 1541 switch (kind) { 1542 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor"); 1543 case QualType::DK_cxx_destructor: 1544 return destroyCXXObject; 1545 case QualType::DK_objc_strong_lifetime: 1546 return destroyARCStrongPrecise; 1547 case QualType::DK_objc_weak_lifetime: 1548 return destroyARCWeak; 1549 case QualType::DK_nontrivial_c_struct: 1550 return destroyNonTrivialCStruct; 1551 } 1552 llvm_unreachable("Unknown DestructionKind"); 1553 } 1554 1555 /// pushEHDestroy - Push the standard destructor for the given type as 1556 /// an EH-only cleanup. 1557 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind, 1558 Address addr, QualType type) { 1559 assert(dtorKind && "cannot push destructor for trivial type"); 1560 assert(needsEHCleanup(dtorKind)); 1561 1562 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true); 1563 } 1564 1565 /// pushDestroy - Push the standard destructor for the given type as 1566 /// at least a normal cleanup. 1567 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind, 1568 Address addr, QualType type) { 1569 assert(dtorKind && "cannot push destructor for trivial type"); 1570 1571 CleanupKind cleanupKind = getCleanupKind(dtorKind); 1572 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind), 1573 cleanupKind & EHCleanup); 1574 } 1575 1576 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr, 1577 QualType type, Destroyer *destroyer, 1578 bool useEHCleanupForArray) { 1579 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type, 1580 destroyer, useEHCleanupForArray); 1581 } 1582 1583 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) { 1584 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem); 1585 } 1586 1587 void CodeGenFunction::pushLifetimeExtendedDestroy( 1588 CleanupKind cleanupKind, Address addr, QualType type, 1589 Destroyer *destroyer, bool useEHCleanupForArray) { 1590 assert(!isInConditionalBranch() && 1591 "performing lifetime extension from within conditional"); 1592 1593 // Push an EH-only cleanup for the object now. 1594 // FIXME: When popping normal cleanups, we need to keep this EH cleanup 1595 // around in case a temporary's destructor throws an exception. 1596 if (cleanupKind & EHCleanup) 1597 EHStack.pushCleanup<DestroyObject>( 1598 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type, 1599 destroyer, useEHCleanupForArray); 1600 1601 // Remember that we need to push a full cleanup for the object at the 1602 // end of the full-expression. 1603 pushCleanupAfterFullExpr<DestroyObject>( 1604 cleanupKind, addr, type, destroyer, useEHCleanupForArray); 1605 } 1606 1607 /// emitDestroy - Immediately perform the destruction of the given 1608 /// object. 1609 /// 1610 /// \param addr - the address of the object; a type* 1611 /// \param type - the type of the object; if an array type, all 1612 /// objects are destroyed in reverse order 1613 /// \param destroyer - the function to call to destroy individual 1614 /// elements 1615 /// \param useEHCleanupForArray - whether an EH cleanup should be 1616 /// used when destroying array elements, in case one of the 1617 /// destructions throws an exception 1618 void CodeGenFunction::emitDestroy(Address addr, QualType type, 1619 Destroyer *destroyer, 1620 bool useEHCleanupForArray) { 1621 const ArrayType *arrayType = getContext().getAsArrayType(type); 1622 if (!arrayType) 1623 return destroyer(*this, addr, type); 1624 1625 llvm::Value *length = emitArrayLength(arrayType, type, addr); 1626 1627 CharUnits elementAlign = 1628 addr.getAlignment() 1629 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type)); 1630 1631 // Normally we have to check whether the array is zero-length. 1632 bool checkZeroLength = true; 1633 1634 // But if the array length is constant, we can suppress that. 1635 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) { 1636 // ...and if it's constant zero, we can just skip the entire thing. 1637 if (constLength->isZero()) return; 1638 checkZeroLength = false; 1639 } 1640 1641 llvm::Value *begin = addr.getPointer(); 1642 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length); 1643 emitArrayDestroy(begin, end, type, elementAlign, destroyer, 1644 checkZeroLength, useEHCleanupForArray); 1645 } 1646 1647 /// emitArrayDestroy - Destroys all the elements of the given array, 1648 /// beginning from last to first. The array cannot be zero-length. 1649 /// 1650 /// \param begin - a type* denoting the first element of the array 1651 /// \param end - a type* denoting one past the end of the array 1652 /// \param elementType - the element type of the array 1653 /// \param destroyer - the function to call to destroy elements 1654 /// \param useEHCleanup - whether to push an EH cleanup to destroy 1655 /// the remaining elements in case the destruction of a single 1656 /// element throws 1657 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin, 1658 llvm::Value *end, 1659 QualType elementType, 1660 CharUnits elementAlign, 1661 Destroyer *destroyer, 1662 bool checkZeroLength, 1663 bool useEHCleanup) { 1664 assert(!elementType->isArrayType()); 1665 1666 // The basic structure here is a do-while loop, because we don't 1667 // need to check for the zero-element case. 1668 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body"); 1669 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done"); 1670 1671 if (checkZeroLength) { 1672 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end, 1673 "arraydestroy.isempty"); 1674 Builder.CreateCondBr(isEmpty, doneBB, bodyBB); 1675 } 1676 1677 // Enter the loop body, making that address the current address. 1678 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 1679 EmitBlock(bodyBB); 1680 llvm::PHINode *elementPast = 1681 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast"); 1682 elementPast->addIncoming(end, entryBB); 1683 1684 // Shift the address back by one element. 1685 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true); 1686 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne, 1687 "arraydestroy.element"); 1688 1689 if (useEHCleanup) 1690 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign, 1691 destroyer); 1692 1693 // Perform the actual destruction there. 1694 destroyer(*this, Address(element, elementAlign), elementType); 1695 1696 if (useEHCleanup) 1697 PopCleanupBlock(); 1698 1699 // Check whether we've reached the end. 1700 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done"); 1701 Builder.CreateCondBr(done, doneBB, bodyBB); 1702 elementPast->addIncoming(element, Builder.GetInsertBlock()); 1703 1704 // Done. 1705 EmitBlock(doneBB); 1706 } 1707 1708 /// Perform partial array destruction as if in an EH cleanup. Unlike 1709 /// emitArrayDestroy, the element type here may still be an array type. 1710 static void emitPartialArrayDestroy(CodeGenFunction &CGF, 1711 llvm::Value *begin, llvm::Value *end, 1712 QualType type, CharUnits elementAlign, 1713 CodeGenFunction::Destroyer *destroyer) { 1714 // If the element type is itself an array, drill down. 1715 unsigned arrayDepth = 0; 1716 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) { 1717 // VLAs don't require a GEP index to walk into. 1718 if (!isa<VariableArrayType>(arrayType)) 1719 arrayDepth++; 1720 type = arrayType->getElementType(); 1721 } 1722 1723 if (arrayDepth) { 1724 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0); 1725 1726 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero); 1727 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin"); 1728 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend"); 1729 } 1730 1731 // Destroy the array. We don't ever need an EH cleanup because we 1732 // assume that we're in an EH cleanup ourselves, so a throwing 1733 // destructor causes an immediate terminate. 1734 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer, 1735 /*checkZeroLength*/ true, /*useEHCleanup*/ false); 1736 } 1737 1738 namespace { 1739 /// RegularPartialArrayDestroy - a cleanup which performs a partial 1740 /// array destroy where the end pointer is regularly determined and 1741 /// does not need to be loaded from a local. 1742 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup { 1743 llvm::Value *ArrayBegin; 1744 llvm::Value *ArrayEnd; 1745 QualType ElementType; 1746 CodeGenFunction::Destroyer *Destroyer; 1747 CharUnits ElementAlign; 1748 public: 1749 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd, 1750 QualType elementType, CharUnits elementAlign, 1751 CodeGenFunction::Destroyer *destroyer) 1752 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd), 1753 ElementType(elementType), Destroyer(destroyer), 1754 ElementAlign(elementAlign) {} 1755 1756 void Emit(CodeGenFunction &CGF, Flags flags) override { 1757 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd, 1758 ElementType, ElementAlign, Destroyer); 1759 } 1760 }; 1761 1762 /// IrregularPartialArrayDestroy - a cleanup which performs a 1763 /// partial array destroy where the end pointer is irregularly 1764 /// determined and must be loaded from a local. 1765 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup { 1766 llvm::Value *ArrayBegin; 1767 Address ArrayEndPointer; 1768 QualType ElementType; 1769 CodeGenFunction::Destroyer *Destroyer; 1770 CharUnits ElementAlign; 1771 public: 1772 IrregularPartialArrayDestroy(llvm::Value *arrayBegin, 1773 Address arrayEndPointer, 1774 QualType elementType, 1775 CharUnits elementAlign, 1776 CodeGenFunction::Destroyer *destroyer) 1777 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer), 1778 ElementType(elementType), Destroyer(destroyer), 1779 ElementAlign(elementAlign) {} 1780 1781 void Emit(CodeGenFunction &CGF, Flags flags) override { 1782 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer); 1783 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd, 1784 ElementType, ElementAlign, Destroyer); 1785 } 1786 }; 1787 } // end anonymous namespace 1788 1789 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy 1790 /// already-constructed elements of the given array. The cleanup 1791 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock. 1792 /// 1793 /// \param elementType - the immediate element type of the array; 1794 /// possibly still an array type 1795 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 1796 Address arrayEndPointer, 1797 QualType elementType, 1798 CharUnits elementAlign, 1799 Destroyer *destroyer) { 1800 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup, 1801 arrayBegin, arrayEndPointer, 1802 elementType, elementAlign, 1803 destroyer); 1804 } 1805 1806 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy 1807 /// already-constructed elements of the given array. The cleanup 1808 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock. 1809 /// 1810 /// \param elementType - the immediate element type of the array; 1811 /// possibly still an array type 1812 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 1813 llvm::Value *arrayEnd, 1814 QualType elementType, 1815 CharUnits elementAlign, 1816 Destroyer *destroyer) { 1817 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup, 1818 arrayBegin, arrayEnd, 1819 elementType, elementAlign, 1820 destroyer); 1821 } 1822 1823 /// Lazily declare the @llvm.lifetime.start intrinsic. 1824 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() { 1825 if (LifetimeStartFn) 1826 return LifetimeStartFn; 1827 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(), 1828 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy); 1829 return LifetimeStartFn; 1830 } 1831 1832 /// Lazily declare the @llvm.lifetime.end intrinsic. 1833 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() { 1834 if (LifetimeEndFn) 1835 return LifetimeEndFn; 1836 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(), 1837 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy); 1838 return LifetimeEndFn; 1839 } 1840 1841 namespace { 1842 /// A cleanup to perform a release of an object at the end of a 1843 /// function. This is used to balance out the incoming +1 of a 1844 /// ns_consumed argument when we can't reasonably do that just by 1845 /// not doing the initial retain for a __block argument. 1846 struct ConsumeARCParameter final : EHScopeStack::Cleanup { 1847 ConsumeARCParameter(llvm::Value *param, 1848 ARCPreciseLifetime_t precise) 1849 : Param(param), Precise(precise) {} 1850 1851 llvm::Value *Param; 1852 ARCPreciseLifetime_t Precise; 1853 1854 void Emit(CodeGenFunction &CGF, Flags flags) override { 1855 CGF.EmitARCRelease(Param, Precise); 1856 } 1857 }; 1858 } // end anonymous namespace 1859 1860 /// Emit an alloca (or GlobalValue depending on target) 1861 /// for the specified parameter and set up LocalDeclMap. 1862 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg, 1863 unsigned ArgNo) { 1864 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl? 1865 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) && 1866 "Invalid argument to EmitParmDecl"); 1867 1868 Arg.getAnyValue()->setName(D.getName()); 1869 1870 QualType Ty = D.getType(); 1871 1872 // Use better IR generation for certain implicit parameters. 1873 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) { 1874 // The only implicit argument a block has is its literal. 1875 // This may be passed as an inalloca'ed value on Windows x86. 1876 if (BlockInfo) { 1877 llvm::Value *V = Arg.isIndirect() 1878 ? Builder.CreateLoad(Arg.getIndirectAddress()) 1879 : Arg.getDirectValue(); 1880 setBlockContextParameter(IPD, ArgNo, V); 1881 return; 1882 } 1883 } 1884 1885 Address DeclPtr = Address::invalid(); 1886 bool DoStore = false; 1887 bool IsScalar = hasScalarEvaluationKind(Ty); 1888 // If we already have a pointer to the argument, reuse the input pointer. 1889 if (Arg.isIndirect()) { 1890 DeclPtr = Arg.getIndirectAddress(); 1891 // If we have a prettier pointer type at this point, bitcast to that. 1892 unsigned AS = DeclPtr.getType()->getAddressSpace(); 1893 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS); 1894 if (DeclPtr.getType() != IRTy) 1895 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName()); 1896 // Indirect argument is in alloca address space, which may be different 1897 // from the default address space. 1898 auto AllocaAS = CGM.getASTAllocaAddressSpace(); 1899 auto *V = DeclPtr.getPointer(); 1900 auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS; 1901 auto DestLangAS = 1902 getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default; 1903 if (SrcLangAS != DestLangAS) { 1904 assert(getContext().getTargetAddressSpace(SrcLangAS) == 1905 CGM.getDataLayout().getAllocaAddrSpace()); 1906 auto DestAS = getContext().getTargetAddressSpace(DestLangAS); 1907 auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS); 1908 DeclPtr = Address(getTargetHooks().performAddrSpaceCast( 1909 *this, V, SrcLangAS, DestLangAS, T, true), 1910 DeclPtr.getAlignment()); 1911 } 1912 1913 // Push a destructor cleanup for this parameter if the ABI requires it. 1914 // Don't push a cleanup in a thunk for a method that will also emit a 1915 // cleanup. 1916 if (!IsScalar && !CurFuncIsThunk && 1917 getContext().isParamDestroyedInCallee(Ty)) { 1918 if (QualType::DestructionKind DtorKind = Ty.isDestructedType()) { 1919 assert((DtorKind == QualType::DK_cxx_destructor || 1920 DtorKind == QualType::DK_nontrivial_c_struct) && 1921 "unexpected destructor type"); 1922 pushDestroy(DtorKind, DeclPtr, Ty); 1923 } 1924 } 1925 } else { 1926 // Check if the parameter address is controlled by OpenMP runtime. 1927 Address OpenMPLocalAddr = 1928 getLangOpts().OpenMP 1929 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D) 1930 : Address::invalid(); 1931 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) { 1932 DeclPtr = OpenMPLocalAddr; 1933 } else { 1934 // Otherwise, create a temporary to hold the value. 1935 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D), 1936 D.getName() + ".addr"); 1937 } 1938 DoStore = true; 1939 } 1940 1941 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr); 1942 1943 LValue lv = MakeAddrLValue(DeclPtr, Ty); 1944 if (IsScalar) { 1945 Qualifiers qs = Ty.getQualifiers(); 1946 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) { 1947 // We honor __attribute__((ns_consumed)) for types with lifetime. 1948 // For __strong, it's handled by just skipping the initial retain; 1949 // otherwise we have to balance out the initial +1 with an extra 1950 // cleanup to do the release at the end of the function. 1951 bool isConsumed = D.hasAttr<NSConsumedAttr>(); 1952 1953 // 'self' is always formally __strong, but if this is not an 1954 // init method then we don't want to retain it. 1955 if (D.isARCPseudoStrong()) { 1956 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl); 1957 assert(&D == method->getSelfDecl()); 1958 assert(lt == Qualifiers::OCL_Strong); 1959 assert(qs.hasConst()); 1960 assert(method->getMethodFamily() != OMF_init); 1961 (void) method; 1962 lt = Qualifiers::OCL_ExplicitNone; 1963 } 1964 1965 // Load objects passed indirectly. 1966 if (Arg.isIndirect() && !ArgVal) 1967 ArgVal = Builder.CreateLoad(DeclPtr); 1968 1969 if (lt == Qualifiers::OCL_Strong) { 1970 if (!isConsumed) { 1971 if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 1972 // use objc_storeStrong(&dest, value) for retaining the 1973 // object. But first, store a null into 'dest' because 1974 // objc_storeStrong attempts to release its old value. 1975 llvm::Value *Null = CGM.EmitNullConstant(D.getType()); 1976 EmitStoreOfScalar(Null, lv, /* isInitialization */ true); 1977 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true); 1978 DoStore = false; 1979 } 1980 else 1981 // Don't use objc_retainBlock for block pointers, because we 1982 // don't want to Block_copy something just because we got it 1983 // as a parameter. 1984 ArgVal = EmitARCRetainNonBlock(ArgVal); 1985 } 1986 } else { 1987 // Push the cleanup for a consumed parameter. 1988 if (isConsumed) { 1989 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>() 1990 ? ARCPreciseLifetime : ARCImpreciseLifetime); 1991 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal, 1992 precise); 1993 } 1994 1995 if (lt == Qualifiers::OCL_Weak) { 1996 EmitARCInitWeak(DeclPtr, ArgVal); 1997 DoStore = false; // The weak init is a store, no need to do two. 1998 } 1999 } 2000 2001 // Enter the cleanup scope. 2002 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt); 2003 } 2004 } 2005 2006 // Store the initial value into the alloca. 2007 if (DoStore) 2008 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true); 2009 2010 setAddrOfLocalVar(&D, DeclPtr); 2011 2012 // Emit debug info for param declaration. 2013 if (CGDebugInfo *DI = getDebugInfo()) { 2014 if (CGM.getCodeGenOpts().getDebugInfo() >= 2015 codegenoptions::LimitedDebugInfo) { 2016 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder); 2017 } 2018 } 2019 2020 if (D.hasAttr<AnnotateAttr>()) 2021 EmitVarAnnotations(&D, DeclPtr.getPointer()); 2022 2023 // We can only check return value nullability if all arguments to the 2024 // function satisfy their nullability preconditions. This makes it necessary 2025 // to emit null checks for args in the function body itself. 2026 if (requiresReturnValueNullabilityCheck()) { 2027 auto Nullability = Ty->getNullability(getContext()); 2028 if (Nullability && *Nullability == NullabilityKind::NonNull) { 2029 SanitizerScope SanScope(this); 2030 RetValNullabilityPrecondition = 2031 Builder.CreateAnd(RetValNullabilityPrecondition, 2032 Builder.CreateIsNotNull(Arg.getAnyValue())); 2033 } 2034 } 2035 } 2036 2037 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, 2038 CodeGenFunction *CGF) { 2039 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed())) 2040 return; 2041 getOpenMPRuntime().emitUserDefinedReduction(CGF, D); 2042 } 2043