1 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Decl nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
17 #include "CGCleanup.h"
18 #include "CGDebugInfo.h"
19 #include "CGOpenCLRuntime.h"
20 #include "CGOpenMPRuntime.h"
21 #include "CodeGenModule.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/CharUnits.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclOpenMP.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/CodeGen/CGFunctionInfo.h"
30 #include "clang/Frontend/CodeGenOptions.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/Type.h"
36 using namespace clang;
37 using namespace CodeGen;
39 void CodeGenFunction::EmitDecl(const Decl &D) {
40 switch (D.getKind()) {
41 case Decl::BuiltinTemplate:
42 case Decl::TranslationUnit:
43 case Decl::ExternCContext:
45 case Decl::UnresolvedUsingTypename:
46 case Decl::ClassTemplateSpecialization:
47 case Decl::ClassTemplatePartialSpecialization:
48 case Decl::VarTemplateSpecialization:
49 case Decl::VarTemplatePartialSpecialization:
50 case Decl::TemplateTypeParm:
51 case Decl::UnresolvedUsingValue:
52 case Decl::NonTypeTemplateParm:
54 case Decl::CXXConstructor:
55 case Decl::CXXDestructor:
56 case Decl::CXXConversion:
58 case Decl::MSProperty:
59 case Decl::IndirectField:
61 case Decl::ObjCAtDefsField:
63 case Decl::ImplicitParam:
64 case Decl::ClassTemplate:
65 case Decl::VarTemplate:
66 case Decl::FunctionTemplate:
67 case Decl::TypeAliasTemplate:
68 case Decl::TemplateTemplateParm:
69 case Decl::ObjCMethod:
70 case Decl::ObjCCategory:
71 case Decl::ObjCProtocol:
72 case Decl::ObjCInterface:
73 case Decl::ObjCCategoryImpl:
74 case Decl::ObjCImplementation:
75 case Decl::ObjCProperty:
76 case Decl::ObjCCompatibleAlias:
77 case Decl::PragmaComment:
78 case Decl::PragmaDetectMismatch:
79 case Decl::AccessSpec:
80 case Decl::LinkageSpec:
82 case Decl::ObjCPropertyImpl:
83 case Decl::FileScopeAsm:
85 case Decl::FriendTemplate:
88 case Decl::ClassScopeFunctionSpecialization:
89 case Decl::UsingShadow:
90 case Decl::ConstructorUsingShadow:
91 case Decl::ObjCTypeParam:
93 llvm_unreachable("Declaration should not be in declstmts!");
94 case Decl::Function: // void X();
95 case Decl::Record: // struct/union/class X;
96 case Decl::Enum: // enum X;
97 case Decl::EnumConstant: // enum ? { X = ? }
98 case Decl::CXXRecord: // struct/union/class X; [C++]
99 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
100 case Decl::Label: // __label__ x;
102 case Decl::OMPThreadPrivate:
103 case Decl::OMPCapturedExpr:
105 // None of these decls require codegen support.
108 case Decl::NamespaceAlias:
109 if (CGDebugInfo *DI = getDebugInfo())
110 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
112 case Decl::Using: // using X; [C++]
113 if (CGDebugInfo *DI = getDebugInfo())
114 DI->EmitUsingDecl(cast<UsingDecl>(D));
116 case Decl::UsingPack:
117 for (auto *Using : cast<UsingPackDecl>(D).expansions())
120 case Decl::UsingDirective: // using namespace X; [C++]
121 if (CGDebugInfo *DI = getDebugInfo())
122 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
125 case Decl::Decomposition: {
126 const VarDecl &VD = cast<VarDecl>(D);
127 assert(VD.isLocalVarDecl() &&
128 "Should not see file-scope variables inside a function!");
130 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
131 for (auto *B : DD->bindings())
132 if (auto *HD = B->getHoldingVar())
137 case Decl::OMPDeclareReduction:
138 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
140 case Decl::Typedef: // typedef int X;
141 case Decl::TypeAlias: { // using X = int; [C++0x]
142 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
143 QualType Ty = TD.getUnderlyingType();
145 if (Ty->isVariablyModifiedType())
146 EmitVariablyModifiedType(Ty);
151 /// EmitVarDecl - This method handles emission of any variable declaration
152 /// inside a function, including static vars etc.
153 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
154 if (D.isStaticLocal()) {
155 llvm::GlobalValue::LinkageTypes Linkage =
156 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
158 // FIXME: We need to force the emission/use of a guard variable for
159 // some variables even if we can constant-evaluate them because
160 // we can't guarantee every translation unit will constant-evaluate them.
162 return EmitStaticVarDecl(D, Linkage);
165 if (D.hasExternalStorage())
166 // Don't emit it now, allow it to be emitted lazily on its first use.
169 if (D.getType().getAddressSpace() == LangAS::opencl_local)
170 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
172 assert(D.hasLocalStorage());
173 return EmitAutoVarDecl(D);
176 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
177 if (CGM.getLangOpts().CPlusPlus)
178 return CGM.getMangledName(&D).str();
180 // If this isn't C++, we don't need a mangled name, just a pretty one.
181 assert(!D.isExternallyVisible() && "name shouldn't matter");
182 std::string ContextName;
183 const DeclContext *DC = D.getDeclContext();
184 if (auto *CD = dyn_cast<CapturedDecl>(DC))
185 DC = cast<DeclContext>(CD->getNonClosureContext());
186 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
187 ContextName = CGM.getMangledName(FD);
188 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
189 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
190 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
191 ContextName = OMD->getSelector().getAsString();
193 llvm_unreachable("Unknown context for static var decl");
195 ContextName += "." + D.getNameAsString();
199 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
200 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
201 // In general, we don't always emit static var decls once before we reference
202 // them. It is possible to reference them before emitting the function that
203 // contains them, and it is possible to emit the containing function multiple
205 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
208 QualType Ty = D.getType();
209 assert(Ty->isConstantSizeType() && "VLAs can't be static");
211 // Use the label if the variable is renamed with the asm-label extension.
213 if (D.hasAttr<AsmLabelAttr>())
214 Name = getMangledName(&D);
216 Name = getStaticDeclName(*this, D);
218 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
220 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
222 // Local address space cannot have an initializer.
223 llvm::Constant *Init = nullptr;
224 if (Ty.getAddressSpace() != LangAS::opencl_local)
225 Init = EmitNullConstant(Ty);
227 Init = llvm::UndefValue::get(LTy);
229 llvm::GlobalVariable *GV =
230 new llvm::GlobalVariable(getModule(), LTy,
231 Ty.isConstant(getContext()), Linkage,
233 llvm::GlobalVariable::NotThreadLocal,
235 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
236 setGlobalVisibility(GV, &D);
238 if (supportsCOMDAT() && GV->isWeakForLinker())
239 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
244 if (D.isExternallyVisible()) {
245 if (D.hasAttr<DLLImportAttr>())
246 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
247 else if (D.hasAttr<DLLExportAttr>())
248 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
251 // Make sure the result is of the correct type.
252 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
253 llvm::Constant *Addr = GV;
254 if (AddrSpace != ExpectedAddrSpace) {
255 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
256 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
259 setStaticLocalDeclAddress(&D, Addr);
261 // Ensure that the static local gets initialized by making sure the parent
262 // function gets emitted eventually.
263 const Decl *DC = cast<Decl>(D.getDeclContext());
265 // We can't name blocks or captured statements directly, so try to emit their
267 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
268 DC = DC->getNonClosureContext();
269 // FIXME: Ensure that global blocks get emitted.
275 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
276 GD = GlobalDecl(CD, Ctor_Base);
277 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
278 GD = GlobalDecl(DD, Dtor_Base);
279 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
282 // Don't do anything for Obj-C method decls or global closures. We should
284 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
287 (void)GetAddrOfGlobal(GD);
292 /// hasNontrivialDestruction - Determine whether a type's destruction is
293 /// non-trivial. If so, and the variable uses static initialization, we must
294 /// register its destructor to run on exit.
295 static bool hasNontrivialDestruction(QualType T) {
296 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
297 return RD && !RD->hasTrivialDestructor();
300 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
301 /// global variable that has already been created for it. If the initializer
302 /// has a different type than GV does, this may free GV and return a different
303 /// one. Otherwise it just returns GV.
304 llvm::GlobalVariable *
305 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
306 llvm::GlobalVariable *GV) {
307 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
309 // If constant emission failed, then this should be a C++ static
312 if (!getLangOpts().CPlusPlus)
313 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
314 else if (Builder.GetInsertBlock()) {
315 // Since we have a static initializer, this global variable can't
317 GV->setConstant(false);
319 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
324 // The initializer may differ in type from the global. Rewrite
325 // the global to match the initializer. (We have to do this
326 // because some types, like unions, can't be completely represented
327 // in the LLVM type system.)
328 if (GV->getType()->getElementType() != Init->getType()) {
329 llvm::GlobalVariable *OldGV = GV;
331 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
333 OldGV->getLinkage(), Init, "",
334 /*InsertBefore*/ OldGV,
335 OldGV->getThreadLocalMode(),
336 CGM.getContext().getTargetAddressSpace(D.getType()));
337 GV->setVisibility(OldGV->getVisibility());
338 GV->setComdat(OldGV->getComdat());
340 // Steal the name of the old global
343 // Replace all uses of the old global with the new global
344 llvm::Constant *NewPtrForOldDecl =
345 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
346 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
348 // Erase the old global, since it is no longer used.
349 OldGV->eraseFromParent();
352 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
353 GV->setInitializer(Init);
355 if (hasNontrivialDestruction(D.getType())) {
356 // We have a constant initializer, but a nontrivial destructor. We still
357 // need to perform a guarded "initialization" in order to register the
359 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
365 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
366 llvm::GlobalValue::LinkageTypes Linkage) {
367 // Check to see if we already have a global variable for this
368 // declaration. This can happen when double-emitting function
369 // bodies, e.g. with complete and base constructors.
370 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
371 CharUnits alignment = getContext().getDeclAlign(&D);
373 // Store into LocalDeclMap before generating initializer to handle
374 // circular references.
375 setAddrOfLocalVar(&D, Address(addr, alignment));
377 // We can't have a VLA here, but we can have a pointer to a VLA,
378 // even though that doesn't really make any sense.
379 // Make sure to evaluate VLA bounds now so that we have them for later.
380 if (D.getType()->isVariablyModifiedType())
381 EmitVariablyModifiedType(D.getType());
383 // Save the type in case adding the initializer forces a type change.
384 llvm::Type *expectedType = addr->getType();
386 llvm::GlobalVariable *var =
387 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
389 // CUDA's local and local static __shared__ variables should not
390 // have any non-empty initializers. This is ensured by Sema.
391 // Whatever initializer such variable may have when it gets here is
392 // a no-op and should not be emitted.
393 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
394 D.hasAttr<CUDASharedAttr>();
395 // If this value has an initializer, emit it.
396 if (D.getInit() && !isCudaSharedVar)
397 var = AddInitializerToStaticVarDecl(D, var);
399 var->setAlignment(alignment.getQuantity());
401 if (D.hasAttr<AnnotateAttr>())
402 CGM.AddGlobalAnnotations(&D, var);
404 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
405 var->setSection(SA->getName());
407 if (D.hasAttr<UsedAttr>())
408 CGM.addUsedGlobal(var);
410 // We may have to cast the constant because of the initializer
413 // FIXME: It is really dangerous to store this in the map; if anyone
414 // RAUW's the GV uses of this constant will be invalid.
415 llvm::Constant *castedAddr =
416 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
417 if (var != castedAddr)
418 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
419 CGM.setStaticLocalDeclAddress(&D, castedAddr);
421 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
423 // Emit global variable debug descriptor for static vars.
424 CGDebugInfo *DI = getDebugInfo();
426 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
427 DI->setLocation(D.getLocation());
428 DI->EmitGlobalVariable(var, &D);
433 struct DestroyObject final : EHScopeStack::Cleanup {
434 DestroyObject(Address addr, QualType type,
435 CodeGenFunction::Destroyer *destroyer,
436 bool useEHCleanupForArray)
437 : addr(addr), type(type), destroyer(destroyer),
438 useEHCleanupForArray(useEHCleanupForArray) {}
442 CodeGenFunction::Destroyer *destroyer;
443 bool useEHCleanupForArray;
445 void Emit(CodeGenFunction &CGF, Flags flags) override {
446 // Don't use an EH cleanup recursively from an EH cleanup.
447 bool useEHCleanupForArray =
448 flags.isForNormalCleanup() && this->useEHCleanupForArray;
450 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
454 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
455 DestroyNRVOVariable(Address addr,
456 const CXXDestructorDecl *Dtor,
457 llvm::Value *NRVOFlag)
458 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
460 const CXXDestructorDecl *Dtor;
461 llvm::Value *NRVOFlag;
464 void Emit(CodeGenFunction &CGF, Flags flags) override {
465 // Along the exceptions path we always execute the dtor.
466 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
468 llvm::BasicBlock *SkipDtorBB = nullptr;
470 // If we exited via NRVO, we skip the destructor call.
471 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
472 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
473 llvm::Value *DidNRVO =
474 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
475 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
476 CGF.EmitBlock(RunDtorBB);
479 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
480 /*ForVirtualBase=*/false,
481 /*Delegating=*/false,
484 if (NRVO) CGF.EmitBlock(SkipDtorBB);
488 struct CallStackRestore final : EHScopeStack::Cleanup {
490 CallStackRestore(Address Stack) : Stack(Stack) {}
491 void Emit(CodeGenFunction &CGF, Flags flags) override {
492 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
493 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
494 CGF.Builder.CreateCall(F, V);
498 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
500 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
502 void Emit(CodeGenFunction &CGF, Flags flags) override {
503 // Compute the address of the local variable, in case it's a
504 // byref or something.
505 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
506 Var.getType(), VK_LValue, SourceLocation());
507 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
509 CGF.EmitExtendGCLifetime(value);
513 struct CallCleanupFunction final : EHScopeStack::Cleanup {
514 llvm::Constant *CleanupFn;
515 const CGFunctionInfo &FnInfo;
518 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
520 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
522 void Emit(CodeGenFunction &CGF, Flags flags) override {
523 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
524 Var.getType(), VK_LValue, SourceLocation());
525 // Compute the address of the local variable, in case it's a byref
527 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
529 // In some cases, the type of the function argument will be different from
530 // the type of the pointer. An example of this is
531 // void f(void* arg);
532 // __attribute__((cleanup(f))) void *g;
534 // To fix this we insert a bitcast here.
535 QualType ArgTy = FnInfo.arg_begin()->type;
537 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
540 Args.add(RValue::get(Arg),
541 CGF.getContext().getPointerType(Var.getType()));
542 auto Callee = CGCallee::forDirect(CleanupFn);
543 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
546 } // end anonymous namespace
548 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
549 /// variable with lifetime.
550 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
552 Qualifiers::ObjCLifetime lifetime) {
554 case Qualifiers::OCL_None:
555 llvm_unreachable("present but none");
557 case Qualifiers::OCL_ExplicitNone:
561 case Qualifiers::OCL_Strong: {
562 CodeGenFunction::Destroyer *destroyer =
563 (var.hasAttr<ObjCPreciseLifetimeAttr>()
564 ? CodeGenFunction::destroyARCStrongPrecise
565 : CodeGenFunction::destroyARCStrongImprecise);
567 CleanupKind cleanupKind = CGF.getARCCleanupKind();
568 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
569 cleanupKind & EHCleanup);
572 case Qualifiers::OCL_Autoreleasing:
576 case Qualifiers::OCL_Weak:
577 // __weak objects always get EH cleanups; otherwise, exceptions
578 // could cause really nasty crashes instead of mere leaks.
579 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
580 CodeGenFunction::destroyARCWeak,
581 /*useEHCleanup*/ true);
586 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
587 if (const Expr *e = dyn_cast<Expr>(s)) {
588 // Skip the most common kinds of expressions that make
589 // hierarchy-walking expensive.
590 s = e = e->IgnoreParenCasts();
592 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
593 return (ref->getDecl() == &var);
594 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
595 const BlockDecl *block = be->getBlockDecl();
596 for (const auto &I : block->captures()) {
597 if (I.getVariable() == &var)
603 for (const Stmt *SubStmt : s->children())
604 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
605 if (SubStmt && isAccessedBy(var, SubStmt))
611 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
612 if (!decl) return false;
613 if (!isa<VarDecl>(decl)) return false;
614 const VarDecl *var = cast<VarDecl>(decl);
615 return isAccessedBy(*var, e);
618 static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
619 const LValue &destLV, const Expr *init) {
620 bool needsCast = false;
622 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
623 switch (castExpr->getCastKind()) {
624 // Look through casts that don't require representation changes.
627 case CK_BlockPointerToObjCPointerCast:
631 // If we find an l-value to r-value cast from a __weak variable,
632 // emit this operation as a copy or move.
633 case CK_LValueToRValue: {
634 const Expr *srcExpr = castExpr->getSubExpr();
635 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
638 // Emit the source l-value.
639 LValue srcLV = CGF.EmitLValue(srcExpr);
641 // Handle a formal type change to avoid asserting.
642 auto srcAddr = srcLV.getAddress();
644 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
645 destLV.getAddress().getElementType());
648 // If it was an l-value, use objc_copyWeak.
649 if (srcExpr->getValueKind() == VK_LValue) {
650 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
652 assert(srcExpr->getValueKind() == VK_XValue);
653 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
658 // Stop at anything else.
663 init = castExpr->getSubExpr();
668 static void drillIntoBlockVariable(CodeGenFunction &CGF,
670 const VarDecl *var) {
671 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
674 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
675 LValue lvalue, bool capturedByInit) {
676 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
678 llvm::Value *value = EmitScalarExpr(init);
680 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
681 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
685 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
686 init = DIE->getExpr();
688 // If we're emitting a value with lifetime, we have to do the
689 // initialization *before* we leave the cleanup scopes.
690 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
691 enterFullExpression(ewc);
692 init = ewc->getSubExpr();
694 CodeGenFunction::RunCleanupsScope Scope(*this);
696 // We have to maintain the illusion that the variable is
697 // zero-initialized. If the variable might be accessed in its
698 // initializer, zero-initialize before running the initializer, then
699 // actually perform the initialization with an assign.
700 bool accessedByInit = false;
701 if (lifetime != Qualifiers::OCL_ExplicitNone)
702 accessedByInit = (capturedByInit || isAccessedBy(D, init));
703 if (accessedByInit) {
704 LValue tempLV = lvalue;
705 // Drill down to the __block object if necessary.
706 if (capturedByInit) {
707 // We can use a simple GEP for this because it can't have been
709 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
714 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
715 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
717 // If __weak, we want to use a barrier under certain conditions.
718 if (lifetime == Qualifiers::OCL_Weak)
719 EmitARCInitWeak(tempLV.getAddress(), zero);
721 // Otherwise just do a simple store.
723 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
726 // Emit the initializer.
727 llvm::Value *value = nullptr;
730 case Qualifiers::OCL_None:
731 llvm_unreachable("present but none");
733 case Qualifiers::OCL_ExplicitNone:
734 value = EmitARCUnsafeUnretainedScalarExpr(init);
737 case Qualifiers::OCL_Strong: {
738 value = EmitARCRetainScalarExpr(init);
742 case Qualifiers::OCL_Weak: {
743 // If it's not accessed by the initializer, try to emit the
744 // initialization with a copy or move.
745 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
749 // No way to optimize a producing initializer into this. It's not
750 // worth optimizing for, because the value will immediately
751 // disappear in the common case.
752 value = EmitScalarExpr(init);
754 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
756 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
758 EmitARCInitWeak(lvalue.getAddress(), value);
762 case Qualifiers::OCL_Autoreleasing:
763 value = EmitARCRetainAutoreleaseScalarExpr(init);
767 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
769 // If the variable might have been accessed by its initializer, we
770 // might have to initialize with a barrier. We have to do this for
771 // both __weak and __strong, but __weak got filtered out above.
772 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
773 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
774 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
775 EmitARCRelease(oldValue, ARCImpreciseLifetime);
779 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
782 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
783 /// non-zero parts of the specified initializer with equal or fewer than
784 /// NumStores scalar stores.
785 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
786 unsigned &NumStores) {
787 // Zero and Undef never requires any extra stores.
788 if (isa<llvm::ConstantAggregateZero>(Init) ||
789 isa<llvm::ConstantPointerNull>(Init) ||
790 isa<llvm::UndefValue>(Init))
792 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
793 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
794 isa<llvm::ConstantExpr>(Init))
795 return Init->isNullValue() || NumStores--;
797 // See if we can emit each element.
798 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
799 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
800 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
801 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
807 if (llvm::ConstantDataSequential *CDS =
808 dyn_cast<llvm::ConstantDataSequential>(Init)) {
809 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
810 llvm::Constant *Elt = CDS->getElementAsConstant(i);
811 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
817 // Anything else is hard and scary.
821 /// emitStoresForInitAfterMemset - For inits that
822 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
823 /// stores that would be required.
824 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
825 bool isVolatile, CGBuilderTy &Builder) {
826 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
827 "called emitStoresForInitAfterMemset for zero or undef value.");
829 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
830 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
831 isa<llvm::ConstantExpr>(Init)) {
832 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
836 if (llvm::ConstantDataSequential *CDS =
837 dyn_cast<llvm::ConstantDataSequential>(Init)) {
838 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
839 llvm::Constant *Elt = CDS->getElementAsConstant(i);
841 // If necessary, get a pointer to the element and emit it.
842 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
843 emitStoresForInitAfterMemset(
844 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
845 isVolatile, Builder);
850 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
851 "Unknown value type!");
853 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
854 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
856 // If necessary, get a pointer to the element and emit it.
857 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
858 emitStoresForInitAfterMemset(
859 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
860 isVolatile, Builder);
864 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
865 /// plus some stores to initialize a local variable instead of using a memcpy
866 /// from a constant global. It is beneficial to use memset if the global is all
867 /// zeros, or mostly zeros and large.
868 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
869 uint64_t GlobalSize) {
870 // If a global is all zeros, always use a memset.
871 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
873 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
874 // do it if it will require 6 or fewer scalar stores.
875 // TODO: Should budget depends on the size? Avoiding a large global warrants
876 // plopping in more stores.
877 unsigned StoreBudget = 6;
878 uint64_t SizeLimit = 32;
880 return GlobalSize > SizeLimit &&
881 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
884 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
885 /// variable declaration with auto, register, or no storage class specifier.
886 /// These turn into simple stack objects, or GlobalValues depending on target.
887 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
888 AutoVarEmission emission = EmitAutoVarAlloca(D);
889 EmitAutoVarInit(emission);
890 EmitAutoVarCleanups(emission);
893 /// Emit a lifetime.begin marker if some criteria are satisfied.
894 /// \return a pointer to the temporary size Value if a marker was emitted, null
896 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
898 if (!ShouldEmitLifetimeMarkers)
901 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
902 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
904 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
905 C->setDoesNotThrow();
909 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
910 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
912 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
913 C->setDoesNotThrow();
916 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
917 /// local variable. Does not emit initialization or destruction.
918 CodeGenFunction::AutoVarEmission
919 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
920 QualType Ty = D.getType();
922 AutoVarEmission emission(D);
924 bool isByRef = D.hasAttr<BlocksAttr>();
925 emission.IsByRef = isByRef;
927 CharUnits alignment = getContext().getDeclAlign(&D);
929 // If the type is variably-modified, emit all the VLA sizes for it.
930 if (Ty->isVariablyModifiedType())
931 EmitVariablyModifiedType(Ty);
933 Address address = Address::invalid();
934 if (Ty->isConstantSizeType()) {
935 bool NRVO = getLangOpts().ElideConstructors &&
938 // If this value is an array or struct with a statically determinable
939 // constant initializer, there are optimizations we can do.
941 // TODO: We should constant-evaluate the initializer of any variable,
942 // as long as it is initialized by a constant expression. Currently,
943 // isConstantInitializer produces wrong answers for structs with
944 // reference or bitfield members, and a few other cases, and checking
945 // for POD-ness protects us from some of these.
946 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
948 ((Ty.isPODType(getContext()) ||
949 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
950 D.getInit()->isConstantInitializer(getContext(), false)))) {
952 // If the variable's a const type, and it's neither an NRVO
953 // candidate nor a __block variable and has no mutable members,
954 // emit it as a global instead.
955 // Exception is if a variable is located in non-constant address space
957 if ((!getLangOpts().OpenCL ||
958 Ty.getAddressSpace() == LangAS::opencl_constant) &&
959 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
960 CGM.isTypeConstant(Ty, true))) {
961 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
963 // Signal this condition to later callbacks.
964 emission.Addr = Address::invalid();
965 assert(emission.wasEmittedAsGlobal());
969 // Otherwise, tell the initialization code that we're in this case.
970 emission.IsConstantAggregate = true;
973 // A normal fixed sized variable becomes an alloca in the entry block,
974 // unless it's an NRVO variable.
977 // The named return value optimization: allocate this variable in the
978 // return slot, so that we can elide the copy when returning this
979 // variable (C++0x [class.copy]p34).
980 address = ReturnValue;
982 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
983 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
984 // Create a flag that is used to indicate when the NRVO was applied
985 // to this variable. Set it to zero to indicate that NRVO was not
987 llvm::Value *Zero = Builder.getFalse();
989 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
991 Builder.CreateStore(Zero, NRVOFlag);
993 // Record the NRVO flag for this variable.
994 NRVOFlags[&D] = NRVOFlag.getPointer();
995 emission.NRVOFlag = NRVOFlag.getPointer();
999 CharUnits allocaAlignment;
1000 llvm::Type *allocaTy;
1002 auto &byrefInfo = getBlockByrefInfo(&D);
1003 allocaTy = byrefInfo.Type;
1004 allocaAlignment = byrefInfo.ByrefAlignment;
1006 allocaTy = ConvertTypeForMem(Ty);
1007 allocaAlignment = alignment;
1010 // Create the alloca. Note that we set the name separately from
1011 // building the instruction so that it's there even in no-asserts
1013 address = CreateTempAlloca(allocaTy, allocaAlignment);
1014 address.getPointer()->setName(D.getName());
1016 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1017 // the catch parameter starts in the catchpad instruction, and we can't
1018 // insert code in those basic blocks.
1019 bool IsMSCatchParam =
1020 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1022 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1023 // if we don't have a valid insertion point (?).
1024 if (HaveInsertPoint() && !IsMSCatchParam) {
1025 // goto or switch-case statements can break lifetime into several
1026 // regions which need more efforts to handle them correctly. PR28267
1027 // This is rare case, but it's better just omit intrinsics than have
1028 // them incorrectly placed.
1029 if (!Bypasses.IsBypassed(&D)) {
1030 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1031 emission.SizeForLifetimeMarkers =
1032 EmitLifetimeStart(size, address.getPointer());
1035 assert(!emission.useLifetimeMarkers());
1039 EnsureInsertPoint();
1041 if (!DidCallStackSave) {
1044 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
1046 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
1047 llvm::Value *V = Builder.CreateCall(F);
1048 Builder.CreateStore(V, Stack);
1050 DidCallStackSave = true;
1052 // Push a cleanup block and restore the stack there.
1053 // FIXME: in general circumstances, this should be an EH cleanup.
1054 pushStackRestore(NormalCleanup, Stack);
1057 llvm::Value *elementCount;
1058 QualType elementType;
1059 std::tie(elementCount, elementType) = getVLASize(Ty);
1061 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
1063 // Allocate memory for the array.
1064 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1065 vla->setAlignment(alignment.getQuantity());
1067 address = Address(vla, alignment);
1070 setAddrOfLocalVar(&D, address);
1071 emission.Addr = address;
1073 // Emit debug info for local var declaration.
1074 if (HaveInsertPoint())
1075 if (CGDebugInfo *DI = getDebugInfo()) {
1076 if (CGM.getCodeGenOpts().getDebugInfo() >=
1077 codegenoptions::LimitedDebugInfo) {
1078 DI->setLocation(D.getLocation());
1079 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1083 if (D.hasAttr<AnnotateAttr>())
1084 EmitVarAnnotations(&D, address.getPointer());
1089 /// Determines whether the given __block variable is potentially
1090 /// captured by the given expression.
1091 static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1092 // Skip the most common kinds of expressions that make
1093 // hierarchy-walking expensive.
1094 e = e->IgnoreParenCasts();
1096 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1097 const BlockDecl *block = be->getBlockDecl();
1098 for (const auto &I : block->captures()) {
1099 if (I.getVariable() == &var)
1103 // No need to walk into the subexpressions.
1107 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1108 const CompoundStmt *CS = SE->getSubStmt();
1109 for (const auto *BI : CS->body())
1110 if (const auto *E = dyn_cast<Expr>(BI)) {
1111 if (isCapturedBy(var, E))
1114 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1115 // special case declarations
1116 for (const auto *I : DS->decls()) {
1117 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1118 const Expr *Init = VD->getInit();
1119 if (Init && isCapturedBy(var, Init))
1125 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1126 // Later, provide code to poke into statements for capture analysis.
1131 for (const Stmt *SubStmt : e->children())
1132 if (isCapturedBy(var, cast<Expr>(SubStmt)))
1138 /// \brief Determine whether the given initializer is trivial in the sense
1139 /// that it requires no code to be generated.
1140 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1144 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1145 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1146 if (Constructor->isTrivial() &&
1147 Constructor->isDefaultConstructor() &&
1148 !Construct->requiresZeroInitialization())
1154 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1155 assert(emission.Variable && "emission was not valid!");
1157 // If this was emitted as a global constant, we're done.
1158 if (emission.wasEmittedAsGlobal()) return;
1160 const VarDecl &D = *emission.Variable;
1161 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1162 QualType type = D.getType();
1164 // If this local has an initializer, emit it now.
1165 const Expr *Init = D.getInit();
1167 // If we are at an unreachable point, we don't need to emit the initializer
1168 // unless it contains a label.
1169 if (!HaveInsertPoint()) {
1170 if (!Init || !ContainsLabel(Init)) return;
1171 EnsureInsertPoint();
1174 // Initialize the structure of a __block variable.
1175 if (emission.IsByRef)
1176 emitByrefStructureInit(emission);
1178 if (isTrivialInitializer(Init))
1181 // Check whether this is a byref variable that's potentially
1182 // captured and moved by its own initializer. If so, we'll need to
1183 // emit the initializer first, then copy into the variable.
1184 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1187 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
1189 llvm::Constant *constant = nullptr;
1190 if (emission.IsConstantAggregate || D.isConstexpr()) {
1191 assert(!capturedByInit && "constant init contains a capturing block?");
1192 constant = CGM.EmitConstantInit(D, this);
1196 LValue lv = MakeAddrLValue(Loc, type);
1198 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1201 if (!emission.IsConstantAggregate) {
1202 // For simple scalar/complex initialization, store the value directly.
1203 LValue lv = MakeAddrLValue(Loc, type);
1205 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1208 // If this is a simple aggregate initialization, we can optimize it
1210 bool isVolatile = type.isVolatileQualified();
1212 llvm::Value *SizeVal =
1213 llvm::ConstantInt::get(IntPtrTy,
1214 getContext().getTypeSizeInChars(type).getQuantity());
1216 llvm::Type *BP = Int8PtrTy;
1217 if (Loc.getType() != BP)
1218 Loc = Builder.CreateBitCast(Loc, BP);
1220 // If the initializer is all or mostly zeros, codegen with memset then do
1221 // a few stores afterward.
1222 if (shouldUseMemSetPlusStoresToInitialize(constant,
1223 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
1224 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1226 // Zero and undef don't require a stores.
1227 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
1228 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1229 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1230 isVolatile, Builder);
1233 // Otherwise, create a temporary global with the initializer then
1234 // memcpy from the global to the alloca.
1235 std::string Name = getStaticDeclName(CGM, D);
1237 if (getLangOpts().OpenCL) {
1238 AS = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
1239 BP = llvm::PointerType::getInt8PtrTy(getLLVMContext(), AS);
1241 llvm::GlobalVariable *GV =
1242 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1243 llvm::GlobalValue::PrivateLinkage,
1244 constant, Name, nullptr,
1245 llvm::GlobalValue::NotThreadLocal, AS);
1246 GV->setAlignment(Loc.getAlignment().getQuantity());
1247 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1249 Address SrcPtr = Address(GV, Loc.getAlignment());
1250 if (SrcPtr.getType() != BP)
1251 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1253 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
1257 /// Emit an expression as an initializer for a variable at the given
1258 /// location. The expression is not necessarily the normal
1259 /// initializer for the variable, and the address is not necessarily
1260 /// its normal location.
1262 /// \param init the initializing expression
1263 /// \param var the variable to act as if we're initializing
1264 /// \param loc the address to initialize; its type is a pointer
1265 /// to the LLVM mapping of the variable's type
1266 /// \param alignment the alignment of the address
1267 /// \param capturedByInit true if the variable is a __block variable
1268 /// whose address is potentially changed by the initializer
1269 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1270 LValue lvalue, bool capturedByInit) {
1271 QualType type = D->getType();
1273 if (type->isReferenceType()) {
1274 RValue rvalue = EmitReferenceBindingToExpr(init);
1276 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1277 EmitStoreThroughLValue(rvalue, lvalue, true);
1280 switch (getEvaluationKind(type)) {
1282 EmitScalarInit(init, D, lvalue, capturedByInit);
1285 ComplexPairTy complex = EmitComplexExpr(init);
1287 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1288 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1292 if (type->isAtomicType()) {
1293 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1295 // TODO: how can we delay here if D is captured by its initializer?
1296 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1297 AggValueSlot::IsDestructed,
1298 AggValueSlot::DoesNotNeedGCBarriers,
1299 AggValueSlot::IsNotAliased));
1303 llvm_unreachable("bad evaluation kind");
1306 /// Enter a destroy cleanup for the given local variable.
1307 void CodeGenFunction::emitAutoVarTypeCleanup(
1308 const CodeGenFunction::AutoVarEmission &emission,
1309 QualType::DestructionKind dtorKind) {
1310 assert(dtorKind != QualType::DK_none);
1312 // Note that for __block variables, we want to destroy the
1313 // original stack object, not the possibly forwarded object.
1314 Address addr = emission.getObjectAddress(*this);
1316 const VarDecl *var = emission.Variable;
1317 QualType type = var->getType();
1319 CleanupKind cleanupKind = NormalAndEHCleanup;
1320 CodeGenFunction::Destroyer *destroyer = nullptr;
1323 case QualType::DK_none:
1324 llvm_unreachable("no cleanup for trivially-destructible variable");
1326 case QualType::DK_cxx_destructor:
1327 // If there's an NRVO flag on the emission, we need a different
1329 if (emission.NRVOFlag) {
1330 assert(!type->isArrayType());
1331 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1332 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1333 dtor, emission.NRVOFlag);
1338 case QualType::DK_objc_strong_lifetime:
1339 // Suppress cleanups for pseudo-strong variables.
1340 if (var->isARCPseudoStrong()) return;
1342 // Otherwise, consider whether to use an EH cleanup or not.
1343 cleanupKind = getARCCleanupKind();
1345 // Use the imprecise destroyer by default.
1346 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1347 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1350 case QualType::DK_objc_weak_lifetime:
1354 // If we haven't chosen a more specific destroyer, use the default.
1355 if (!destroyer) destroyer = getDestroyer(dtorKind);
1357 // Use an EH cleanup in array destructors iff the destructor itself
1358 // is being pushed as an EH cleanup.
1359 bool useEHCleanup = (cleanupKind & EHCleanup);
1360 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1364 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1365 assert(emission.Variable && "emission was not valid!");
1367 // If this was emitted as a global constant, we're done.
1368 if (emission.wasEmittedAsGlobal()) return;
1370 // If we don't have an insertion point, we're done. Sema prevents
1371 // us from jumping into any of these scopes anyway.
1372 if (!HaveInsertPoint()) return;
1374 const VarDecl &D = *emission.Variable;
1376 // Make sure we call @llvm.lifetime.end. This needs to happen
1377 // *last*, so the cleanup needs to be pushed *first*.
1378 if (emission.useLifetimeMarkers())
1379 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1380 emission.getAllocatedAddress(),
1381 emission.getSizeForLifetimeMarkers());
1383 // Check the type for a cleanup.
1384 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1385 emitAutoVarTypeCleanup(emission, dtorKind);
1387 // In GC mode, honor objc_precise_lifetime.
1388 if (getLangOpts().getGC() != LangOptions::NonGC &&
1389 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1390 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1393 // Handle the cleanup attribute.
1394 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1395 const FunctionDecl *FD = CA->getFunctionDecl();
1397 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1398 assert(F && "Could not find function!");
1400 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
1401 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1404 // If this is a block variable, call _Block_object_destroy
1405 // (on the unforwarded address).
1406 if (emission.IsByRef)
1407 enterByrefCleanup(emission);
1410 CodeGenFunction::Destroyer *
1411 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1413 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1414 case QualType::DK_cxx_destructor:
1415 return destroyCXXObject;
1416 case QualType::DK_objc_strong_lifetime:
1417 return destroyARCStrongPrecise;
1418 case QualType::DK_objc_weak_lifetime:
1419 return destroyARCWeak;
1421 llvm_unreachable("Unknown DestructionKind");
1424 /// pushEHDestroy - Push the standard destructor for the given type as
1425 /// an EH-only cleanup.
1426 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1427 Address addr, QualType type) {
1428 assert(dtorKind && "cannot push destructor for trivial type");
1429 assert(needsEHCleanup(dtorKind));
1431 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1434 /// pushDestroy - Push the standard destructor for the given type as
1435 /// at least a normal cleanup.
1436 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1437 Address addr, QualType type) {
1438 assert(dtorKind && "cannot push destructor for trivial type");
1440 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1441 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1442 cleanupKind & EHCleanup);
1445 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
1446 QualType type, Destroyer *destroyer,
1447 bool useEHCleanupForArray) {
1448 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1449 destroyer, useEHCleanupForArray);
1452 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
1453 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1456 void CodeGenFunction::pushLifetimeExtendedDestroy(
1457 CleanupKind cleanupKind, Address addr, QualType type,
1458 Destroyer *destroyer, bool useEHCleanupForArray) {
1459 assert(!isInConditionalBranch() &&
1460 "performing lifetime extension from within conditional");
1462 // Push an EH-only cleanup for the object now.
1463 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1464 // around in case a temporary's destructor throws an exception.
1465 if (cleanupKind & EHCleanup)
1466 EHStack.pushCleanup<DestroyObject>(
1467 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1468 destroyer, useEHCleanupForArray);
1470 // Remember that we need to push a full cleanup for the object at the
1471 // end of the full-expression.
1472 pushCleanupAfterFullExpr<DestroyObject>(
1473 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1476 /// emitDestroy - Immediately perform the destruction of the given
1479 /// \param addr - the address of the object; a type*
1480 /// \param type - the type of the object; if an array type, all
1481 /// objects are destroyed in reverse order
1482 /// \param destroyer - the function to call to destroy individual
1484 /// \param useEHCleanupForArray - whether an EH cleanup should be
1485 /// used when destroying array elements, in case one of the
1486 /// destructions throws an exception
1487 void CodeGenFunction::emitDestroy(Address addr, QualType type,
1488 Destroyer *destroyer,
1489 bool useEHCleanupForArray) {
1490 const ArrayType *arrayType = getContext().getAsArrayType(type);
1492 return destroyer(*this, addr, type);
1494 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1496 CharUnits elementAlign =
1498 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1500 // Normally we have to check whether the array is zero-length.
1501 bool checkZeroLength = true;
1503 // But if the array length is constant, we can suppress that.
1504 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1505 // ...and if it's constant zero, we can just skip the entire thing.
1506 if (constLength->isZero()) return;
1507 checkZeroLength = false;
1510 llvm::Value *begin = addr.getPointer();
1511 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1512 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1513 checkZeroLength, useEHCleanupForArray);
1516 /// emitArrayDestroy - Destroys all the elements of the given array,
1517 /// beginning from last to first. The array cannot be zero-length.
1519 /// \param begin - a type* denoting the first element of the array
1520 /// \param end - a type* denoting one past the end of the array
1521 /// \param elementType - the element type of the array
1522 /// \param destroyer - the function to call to destroy elements
1523 /// \param useEHCleanup - whether to push an EH cleanup to destroy
1524 /// the remaining elements in case the destruction of a single
1526 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1528 QualType elementType,
1529 CharUnits elementAlign,
1530 Destroyer *destroyer,
1531 bool checkZeroLength,
1532 bool useEHCleanup) {
1533 assert(!elementType->isArrayType());
1535 // The basic structure here is a do-while loop, because we don't
1536 // need to check for the zero-element case.
1537 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1538 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1540 if (checkZeroLength) {
1541 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1542 "arraydestroy.isempty");
1543 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1546 // Enter the loop body, making that address the current address.
1547 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1549 llvm::PHINode *elementPast =
1550 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1551 elementPast->addIncoming(end, entryBB);
1553 // Shift the address back by one element.
1554 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1555 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1556 "arraydestroy.element");
1559 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1562 // Perform the actual destruction there.
1563 destroyer(*this, Address(element, elementAlign), elementType);
1568 // Check whether we've reached the end.
1569 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1570 Builder.CreateCondBr(done, doneBB, bodyBB);
1571 elementPast->addIncoming(element, Builder.GetInsertBlock());
1577 /// Perform partial array destruction as if in an EH cleanup. Unlike
1578 /// emitArrayDestroy, the element type here may still be an array type.
1579 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1580 llvm::Value *begin, llvm::Value *end,
1581 QualType type, CharUnits elementAlign,
1582 CodeGenFunction::Destroyer *destroyer) {
1583 // If the element type is itself an array, drill down.
1584 unsigned arrayDepth = 0;
1585 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1586 // VLAs don't require a GEP index to walk into.
1587 if (!isa<VariableArrayType>(arrayType))
1589 type = arrayType->getElementType();
1593 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1595 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
1596 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1597 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1600 // Destroy the array. We don't ever need an EH cleanup because we
1601 // assume that we're in an EH cleanup ourselves, so a throwing
1602 // destructor causes an immediate terminate.
1603 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1604 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1608 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1609 /// array destroy where the end pointer is regularly determined and
1610 /// does not need to be loaded from a local.
1611 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1612 llvm::Value *ArrayBegin;
1613 llvm::Value *ArrayEnd;
1614 QualType ElementType;
1615 CodeGenFunction::Destroyer *Destroyer;
1616 CharUnits ElementAlign;
1618 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1619 QualType elementType, CharUnits elementAlign,
1620 CodeGenFunction::Destroyer *destroyer)
1621 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1622 ElementType(elementType), Destroyer(destroyer),
1623 ElementAlign(elementAlign) {}
1625 void Emit(CodeGenFunction &CGF, Flags flags) override {
1626 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1627 ElementType, ElementAlign, Destroyer);
1631 /// IrregularPartialArrayDestroy - a cleanup which performs a
1632 /// partial array destroy where the end pointer is irregularly
1633 /// determined and must be loaded from a local.
1634 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1635 llvm::Value *ArrayBegin;
1636 Address ArrayEndPointer;
1637 QualType ElementType;
1638 CodeGenFunction::Destroyer *Destroyer;
1639 CharUnits ElementAlign;
1641 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1642 Address arrayEndPointer,
1643 QualType elementType,
1644 CharUnits elementAlign,
1645 CodeGenFunction::Destroyer *destroyer)
1646 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1647 ElementType(elementType), Destroyer(destroyer),
1648 ElementAlign(elementAlign) {}
1650 void Emit(CodeGenFunction &CGF, Flags flags) override {
1651 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1652 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1653 ElementType, ElementAlign, Destroyer);
1656 } // end anonymous namespace
1658 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1659 /// already-constructed elements of the given array. The cleanup
1660 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1662 /// \param elementType - the immediate element type of the array;
1663 /// possibly still an array type
1664 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1665 Address arrayEndPointer,
1666 QualType elementType,
1667 CharUnits elementAlign,
1668 Destroyer *destroyer) {
1669 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1670 arrayBegin, arrayEndPointer,
1671 elementType, elementAlign,
1675 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1676 /// already-constructed elements of the given array. The cleanup
1677 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1679 /// \param elementType - the immediate element type of the array;
1680 /// possibly still an array type
1681 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1682 llvm::Value *arrayEnd,
1683 QualType elementType,
1684 CharUnits elementAlign,
1685 Destroyer *destroyer) {
1686 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1687 arrayBegin, arrayEnd,
1688 elementType, elementAlign,
1692 /// Lazily declare the @llvm.lifetime.start intrinsic.
1693 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1694 if (LifetimeStartFn) return LifetimeStartFn;
1695 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1696 llvm::Intrinsic::lifetime_start);
1697 return LifetimeStartFn;
1700 /// Lazily declare the @llvm.lifetime.end intrinsic.
1701 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1702 if (LifetimeEndFn) return LifetimeEndFn;
1703 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1704 llvm::Intrinsic::lifetime_end);
1705 return LifetimeEndFn;
1709 /// A cleanup to perform a release of an object at the end of a
1710 /// function. This is used to balance out the incoming +1 of a
1711 /// ns_consumed argument when we can't reasonably do that just by
1712 /// not doing the initial retain for a __block argument.
1713 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
1714 ConsumeARCParameter(llvm::Value *param,
1715 ARCPreciseLifetime_t precise)
1716 : Param(param), Precise(precise) {}
1719 ARCPreciseLifetime_t Precise;
1721 void Emit(CodeGenFunction &CGF, Flags flags) override {
1722 CGF.EmitARCRelease(Param, Precise);
1725 } // end anonymous namespace
1727 /// Emit an alloca (or GlobalValue depending on target)
1728 /// for the specified parameter and set up LocalDeclMap.
1729 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1731 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1732 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1733 "Invalid argument to EmitParmDecl");
1735 Arg.getAnyValue()->setName(D.getName());
1737 QualType Ty = D.getType();
1739 // Use better IR generation for certain implicit parameters.
1740 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
1741 // The only implicit argument a block has is its literal.
1742 // We assume this is always passed directly.
1744 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
1748 // Apply any prologue 'this' adjustments required by the ABI. Be careful to
1749 // handle the case where 'this' is passed indirectly as part of an inalloca
1751 if (const CXXMethodDecl *MD =
1752 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
1753 if (MD->isVirtual() && IPD == CXXABIThisDecl) {
1754 llvm::Value *This = Arg.isIndirect()
1755 ? Builder.CreateLoad(Arg.getIndirectAddress())
1756 : Arg.getDirectValue();
1757 This = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue(
1758 *this, CurGD, This);
1759 if (Arg.isIndirect())
1760 Builder.CreateStore(This, Arg.getIndirectAddress());
1762 Arg = ParamValue::forDirect(This);
1767 Address DeclPtr = Address::invalid();
1768 bool DoStore = false;
1769 bool IsScalar = hasScalarEvaluationKind(Ty);
1770 // If we already have a pointer to the argument, reuse the input pointer.
1771 if (Arg.isIndirect()) {
1772 DeclPtr = Arg.getIndirectAddress();
1773 // If we have a prettier pointer type at this point, bitcast to that.
1774 unsigned AS = DeclPtr.getType()->getAddressSpace();
1775 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
1776 if (DeclPtr.getType() != IRTy)
1777 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1779 // Push a destructor cleanup for this parameter if the ABI requires it.
1780 // Don't push a cleanup in a thunk for a method that will also emit a
1782 if (!IsScalar && !CurFuncIsThunk &&
1783 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1784 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1785 if (RD && RD->hasNonTrivialDestructor())
1786 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
1789 // Otherwise, create a temporary to hold the value.
1790 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1791 D.getName() + ".addr");
1795 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1797 LValue lv = MakeAddrLValue(DeclPtr, Ty);
1799 Qualifiers qs = Ty.getQualifiers();
1800 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1801 // We honor __attribute__((ns_consumed)) for types with lifetime.
1802 // For __strong, it's handled by just skipping the initial retain;
1803 // otherwise we have to balance out the initial +1 with an extra
1804 // cleanup to do the release at the end of the function.
1805 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1807 // 'self' is always formally __strong, but if this is not an
1808 // init method then we don't want to retain it.
1809 if (D.isARCPseudoStrong()) {
1810 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1811 assert(&D == method->getSelfDecl());
1812 assert(lt == Qualifiers::OCL_Strong);
1813 assert(qs.hasConst());
1814 assert(method->getMethodFamily() != OMF_init);
1816 lt = Qualifiers::OCL_ExplicitNone;
1819 if (lt == Qualifiers::OCL_Strong) {
1821 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1822 // use objc_storeStrong(&dest, value) for retaining the
1823 // object. But first, store a null into 'dest' because
1824 // objc_storeStrong attempts to release its old value.
1825 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
1826 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1827 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
1831 // Don't use objc_retainBlock for block pointers, because we
1832 // don't want to Block_copy something just because we got it
1834 ArgVal = EmitARCRetainNonBlock(ArgVal);
1837 // Push the cleanup for a consumed parameter.
1839 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1840 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1841 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
1845 if (lt == Qualifiers::OCL_Weak) {
1846 EmitARCInitWeak(DeclPtr, ArgVal);
1847 DoStore = false; // The weak init is a store, no need to do two.
1851 // Enter the cleanup scope.
1852 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1856 // Store the initial value into the alloca.
1858 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
1860 setAddrOfLocalVar(&D, DeclPtr);
1862 // Emit debug info for param declaration.
1863 if (CGDebugInfo *DI = getDebugInfo()) {
1864 if (CGM.getCodeGenOpts().getDebugInfo() >=
1865 codegenoptions::LimitedDebugInfo) {
1866 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
1870 if (D.hasAttr<AnnotateAttr>())
1871 EmitVarAnnotations(&D, DeclPtr.getPointer());
1874 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1875 CodeGenFunction *CGF) {
1876 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1878 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);