1f4a2713aSLionel Sambuc //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc // The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This contains code to emit Decl nodes as LLVM code.
11f4a2713aSLionel Sambuc //
12f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
13f4a2713aSLionel Sambuc
14f4a2713aSLionel Sambuc #include "CodeGenFunction.h"
15f4a2713aSLionel Sambuc #include "CGDebugInfo.h"
16f4a2713aSLionel Sambuc #include "CGOpenCLRuntime.h"
17f4a2713aSLionel Sambuc #include "CodeGenModule.h"
18f4a2713aSLionel Sambuc #include "clang/AST/ASTContext.h"
19f4a2713aSLionel Sambuc #include "clang/AST/CharUnits.h"
20f4a2713aSLionel Sambuc #include "clang/AST/Decl.h"
21f4a2713aSLionel Sambuc #include "clang/AST/DeclObjC.h"
22f4a2713aSLionel Sambuc #include "clang/Basic/SourceManager.h"
23f4a2713aSLionel Sambuc #include "clang/Basic/TargetInfo.h"
24f4a2713aSLionel Sambuc #include "clang/CodeGen/CGFunctionInfo.h"
25f4a2713aSLionel Sambuc #include "clang/Frontend/CodeGenOptions.h"
26f4a2713aSLionel Sambuc #include "llvm/IR/DataLayout.h"
27f4a2713aSLionel Sambuc #include "llvm/IR/GlobalVariable.h"
28f4a2713aSLionel Sambuc #include "llvm/IR/Intrinsics.h"
29f4a2713aSLionel Sambuc #include "llvm/IR/Type.h"
30f4a2713aSLionel Sambuc using namespace clang;
31f4a2713aSLionel Sambuc using namespace CodeGen;
32f4a2713aSLionel Sambuc
33f4a2713aSLionel Sambuc
EmitDecl(const Decl & D)34f4a2713aSLionel Sambuc void CodeGenFunction::EmitDecl(const Decl &D) {
35f4a2713aSLionel Sambuc switch (D.getKind()) {
36f4a2713aSLionel Sambuc case Decl::TranslationUnit:
37f4a2713aSLionel Sambuc case Decl::Namespace:
38f4a2713aSLionel Sambuc case Decl::UnresolvedUsingTypename:
39f4a2713aSLionel Sambuc case Decl::ClassTemplateSpecialization:
40f4a2713aSLionel Sambuc case Decl::ClassTemplatePartialSpecialization:
41f4a2713aSLionel Sambuc case Decl::VarTemplateSpecialization:
42f4a2713aSLionel Sambuc case Decl::VarTemplatePartialSpecialization:
43f4a2713aSLionel Sambuc case Decl::TemplateTypeParm:
44f4a2713aSLionel Sambuc case Decl::UnresolvedUsingValue:
45f4a2713aSLionel Sambuc case Decl::NonTypeTemplateParm:
46f4a2713aSLionel Sambuc case Decl::CXXMethod:
47f4a2713aSLionel Sambuc case Decl::CXXConstructor:
48f4a2713aSLionel Sambuc case Decl::CXXDestructor:
49f4a2713aSLionel Sambuc case Decl::CXXConversion:
50f4a2713aSLionel Sambuc case Decl::Field:
51f4a2713aSLionel Sambuc case Decl::MSProperty:
52f4a2713aSLionel Sambuc case Decl::IndirectField:
53f4a2713aSLionel Sambuc case Decl::ObjCIvar:
54f4a2713aSLionel Sambuc case Decl::ObjCAtDefsField:
55f4a2713aSLionel Sambuc case Decl::ParmVar:
56f4a2713aSLionel Sambuc case Decl::ImplicitParam:
57f4a2713aSLionel Sambuc case Decl::ClassTemplate:
58f4a2713aSLionel Sambuc case Decl::VarTemplate:
59f4a2713aSLionel Sambuc case Decl::FunctionTemplate:
60f4a2713aSLionel Sambuc case Decl::TypeAliasTemplate:
61f4a2713aSLionel Sambuc case Decl::TemplateTemplateParm:
62f4a2713aSLionel Sambuc case Decl::ObjCMethod:
63f4a2713aSLionel Sambuc case Decl::ObjCCategory:
64f4a2713aSLionel Sambuc case Decl::ObjCProtocol:
65f4a2713aSLionel Sambuc case Decl::ObjCInterface:
66f4a2713aSLionel Sambuc case Decl::ObjCCategoryImpl:
67f4a2713aSLionel Sambuc case Decl::ObjCImplementation:
68f4a2713aSLionel Sambuc case Decl::ObjCProperty:
69f4a2713aSLionel Sambuc case Decl::ObjCCompatibleAlias:
70f4a2713aSLionel Sambuc case Decl::AccessSpec:
71f4a2713aSLionel Sambuc case Decl::LinkageSpec:
72f4a2713aSLionel Sambuc case Decl::ObjCPropertyImpl:
73f4a2713aSLionel Sambuc case Decl::FileScopeAsm:
74f4a2713aSLionel Sambuc case Decl::Friend:
75f4a2713aSLionel Sambuc case Decl::FriendTemplate:
76f4a2713aSLionel Sambuc case Decl::Block:
77f4a2713aSLionel Sambuc case Decl::Captured:
78f4a2713aSLionel Sambuc case Decl::ClassScopeFunctionSpecialization:
79f4a2713aSLionel Sambuc case Decl::UsingShadow:
80f4a2713aSLionel Sambuc llvm_unreachable("Declaration should not be in declstmts!");
81f4a2713aSLionel Sambuc case Decl::Function: // void X();
82f4a2713aSLionel Sambuc case Decl::Record: // struct/union/class X;
83f4a2713aSLionel Sambuc case Decl::Enum: // enum X;
84f4a2713aSLionel Sambuc case Decl::EnumConstant: // enum ? { X = ? }
85f4a2713aSLionel Sambuc case Decl::CXXRecord: // struct/union/class X; [C++]
86f4a2713aSLionel Sambuc case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
87f4a2713aSLionel Sambuc case Decl::Label: // __label__ x;
88f4a2713aSLionel Sambuc case Decl::Import:
89f4a2713aSLionel Sambuc case Decl::OMPThreadPrivate:
90f4a2713aSLionel Sambuc case Decl::Empty:
91f4a2713aSLionel Sambuc // None of these decls require codegen support.
92f4a2713aSLionel Sambuc return;
93f4a2713aSLionel Sambuc
94f4a2713aSLionel Sambuc case Decl::NamespaceAlias:
95f4a2713aSLionel Sambuc if (CGDebugInfo *DI = getDebugInfo())
96f4a2713aSLionel Sambuc DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
97f4a2713aSLionel Sambuc return;
98f4a2713aSLionel Sambuc case Decl::Using: // using X; [C++]
99f4a2713aSLionel Sambuc if (CGDebugInfo *DI = getDebugInfo())
100f4a2713aSLionel Sambuc DI->EmitUsingDecl(cast<UsingDecl>(D));
101f4a2713aSLionel Sambuc return;
102f4a2713aSLionel Sambuc case Decl::UsingDirective: // using namespace X; [C++]
103f4a2713aSLionel Sambuc if (CGDebugInfo *DI = getDebugInfo())
104f4a2713aSLionel Sambuc DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
105f4a2713aSLionel Sambuc return;
106f4a2713aSLionel Sambuc case Decl::Var: {
107f4a2713aSLionel Sambuc const VarDecl &VD = cast<VarDecl>(D);
108f4a2713aSLionel Sambuc assert(VD.isLocalVarDecl() &&
109f4a2713aSLionel Sambuc "Should not see file-scope variables inside a function!");
110f4a2713aSLionel Sambuc return EmitVarDecl(VD);
111f4a2713aSLionel Sambuc }
112f4a2713aSLionel Sambuc
113f4a2713aSLionel Sambuc case Decl::Typedef: // typedef int X;
114f4a2713aSLionel Sambuc case Decl::TypeAlias: { // using X = int; [C++0x]
115f4a2713aSLionel Sambuc const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
116f4a2713aSLionel Sambuc QualType Ty = TD.getUnderlyingType();
117f4a2713aSLionel Sambuc
118f4a2713aSLionel Sambuc if (Ty->isVariablyModifiedType())
119f4a2713aSLionel Sambuc EmitVariablyModifiedType(Ty);
120f4a2713aSLionel Sambuc }
121f4a2713aSLionel Sambuc }
122f4a2713aSLionel Sambuc }
123f4a2713aSLionel Sambuc
124f4a2713aSLionel Sambuc /// EmitVarDecl - This method handles emission of any variable declaration
125f4a2713aSLionel Sambuc /// inside a function, including static vars etc.
EmitVarDecl(const VarDecl & D)126f4a2713aSLionel Sambuc void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
127f4a2713aSLionel Sambuc if (D.isStaticLocal()) {
128f4a2713aSLionel Sambuc llvm::GlobalValue::LinkageTypes Linkage =
129*0a6a1f1dSLionel Sambuc CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
130f4a2713aSLionel Sambuc
131f4a2713aSLionel Sambuc // FIXME: We need to force the emission/use of a guard variable for
132f4a2713aSLionel Sambuc // some variables even if we can constant-evaluate them because
133f4a2713aSLionel Sambuc // we can't guarantee every translation unit will constant-evaluate them.
134f4a2713aSLionel Sambuc
135f4a2713aSLionel Sambuc return EmitStaticVarDecl(D, Linkage);
136f4a2713aSLionel Sambuc }
137f4a2713aSLionel Sambuc
138f4a2713aSLionel Sambuc if (D.hasExternalStorage())
139f4a2713aSLionel Sambuc // Don't emit it now, allow it to be emitted lazily on its first use.
140f4a2713aSLionel Sambuc return;
141f4a2713aSLionel Sambuc
142f4a2713aSLionel Sambuc if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
143f4a2713aSLionel Sambuc return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
144f4a2713aSLionel Sambuc
145f4a2713aSLionel Sambuc assert(D.hasLocalStorage());
146f4a2713aSLionel Sambuc return EmitAutoVarDecl(D);
147f4a2713aSLionel Sambuc }
148f4a2713aSLionel Sambuc
getStaticDeclName(CodeGenModule & CGM,const VarDecl & D)149*0a6a1f1dSLionel Sambuc static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
150*0a6a1f1dSLionel Sambuc if (CGM.getLangOpts().CPlusPlus)
151*0a6a1f1dSLionel Sambuc return CGM.getMangledName(&D).str();
152f4a2713aSLionel Sambuc
153*0a6a1f1dSLionel Sambuc // If this isn't C++, we don't need a mangled name, just a pretty one.
154*0a6a1f1dSLionel Sambuc assert(!D.isExternallyVisible() && "name shouldn't matter");
155f4a2713aSLionel Sambuc std::string ContextName;
156*0a6a1f1dSLionel Sambuc const DeclContext *DC = D.getDeclContext();
157*0a6a1f1dSLionel Sambuc if (const auto *FD = dyn_cast<FunctionDecl>(DC))
158*0a6a1f1dSLionel Sambuc ContextName = CGM.getMangledName(FD);
159*0a6a1f1dSLionel Sambuc else if (const auto *BD = dyn_cast<BlockDecl>(DC))
160*0a6a1f1dSLionel Sambuc ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
161*0a6a1f1dSLionel Sambuc else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
162*0a6a1f1dSLionel Sambuc ContextName = OMD->getSelector().getAsString();
163f4a2713aSLionel Sambuc else
164f4a2713aSLionel Sambuc llvm_unreachable("Unknown context for static var decl");
165f4a2713aSLionel Sambuc
166*0a6a1f1dSLionel Sambuc ContextName += "." + D.getNameAsString();
167*0a6a1f1dSLionel Sambuc return ContextName;
168f4a2713aSLionel Sambuc }
169f4a2713aSLionel Sambuc
getOrCreateStaticVarDecl(const VarDecl & D,llvm::GlobalValue::LinkageTypes Linkage)170*0a6a1f1dSLionel Sambuc llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
171*0a6a1f1dSLionel Sambuc const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
172*0a6a1f1dSLionel Sambuc // In general, we don't always emit static var decls once before we reference
173*0a6a1f1dSLionel Sambuc // them. It is possible to reference them before emitting the function that
174*0a6a1f1dSLionel Sambuc // contains them, and it is possible to emit the containing function multiple
175*0a6a1f1dSLionel Sambuc // times.
176*0a6a1f1dSLionel Sambuc if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
177*0a6a1f1dSLionel Sambuc return ExistingGV;
178*0a6a1f1dSLionel Sambuc
179f4a2713aSLionel Sambuc QualType Ty = D.getType();
180f4a2713aSLionel Sambuc assert(Ty->isConstantSizeType() && "VLAs can't be static");
181f4a2713aSLionel Sambuc
182f4a2713aSLionel Sambuc // Use the label if the variable is renamed with the asm-label extension.
183f4a2713aSLionel Sambuc std::string Name;
184f4a2713aSLionel Sambuc if (D.hasAttr<AsmLabelAttr>())
185*0a6a1f1dSLionel Sambuc Name = getMangledName(&D);
186f4a2713aSLionel Sambuc else
187*0a6a1f1dSLionel Sambuc Name = getStaticDeclName(*this, D);
188f4a2713aSLionel Sambuc
189*0a6a1f1dSLionel Sambuc llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
190f4a2713aSLionel Sambuc unsigned AddrSpace =
191*0a6a1f1dSLionel Sambuc GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
192*0a6a1f1dSLionel Sambuc
193*0a6a1f1dSLionel Sambuc // Local address space cannot have an initializer.
194*0a6a1f1dSLionel Sambuc llvm::Constant *Init = nullptr;
195*0a6a1f1dSLionel Sambuc if (Ty.getAddressSpace() != LangAS::opencl_local)
196*0a6a1f1dSLionel Sambuc Init = EmitNullConstant(Ty);
197*0a6a1f1dSLionel Sambuc else
198*0a6a1f1dSLionel Sambuc Init = llvm::UndefValue::get(LTy);
199*0a6a1f1dSLionel Sambuc
200f4a2713aSLionel Sambuc llvm::GlobalVariable *GV =
201*0a6a1f1dSLionel Sambuc new llvm::GlobalVariable(getModule(), LTy,
202f4a2713aSLionel Sambuc Ty.isConstant(getContext()), Linkage,
203*0a6a1f1dSLionel Sambuc Init, Name, nullptr,
204f4a2713aSLionel Sambuc llvm::GlobalVariable::NotThreadLocal,
205f4a2713aSLionel Sambuc AddrSpace);
206f4a2713aSLionel Sambuc GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
207*0a6a1f1dSLionel Sambuc setGlobalVisibility(GV, &D);
208f4a2713aSLionel Sambuc
209f4a2713aSLionel Sambuc if (D.getTLSKind())
210*0a6a1f1dSLionel Sambuc setTLSMode(GV, D);
211f4a2713aSLionel Sambuc
212*0a6a1f1dSLionel Sambuc if (D.isExternallyVisible()) {
213*0a6a1f1dSLionel Sambuc if (D.hasAttr<DLLImportAttr>())
214*0a6a1f1dSLionel Sambuc GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
215*0a6a1f1dSLionel Sambuc else if (D.hasAttr<DLLExportAttr>())
216*0a6a1f1dSLionel Sambuc GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
217*0a6a1f1dSLionel Sambuc }
218*0a6a1f1dSLionel Sambuc
219*0a6a1f1dSLionel Sambuc // Make sure the result is of the correct type.
220*0a6a1f1dSLionel Sambuc unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
221*0a6a1f1dSLionel Sambuc llvm::Constant *Addr = GV;
222*0a6a1f1dSLionel Sambuc if (AddrSpace != ExpectedAddrSpace) {
223*0a6a1f1dSLionel Sambuc llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
224*0a6a1f1dSLionel Sambuc Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
225*0a6a1f1dSLionel Sambuc }
226*0a6a1f1dSLionel Sambuc
227*0a6a1f1dSLionel Sambuc setStaticLocalDeclAddress(&D, Addr);
228*0a6a1f1dSLionel Sambuc
229*0a6a1f1dSLionel Sambuc // Ensure that the static local gets initialized by making sure the parent
230*0a6a1f1dSLionel Sambuc // function gets emitted eventually.
231*0a6a1f1dSLionel Sambuc const Decl *DC = cast<Decl>(D.getDeclContext());
232*0a6a1f1dSLionel Sambuc
233*0a6a1f1dSLionel Sambuc // We can't name blocks or captured statements directly, so try to emit their
234*0a6a1f1dSLionel Sambuc // parents.
235*0a6a1f1dSLionel Sambuc if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
236*0a6a1f1dSLionel Sambuc DC = DC->getNonClosureContext();
237*0a6a1f1dSLionel Sambuc // FIXME: Ensure that global blocks get emitted.
238*0a6a1f1dSLionel Sambuc if (!DC)
239*0a6a1f1dSLionel Sambuc return Addr;
240*0a6a1f1dSLionel Sambuc }
241*0a6a1f1dSLionel Sambuc
242*0a6a1f1dSLionel Sambuc GlobalDecl GD;
243*0a6a1f1dSLionel Sambuc if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
244*0a6a1f1dSLionel Sambuc GD = GlobalDecl(CD, Ctor_Base);
245*0a6a1f1dSLionel Sambuc else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
246*0a6a1f1dSLionel Sambuc GD = GlobalDecl(DD, Dtor_Base);
247*0a6a1f1dSLionel Sambuc else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
248*0a6a1f1dSLionel Sambuc GD = GlobalDecl(FD);
249*0a6a1f1dSLionel Sambuc else {
250*0a6a1f1dSLionel Sambuc // Don't do anything for Obj-C method decls or global closures. We should
251*0a6a1f1dSLionel Sambuc // never defer them.
252*0a6a1f1dSLionel Sambuc assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
253*0a6a1f1dSLionel Sambuc }
254*0a6a1f1dSLionel Sambuc if (GD.getDecl())
255*0a6a1f1dSLionel Sambuc (void)GetAddrOfGlobal(GD);
256*0a6a1f1dSLionel Sambuc
257*0a6a1f1dSLionel Sambuc return Addr;
258f4a2713aSLionel Sambuc }
259f4a2713aSLionel Sambuc
260f4a2713aSLionel Sambuc /// hasNontrivialDestruction - Determine whether a type's destruction is
261f4a2713aSLionel Sambuc /// non-trivial. If so, and the variable uses static initialization, we must
262f4a2713aSLionel Sambuc /// register its destructor to run on exit.
hasNontrivialDestruction(QualType T)263f4a2713aSLionel Sambuc static bool hasNontrivialDestruction(QualType T) {
264f4a2713aSLionel Sambuc CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
265f4a2713aSLionel Sambuc return RD && !RD->hasTrivialDestructor();
266f4a2713aSLionel Sambuc }
267f4a2713aSLionel Sambuc
268f4a2713aSLionel Sambuc /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
269f4a2713aSLionel Sambuc /// global variable that has already been created for it. If the initializer
270f4a2713aSLionel Sambuc /// has a different type than GV does, this may free GV and return a different
271f4a2713aSLionel Sambuc /// one. Otherwise it just returns GV.
272f4a2713aSLionel Sambuc llvm::GlobalVariable *
AddInitializerToStaticVarDecl(const VarDecl & D,llvm::GlobalVariable * GV)273f4a2713aSLionel Sambuc CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
274f4a2713aSLionel Sambuc llvm::GlobalVariable *GV) {
275f4a2713aSLionel Sambuc llvm::Constant *Init = CGM.EmitConstantInit(D, this);
276f4a2713aSLionel Sambuc
277f4a2713aSLionel Sambuc // If constant emission failed, then this should be a C++ static
278f4a2713aSLionel Sambuc // initializer.
279f4a2713aSLionel Sambuc if (!Init) {
280f4a2713aSLionel Sambuc if (!getLangOpts().CPlusPlus)
281f4a2713aSLionel Sambuc CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
282f4a2713aSLionel Sambuc else if (Builder.GetInsertBlock()) {
283f4a2713aSLionel Sambuc // Since we have a static initializer, this global variable can't
284f4a2713aSLionel Sambuc // be constant.
285f4a2713aSLionel Sambuc GV->setConstant(false);
286f4a2713aSLionel Sambuc
287f4a2713aSLionel Sambuc EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
288f4a2713aSLionel Sambuc }
289f4a2713aSLionel Sambuc return GV;
290f4a2713aSLionel Sambuc }
291f4a2713aSLionel Sambuc
292f4a2713aSLionel Sambuc // The initializer may differ in type from the global. Rewrite
293f4a2713aSLionel Sambuc // the global to match the initializer. (We have to do this
294f4a2713aSLionel Sambuc // because some types, like unions, can't be completely represented
295f4a2713aSLionel Sambuc // in the LLVM type system.)
296f4a2713aSLionel Sambuc if (GV->getType()->getElementType() != Init->getType()) {
297f4a2713aSLionel Sambuc llvm::GlobalVariable *OldGV = GV;
298f4a2713aSLionel Sambuc
299f4a2713aSLionel Sambuc GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
300f4a2713aSLionel Sambuc OldGV->isConstant(),
301f4a2713aSLionel Sambuc OldGV->getLinkage(), Init, "",
302f4a2713aSLionel Sambuc /*InsertBefore*/ OldGV,
303f4a2713aSLionel Sambuc OldGV->getThreadLocalMode(),
304f4a2713aSLionel Sambuc CGM.getContext().getTargetAddressSpace(D.getType()));
305f4a2713aSLionel Sambuc GV->setVisibility(OldGV->getVisibility());
306f4a2713aSLionel Sambuc
307f4a2713aSLionel Sambuc // Steal the name of the old global
308f4a2713aSLionel Sambuc GV->takeName(OldGV);
309f4a2713aSLionel Sambuc
310f4a2713aSLionel Sambuc // Replace all uses of the old global with the new global
311f4a2713aSLionel Sambuc llvm::Constant *NewPtrForOldDecl =
312f4a2713aSLionel Sambuc llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
313f4a2713aSLionel Sambuc OldGV->replaceAllUsesWith(NewPtrForOldDecl);
314f4a2713aSLionel Sambuc
315f4a2713aSLionel Sambuc // Erase the old global, since it is no longer used.
316f4a2713aSLionel Sambuc OldGV->eraseFromParent();
317f4a2713aSLionel Sambuc }
318f4a2713aSLionel Sambuc
319f4a2713aSLionel Sambuc GV->setConstant(CGM.isTypeConstant(D.getType(), true));
320f4a2713aSLionel Sambuc GV->setInitializer(Init);
321f4a2713aSLionel Sambuc
322f4a2713aSLionel Sambuc if (hasNontrivialDestruction(D.getType())) {
323f4a2713aSLionel Sambuc // We have a constant initializer, but a nontrivial destructor. We still
324f4a2713aSLionel Sambuc // need to perform a guarded "initialization" in order to register the
325f4a2713aSLionel Sambuc // destructor.
326f4a2713aSLionel Sambuc EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
327f4a2713aSLionel Sambuc }
328f4a2713aSLionel Sambuc
329f4a2713aSLionel Sambuc return GV;
330f4a2713aSLionel Sambuc }
331f4a2713aSLionel Sambuc
EmitStaticVarDecl(const VarDecl & D,llvm::GlobalValue::LinkageTypes Linkage)332f4a2713aSLionel Sambuc void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
333f4a2713aSLionel Sambuc llvm::GlobalValue::LinkageTypes Linkage) {
334f4a2713aSLionel Sambuc llvm::Value *&DMEntry = LocalDeclMap[&D];
335*0a6a1f1dSLionel Sambuc assert(!DMEntry && "Decl already exists in localdeclmap!");
336f4a2713aSLionel Sambuc
337f4a2713aSLionel Sambuc // Check to see if we already have a global variable for this
338f4a2713aSLionel Sambuc // declaration. This can happen when double-emitting function
339f4a2713aSLionel Sambuc // bodies, e.g. with complete and base constructors.
340*0a6a1f1dSLionel Sambuc llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
341f4a2713aSLionel Sambuc
342f4a2713aSLionel Sambuc // Store into LocalDeclMap before generating initializer to handle
343f4a2713aSLionel Sambuc // circular references.
344f4a2713aSLionel Sambuc DMEntry = addr;
345f4a2713aSLionel Sambuc
346f4a2713aSLionel Sambuc // We can't have a VLA here, but we can have a pointer to a VLA,
347f4a2713aSLionel Sambuc // even though that doesn't really make any sense.
348f4a2713aSLionel Sambuc // Make sure to evaluate VLA bounds now so that we have them for later.
349f4a2713aSLionel Sambuc if (D.getType()->isVariablyModifiedType())
350f4a2713aSLionel Sambuc EmitVariablyModifiedType(D.getType());
351f4a2713aSLionel Sambuc
352f4a2713aSLionel Sambuc // Save the type in case adding the initializer forces a type change.
353f4a2713aSLionel Sambuc llvm::Type *expectedType = addr->getType();
354f4a2713aSLionel Sambuc
355*0a6a1f1dSLionel Sambuc llvm::GlobalVariable *var =
356*0a6a1f1dSLionel Sambuc cast<llvm::GlobalVariable>(addr->stripPointerCasts());
357f4a2713aSLionel Sambuc // If this value has an initializer, emit it.
358f4a2713aSLionel Sambuc if (D.getInit())
359f4a2713aSLionel Sambuc var = AddInitializerToStaticVarDecl(D, var);
360f4a2713aSLionel Sambuc
361f4a2713aSLionel Sambuc var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
362f4a2713aSLionel Sambuc
363f4a2713aSLionel Sambuc if (D.hasAttr<AnnotateAttr>())
364f4a2713aSLionel Sambuc CGM.AddGlobalAnnotations(&D, var);
365f4a2713aSLionel Sambuc
366f4a2713aSLionel Sambuc if (const SectionAttr *SA = D.getAttr<SectionAttr>())
367f4a2713aSLionel Sambuc var->setSection(SA->getName());
368f4a2713aSLionel Sambuc
369f4a2713aSLionel Sambuc if (D.hasAttr<UsedAttr>())
370*0a6a1f1dSLionel Sambuc CGM.addUsedGlobal(var);
371f4a2713aSLionel Sambuc
372f4a2713aSLionel Sambuc // We may have to cast the constant because of the initializer
373f4a2713aSLionel Sambuc // mismatch above.
374f4a2713aSLionel Sambuc //
375f4a2713aSLionel Sambuc // FIXME: It is really dangerous to store this in the map; if anyone
376f4a2713aSLionel Sambuc // RAUW's the GV uses of this constant will be invalid.
377*0a6a1f1dSLionel Sambuc llvm::Constant *castedAddr =
378*0a6a1f1dSLionel Sambuc llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
379f4a2713aSLionel Sambuc DMEntry = castedAddr;
380f4a2713aSLionel Sambuc CGM.setStaticLocalDeclAddress(&D, castedAddr);
381f4a2713aSLionel Sambuc
382*0a6a1f1dSLionel Sambuc CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
383*0a6a1f1dSLionel Sambuc
384f4a2713aSLionel Sambuc // Emit global variable debug descriptor for static vars.
385f4a2713aSLionel Sambuc CGDebugInfo *DI = getDebugInfo();
386f4a2713aSLionel Sambuc if (DI &&
387f4a2713aSLionel Sambuc CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
388f4a2713aSLionel Sambuc DI->setLocation(D.getLocation());
389f4a2713aSLionel Sambuc DI->EmitGlobalVariable(var, &D);
390f4a2713aSLionel Sambuc }
391f4a2713aSLionel Sambuc }
392f4a2713aSLionel Sambuc
393f4a2713aSLionel Sambuc namespace {
394f4a2713aSLionel Sambuc struct DestroyObject : EHScopeStack::Cleanup {
DestroyObject__anon398828f30111::DestroyObject395f4a2713aSLionel Sambuc DestroyObject(llvm::Value *addr, QualType type,
396f4a2713aSLionel Sambuc CodeGenFunction::Destroyer *destroyer,
397f4a2713aSLionel Sambuc bool useEHCleanupForArray)
398f4a2713aSLionel Sambuc : addr(addr), type(type), destroyer(destroyer),
399f4a2713aSLionel Sambuc useEHCleanupForArray(useEHCleanupForArray) {}
400f4a2713aSLionel Sambuc
401f4a2713aSLionel Sambuc llvm::Value *addr;
402f4a2713aSLionel Sambuc QualType type;
403f4a2713aSLionel Sambuc CodeGenFunction::Destroyer *destroyer;
404f4a2713aSLionel Sambuc bool useEHCleanupForArray;
405f4a2713aSLionel Sambuc
Emit__anon398828f30111::DestroyObject406*0a6a1f1dSLionel Sambuc void Emit(CodeGenFunction &CGF, Flags flags) override {
407f4a2713aSLionel Sambuc // Don't use an EH cleanup recursively from an EH cleanup.
408f4a2713aSLionel Sambuc bool useEHCleanupForArray =
409f4a2713aSLionel Sambuc flags.isForNormalCleanup() && this->useEHCleanupForArray;
410f4a2713aSLionel Sambuc
411f4a2713aSLionel Sambuc CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
412f4a2713aSLionel Sambuc }
413f4a2713aSLionel Sambuc };
414f4a2713aSLionel Sambuc
415f4a2713aSLionel Sambuc struct DestroyNRVOVariable : EHScopeStack::Cleanup {
DestroyNRVOVariable__anon398828f30111::DestroyNRVOVariable416f4a2713aSLionel Sambuc DestroyNRVOVariable(llvm::Value *addr,
417f4a2713aSLionel Sambuc const CXXDestructorDecl *Dtor,
418f4a2713aSLionel Sambuc llvm::Value *NRVOFlag)
419f4a2713aSLionel Sambuc : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
420f4a2713aSLionel Sambuc
421f4a2713aSLionel Sambuc const CXXDestructorDecl *Dtor;
422f4a2713aSLionel Sambuc llvm::Value *NRVOFlag;
423f4a2713aSLionel Sambuc llvm::Value *Loc;
424f4a2713aSLionel Sambuc
Emit__anon398828f30111::DestroyNRVOVariable425*0a6a1f1dSLionel Sambuc void Emit(CodeGenFunction &CGF, Flags flags) override {
426f4a2713aSLionel Sambuc // Along the exceptions path we always execute the dtor.
427f4a2713aSLionel Sambuc bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
428f4a2713aSLionel Sambuc
429*0a6a1f1dSLionel Sambuc llvm::BasicBlock *SkipDtorBB = nullptr;
430f4a2713aSLionel Sambuc if (NRVO) {
431f4a2713aSLionel Sambuc // If we exited via NRVO, we skip the destructor call.
432f4a2713aSLionel Sambuc llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
433f4a2713aSLionel Sambuc SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
434f4a2713aSLionel Sambuc llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
435f4a2713aSLionel Sambuc CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
436f4a2713aSLionel Sambuc CGF.EmitBlock(RunDtorBB);
437f4a2713aSLionel Sambuc }
438f4a2713aSLionel Sambuc
439f4a2713aSLionel Sambuc CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
440f4a2713aSLionel Sambuc /*ForVirtualBase=*/false,
441f4a2713aSLionel Sambuc /*Delegating=*/false,
442f4a2713aSLionel Sambuc Loc);
443f4a2713aSLionel Sambuc
444f4a2713aSLionel Sambuc if (NRVO) CGF.EmitBlock(SkipDtorBB);
445f4a2713aSLionel Sambuc }
446f4a2713aSLionel Sambuc };
447f4a2713aSLionel Sambuc
448f4a2713aSLionel Sambuc struct CallStackRestore : EHScopeStack::Cleanup {
449f4a2713aSLionel Sambuc llvm::Value *Stack;
CallStackRestore__anon398828f30111::CallStackRestore450f4a2713aSLionel Sambuc CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
Emit__anon398828f30111::CallStackRestore451*0a6a1f1dSLionel Sambuc void Emit(CodeGenFunction &CGF, Flags flags) override {
452f4a2713aSLionel Sambuc llvm::Value *V = CGF.Builder.CreateLoad(Stack);
453f4a2713aSLionel Sambuc llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
454f4a2713aSLionel Sambuc CGF.Builder.CreateCall(F, V);
455f4a2713aSLionel Sambuc }
456f4a2713aSLionel Sambuc };
457f4a2713aSLionel Sambuc
458f4a2713aSLionel Sambuc struct ExtendGCLifetime : EHScopeStack::Cleanup {
459f4a2713aSLionel Sambuc const VarDecl &Var;
ExtendGCLifetime__anon398828f30111::ExtendGCLifetime460f4a2713aSLionel Sambuc ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
461f4a2713aSLionel Sambuc
Emit__anon398828f30111::ExtendGCLifetime462*0a6a1f1dSLionel Sambuc void Emit(CodeGenFunction &CGF, Flags flags) override {
463f4a2713aSLionel Sambuc // Compute the address of the local variable, in case it's a
464f4a2713aSLionel Sambuc // byref or something.
465f4a2713aSLionel Sambuc DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
466f4a2713aSLionel Sambuc Var.getType(), VK_LValue, SourceLocation());
467f4a2713aSLionel Sambuc llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
468f4a2713aSLionel Sambuc SourceLocation());
469f4a2713aSLionel Sambuc CGF.EmitExtendGCLifetime(value);
470f4a2713aSLionel Sambuc }
471f4a2713aSLionel Sambuc };
472f4a2713aSLionel Sambuc
473f4a2713aSLionel Sambuc struct CallCleanupFunction : EHScopeStack::Cleanup {
474f4a2713aSLionel Sambuc llvm::Constant *CleanupFn;
475f4a2713aSLionel Sambuc const CGFunctionInfo &FnInfo;
476f4a2713aSLionel Sambuc const VarDecl &Var;
477f4a2713aSLionel Sambuc
CallCleanupFunction__anon398828f30111::CallCleanupFunction478f4a2713aSLionel Sambuc CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
479f4a2713aSLionel Sambuc const VarDecl *Var)
480f4a2713aSLionel Sambuc : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
481f4a2713aSLionel Sambuc
Emit__anon398828f30111::CallCleanupFunction482*0a6a1f1dSLionel Sambuc void Emit(CodeGenFunction &CGF, Flags flags) override {
483f4a2713aSLionel Sambuc DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
484f4a2713aSLionel Sambuc Var.getType(), VK_LValue, SourceLocation());
485f4a2713aSLionel Sambuc // Compute the address of the local variable, in case it's a byref
486f4a2713aSLionel Sambuc // or something.
487f4a2713aSLionel Sambuc llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
488f4a2713aSLionel Sambuc
489f4a2713aSLionel Sambuc // In some cases, the type of the function argument will be different from
490f4a2713aSLionel Sambuc // the type of the pointer. An example of this is
491f4a2713aSLionel Sambuc // void f(void* arg);
492f4a2713aSLionel Sambuc // __attribute__((cleanup(f))) void *g;
493f4a2713aSLionel Sambuc //
494f4a2713aSLionel Sambuc // To fix this we insert a bitcast here.
495f4a2713aSLionel Sambuc QualType ArgTy = FnInfo.arg_begin()->type;
496f4a2713aSLionel Sambuc llvm::Value *Arg =
497f4a2713aSLionel Sambuc CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
498f4a2713aSLionel Sambuc
499f4a2713aSLionel Sambuc CallArgList Args;
500f4a2713aSLionel Sambuc Args.add(RValue::get(Arg),
501f4a2713aSLionel Sambuc CGF.getContext().getPointerType(Var.getType()));
502f4a2713aSLionel Sambuc CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
503f4a2713aSLionel Sambuc }
504f4a2713aSLionel Sambuc };
505f4a2713aSLionel Sambuc
506f4a2713aSLionel Sambuc /// A cleanup to call @llvm.lifetime.end.
507f4a2713aSLionel Sambuc class CallLifetimeEnd : public EHScopeStack::Cleanup {
508f4a2713aSLionel Sambuc llvm::Value *Addr;
509f4a2713aSLionel Sambuc llvm::Value *Size;
510f4a2713aSLionel Sambuc public:
CallLifetimeEnd(llvm::Value * addr,llvm::Value * size)511f4a2713aSLionel Sambuc CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
512f4a2713aSLionel Sambuc : Addr(addr), Size(size) {}
513f4a2713aSLionel Sambuc
Emit(CodeGenFunction & CGF,Flags flags)514*0a6a1f1dSLionel Sambuc void Emit(CodeGenFunction &CGF, Flags flags) override {
515f4a2713aSLionel Sambuc llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
516f4a2713aSLionel Sambuc CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
517f4a2713aSLionel Sambuc Size, castAddr)
518f4a2713aSLionel Sambuc ->setDoesNotThrow();
519f4a2713aSLionel Sambuc }
520f4a2713aSLionel Sambuc };
521f4a2713aSLionel Sambuc }
522f4a2713aSLionel Sambuc
523f4a2713aSLionel Sambuc /// EmitAutoVarWithLifetime - Does the setup required for an automatic
524f4a2713aSLionel Sambuc /// variable with lifetime.
EmitAutoVarWithLifetime(CodeGenFunction & CGF,const VarDecl & var,llvm::Value * addr,Qualifiers::ObjCLifetime lifetime)525f4a2713aSLionel Sambuc static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
526f4a2713aSLionel Sambuc llvm::Value *addr,
527f4a2713aSLionel Sambuc Qualifiers::ObjCLifetime lifetime) {
528f4a2713aSLionel Sambuc switch (lifetime) {
529f4a2713aSLionel Sambuc case Qualifiers::OCL_None:
530f4a2713aSLionel Sambuc llvm_unreachable("present but none");
531f4a2713aSLionel Sambuc
532f4a2713aSLionel Sambuc case Qualifiers::OCL_ExplicitNone:
533f4a2713aSLionel Sambuc // nothing to do
534f4a2713aSLionel Sambuc break;
535f4a2713aSLionel Sambuc
536f4a2713aSLionel Sambuc case Qualifiers::OCL_Strong: {
537f4a2713aSLionel Sambuc CodeGenFunction::Destroyer *destroyer =
538f4a2713aSLionel Sambuc (var.hasAttr<ObjCPreciseLifetimeAttr>()
539f4a2713aSLionel Sambuc ? CodeGenFunction::destroyARCStrongPrecise
540f4a2713aSLionel Sambuc : CodeGenFunction::destroyARCStrongImprecise);
541f4a2713aSLionel Sambuc
542f4a2713aSLionel Sambuc CleanupKind cleanupKind = CGF.getARCCleanupKind();
543f4a2713aSLionel Sambuc CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
544f4a2713aSLionel Sambuc cleanupKind & EHCleanup);
545f4a2713aSLionel Sambuc break;
546f4a2713aSLionel Sambuc }
547f4a2713aSLionel Sambuc case Qualifiers::OCL_Autoreleasing:
548f4a2713aSLionel Sambuc // nothing to do
549f4a2713aSLionel Sambuc break;
550f4a2713aSLionel Sambuc
551f4a2713aSLionel Sambuc case Qualifiers::OCL_Weak:
552f4a2713aSLionel Sambuc // __weak objects always get EH cleanups; otherwise, exceptions
553f4a2713aSLionel Sambuc // could cause really nasty crashes instead of mere leaks.
554f4a2713aSLionel Sambuc CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
555f4a2713aSLionel Sambuc CodeGenFunction::destroyARCWeak,
556f4a2713aSLionel Sambuc /*useEHCleanup*/ true);
557f4a2713aSLionel Sambuc break;
558f4a2713aSLionel Sambuc }
559f4a2713aSLionel Sambuc }
560f4a2713aSLionel Sambuc
isAccessedBy(const VarDecl & var,const Stmt * s)561f4a2713aSLionel Sambuc static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
562f4a2713aSLionel Sambuc if (const Expr *e = dyn_cast<Expr>(s)) {
563f4a2713aSLionel Sambuc // Skip the most common kinds of expressions that make
564f4a2713aSLionel Sambuc // hierarchy-walking expensive.
565f4a2713aSLionel Sambuc s = e = e->IgnoreParenCasts();
566f4a2713aSLionel Sambuc
567f4a2713aSLionel Sambuc if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
568f4a2713aSLionel Sambuc return (ref->getDecl() == &var);
569f4a2713aSLionel Sambuc if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
570f4a2713aSLionel Sambuc const BlockDecl *block = be->getBlockDecl();
571*0a6a1f1dSLionel Sambuc for (const auto &I : block->captures()) {
572*0a6a1f1dSLionel Sambuc if (I.getVariable() == &var)
573f4a2713aSLionel Sambuc return true;
574f4a2713aSLionel Sambuc }
575f4a2713aSLionel Sambuc }
576f4a2713aSLionel Sambuc }
577f4a2713aSLionel Sambuc
578f4a2713aSLionel Sambuc for (Stmt::const_child_range children = s->children(); children; ++children)
579f4a2713aSLionel Sambuc // children might be null; as in missing decl or conditional of an if-stmt.
580f4a2713aSLionel Sambuc if ((*children) && isAccessedBy(var, *children))
581f4a2713aSLionel Sambuc return true;
582f4a2713aSLionel Sambuc
583f4a2713aSLionel Sambuc return false;
584f4a2713aSLionel Sambuc }
585f4a2713aSLionel Sambuc
isAccessedBy(const ValueDecl * decl,const Expr * e)586f4a2713aSLionel Sambuc static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
587f4a2713aSLionel Sambuc if (!decl) return false;
588f4a2713aSLionel Sambuc if (!isa<VarDecl>(decl)) return false;
589f4a2713aSLionel Sambuc const VarDecl *var = cast<VarDecl>(decl);
590f4a2713aSLionel Sambuc return isAccessedBy(*var, e);
591f4a2713aSLionel Sambuc }
592f4a2713aSLionel Sambuc
drillIntoBlockVariable(CodeGenFunction & CGF,LValue & lvalue,const VarDecl * var)593f4a2713aSLionel Sambuc static void drillIntoBlockVariable(CodeGenFunction &CGF,
594f4a2713aSLionel Sambuc LValue &lvalue,
595f4a2713aSLionel Sambuc const VarDecl *var) {
596f4a2713aSLionel Sambuc lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
597f4a2713aSLionel Sambuc }
598f4a2713aSLionel Sambuc
EmitScalarInit(const Expr * init,const ValueDecl * D,LValue lvalue,bool capturedByInit)599*0a6a1f1dSLionel Sambuc void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
600*0a6a1f1dSLionel Sambuc LValue lvalue, bool capturedByInit) {
601f4a2713aSLionel Sambuc Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
602f4a2713aSLionel Sambuc if (!lifetime) {
603f4a2713aSLionel Sambuc llvm::Value *value = EmitScalarExpr(init);
604f4a2713aSLionel Sambuc if (capturedByInit)
605f4a2713aSLionel Sambuc drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
606f4a2713aSLionel Sambuc EmitStoreThroughLValue(RValue::get(value), lvalue, true);
607f4a2713aSLionel Sambuc return;
608f4a2713aSLionel Sambuc }
609f4a2713aSLionel Sambuc
610*0a6a1f1dSLionel Sambuc if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
611*0a6a1f1dSLionel Sambuc init = DIE->getExpr();
612*0a6a1f1dSLionel Sambuc
613f4a2713aSLionel Sambuc // If we're emitting a value with lifetime, we have to do the
614f4a2713aSLionel Sambuc // initialization *before* we leave the cleanup scopes.
615f4a2713aSLionel Sambuc if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
616f4a2713aSLionel Sambuc enterFullExpression(ewc);
617f4a2713aSLionel Sambuc init = ewc->getSubExpr();
618f4a2713aSLionel Sambuc }
619f4a2713aSLionel Sambuc CodeGenFunction::RunCleanupsScope Scope(*this);
620f4a2713aSLionel Sambuc
621f4a2713aSLionel Sambuc // We have to maintain the illusion that the variable is
622f4a2713aSLionel Sambuc // zero-initialized. If the variable might be accessed in its
623f4a2713aSLionel Sambuc // initializer, zero-initialize before running the initializer, then
624f4a2713aSLionel Sambuc // actually perform the initialization with an assign.
625f4a2713aSLionel Sambuc bool accessedByInit = false;
626f4a2713aSLionel Sambuc if (lifetime != Qualifiers::OCL_ExplicitNone)
627f4a2713aSLionel Sambuc accessedByInit = (capturedByInit || isAccessedBy(D, init));
628f4a2713aSLionel Sambuc if (accessedByInit) {
629f4a2713aSLionel Sambuc LValue tempLV = lvalue;
630f4a2713aSLionel Sambuc // Drill down to the __block object if necessary.
631f4a2713aSLionel Sambuc if (capturedByInit) {
632f4a2713aSLionel Sambuc // We can use a simple GEP for this because it can't have been
633f4a2713aSLionel Sambuc // moved yet.
634f4a2713aSLionel Sambuc tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
635f4a2713aSLionel Sambuc getByRefValueLLVMField(cast<VarDecl>(D))));
636f4a2713aSLionel Sambuc }
637f4a2713aSLionel Sambuc
638f4a2713aSLionel Sambuc llvm::PointerType *ty
639f4a2713aSLionel Sambuc = cast<llvm::PointerType>(tempLV.getAddress()->getType());
640f4a2713aSLionel Sambuc ty = cast<llvm::PointerType>(ty->getElementType());
641f4a2713aSLionel Sambuc
642f4a2713aSLionel Sambuc llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
643f4a2713aSLionel Sambuc
644f4a2713aSLionel Sambuc // If __weak, we want to use a barrier under certain conditions.
645f4a2713aSLionel Sambuc if (lifetime == Qualifiers::OCL_Weak)
646f4a2713aSLionel Sambuc EmitARCInitWeak(tempLV.getAddress(), zero);
647f4a2713aSLionel Sambuc
648f4a2713aSLionel Sambuc // Otherwise just do a simple store.
649f4a2713aSLionel Sambuc else
650f4a2713aSLionel Sambuc EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
651f4a2713aSLionel Sambuc }
652f4a2713aSLionel Sambuc
653f4a2713aSLionel Sambuc // Emit the initializer.
654*0a6a1f1dSLionel Sambuc llvm::Value *value = nullptr;
655f4a2713aSLionel Sambuc
656f4a2713aSLionel Sambuc switch (lifetime) {
657f4a2713aSLionel Sambuc case Qualifiers::OCL_None:
658f4a2713aSLionel Sambuc llvm_unreachable("present but none");
659f4a2713aSLionel Sambuc
660f4a2713aSLionel Sambuc case Qualifiers::OCL_ExplicitNone:
661f4a2713aSLionel Sambuc // nothing to do
662f4a2713aSLionel Sambuc value = EmitScalarExpr(init);
663f4a2713aSLionel Sambuc break;
664f4a2713aSLionel Sambuc
665f4a2713aSLionel Sambuc case Qualifiers::OCL_Strong: {
666f4a2713aSLionel Sambuc value = EmitARCRetainScalarExpr(init);
667f4a2713aSLionel Sambuc break;
668f4a2713aSLionel Sambuc }
669f4a2713aSLionel Sambuc
670f4a2713aSLionel Sambuc case Qualifiers::OCL_Weak: {
671f4a2713aSLionel Sambuc // No way to optimize a producing initializer into this. It's not
672f4a2713aSLionel Sambuc // worth optimizing for, because the value will immediately
673f4a2713aSLionel Sambuc // disappear in the common case.
674f4a2713aSLionel Sambuc value = EmitScalarExpr(init);
675f4a2713aSLionel Sambuc
676f4a2713aSLionel Sambuc if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
677f4a2713aSLionel Sambuc if (accessedByInit)
678f4a2713aSLionel Sambuc EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
679f4a2713aSLionel Sambuc else
680f4a2713aSLionel Sambuc EmitARCInitWeak(lvalue.getAddress(), value);
681f4a2713aSLionel Sambuc return;
682f4a2713aSLionel Sambuc }
683f4a2713aSLionel Sambuc
684f4a2713aSLionel Sambuc case Qualifiers::OCL_Autoreleasing:
685f4a2713aSLionel Sambuc value = EmitARCRetainAutoreleaseScalarExpr(init);
686f4a2713aSLionel Sambuc break;
687f4a2713aSLionel Sambuc }
688f4a2713aSLionel Sambuc
689f4a2713aSLionel Sambuc if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
690f4a2713aSLionel Sambuc
691f4a2713aSLionel Sambuc // If the variable might have been accessed by its initializer, we
692f4a2713aSLionel Sambuc // might have to initialize with a barrier. We have to do this for
693f4a2713aSLionel Sambuc // both __weak and __strong, but __weak got filtered out above.
694f4a2713aSLionel Sambuc if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
695f4a2713aSLionel Sambuc llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
696f4a2713aSLionel Sambuc EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
697f4a2713aSLionel Sambuc EmitARCRelease(oldValue, ARCImpreciseLifetime);
698f4a2713aSLionel Sambuc return;
699f4a2713aSLionel Sambuc }
700f4a2713aSLionel Sambuc
701f4a2713aSLionel Sambuc EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
702f4a2713aSLionel Sambuc }
703f4a2713aSLionel Sambuc
704f4a2713aSLionel Sambuc /// EmitScalarInit - Initialize the given lvalue with the given object.
EmitScalarInit(llvm::Value * init,LValue lvalue)705f4a2713aSLionel Sambuc void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
706f4a2713aSLionel Sambuc Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
707f4a2713aSLionel Sambuc if (!lifetime)
708f4a2713aSLionel Sambuc return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
709f4a2713aSLionel Sambuc
710f4a2713aSLionel Sambuc switch (lifetime) {
711f4a2713aSLionel Sambuc case Qualifiers::OCL_None:
712f4a2713aSLionel Sambuc llvm_unreachable("present but none");
713f4a2713aSLionel Sambuc
714f4a2713aSLionel Sambuc case Qualifiers::OCL_ExplicitNone:
715f4a2713aSLionel Sambuc // nothing to do
716f4a2713aSLionel Sambuc break;
717f4a2713aSLionel Sambuc
718f4a2713aSLionel Sambuc case Qualifiers::OCL_Strong:
719f4a2713aSLionel Sambuc init = EmitARCRetain(lvalue.getType(), init);
720f4a2713aSLionel Sambuc break;
721f4a2713aSLionel Sambuc
722f4a2713aSLionel Sambuc case Qualifiers::OCL_Weak:
723f4a2713aSLionel Sambuc // Initialize and then skip the primitive store.
724f4a2713aSLionel Sambuc EmitARCInitWeak(lvalue.getAddress(), init);
725f4a2713aSLionel Sambuc return;
726f4a2713aSLionel Sambuc
727f4a2713aSLionel Sambuc case Qualifiers::OCL_Autoreleasing:
728f4a2713aSLionel Sambuc init = EmitARCRetainAutorelease(lvalue.getType(), init);
729f4a2713aSLionel Sambuc break;
730f4a2713aSLionel Sambuc }
731f4a2713aSLionel Sambuc
732f4a2713aSLionel Sambuc EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
733f4a2713aSLionel Sambuc }
734f4a2713aSLionel Sambuc
735f4a2713aSLionel Sambuc /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
736f4a2713aSLionel Sambuc /// non-zero parts of the specified initializer with equal or fewer than
737f4a2713aSLionel Sambuc /// NumStores scalar stores.
canEmitInitWithFewStoresAfterMemset(llvm::Constant * Init,unsigned & NumStores)738f4a2713aSLionel Sambuc static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
739f4a2713aSLionel Sambuc unsigned &NumStores) {
740f4a2713aSLionel Sambuc // Zero and Undef never requires any extra stores.
741f4a2713aSLionel Sambuc if (isa<llvm::ConstantAggregateZero>(Init) ||
742f4a2713aSLionel Sambuc isa<llvm::ConstantPointerNull>(Init) ||
743f4a2713aSLionel Sambuc isa<llvm::UndefValue>(Init))
744f4a2713aSLionel Sambuc return true;
745f4a2713aSLionel Sambuc if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
746f4a2713aSLionel Sambuc isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
747f4a2713aSLionel Sambuc isa<llvm::ConstantExpr>(Init))
748f4a2713aSLionel Sambuc return Init->isNullValue() || NumStores--;
749f4a2713aSLionel Sambuc
750f4a2713aSLionel Sambuc // See if we can emit each element.
751f4a2713aSLionel Sambuc if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
752f4a2713aSLionel Sambuc for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
753f4a2713aSLionel Sambuc llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
754f4a2713aSLionel Sambuc if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
755f4a2713aSLionel Sambuc return false;
756f4a2713aSLionel Sambuc }
757f4a2713aSLionel Sambuc return true;
758f4a2713aSLionel Sambuc }
759f4a2713aSLionel Sambuc
760f4a2713aSLionel Sambuc if (llvm::ConstantDataSequential *CDS =
761f4a2713aSLionel Sambuc dyn_cast<llvm::ConstantDataSequential>(Init)) {
762f4a2713aSLionel Sambuc for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
763f4a2713aSLionel Sambuc llvm::Constant *Elt = CDS->getElementAsConstant(i);
764f4a2713aSLionel Sambuc if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
765f4a2713aSLionel Sambuc return false;
766f4a2713aSLionel Sambuc }
767f4a2713aSLionel Sambuc return true;
768f4a2713aSLionel Sambuc }
769f4a2713aSLionel Sambuc
770f4a2713aSLionel Sambuc // Anything else is hard and scary.
771f4a2713aSLionel Sambuc return false;
772f4a2713aSLionel Sambuc }
773f4a2713aSLionel Sambuc
774f4a2713aSLionel Sambuc /// emitStoresForInitAfterMemset - For inits that
775f4a2713aSLionel Sambuc /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
776f4a2713aSLionel Sambuc /// stores that would be required.
emitStoresForInitAfterMemset(llvm::Constant * Init,llvm::Value * Loc,bool isVolatile,CGBuilderTy & Builder)777f4a2713aSLionel Sambuc static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
778f4a2713aSLionel Sambuc bool isVolatile, CGBuilderTy &Builder) {
779f4a2713aSLionel Sambuc assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
780f4a2713aSLionel Sambuc "called emitStoresForInitAfterMemset for zero or undef value.");
781f4a2713aSLionel Sambuc
782f4a2713aSLionel Sambuc if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
783f4a2713aSLionel Sambuc isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
784f4a2713aSLionel Sambuc isa<llvm::ConstantExpr>(Init)) {
785f4a2713aSLionel Sambuc Builder.CreateStore(Init, Loc, isVolatile);
786f4a2713aSLionel Sambuc return;
787f4a2713aSLionel Sambuc }
788f4a2713aSLionel Sambuc
789f4a2713aSLionel Sambuc if (llvm::ConstantDataSequential *CDS =
790f4a2713aSLionel Sambuc dyn_cast<llvm::ConstantDataSequential>(Init)) {
791f4a2713aSLionel Sambuc for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
792f4a2713aSLionel Sambuc llvm::Constant *Elt = CDS->getElementAsConstant(i);
793f4a2713aSLionel Sambuc
794f4a2713aSLionel Sambuc // If necessary, get a pointer to the element and emit it.
795f4a2713aSLionel Sambuc if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
796f4a2713aSLionel Sambuc emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
797f4a2713aSLionel Sambuc isVolatile, Builder);
798f4a2713aSLionel Sambuc }
799f4a2713aSLionel Sambuc return;
800f4a2713aSLionel Sambuc }
801f4a2713aSLionel Sambuc
802f4a2713aSLionel Sambuc assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
803f4a2713aSLionel Sambuc "Unknown value type!");
804f4a2713aSLionel Sambuc
805f4a2713aSLionel Sambuc for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
806f4a2713aSLionel Sambuc llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
807f4a2713aSLionel Sambuc
808f4a2713aSLionel Sambuc // If necessary, get a pointer to the element and emit it.
809f4a2713aSLionel Sambuc if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
810f4a2713aSLionel Sambuc emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
811f4a2713aSLionel Sambuc isVolatile, Builder);
812f4a2713aSLionel Sambuc }
813f4a2713aSLionel Sambuc }
814f4a2713aSLionel Sambuc
815f4a2713aSLionel Sambuc
816f4a2713aSLionel Sambuc /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
817f4a2713aSLionel Sambuc /// plus some stores to initialize a local variable instead of using a memcpy
818f4a2713aSLionel Sambuc /// from a constant global. It is beneficial to use memset if the global is all
819f4a2713aSLionel Sambuc /// zeros, or mostly zeros and large.
shouldUseMemSetPlusStoresToInitialize(llvm::Constant * Init,uint64_t GlobalSize)820f4a2713aSLionel Sambuc static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
821f4a2713aSLionel Sambuc uint64_t GlobalSize) {
822f4a2713aSLionel Sambuc // If a global is all zeros, always use a memset.
823f4a2713aSLionel Sambuc if (isa<llvm::ConstantAggregateZero>(Init)) return true;
824f4a2713aSLionel Sambuc
825f4a2713aSLionel Sambuc // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
826f4a2713aSLionel Sambuc // do it if it will require 6 or fewer scalar stores.
827f4a2713aSLionel Sambuc // TODO: Should budget depends on the size? Avoiding a large global warrants
828f4a2713aSLionel Sambuc // plopping in more stores.
829f4a2713aSLionel Sambuc unsigned StoreBudget = 6;
830f4a2713aSLionel Sambuc uint64_t SizeLimit = 32;
831f4a2713aSLionel Sambuc
832f4a2713aSLionel Sambuc return GlobalSize > SizeLimit &&
833f4a2713aSLionel Sambuc canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
834f4a2713aSLionel Sambuc }
835f4a2713aSLionel Sambuc
836f4a2713aSLionel Sambuc /// Should we use the LLVM lifetime intrinsics for the given local variable?
shouldUseLifetimeMarkers(CodeGenFunction & CGF,const VarDecl & D,unsigned Size)837f4a2713aSLionel Sambuc static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
838f4a2713aSLionel Sambuc unsigned Size) {
839f4a2713aSLionel Sambuc // For now, only in optimized builds.
840f4a2713aSLionel Sambuc if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
841f4a2713aSLionel Sambuc return false;
842f4a2713aSLionel Sambuc
843f4a2713aSLionel Sambuc // Limit the size of marked objects to 32 bytes. We don't want to increase
844f4a2713aSLionel Sambuc // compile time by marking tiny objects.
845f4a2713aSLionel Sambuc unsigned SizeThreshold = 32;
846f4a2713aSLionel Sambuc
847f4a2713aSLionel Sambuc return Size > SizeThreshold;
848f4a2713aSLionel Sambuc }
849f4a2713aSLionel Sambuc
850f4a2713aSLionel Sambuc
851f4a2713aSLionel Sambuc /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
852f4a2713aSLionel Sambuc /// variable declaration with auto, register, or no storage class specifier.
853f4a2713aSLionel Sambuc /// These turn into simple stack objects, or GlobalValues depending on target.
EmitAutoVarDecl(const VarDecl & D)854f4a2713aSLionel Sambuc void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
855f4a2713aSLionel Sambuc AutoVarEmission emission = EmitAutoVarAlloca(D);
856f4a2713aSLionel Sambuc EmitAutoVarInit(emission);
857f4a2713aSLionel Sambuc EmitAutoVarCleanups(emission);
858f4a2713aSLionel Sambuc }
859f4a2713aSLionel Sambuc
860f4a2713aSLionel Sambuc /// EmitAutoVarAlloca - Emit the alloca and debug information for a
861*0a6a1f1dSLionel Sambuc /// local variable. Does not emit initialization or destruction.
862f4a2713aSLionel Sambuc CodeGenFunction::AutoVarEmission
EmitAutoVarAlloca(const VarDecl & D)863f4a2713aSLionel Sambuc CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
864f4a2713aSLionel Sambuc QualType Ty = D.getType();
865f4a2713aSLionel Sambuc
866f4a2713aSLionel Sambuc AutoVarEmission emission(D);
867f4a2713aSLionel Sambuc
868f4a2713aSLionel Sambuc bool isByRef = D.hasAttr<BlocksAttr>();
869f4a2713aSLionel Sambuc emission.IsByRef = isByRef;
870f4a2713aSLionel Sambuc
871f4a2713aSLionel Sambuc CharUnits alignment = getContext().getDeclAlign(&D);
872f4a2713aSLionel Sambuc emission.Alignment = alignment;
873f4a2713aSLionel Sambuc
874f4a2713aSLionel Sambuc // If the type is variably-modified, emit all the VLA sizes for it.
875f4a2713aSLionel Sambuc if (Ty->isVariablyModifiedType())
876f4a2713aSLionel Sambuc EmitVariablyModifiedType(Ty);
877f4a2713aSLionel Sambuc
878f4a2713aSLionel Sambuc llvm::Value *DeclPtr;
879f4a2713aSLionel Sambuc if (Ty->isConstantSizeType()) {
880f4a2713aSLionel Sambuc bool NRVO = getLangOpts().ElideConstructors &&
881f4a2713aSLionel Sambuc D.isNRVOVariable();
882f4a2713aSLionel Sambuc
883f4a2713aSLionel Sambuc // If this value is an array or struct with a statically determinable
884f4a2713aSLionel Sambuc // constant initializer, there are optimizations we can do.
885f4a2713aSLionel Sambuc //
886f4a2713aSLionel Sambuc // TODO: We should constant-evaluate the initializer of any variable,
887f4a2713aSLionel Sambuc // as long as it is initialized by a constant expression. Currently,
888f4a2713aSLionel Sambuc // isConstantInitializer produces wrong answers for structs with
889f4a2713aSLionel Sambuc // reference or bitfield members, and a few other cases, and checking
890f4a2713aSLionel Sambuc // for POD-ness protects us from some of these.
891f4a2713aSLionel Sambuc if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
892f4a2713aSLionel Sambuc (D.isConstexpr() ||
893f4a2713aSLionel Sambuc ((Ty.isPODType(getContext()) ||
894f4a2713aSLionel Sambuc getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
895f4a2713aSLionel Sambuc D.getInit()->isConstantInitializer(getContext(), false)))) {
896f4a2713aSLionel Sambuc
897f4a2713aSLionel Sambuc // If the variable's a const type, and it's neither an NRVO
898f4a2713aSLionel Sambuc // candidate nor a __block variable and has no mutable members,
899f4a2713aSLionel Sambuc // emit it as a global instead.
900f4a2713aSLionel Sambuc if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
901f4a2713aSLionel Sambuc CGM.isTypeConstant(Ty, true)) {
902f4a2713aSLionel Sambuc EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
903f4a2713aSLionel Sambuc
904*0a6a1f1dSLionel Sambuc emission.Address = nullptr; // signal this condition to later callbacks
905f4a2713aSLionel Sambuc assert(emission.wasEmittedAsGlobal());
906f4a2713aSLionel Sambuc return emission;
907f4a2713aSLionel Sambuc }
908f4a2713aSLionel Sambuc
909f4a2713aSLionel Sambuc // Otherwise, tell the initialization code that we're in this case.
910f4a2713aSLionel Sambuc emission.IsConstantAggregate = true;
911f4a2713aSLionel Sambuc }
912f4a2713aSLionel Sambuc
913f4a2713aSLionel Sambuc // A normal fixed sized variable becomes an alloca in the entry block,
914f4a2713aSLionel Sambuc // unless it's an NRVO variable.
915f4a2713aSLionel Sambuc llvm::Type *LTy = ConvertTypeForMem(Ty);
916f4a2713aSLionel Sambuc
917f4a2713aSLionel Sambuc if (NRVO) {
918f4a2713aSLionel Sambuc // The named return value optimization: allocate this variable in the
919f4a2713aSLionel Sambuc // return slot, so that we can elide the copy when returning this
920f4a2713aSLionel Sambuc // variable (C++0x [class.copy]p34).
921f4a2713aSLionel Sambuc DeclPtr = ReturnValue;
922f4a2713aSLionel Sambuc
923f4a2713aSLionel Sambuc if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
924f4a2713aSLionel Sambuc if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
925f4a2713aSLionel Sambuc // Create a flag that is used to indicate when the NRVO was applied
926f4a2713aSLionel Sambuc // to this variable. Set it to zero to indicate that NRVO was not
927f4a2713aSLionel Sambuc // applied.
928f4a2713aSLionel Sambuc llvm::Value *Zero = Builder.getFalse();
929f4a2713aSLionel Sambuc llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
930f4a2713aSLionel Sambuc EnsureInsertPoint();
931f4a2713aSLionel Sambuc Builder.CreateStore(Zero, NRVOFlag);
932f4a2713aSLionel Sambuc
933f4a2713aSLionel Sambuc // Record the NRVO flag for this variable.
934f4a2713aSLionel Sambuc NRVOFlags[&D] = NRVOFlag;
935f4a2713aSLionel Sambuc emission.NRVOFlag = NRVOFlag;
936f4a2713aSLionel Sambuc }
937f4a2713aSLionel Sambuc }
938f4a2713aSLionel Sambuc } else {
939f4a2713aSLionel Sambuc if (isByRef)
940f4a2713aSLionel Sambuc LTy = BuildByRefType(&D);
941f4a2713aSLionel Sambuc
942f4a2713aSLionel Sambuc llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
943f4a2713aSLionel Sambuc Alloc->setName(D.getName());
944f4a2713aSLionel Sambuc
945f4a2713aSLionel Sambuc CharUnits allocaAlignment = alignment;
946f4a2713aSLionel Sambuc if (isByRef)
947f4a2713aSLionel Sambuc allocaAlignment = std::max(allocaAlignment,
948f4a2713aSLionel Sambuc getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
949f4a2713aSLionel Sambuc Alloc->setAlignment(allocaAlignment.getQuantity());
950f4a2713aSLionel Sambuc DeclPtr = Alloc;
951f4a2713aSLionel Sambuc
952f4a2713aSLionel Sambuc // Emit a lifetime intrinsic if meaningful. There's no point
953f4a2713aSLionel Sambuc // in doing this if we don't have a valid insertion point (?).
954f4a2713aSLionel Sambuc uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
955f4a2713aSLionel Sambuc if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
956f4a2713aSLionel Sambuc llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
957f4a2713aSLionel Sambuc
958f4a2713aSLionel Sambuc emission.SizeForLifetimeMarkers = sizeV;
959f4a2713aSLionel Sambuc llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
960f4a2713aSLionel Sambuc Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
961f4a2713aSLionel Sambuc ->setDoesNotThrow();
962f4a2713aSLionel Sambuc } else {
963f4a2713aSLionel Sambuc assert(!emission.useLifetimeMarkers());
964f4a2713aSLionel Sambuc }
965f4a2713aSLionel Sambuc }
966f4a2713aSLionel Sambuc } else {
967f4a2713aSLionel Sambuc EnsureInsertPoint();
968f4a2713aSLionel Sambuc
969f4a2713aSLionel Sambuc if (!DidCallStackSave) {
970f4a2713aSLionel Sambuc // Save the stack.
971f4a2713aSLionel Sambuc llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
972f4a2713aSLionel Sambuc
973f4a2713aSLionel Sambuc llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
974f4a2713aSLionel Sambuc llvm::Value *V = Builder.CreateCall(F);
975f4a2713aSLionel Sambuc
976f4a2713aSLionel Sambuc Builder.CreateStore(V, Stack);
977f4a2713aSLionel Sambuc
978f4a2713aSLionel Sambuc DidCallStackSave = true;
979f4a2713aSLionel Sambuc
980f4a2713aSLionel Sambuc // Push a cleanup block and restore the stack there.
981f4a2713aSLionel Sambuc // FIXME: in general circumstances, this should be an EH cleanup.
982*0a6a1f1dSLionel Sambuc pushStackRestore(NormalCleanup, Stack);
983f4a2713aSLionel Sambuc }
984f4a2713aSLionel Sambuc
985f4a2713aSLionel Sambuc llvm::Value *elementCount;
986f4a2713aSLionel Sambuc QualType elementType;
987*0a6a1f1dSLionel Sambuc std::tie(elementCount, elementType) = getVLASize(Ty);
988f4a2713aSLionel Sambuc
989f4a2713aSLionel Sambuc llvm::Type *llvmTy = ConvertTypeForMem(elementType);
990f4a2713aSLionel Sambuc
991f4a2713aSLionel Sambuc // Allocate memory for the array.
992f4a2713aSLionel Sambuc llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
993f4a2713aSLionel Sambuc vla->setAlignment(alignment.getQuantity());
994f4a2713aSLionel Sambuc
995f4a2713aSLionel Sambuc DeclPtr = vla;
996f4a2713aSLionel Sambuc }
997f4a2713aSLionel Sambuc
998f4a2713aSLionel Sambuc llvm::Value *&DMEntry = LocalDeclMap[&D];
999*0a6a1f1dSLionel Sambuc assert(!DMEntry && "Decl already exists in localdeclmap!");
1000f4a2713aSLionel Sambuc DMEntry = DeclPtr;
1001f4a2713aSLionel Sambuc emission.Address = DeclPtr;
1002f4a2713aSLionel Sambuc
1003f4a2713aSLionel Sambuc // Emit debug info for local var declaration.
1004f4a2713aSLionel Sambuc if (HaveInsertPoint())
1005f4a2713aSLionel Sambuc if (CGDebugInfo *DI = getDebugInfo()) {
1006f4a2713aSLionel Sambuc if (CGM.getCodeGenOpts().getDebugInfo()
1007f4a2713aSLionel Sambuc >= CodeGenOptions::LimitedDebugInfo) {
1008f4a2713aSLionel Sambuc DI->setLocation(D.getLocation());
1009f4a2713aSLionel Sambuc DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
1010f4a2713aSLionel Sambuc }
1011f4a2713aSLionel Sambuc }
1012f4a2713aSLionel Sambuc
1013f4a2713aSLionel Sambuc if (D.hasAttr<AnnotateAttr>())
1014f4a2713aSLionel Sambuc EmitVarAnnotations(&D, emission.Address);
1015f4a2713aSLionel Sambuc
1016f4a2713aSLionel Sambuc return emission;
1017f4a2713aSLionel Sambuc }
1018f4a2713aSLionel Sambuc
1019f4a2713aSLionel Sambuc /// Determines whether the given __block variable is potentially
1020f4a2713aSLionel Sambuc /// captured by the given expression.
isCapturedBy(const VarDecl & var,const Expr * e)1021f4a2713aSLionel Sambuc static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1022f4a2713aSLionel Sambuc // Skip the most common kinds of expressions that make
1023f4a2713aSLionel Sambuc // hierarchy-walking expensive.
1024f4a2713aSLionel Sambuc e = e->IgnoreParenCasts();
1025f4a2713aSLionel Sambuc
1026f4a2713aSLionel Sambuc if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1027f4a2713aSLionel Sambuc const BlockDecl *block = be->getBlockDecl();
1028*0a6a1f1dSLionel Sambuc for (const auto &I : block->captures()) {
1029*0a6a1f1dSLionel Sambuc if (I.getVariable() == &var)
1030f4a2713aSLionel Sambuc return true;
1031f4a2713aSLionel Sambuc }
1032f4a2713aSLionel Sambuc
1033f4a2713aSLionel Sambuc // No need to walk into the subexpressions.
1034f4a2713aSLionel Sambuc return false;
1035f4a2713aSLionel Sambuc }
1036f4a2713aSLionel Sambuc
1037f4a2713aSLionel Sambuc if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1038f4a2713aSLionel Sambuc const CompoundStmt *CS = SE->getSubStmt();
1039*0a6a1f1dSLionel Sambuc for (const auto *BI : CS->body())
1040*0a6a1f1dSLionel Sambuc if (const auto *E = dyn_cast<Expr>(BI)) {
1041f4a2713aSLionel Sambuc if (isCapturedBy(var, E))
1042f4a2713aSLionel Sambuc return true;
1043f4a2713aSLionel Sambuc }
1044*0a6a1f1dSLionel Sambuc else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1045f4a2713aSLionel Sambuc // special case declarations
1046*0a6a1f1dSLionel Sambuc for (const auto *I : DS->decls()) {
1047*0a6a1f1dSLionel Sambuc if (const auto *VD = dyn_cast<VarDecl>((I))) {
1048*0a6a1f1dSLionel Sambuc const Expr *Init = VD->getInit();
1049f4a2713aSLionel Sambuc if (Init && isCapturedBy(var, Init))
1050f4a2713aSLionel Sambuc return true;
1051f4a2713aSLionel Sambuc }
1052f4a2713aSLionel Sambuc }
1053f4a2713aSLionel Sambuc }
1054f4a2713aSLionel Sambuc else
1055f4a2713aSLionel Sambuc // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1056f4a2713aSLionel Sambuc // Later, provide code to poke into statements for capture analysis.
1057f4a2713aSLionel Sambuc return true;
1058f4a2713aSLionel Sambuc return false;
1059f4a2713aSLionel Sambuc }
1060f4a2713aSLionel Sambuc
1061f4a2713aSLionel Sambuc for (Stmt::const_child_range children = e->children(); children; ++children)
1062f4a2713aSLionel Sambuc if (isCapturedBy(var, cast<Expr>(*children)))
1063f4a2713aSLionel Sambuc return true;
1064f4a2713aSLionel Sambuc
1065f4a2713aSLionel Sambuc return false;
1066f4a2713aSLionel Sambuc }
1067f4a2713aSLionel Sambuc
1068f4a2713aSLionel Sambuc /// \brief Determine whether the given initializer is trivial in the sense
1069f4a2713aSLionel Sambuc /// that it requires no code to be generated.
isTrivialInitializer(const Expr * Init)1070*0a6a1f1dSLionel Sambuc bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1071f4a2713aSLionel Sambuc if (!Init)
1072f4a2713aSLionel Sambuc return true;
1073f4a2713aSLionel Sambuc
1074f4a2713aSLionel Sambuc if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1075f4a2713aSLionel Sambuc if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1076f4a2713aSLionel Sambuc if (Constructor->isTrivial() &&
1077f4a2713aSLionel Sambuc Constructor->isDefaultConstructor() &&
1078f4a2713aSLionel Sambuc !Construct->requiresZeroInitialization())
1079f4a2713aSLionel Sambuc return true;
1080f4a2713aSLionel Sambuc
1081f4a2713aSLionel Sambuc return false;
1082f4a2713aSLionel Sambuc }
EmitAutoVarInit(const AutoVarEmission & emission)1083f4a2713aSLionel Sambuc void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1084f4a2713aSLionel Sambuc assert(emission.Variable && "emission was not valid!");
1085f4a2713aSLionel Sambuc
1086f4a2713aSLionel Sambuc // If this was emitted as a global constant, we're done.
1087f4a2713aSLionel Sambuc if (emission.wasEmittedAsGlobal()) return;
1088f4a2713aSLionel Sambuc
1089f4a2713aSLionel Sambuc const VarDecl &D = *emission.Variable;
1090*0a6a1f1dSLionel Sambuc ApplyDebugLocation DL(*this, D.getLocation());
1091f4a2713aSLionel Sambuc QualType type = D.getType();
1092f4a2713aSLionel Sambuc
1093f4a2713aSLionel Sambuc // If this local has an initializer, emit it now.
1094f4a2713aSLionel Sambuc const Expr *Init = D.getInit();
1095f4a2713aSLionel Sambuc
1096f4a2713aSLionel Sambuc // If we are at an unreachable point, we don't need to emit the initializer
1097f4a2713aSLionel Sambuc // unless it contains a label.
1098f4a2713aSLionel Sambuc if (!HaveInsertPoint()) {
1099f4a2713aSLionel Sambuc if (!Init || !ContainsLabel(Init)) return;
1100f4a2713aSLionel Sambuc EnsureInsertPoint();
1101f4a2713aSLionel Sambuc }
1102f4a2713aSLionel Sambuc
1103f4a2713aSLionel Sambuc // Initialize the structure of a __block variable.
1104f4a2713aSLionel Sambuc if (emission.IsByRef)
1105f4a2713aSLionel Sambuc emitByrefStructureInit(emission);
1106f4a2713aSLionel Sambuc
1107f4a2713aSLionel Sambuc if (isTrivialInitializer(Init))
1108f4a2713aSLionel Sambuc return;
1109f4a2713aSLionel Sambuc
1110f4a2713aSLionel Sambuc CharUnits alignment = emission.Alignment;
1111f4a2713aSLionel Sambuc
1112f4a2713aSLionel Sambuc // Check whether this is a byref variable that's potentially
1113f4a2713aSLionel Sambuc // captured and moved by its own initializer. If so, we'll need to
1114f4a2713aSLionel Sambuc // emit the initializer first, then copy into the variable.
1115f4a2713aSLionel Sambuc bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1116f4a2713aSLionel Sambuc
1117f4a2713aSLionel Sambuc llvm::Value *Loc =
1118f4a2713aSLionel Sambuc capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1119f4a2713aSLionel Sambuc
1120*0a6a1f1dSLionel Sambuc llvm::Constant *constant = nullptr;
1121f4a2713aSLionel Sambuc if (emission.IsConstantAggregate || D.isConstexpr()) {
1122f4a2713aSLionel Sambuc assert(!capturedByInit && "constant init contains a capturing block?");
1123f4a2713aSLionel Sambuc constant = CGM.EmitConstantInit(D, this);
1124f4a2713aSLionel Sambuc }
1125f4a2713aSLionel Sambuc
1126f4a2713aSLionel Sambuc if (!constant) {
1127f4a2713aSLionel Sambuc LValue lv = MakeAddrLValue(Loc, type, alignment);
1128f4a2713aSLionel Sambuc lv.setNonGC(true);
1129f4a2713aSLionel Sambuc return EmitExprAsInit(Init, &D, lv, capturedByInit);
1130f4a2713aSLionel Sambuc }
1131f4a2713aSLionel Sambuc
1132f4a2713aSLionel Sambuc if (!emission.IsConstantAggregate) {
1133f4a2713aSLionel Sambuc // For simple scalar/complex initialization, store the value directly.
1134f4a2713aSLionel Sambuc LValue lv = MakeAddrLValue(Loc, type, alignment);
1135f4a2713aSLionel Sambuc lv.setNonGC(true);
1136f4a2713aSLionel Sambuc return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1137f4a2713aSLionel Sambuc }
1138f4a2713aSLionel Sambuc
1139f4a2713aSLionel Sambuc // If this is a simple aggregate initialization, we can optimize it
1140f4a2713aSLionel Sambuc // in various ways.
1141f4a2713aSLionel Sambuc bool isVolatile = type.isVolatileQualified();
1142f4a2713aSLionel Sambuc
1143f4a2713aSLionel Sambuc llvm::Value *SizeVal =
1144f4a2713aSLionel Sambuc llvm::ConstantInt::get(IntPtrTy,
1145f4a2713aSLionel Sambuc getContext().getTypeSizeInChars(type).getQuantity());
1146f4a2713aSLionel Sambuc
1147f4a2713aSLionel Sambuc llvm::Type *BP = Int8PtrTy;
1148f4a2713aSLionel Sambuc if (Loc->getType() != BP)
1149f4a2713aSLionel Sambuc Loc = Builder.CreateBitCast(Loc, BP);
1150f4a2713aSLionel Sambuc
1151f4a2713aSLionel Sambuc // If the initializer is all or mostly zeros, codegen with memset then do
1152f4a2713aSLionel Sambuc // a few stores afterward.
1153f4a2713aSLionel Sambuc if (shouldUseMemSetPlusStoresToInitialize(constant,
1154f4a2713aSLionel Sambuc CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
1155f4a2713aSLionel Sambuc Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1156f4a2713aSLionel Sambuc alignment.getQuantity(), isVolatile);
1157f4a2713aSLionel Sambuc // Zero and undef don't require a stores.
1158f4a2713aSLionel Sambuc if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
1159f4a2713aSLionel Sambuc Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1160f4a2713aSLionel Sambuc emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
1161f4a2713aSLionel Sambuc }
1162f4a2713aSLionel Sambuc } else {
1163f4a2713aSLionel Sambuc // Otherwise, create a temporary global with the initializer then
1164f4a2713aSLionel Sambuc // memcpy from the global to the alloca.
1165*0a6a1f1dSLionel Sambuc std::string Name = getStaticDeclName(CGM, D);
1166f4a2713aSLionel Sambuc llvm::GlobalVariable *GV =
1167f4a2713aSLionel Sambuc new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1168f4a2713aSLionel Sambuc llvm::GlobalValue::PrivateLinkage,
1169f4a2713aSLionel Sambuc constant, Name);
1170f4a2713aSLionel Sambuc GV->setAlignment(alignment.getQuantity());
1171f4a2713aSLionel Sambuc GV->setUnnamedAddr(true);
1172f4a2713aSLionel Sambuc
1173f4a2713aSLionel Sambuc llvm::Value *SrcPtr = GV;
1174f4a2713aSLionel Sambuc if (SrcPtr->getType() != BP)
1175f4a2713aSLionel Sambuc SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1176f4a2713aSLionel Sambuc
1177f4a2713aSLionel Sambuc Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1178f4a2713aSLionel Sambuc isVolatile);
1179f4a2713aSLionel Sambuc }
1180f4a2713aSLionel Sambuc }
1181f4a2713aSLionel Sambuc
1182f4a2713aSLionel Sambuc /// Emit an expression as an initializer for a variable at the given
1183f4a2713aSLionel Sambuc /// location. The expression is not necessarily the normal
1184f4a2713aSLionel Sambuc /// initializer for the variable, and the address is not necessarily
1185f4a2713aSLionel Sambuc /// its normal location.
1186f4a2713aSLionel Sambuc ///
1187f4a2713aSLionel Sambuc /// \param init the initializing expression
1188f4a2713aSLionel Sambuc /// \param var the variable to act as if we're initializing
1189f4a2713aSLionel Sambuc /// \param loc the address to initialize; its type is a pointer
1190f4a2713aSLionel Sambuc /// to the LLVM mapping of the variable's type
1191f4a2713aSLionel Sambuc /// \param alignment the alignment of the address
1192f4a2713aSLionel Sambuc /// \param capturedByInit true if the variable is a __block variable
1193f4a2713aSLionel Sambuc /// whose address is potentially changed by the initializer
EmitExprAsInit(const Expr * init,const ValueDecl * D,LValue lvalue,bool capturedByInit)1194*0a6a1f1dSLionel Sambuc void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1195*0a6a1f1dSLionel Sambuc LValue lvalue, bool capturedByInit) {
1196f4a2713aSLionel Sambuc QualType type = D->getType();
1197f4a2713aSLionel Sambuc
1198f4a2713aSLionel Sambuc if (type->isReferenceType()) {
1199f4a2713aSLionel Sambuc RValue rvalue = EmitReferenceBindingToExpr(init);
1200f4a2713aSLionel Sambuc if (capturedByInit)
1201f4a2713aSLionel Sambuc drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1202f4a2713aSLionel Sambuc EmitStoreThroughLValue(rvalue, lvalue, true);
1203f4a2713aSLionel Sambuc return;
1204f4a2713aSLionel Sambuc }
1205f4a2713aSLionel Sambuc switch (getEvaluationKind(type)) {
1206f4a2713aSLionel Sambuc case TEK_Scalar:
1207f4a2713aSLionel Sambuc EmitScalarInit(init, D, lvalue, capturedByInit);
1208f4a2713aSLionel Sambuc return;
1209f4a2713aSLionel Sambuc case TEK_Complex: {
1210f4a2713aSLionel Sambuc ComplexPairTy complex = EmitComplexExpr(init);
1211f4a2713aSLionel Sambuc if (capturedByInit)
1212f4a2713aSLionel Sambuc drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1213f4a2713aSLionel Sambuc EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1214f4a2713aSLionel Sambuc return;
1215f4a2713aSLionel Sambuc }
1216f4a2713aSLionel Sambuc case TEK_Aggregate:
1217f4a2713aSLionel Sambuc if (type->isAtomicType()) {
1218f4a2713aSLionel Sambuc EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1219f4a2713aSLionel Sambuc } else {
1220f4a2713aSLionel Sambuc // TODO: how can we delay here if D is captured by its initializer?
1221f4a2713aSLionel Sambuc EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1222f4a2713aSLionel Sambuc AggValueSlot::IsDestructed,
1223f4a2713aSLionel Sambuc AggValueSlot::DoesNotNeedGCBarriers,
1224f4a2713aSLionel Sambuc AggValueSlot::IsNotAliased));
1225f4a2713aSLionel Sambuc }
1226f4a2713aSLionel Sambuc return;
1227f4a2713aSLionel Sambuc }
1228f4a2713aSLionel Sambuc llvm_unreachable("bad evaluation kind");
1229f4a2713aSLionel Sambuc }
1230f4a2713aSLionel Sambuc
1231f4a2713aSLionel Sambuc /// Enter a destroy cleanup for the given local variable.
emitAutoVarTypeCleanup(const CodeGenFunction::AutoVarEmission & emission,QualType::DestructionKind dtorKind)1232f4a2713aSLionel Sambuc void CodeGenFunction::emitAutoVarTypeCleanup(
1233f4a2713aSLionel Sambuc const CodeGenFunction::AutoVarEmission &emission,
1234f4a2713aSLionel Sambuc QualType::DestructionKind dtorKind) {
1235f4a2713aSLionel Sambuc assert(dtorKind != QualType::DK_none);
1236f4a2713aSLionel Sambuc
1237f4a2713aSLionel Sambuc // Note that for __block variables, we want to destroy the
1238f4a2713aSLionel Sambuc // original stack object, not the possibly forwarded object.
1239f4a2713aSLionel Sambuc llvm::Value *addr = emission.getObjectAddress(*this);
1240f4a2713aSLionel Sambuc
1241f4a2713aSLionel Sambuc const VarDecl *var = emission.Variable;
1242f4a2713aSLionel Sambuc QualType type = var->getType();
1243f4a2713aSLionel Sambuc
1244f4a2713aSLionel Sambuc CleanupKind cleanupKind = NormalAndEHCleanup;
1245*0a6a1f1dSLionel Sambuc CodeGenFunction::Destroyer *destroyer = nullptr;
1246f4a2713aSLionel Sambuc
1247f4a2713aSLionel Sambuc switch (dtorKind) {
1248f4a2713aSLionel Sambuc case QualType::DK_none:
1249f4a2713aSLionel Sambuc llvm_unreachable("no cleanup for trivially-destructible variable");
1250f4a2713aSLionel Sambuc
1251f4a2713aSLionel Sambuc case QualType::DK_cxx_destructor:
1252f4a2713aSLionel Sambuc // If there's an NRVO flag on the emission, we need a different
1253f4a2713aSLionel Sambuc // cleanup.
1254f4a2713aSLionel Sambuc if (emission.NRVOFlag) {
1255f4a2713aSLionel Sambuc assert(!type->isArrayType());
1256f4a2713aSLionel Sambuc CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1257f4a2713aSLionel Sambuc EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1258f4a2713aSLionel Sambuc emission.NRVOFlag);
1259f4a2713aSLionel Sambuc return;
1260f4a2713aSLionel Sambuc }
1261f4a2713aSLionel Sambuc break;
1262f4a2713aSLionel Sambuc
1263f4a2713aSLionel Sambuc case QualType::DK_objc_strong_lifetime:
1264f4a2713aSLionel Sambuc // Suppress cleanups for pseudo-strong variables.
1265f4a2713aSLionel Sambuc if (var->isARCPseudoStrong()) return;
1266f4a2713aSLionel Sambuc
1267f4a2713aSLionel Sambuc // Otherwise, consider whether to use an EH cleanup or not.
1268f4a2713aSLionel Sambuc cleanupKind = getARCCleanupKind();
1269f4a2713aSLionel Sambuc
1270f4a2713aSLionel Sambuc // Use the imprecise destroyer by default.
1271f4a2713aSLionel Sambuc if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1272f4a2713aSLionel Sambuc destroyer = CodeGenFunction::destroyARCStrongImprecise;
1273f4a2713aSLionel Sambuc break;
1274f4a2713aSLionel Sambuc
1275f4a2713aSLionel Sambuc case QualType::DK_objc_weak_lifetime:
1276f4a2713aSLionel Sambuc break;
1277f4a2713aSLionel Sambuc }
1278f4a2713aSLionel Sambuc
1279f4a2713aSLionel Sambuc // If we haven't chosen a more specific destroyer, use the default.
1280f4a2713aSLionel Sambuc if (!destroyer) destroyer = getDestroyer(dtorKind);
1281f4a2713aSLionel Sambuc
1282f4a2713aSLionel Sambuc // Use an EH cleanup in array destructors iff the destructor itself
1283f4a2713aSLionel Sambuc // is being pushed as an EH cleanup.
1284f4a2713aSLionel Sambuc bool useEHCleanup = (cleanupKind & EHCleanup);
1285f4a2713aSLionel Sambuc EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1286f4a2713aSLionel Sambuc useEHCleanup);
1287f4a2713aSLionel Sambuc }
1288f4a2713aSLionel Sambuc
EmitAutoVarCleanups(const AutoVarEmission & emission)1289f4a2713aSLionel Sambuc void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1290f4a2713aSLionel Sambuc assert(emission.Variable && "emission was not valid!");
1291f4a2713aSLionel Sambuc
1292f4a2713aSLionel Sambuc // If this was emitted as a global constant, we're done.
1293f4a2713aSLionel Sambuc if (emission.wasEmittedAsGlobal()) return;
1294f4a2713aSLionel Sambuc
1295f4a2713aSLionel Sambuc // If we don't have an insertion point, we're done. Sema prevents
1296f4a2713aSLionel Sambuc // us from jumping into any of these scopes anyway.
1297f4a2713aSLionel Sambuc if (!HaveInsertPoint()) return;
1298f4a2713aSLionel Sambuc
1299f4a2713aSLionel Sambuc const VarDecl &D = *emission.Variable;
1300f4a2713aSLionel Sambuc
1301f4a2713aSLionel Sambuc // Make sure we call @llvm.lifetime.end. This needs to happen
1302f4a2713aSLionel Sambuc // *last*, so the cleanup needs to be pushed *first*.
1303f4a2713aSLionel Sambuc if (emission.useLifetimeMarkers()) {
1304f4a2713aSLionel Sambuc EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1305f4a2713aSLionel Sambuc emission.getAllocatedAddress(),
1306f4a2713aSLionel Sambuc emission.getSizeForLifetimeMarkers());
1307f4a2713aSLionel Sambuc }
1308f4a2713aSLionel Sambuc
1309f4a2713aSLionel Sambuc // Check the type for a cleanup.
1310f4a2713aSLionel Sambuc if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1311f4a2713aSLionel Sambuc emitAutoVarTypeCleanup(emission, dtorKind);
1312f4a2713aSLionel Sambuc
1313f4a2713aSLionel Sambuc // In GC mode, honor objc_precise_lifetime.
1314f4a2713aSLionel Sambuc if (getLangOpts().getGC() != LangOptions::NonGC &&
1315f4a2713aSLionel Sambuc D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1316f4a2713aSLionel Sambuc EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1317f4a2713aSLionel Sambuc }
1318f4a2713aSLionel Sambuc
1319f4a2713aSLionel Sambuc // Handle the cleanup attribute.
1320f4a2713aSLionel Sambuc if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1321f4a2713aSLionel Sambuc const FunctionDecl *FD = CA->getFunctionDecl();
1322f4a2713aSLionel Sambuc
1323f4a2713aSLionel Sambuc llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1324f4a2713aSLionel Sambuc assert(F && "Could not find function!");
1325f4a2713aSLionel Sambuc
1326f4a2713aSLionel Sambuc const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
1327f4a2713aSLionel Sambuc EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1328f4a2713aSLionel Sambuc }
1329f4a2713aSLionel Sambuc
1330f4a2713aSLionel Sambuc // If this is a block variable, call _Block_object_destroy
1331f4a2713aSLionel Sambuc // (on the unforwarded address).
1332f4a2713aSLionel Sambuc if (emission.IsByRef)
1333f4a2713aSLionel Sambuc enterByrefCleanup(emission);
1334f4a2713aSLionel Sambuc }
1335f4a2713aSLionel Sambuc
1336f4a2713aSLionel Sambuc CodeGenFunction::Destroyer *
getDestroyer(QualType::DestructionKind kind)1337f4a2713aSLionel Sambuc CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1338f4a2713aSLionel Sambuc switch (kind) {
1339f4a2713aSLionel Sambuc case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1340f4a2713aSLionel Sambuc case QualType::DK_cxx_destructor:
1341f4a2713aSLionel Sambuc return destroyCXXObject;
1342f4a2713aSLionel Sambuc case QualType::DK_objc_strong_lifetime:
1343f4a2713aSLionel Sambuc return destroyARCStrongPrecise;
1344f4a2713aSLionel Sambuc case QualType::DK_objc_weak_lifetime:
1345f4a2713aSLionel Sambuc return destroyARCWeak;
1346f4a2713aSLionel Sambuc }
1347f4a2713aSLionel Sambuc llvm_unreachable("Unknown DestructionKind");
1348f4a2713aSLionel Sambuc }
1349f4a2713aSLionel Sambuc
1350f4a2713aSLionel Sambuc /// pushEHDestroy - Push the standard destructor for the given type as
1351f4a2713aSLionel Sambuc /// an EH-only cleanup.
pushEHDestroy(QualType::DestructionKind dtorKind,llvm::Value * addr,QualType type)1352f4a2713aSLionel Sambuc void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1353f4a2713aSLionel Sambuc llvm::Value *addr, QualType type) {
1354f4a2713aSLionel Sambuc assert(dtorKind && "cannot push destructor for trivial type");
1355f4a2713aSLionel Sambuc assert(needsEHCleanup(dtorKind));
1356f4a2713aSLionel Sambuc
1357f4a2713aSLionel Sambuc pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1358f4a2713aSLionel Sambuc }
1359f4a2713aSLionel Sambuc
1360f4a2713aSLionel Sambuc /// pushDestroy - Push the standard destructor for the given type as
1361f4a2713aSLionel Sambuc /// at least a normal cleanup.
pushDestroy(QualType::DestructionKind dtorKind,llvm::Value * addr,QualType type)1362f4a2713aSLionel Sambuc void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1363f4a2713aSLionel Sambuc llvm::Value *addr, QualType type) {
1364f4a2713aSLionel Sambuc assert(dtorKind && "cannot push destructor for trivial type");
1365f4a2713aSLionel Sambuc
1366f4a2713aSLionel Sambuc CleanupKind cleanupKind = getCleanupKind(dtorKind);
1367f4a2713aSLionel Sambuc pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1368f4a2713aSLionel Sambuc cleanupKind & EHCleanup);
1369f4a2713aSLionel Sambuc }
1370f4a2713aSLionel Sambuc
pushDestroy(CleanupKind cleanupKind,llvm::Value * addr,QualType type,Destroyer * destroyer,bool useEHCleanupForArray)1371f4a2713aSLionel Sambuc void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
1372f4a2713aSLionel Sambuc QualType type, Destroyer *destroyer,
1373f4a2713aSLionel Sambuc bool useEHCleanupForArray) {
1374f4a2713aSLionel Sambuc pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1375f4a2713aSLionel Sambuc destroyer, useEHCleanupForArray);
1376f4a2713aSLionel Sambuc }
1377f4a2713aSLionel Sambuc
pushStackRestore(CleanupKind Kind,llvm::Value * SPMem)1378*0a6a1f1dSLionel Sambuc void CodeGenFunction::pushStackRestore(CleanupKind Kind, llvm::Value *SPMem) {
1379*0a6a1f1dSLionel Sambuc EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1380*0a6a1f1dSLionel Sambuc }
1381*0a6a1f1dSLionel Sambuc
pushLifetimeExtendedDestroy(CleanupKind cleanupKind,llvm::Value * addr,QualType type,Destroyer * destroyer,bool useEHCleanupForArray)1382f4a2713aSLionel Sambuc void CodeGenFunction::pushLifetimeExtendedDestroy(
1383f4a2713aSLionel Sambuc CleanupKind cleanupKind, llvm::Value *addr, QualType type,
1384f4a2713aSLionel Sambuc Destroyer *destroyer, bool useEHCleanupForArray) {
1385f4a2713aSLionel Sambuc assert(!isInConditionalBranch() &&
1386f4a2713aSLionel Sambuc "performing lifetime extension from within conditional");
1387f4a2713aSLionel Sambuc
1388f4a2713aSLionel Sambuc // Push an EH-only cleanup for the object now.
1389f4a2713aSLionel Sambuc // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1390f4a2713aSLionel Sambuc // around in case a temporary's destructor throws an exception.
1391f4a2713aSLionel Sambuc if (cleanupKind & EHCleanup)
1392f4a2713aSLionel Sambuc EHStack.pushCleanup<DestroyObject>(
1393f4a2713aSLionel Sambuc static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1394f4a2713aSLionel Sambuc destroyer, useEHCleanupForArray);
1395f4a2713aSLionel Sambuc
1396f4a2713aSLionel Sambuc // Remember that we need to push a full cleanup for the object at the
1397f4a2713aSLionel Sambuc // end of the full-expression.
1398f4a2713aSLionel Sambuc pushCleanupAfterFullExpr<DestroyObject>(
1399f4a2713aSLionel Sambuc cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1400f4a2713aSLionel Sambuc }
1401f4a2713aSLionel Sambuc
1402f4a2713aSLionel Sambuc /// emitDestroy - Immediately perform the destruction of the given
1403f4a2713aSLionel Sambuc /// object.
1404f4a2713aSLionel Sambuc ///
1405f4a2713aSLionel Sambuc /// \param addr - the address of the object; a type*
1406f4a2713aSLionel Sambuc /// \param type - the type of the object; if an array type, all
1407f4a2713aSLionel Sambuc /// objects are destroyed in reverse order
1408f4a2713aSLionel Sambuc /// \param destroyer - the function to call to destroy individual
1409f4a2713aSLionel Sambuc /// elements
1410f4a2713aSLionel Sambuc /// \param useEHCleanupForArray - whether an EH cleanup should be
1411f4a2713aSLionel Sambuc /// used when destroying array elements, in case one of the
1412f4a2713aSLionel Sambuc /// destructions throws an exception
emitDestroy(llvm::Value * addr,QualType type,Destroyer * destroyer,bool useEHCleanupForArray)1413f4a2713aSLionel Sambuc void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
1414f4a2713aSLionel Sambuc Destroyer *destroyer,
1415f4a2713aSLionel Sambuc bool useEHCleanupForArray) {
1416f4a2713aSLionel Sambuc const ArrayType *arrayType = getContext().getAsArrayType(type);
1417f4a2713aSLionel Sambuc if (!arrayType)
1418f4a2713aSLionel Sambuc return destroyer(*this, addr, type);
1419f4a2713aSLionel Sambuc
1420f4a2713aSLionel Sambuc llvm::Value *begin = addr;
1421f4a2713aSLionel Sambuc llvm::Value *length = emitArrayLength(arrayType, type, begin);
1422f4a2713aSLionel Sambuc
1423f4a2713aSLionel Sambuc // Normally we have to check whether the array is zero-length.
1424f4a2713aSLionel Sambuc bool checkZeroLength = true;
1425f4a2713aSLionel Sambuc
1426f4a2713aSLionel Sambuc // But if the array length is constant, we can suppress that.
1427f4a2713aSLionel Sambuc if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1428f4a2713aSLionel Sambuc // ...and if it's constant zero, we can just skip the entire thing.
1429f4a2713aSLionel Sambuc if (constLength->isZero()) return;
1430f4a2713aSLionel Sambuc checkZeroLength = false;
1431f4a2713aSLionel Sambuc }
1432f4a2713aSLionel Sambuc
1433f4a2713aSLionel Sambuc llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1434f4a2713aSLionel Sambuc emitArrayDestroy(begin, end, type, destroyer,
1435f4a2713aSLionel Sambuc checkZeroLength, useEHCleanupForArray);
1436f4a2713aSLionel Sambuc }
1437f4a2713aSLionel Sambuc
1438f4a2713aSLionel Sambuc /// emitArrayDestroy - Destroys all the elements of the given array,
1439f4a2713aSLionel Sambuc /// beginning from last to first. The array cannot be zero-length.
1440f4a2713aSLionel Sambuc ///
1441f4a2713aSLionel Sambuc /// \param begin - a type* denoting the first element of the array
1442f4a2713aSLionel Sambuc /// \param end - a type* denoting one past the end of the array
1443f4a2713aSLionel Sambuc /// \param type - the element type of the array
1444f4a2713aSLionel Sambuc /// \param destroyer - the function to call to destroy elements
1445f4a2713aSLionel Sambuc /// \param useEHCleanup - whether to push an EH cleanup to destroy
1446f4a2713aSLionel Sambuc /// the remaining elements in case the destruction of a single
1447f4a2713aSLionel Sambuc /// element throws
emitArrayDestroy(llvm::Value * begin,llvm::Value * end,QualType type,Destroyer * destroyer,bool checkZeroLength,bool useEHCleanup)1448f4a2713aSLionel Sambuc void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1449f4a2713aSLionel Sambuc llvm::Value *end,
1450f4a2713aSLionel Sambuc QualType type,
1451f4a2713aSLionel Sambuc Destroyer *destroyer,
1452f4a2713aSLionel Sambuc bool checkZeroLength,
1453f4a2713aSLionel Sambuc bool useEHCleanup) {
1454f4a2713aSLionel Sambuc assert(!type->isArrayType());
1455f4a2713aSLionel Sambuc
1456f4a2713aSLionel Sambuc // The basic structure here is a do-while loop, because we don't
1457f4a2713aSLionel Sambuc // need to check for the zero-element case.
1458f4a2713aSLionel Sambuc llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1459f4a2713aSLionel Sambuc llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1460f4a2713aSLionel Sambuc
1461f4a2713aSLionel Sambuc if (checkZeroLength) {
1462f4a2713aSLionel Sambuc llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1463f4a2713aSLionel Sambuc "arraydestroy.isempty");
1464f4a2713aSLionel Sambuc Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1465f4a2713aSLionel Sambuc }
1466f4a2713aSLionel Sambuc
1467f4a2713aSLionel Sambuc // Enter the loop body, making that address the current address.
1468f4a2713aSLionel Sambuc llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1469f4a2713aSLionel Sambuc EmitBlock(bodyBB);
1470f4a2713aSLionel Sambuc llvm::PHINode *elementPast =
1471f4a2713aSLionel Sambuc Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1472f4a2713aSLionel Sambuc elementPast->addIncoming(end, entryBB);
1473f4a2713aSLionel Sambuc
1474f4a2713aSLionel Sambuc // Shift the address back by one element.
1475f4a2713aSLionel Sambuc llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1476f4a2713aSLionel Sambuc llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1477f4a2713aSLionel Sambuc "arraydestroy.element");
1478f4a2713aSLionel Sambuc
1479f4a2713aSLionel Sambuc if (useEHCleanup)
1480f4a2713aSLionel Sambuc pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1481f4a2713aSLionel Sambuc
1482f4a2713aSLionel Sambuc // Perform the actual destruction there.
1483f4a2713aSLionel Sambuc destroyer(*this, element, type);
1484f4a2713aSLionel Sambuc
1485f4a2713aSLionel Sambuc if (useEHCleanup)
1486f4a2713aSLionel Sambuc PopCleanupBlock();
1487f4a2713aSLionel Sambuc
1488f4a2713aSLionel Sambuc // Check whether we've reached the end.
1489f4a2713aSLionel Sambuc llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1490f4a2713aSLionel Sambuc Builder.CreateCondBr(done, doneBB, bodyBB);
1491f4a2713aSLionel Sambuc elementPast->addIncoming(element, Builder.GetInsertBlock());
1492f4a2713aSLionel Sambuc
1493f4a2713aSLionel Sambuc // Done.
1494f4a2713aSLionel Sambuc EmitBlock(doneBB);
1495f4a2713aSLionel Sambuc }
1496f4a2713aSLionel Sambuc
1497f4a2713aSLionel Sambuc /// Perform partial array destruction as if in an EH cleanup. Unlike
1498f4a2713aSLionel Sambuc /// emitArrayDestroy, the element type here may still be an array type.
emitPartialArrayDestroy(CodeGenFunction & CGF,llvm::Value * begin,llvm::Value * end,QualType type,CodeGenFunction::Destroyer * destroyer)1499f4a2713aSLionel Sambuc static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1500f4a2713aSLionel Sambuc llvm::Value *begin, llvm::Value *end,
1501f4a2713aSLionel Sambuc QualType type,
1502f4a2713aSLionel Sambuc CodeGenFunction::Destroyer *destroyer) {
1503f4a2713aSLionel Sambuc // If the element type is itself an array, drill down.
1504f4a2713aSLionel Sambuc unsigned arrayDepth = 0;
1505f4a2713aSLionel Sambuc while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1506f4a2713aSLionel Sambuc // VLAs don't require a GEP index to walk into.
1507f4a2713aSLionel Sambuc if (!isa<VariableArrayType>(arrayType))
1508f4a2713aSLionel Sambuc arrayDepth++;
1509f4a2713aSLionel Sambuc type = arrayType->getElementType();
1510f4a2713aSLionel Sambuc }
1511f4a2713aSLionel Sambuc
1512f4a2713aSLionel Sambuc if (arrayDepth) {
1513f4a2713aSLionel Sambuc llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1514f4a2713aSLionel Sambuc
1515f4a2713aSLionel Sambuc SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
1516f4a2713aSLionel Sambuc begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1517f4a2713aSLionel Sambuc end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1518f4a2713aSLionel Sambuc }
1519f4a2713aSLionel Sambuc
1520f4a2713aSLionel Sambuc // Destroy the array. We don't ever need an EH cleanup because we
1521f4a2713aSLionel Sambuc // assume that we're in an EH cleanup ourselves, so a throwing
1522f4a2713aSLionel Sambuc // destructor causes an immediate terminate.
1523f4a2713aSLionel Sambuc CGF.emitArrayDestroy(begin, end, type, destroyer,
1524f4a2713aSLionel Sambuc /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1525f4a2713aSLionel Sambuc }
1526f4a2713aSLionel Sambuc
1527f4a2713aSLionel Sambuc namespace {
1528f4a2713aSLionel Sambuc /// RegularPartialArrayDestroy - a cleanup which performs a partial
1529f4a2713aSLionel Sambuc /// array destroy where the end pointer is regularly determined and
1530f4a2713aSLionel Sambuc /// does not need to be loaded from a local.
1531f4a2713aSLionel Sambuc class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1532f4a2713aSLionel Sambuc llvm::Value *ArrayBegin;
1533f4a2713aSLionel Sambuc llvm::Value *ArrayEnd;
1534f4a2713aSLionel Sambuc QualType ElementType;
1535f4a2713aSLionel Sambuc CodeGenFunction::Destroyer *Destroyer;
1536f4a2713aSLionel Sambuc public:
RegularPartialArrayDestroy(llvm::Value * arrayBegin,llvm::Value * arrayEnd,QualType elementType,CodeGenFunction::Destroyer * destroyer)1537f4a2713aSLionel Sambuc RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1538f4a2713aSLionel Sambuc QualType elementType,
1539f4a2713aSLionel Sambuc CodeGenFunction::Destroyer *destroyer)
1540f4a2713aSLionel Sambuc : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1541f4a2713aSLionel Sambuc ElementType(elementType), Destroyer(destroyer) {}
1542f4a2713aSLionel Sambuc
Emit(CodeGenFunction & CGF,Flags flags)1543*0a6a1f1dSLionel Sambuc void Emit(CodeGenFunction &CGF, Flags flags) override {
1544f4a2713aSLionel Sambuc emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1545f4a2713aSLionel Sambuc ElementType, Destroyer);
1546f4a2713aSLionel Sambuc }
1547f4a2713aSLionel Sambuc };
1548f4a2713aSLionel Sambuc
1549f4a2713aSLionel Sambuc /// IrregularPartialArrayDestroy - a cleanup which performs a
1550f4a2713aSLionel Sambuc /// partial array destroy where the end pointer is irregularly
1551f4a2713aSLionel Sambuc /// determined and must be loaded from a local.
1552f4a2713aSLionel Sambuc class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
1553f4a2713aSLionel Sambuc llvm::Value *ArrayBegin;
1554f4a2713aSLionel Sambuc llvm::Value *ArrayEndPointer;
1555f4a2713aSLionel Sambuc QualType ElementType;
1556f4a2713aSLionel Sambuc CodeGenFunction::Destroyer *Destroyer;
1557f4a2713aSLionel Sambuc public:
IrregularPartialArrayDestroy(llvm::Value * arrayBegin,llvm::Value * arrayEndPointer,QualType elementType,CodeGenFunction::Destroyer * destroyer)1558f4a2713aSLionel Sambuc IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1559f4a2713aSLionel Sambuc llvm::Value *arrayEndPointer,
1560f4a2713aSLionel Sambuc QualType elementType,
1561f4a2713aSLionel Sambuc CodeGenFunction::Destroyer *destroyer)
1562f4a2713aSLionel Sambuc : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1563f4a2713aSLionel Sambuc ElementType(elementType), Destroyer(destroyer) {}
1564f4a2713aSLionel Sambuc
Emit(CodeGenFunction & CGF,Flags flags)1565*0a6a1f1dSLionel Sambuc void Emit(CodeGenFunction &CGF, Flags flags) override {
1566f4a2713aSLionel Sambuc llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1567f4a2713aSLionel Sambuc emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1568f4a2713aSLionel Sambuc ElementType, Destroyer);
1569f4a2713aSLionel Sambuc }
1570f4a2713aSLionel Sambuc };
1571f4a2713aSLionel Sambuc }
1572f4a2713aSLionel Sambuc
1573f4a2713aSLionel Sambuc /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1574f4a2713aSLionel Sambuc /// already-constructed elements of the given array. The cleanup
1575f4a2713aSLionel Sambuc /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1576f4a2713aSLionel Sambuc ///
1577f4a2713aSLionel Sambuc /// \param elementType - the immediate element type of the array;
1578f4a2713aSLionel Sambuc /// possibly still an array type
pushIrregularPartialArrayCleanup(llvm::Value * arrayBegin,llvm::Value * arrayEndPointer,QualType elementType,Destroyer * destroyer)1579f4a2713aSLionel Sambuc void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1580f4a2713aSLionel Sambuc llvm::Value *arrayEndPointer,
1581f4a2713aSLionel Sambuc QualType elementType,
1582f4a2713aSLionel Sambuc Destroyer *destroyer) {
1583f4a2713aSLionel Sambuc pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1584f4a2713aSLionel Sambuc arrayBegin, arrayEndPointer,
1585f4a2713aSLionel Sambuc elementType, destroyer);
1586f4a2713aSLionel Sambuc }
1587f4a2713aSLionel Sambuc
1588f4a2713aSLionel Sambuc /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1589f4a2713aSLionel Sambuc /// already-constructed elements of the given array. The cleanup
1590f4a2713aSLionel Sambuc /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1591f4a2713aSLionel Sambuc ///
1592f4a2713aSLionel Sambuc /// \param elementType - the immediate element type of the array;
1593f4a2713aSLionel Sambuc /// possibly still an array type
pushRegularPartialArrayCleanup(llvm::Value * arrayBegin,llvm::Value * arrayEnd,QualType elementType,Destroyer * destroyer)1594f4a2713aSLionel Sambuc void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1595f4a2713aSLionel Sambuc llvm::Value *arrayEnd,
1596f4a2713aSLionel Sambuc QualType elementType,
1597f4a2713aSLionel Sambuc Destroyer *destroyer) {
1598f4a2713aSLionel Sambuc pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1599f4a2713aSLionel Sambuc arrayBegin, arrayEnd,
1600f4a2713aSLionel Sambuc elementType, destroyer);
1601f4a2713aSLionel Sambuc }
1602f4a2713aSLionel Sambuc
1603f4a2713aSLionel Sambuc /// Lazily declare the @llvm.lifetime.start intrinsic.
getLLVMLifetimeStartFn()1604f4a2713aSLionel Sambuc llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1605f4a2713aSLionel Sambuc if (LifetimeStartFn) return LifetimeStartFn;
1606f4a2713aSLionel Sambuc LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1607f4a2713aSLionel Sambuc llvm::Intrinsic::lifetime_start);
1608f4a2713aSLionel Sambuc return LifetimeStartFn;
1609f4a2713aSLionel Sambuc }
1610f4a2713aSLionel Sambuc
1611f4a2713aSLionel Sambuc /// Lazily declare the @llvm.lifetime.end intrinsic.
getLLVMLifetimeEndFn()1612f4a2713aSLionel Sambuc llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1613f4a2713aSLionel Sambuc if (LifetimeEndFn) return LifetimeEndFn;
1614f4a2713aSLionel Sambuc LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1615f4a2713aSLionel Sambuc llvm::Intrinsic::lifetime_end);
1616f4a2713aSLionel Sambuc return LifetimeEndFn;
1617f4a2713aSLionel Sambuc }
1618f4a2713aSLionel Sambuc
1619f4a2713aSLionel Sambuc namespace {
1620f4a2713aSLionel Sambuc /// A cleanup to perform a release of an object at the end of a
1621f4a2713aSLionel Sambuc /// function. This is used to balance out the incoming +1 of a
1622f4a2713aSLionel Sambuc /// ns_consumed argument when we can't reasonably do that just by
1623f4a2713aSLionel Sambuc /// not doing the initial retain for a __block argument.
1624f4a2713aSLionel Sambuc struct ConsumeARCParameter : EHScopeStack::Cleanup {
ConsumeARCParameter__anon398828f30311::ConsumeARCParameter1625f4a2713aSLionel Sambuc ConsumeARCParameter(llvm::Value *param,
1626f4a2713aSLionel Sambuc ARCPreciseLifetime_t precise)
1627f4a2713aSLionel Sambuc : Param(param), Precise(precise) {}
1628f4a2713aSLionel Sambuc
1629f4a2713aSLionel Sambuc llvm::Value *Param;
1630f4a2713aSLionel Sambuc ARCPreciseLifetime_t Precise;
1631f4a2713aSLionel Sambuc
Emit__anon398828f30311::ConsumeARCParameter1632*0a6a1f1dSLionel Sambuc void Emit(CodeGenFunction &CGF, Flags flags) override {
1633f4a2713aSLionel Sambuc CGF.EmitARCRelease(Param, Precise);
1634f4a2713aSLionel Sambuc }
1635f4a2713aSLionel Sambuc };
1636f4a2713aSLionel Sambuc }
1637f4a2713aSLionel Sambuc
1638f4a2713aSLionel Sambuc /// Emit an alloca (or GlobalValue depending on target)
1639f4a2713aSLionel Sambuc /// for the specified parameter and set up LocalDeclMap.
EmitParmDecl(const VarDecl & D,llvm::Value * Arg,bool ArgIsPointer,unsigned ArgNo)1640f4a2713aSLionel Sambuc void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1641*0a6a1f1dSLionel Sambuc bool ArgIsPointer, unsigned ArgNo) {
1642f4a2713aSLionel Sambuc // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1643f4a2713aSLionel Sambuc assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1644f4a2713aSLionel Sambuc "Invalid argument to EmitParmDecl");
1645f4a2713aSLionel Sambuc
1646f4a2713aSLionel Sambuc Arg->setName(D.getName());
1647f4a2713aSLionel Sambuc
1648f4a2713aSLionel Sambuc QualType Ty = D.getType();
1649f4a2713aSLionel Sambuc
1650f4a2713aSLionel Sambuc // Use better IR generation for certain implicit parameters.
1651f4a2713aSLionel Sambuc if (isa<ImplicitParamDecl>(D)) {
1652f4a2713aSLionel Sambuc // The only implicit argument a block has is its literal.
1653f4a2713aSLionel Sambuc if (BlockInfo) {
1654f4a2713aSLionel Sambuc LocalDeclMap[&D] = Arg;
1655*0a6a1f1dSLionel Sambuc llvm::Value *LocalAddr = nullptr;
1656f4a2713aSLionel Sambuc if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1657f4a2713aSLionel Sambuc // Allocate a stack slot to let the debug info survive the RA.
1658f4a2713aSLionel Sambuc llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1659f4a2713aSLionel Sambuc D.getName() + ".addr");
1660f4a2713aSLionel Sambuc Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1661f4a2713aSLionel Sambuc LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1662f4a2713aSLionel Sambuc EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1663f4a2713aSLionel Sambuc LocalAddr = Builder.CreateLoad(Alloc);
1664f4a2713aSLionel Sambuc }
1665f4a2713aSLionel Sambuc
1666f4a2713aSLionel Sambuc if (CGDebugInfo *DI = getDebugInfo()) {
1667f4a2713aSLionel Sambuc if (CGM.getCodeGenOpts().getDebugInfo()
1668f4a2713aSLionel Sambuc >= CodeGenOptions::LimitedDebugInfo) {
1669f4a2713aSLionel Sambuc DI->setLocation(D.getLocation());
1670*0a6a1f1dSLionel Sambuc DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, ArgNo,
1671*0a6a1f1dSLionel Sambuc LocalAddr, Builder);
1672f4a2713aSLionel Sambuc }
1673f4a2713aSLionel Sambuc }
1674f4a2713aSLionel Sambuc
1675f4a2713aSLionel Sambuc return;
1676f4a2713aSLionel Sambuc }
1677f4a2713aSLionel Sambuc }
1678f4a2713aSLionel Sambuc
1679f4a2713aSLionel Sambuc llvm::Value *DeclPtr;
1680*0a6a1f1dSLionel Sambuc bool DoStore = false;
1681*0a6a1f1dSLionel Sambuc bool IsScalar = hasScalarEvaluationKind(Ty);
1682*0a6a1f1dSLionel Sambuc CharUnits Align = getContext().getDeclAlign(&D);
1683*0a6a1f1dSLionel Sambuc // If we already have a pointer to the argument, reuse the input pointer.
1684*0a6a1f1dSLionel Sambuc if (ArgIsPointer) {
1685*0a6a1f1dSLionel Sambuc // If we have a prettier pointer type at this point, bitcast to that.
1686*0a6a1f1dSLionel Sambuc unsigned AS = cast<llvm::PointerType>(Arg->getType())->getAddressSpace();
1687*0a6a1f1dSLionel Sambuc llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
1688*0a6a1f1dSLionel Sambuc DeclPtr = Arg->getType() == IRTy ? Arg : Builder.CreateBitCast(Arg, IRTy,
1689*0a6a1f1dSLionel Sambuc D.getName());
1690f4a2713aSLionel Sambuc // Push a destructor cleanup for this parameter if the ABI requires it.
1691*0a6a1f1dSLionel Sambuc // Don't push a cleanup in a thunk for a method that will also emit a
1692*0a6a1f1dSLionel Sambuc // cleanup.
1693*0a6a1f1dSLionel Sambuc if (!IsScalar && !CurFuncIsThunk &&
1694*0a6a1f1dSLionel Sambuc getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1695*0a6a1f1dSLionel Sambuc const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1696*0a6a1f1dSLionel Sambuc if (RD && RD->hasNonTrivialDestructor())
1697f4a2713aSLionel Sambuc pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
1698f4a2713aSLionel Sambuc }
1699f4a2713aSLionel Sambuc } else {
1700f4a2713aSLionel Sambuc // Otherwise, create a temporary to hold the value.
1701f4a2713aSLionel Sambuc llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1702f4a2713aSLionel Sambuc D.getName() + ".addr");
1703f4a2713aSLionel Sambuc Alloc->setAlignment(Align.getQuantity());
1704f4a2713aSLionel Sambuc DeclPtr = Alloc;
1705*0a6a1f1dSLionel Sambuc DoStore = true;
1706*0a6a1f1dSLionel Sambuc }
1707f4a2713aSLionel Sambuc
1708f4a2713aSLionel Sambuc LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
1709*0a6a1f1dSLionel Sambuc if (IsScalar) {
1710*0a6a1f1dSLionel Sambuc Qualifiers qs = Ty.getQualifiers();
1711f4a2713aSLionel Sambuc if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1712f4a2713aSLionel Sambuc // We honor __attribute__((ns_consumed)) for types with lifetime.
1713f4a2713aSLionel Sambuc // For __strong, it's handled by just skipping the initial retain;
1714f4a2713aSLionel Sambuc // otherwise we have to balance out the initial +1 with an extra
1715f4a2713aSLionel Sambuc // cleanup to do the release at the end of the function.
1716f4a2713aSLionel Sambuc bool isConsumed = D.hasAttr<NSConsumedAttr>();
1717f4a2713aSLionel Sambuc
1718f4a2713aSLionel Sambuc // 'self' is always formally __strong, but if this is not an
1719f4a2713aSLionel Sambuc // init method then we don't want to retain it.
1720f4a2713aSLionel Sambuc if (D.isARCPseudoStrong()) {
1721f4a2713aSLionel Sambuc const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1722f4a2713aSLionel Sambuc assert(&D == method->getSelfDecl());
1723f4a2713aSLionel Sambuc assert(lt == Qualifiers::OCL_Strong);
1724f4a2713aSLionel Sambuc assert(qs.hasConst());
1725f4a2713aSLionel Sambuc assert(method->getMethodFamily() != OMF_init);
1726f4a2713aSLionel Sambuc (void) method;
1727f4a2713aSLionel Sambuc lt = Qualifiers::OCL_ExplicitNone;
1728f4a2713aSLionel Sambuc }
1729f4a2713aSLionel Sambuc
1730f4a2713aSLionel Sambuc if (lt == Qualifiers::OCL_Strong) {
1731f4a2713aSLionel Sambuc if (!isConsumed) {
1732f4a2713aSLionel Sambuc if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1733f4a2713aSLionel Sambuc // use objc_storeStrong(&dest, value) for retaining the
1734f4a2713aSLionel Sambuc // object. But first, store a null into 'dest' because
1735f4a2713aSLionel Sambuc // objc_storeStrong attempts to release its old value.
1736f4a2713aSLionel Sambuc llvm::Value *Null = CGM.EmitNullConstant(D.getType());
1737f4a2713aSLionel Sambuc EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1738f4a2713aSLionel Sambuc EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
1739*0a6a1f1dSLionel Sambuc DoStore = false;
1740f4a2713aSLionel Sambuc }
1741f4a2713aSLionel Sambuc else
1742f4a2713aSLionel Sambuc // Don't use objc_retainBlock for block pointers, because we
1743f4a2713aSLionel Sambuc // don't want to Block_copy something just because we got it
1744f4a2713aSLionel Sambuc // as a parameter.
1745f4a2713aSLionel Sambuc Arg = EmitARCRetainNonBlock(Arg);
1746f4a2713aSLionel Sambuc }
1747f4a2713aSLionel Sambuc } else {
1748f4a2713aSLionel Sambuc // Push the cleanup for a consumed parameter.
1749f4a2713aSLionel Sambuc if (isConsumed) {
1750f4a2713aSLionel Sambuc ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1751f4a2713aSLionel Sambuc ? ARCPreciseLifetime : ARCImpreciseLifetime);
1752f4a2713aSLionel Sambuc EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1753f4a2713aSLionel Sambuc precise);
1754f4a2713aSLionel Sambuc }
1755f4a2713aSLionel Sambuc
1756f4a2713aSLionel Sambuc if (lt == Qualifiers::OCL_Weak) {
1757f4a2713aSLionel Sambuc EmitARCInitWeak(DeclPtr, Arg);
1758*0a6a1f1dSLionel Sambuc DoStore = false; // The weak init is a store, no need to do two.
1759f4a2713aSLionel Sambuc }
1760f4a2713aSLionel Sambuc }
1761f4a2713aSLionel Sambuc
1762f4a2713aSLionel Sambuc // Enter the cleanup scope.
1763f4a2713aSLionel Sambuc EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1764f4a2713aSLionel Sambuc }
1765f4a2713aSLionel Sambuc }
1766f4a2713aSLionel Sambuc
1767*0a6a1f1dSLionel Sambuc // Store the initial value into the alloca.
1768*0a6a1f1dSLionel Sambuc if (DoStore)
1769*0a6a1f1dSLionel Sambuc EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1770*0a6a1f1dSLionel Sambuc
1771f4a2713aSLionel Sambuc llvm::Value *&DMEntry = LocalDeclMap[&D];
1772*0a6a1f1dSLionel Sambuc assert(!DMEntry && "Decl already exists in localdeclmap!");
1773f4a2713aSLionel Sambuc DMEntry = DeclPtr;
1774f4a2713aSLionel Sambuc
1775f4a2713aSLionel Sambuc // Emit debug info for param declaration.
1776f4a2713aSLionel Sambuc if (CGDebugInfo *DI = getDebugInfo()) {
1777f4a2713aSLionel Sambuc if (CGM.getCodeGenOpts().getDebugInfo()
1778f4a2713aSLionel Sambuc >= CodeGenOptions::LimitedDebugInfo) {
1779f4a2713aSLionel Sambuc DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1780f4a2713aSLionel Sambuc }
1781f4a2713aSLionel Sambuc }
1782f4a2713aSLionel Sambuc
1783f4a2713aSLionel Sambuc if (D.hasAttr<AnnotateAttr>())
1784f4a2713aSLionel Sambuc EmitVarAnnotations(&D, DeclPtr);
1785f4a2713aSLionel Sambuc }
1786