blob: f1ccb094f2384ec284f1eb43924196cae8bdde25 [file] [log] [blame]
Chris Lattner84915fa2007-06-02 04:16:21 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner84915fa2007-06-02 04:16:21 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Decl nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000016#include "CGOpenCLRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CodeGenModule.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000018#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000019#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Anders Carlsson4c03d982008-08-25 01:38:19 +000021#include "clang/AST/DeclObjC.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000022#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000023#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000024#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000025#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/GlobalVariable.h"
28#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/Type.h"
Chris Lattner84915fa2007-06-02 04:16:21 +000030using namespace clang;
31using namespace CodeGen;
32
33
Chris Lattner1ad38f82007-06-09 01:20:56 +000034void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000035 switch (D.getKind()) {
Douglas Gregor19043f02010-04-23 02:02:43 +000036 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +000037 case Decl::ExternCContext:
Douglas Gregor19043f02010-04-23 02:02:43 +000038 case Decl::Namespace:
39 case Decl::UnresolvedUsingTypename:
40 case Decl::ClassTemplateSpecialization:
41 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000042 case Decl::VarTemplateSpecialization:
43 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000044 case Decl::TemplateTypeParm:
45 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000046 case Decl::NonTypeTemplateParm:
Douglas Gregor19043f02010-04-23 02:02:43 +000047 case Decl::CXXMethod:
48 case Decl::CXXConstructor:
49 case Decl::CXXDestructor:
50 case Decl::CXXConversion:
51 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000052 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000053 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000054 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000055 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000056 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000057 case Decl::ImplicitParam:
58 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000059 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000060 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000061 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000062 case Decl::TemplateTemplateParm:
63 case Decl::ObjCMethod:
64 case Decl::ObjCCategory:
65 case Decl::ObjCProtocol:
66 case Decl::ObjCInterface:
67 case Decl::ObjCCategoryImpl:
68 case Decl::ObjCImplementation:
69 case Decl::ObjCProperty:
70 case Decl::ObjCCompatibleAlias:
Abramo Bagnarad7340582010-06-05 05:09:32 +000071 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000072 case Decl::LinkageSpec:
73 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000074 case Decl::FileScopeAsm:
75 case Decl::Friend:
76 case Decl::FriendTemplate:
77 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000078 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000079 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000080 case Decl::UsingShadow:
David Blaikie83d382b2011-09-23 05:06:16 +000081 llvm_unreachable("Declaration should not be in declstmts!");
Chris Lattner84915fa2007-06-02 04:16:21 +000082 case Decl::Function: // void X();
Argyrios Kyrtzidis88e1b972008-10-15 00:42:39 +000083 case Decl::Record: // struct/union/class X;
Chris Lattner84915fa2007-06-02 04:16:21 +000084 case Decl::Enum: // enum X;
Mike Stump11289f42009-09-09 15:08:12 +000085 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis88e1b972008-10-15 00:42:39 +000086 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +000087 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +000088 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +000089 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +000090 case Decl::OMPThreadPrivate:
Michael Han84324352013-02-22 17:15:32 +000091 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +000092 // None of these decls require codegen support.
93 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +000094
David Blaikief121b932013-05-20 22:50:41 +000095 case Decl::NamespaceAlias:
96 if (CGDebugInfo *DI = getDebugInfo())
97 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
98 return;
David Blaikiebd483762013-05-20 04:58:53 +000099 case Decl::Using: // using X; [C++]
100 if (CGDebugInfo *DI = getDebugInfo())
101 DI->EmitUsingDecl(cast<UsingDecl>(D));
102 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000103 case Decl::UsingDirective: // using namespace X; [C++]
104 if (CGDebugInfo *DI = getDebugInfo())
105 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
106 return;
Daniel Dunbara7998072008-08-29 17:28:43 +0000107 case Decl::Var: {
108 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000109 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000110 "Should not see file-scope variables inside a function!");
John McCall1c9c3fd2010-10-15 04:57:14 +0000111 return EmitVarDecl(VD);
Chris Lattner84915fa2007-06-02 04:16:21 +0000112 }
Mike Stump11289f42009-09-09 15:08:12 +0000113
Richard Smithdda56e42011-04-15 14:24:37 +0000114 case Decl::Typedef: // typedef int X;
115 case Decl::TypeAlias: { // using X = int; [C++0x]
116 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000117 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000118
Anders Carlsson5d985f52008-12-20 21:51:53 +0000119 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000120 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000121 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000122 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000123}
Chris Lattner03df1222007-06-02 04:53:11 +0000124
John McCall1c9c3fd2010-10-15 04:57:14 +0000125/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000126/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000127void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000128 if (D.isStaticLocal()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000129 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000130 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000131
David Majnemer27d69db2014-04-28 22:17:59 +0000132 // FIXME: We need to force the emission/use of a guard variable for
133 // some variables even if we can constant-evaluate them because
134 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000135
John McCall1c9c3fd2010-10-15 04:57:14 +0000136 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000137 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000138
139 if (D.hasExternalStorage())
Lauro Ramos Venanciobada8d42008-02-16 22:30:38 +0000140 // Don't emit it now, allow it to be emitted lazily on its first use.
141 return;
Daniel Dunbar0ca16602009-04-14 02:25:56 +0000142
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000143 if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
144 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
145
146 assert(D.hasLocalStorage());
147 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000148}
149
Reid Kleckner453e0562014-10-08 01:07:54 +0000150static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
151 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000152 return CGM.getMangledName(&D).str();
153
Reid Kleckner453e0562014-10-08 01:07:54 +0000154 // If this isn't C++, we don't need a mangled name, just a pretty one.
155 assert(!D.isExternallyVisible() && "name shouldn't matter");
156 std::string ContextName;
157 const DeclContext *DC = D.getDeclContext();
158 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000159 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000160 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
161 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
162 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
163 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000164 else
David Blaikie83d382b2011-09-23 05:06:16 +0000165 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000166
Reid Kleckner453e0562014-10-08 01:07:54 +0000167 ContextName += "." + D.getNameAsString();
168 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000169}
170
Reid Kleckner453e0562014-10-08 01:07:54 +0000171llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
172 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
173 // In general, we don't always emit static var decls once before we reference
174 // them. It is possible to reference them before emitting the function that
175 // contains them, and it is possible to emit the containing function multiple
176 // times.
177 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
178 return ExistingGV;
179
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000180 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000181 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000182
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000183 // Use the label if the variable is renamed with the asm-label extension.
184 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000185 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000186 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000187 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000188 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000189
Reid Kleckner453e0562014-10-08 01:07:54 +0000190 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000191 unsigned AddrSpace =
Reid Kleckner453e0562014-10-08 01:07:54 +0000192 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000193
194 // Local address space cannot have an initializer.
195 llvm::Constant *Init = nullptr;
196 if (Ty.getAddressSpace() != LangAS::opencl_local)
197 Init = EmitNullConstant(Ty);
198 else
199 Init = llvm::UndefValue::get(LTy);
200
Anders Carlssone33eed52009-09-26 18:16:06 +0000201 llvm::GlobalVariable *GV =
Reid Kleckner453e0562014-10-08 01:07:54 +0000202 new llvm::GlobalVariable(getModule(), LTy,
Anders Carlssone33eed52009-09-26 18:16:06 +0000203 Ty.isConstant(getContext()), Linkage,
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000204 Init, Name, nullptr,
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000205 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000206 AddrSpace);
Ken Dyck160146e2010-01-27 17:10:57 +0000207 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Reid Kleckner453e0562014-10-08 01:07:54 +0000208 setGlobalVisibility(GV, &D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000209
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000210 if (supportsCOMDAT() && GV->isWeakForLinker())
211 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
212
Richard Smithfd3834f2013-04-13 02:43:54 +0000213 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000214 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000215
Hans Wennborgef2272c2014-06-18 15:55:13 +0000216 if (D.isExternallyVisible()) {
217 if (D.hasAttr<DLLImportAttr>())
218 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
219 else if (D.hasAttr<DLLExportAttr>())
220 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
221 }
222
Eli Benderskycb399432014-03-24 22:05:38 +0000223 // Make sure the result is of the correct type.
Reid Kleckner453e0562014-10-08 01:07:54 +0000224 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
225 llvm::Constant *Addr = GV;
Eli Benderskycb399432014-03-24 22:05:38 +0000226 if (AddrSpace != ExpectedAddrSpace) {
227 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
Reid Kleckner453e0562014-10-08 01:07:54 +0000228 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
Eli Benderskycb399432014-03-24 22:05:38 +0000229 }
230
Reid Kleckner453e0562014-10-08 01:07:54 +0000231 setStaticLocalDeclAddress(&D, Addr);
232
233 // Ensure that the static local gets initialized by making sure the parent
234 // function gets emitted eventually.
235 const Decl *DC = cast<Decl>(D.getDeclContext());
236
237 // We can't name blocks or captured statements directly, so try to emit their
238 // parents.
239 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
240 DC = DC->getNonClosureContext();
241 // FIXME: Ensure that global blocks get emitted.
242 if (!DC)
243 return Addr;
244 }
245
246 GlobalDecl GD;
247 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
248 GD = GlobalDecl(CD, Ctor_Base);
249 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
250 GD = GlobalDecl(DD, Dtor_Base);
251 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
252 GD = GlobalDecl(FD);
253 else {
254 // Don't do anything for Obj-C method decls or global closures. We should
255 // never defer them.
256 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
257 }
258 if (GD.getDecl())
259 (void)GetAddrOfGlobal(GD);
260
261 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000262}
263
Richard Smith6331c402012-02-13 22:16:19 +0000264/// hasNontrivialDestruction - Determine whether a type's destruction is
265/// non-trivial. If so, and the variable uses static initialization, we must
266/// register its destructor to run on exit.
267static bool hasNontrivialDestruction(QualType T) {
268 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
269 return RD && !RD->hasTrivialDestructor();
270}
271
Chandler Carruth84537952012-03-30 19:44:53 +0000272/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
273/// global variable that has already been created for it. If the initializer
274/// has a different type than GV does, this may free GV and return a different
275/// one. Otherwise it just returns GV.
276llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000277CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000278 llvm::GlobalVariable *GV) {
279 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCall70013b62010-07-15 23:40:35 +0000280
Chris Lattnere99c1102009-12-05 08:22:11 +0000281 // If constant emission failed, then this should be a C++ static
282 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000283 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000284 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000285 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall68ff0372010-09-08 01:44:27 +0000286 else if (Builder.GetInsertBlock()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000287 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000288 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000289 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000290
Chandler Carruth84537952012-03-30 19:44:53 +0000291 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000292 }
Chandler Carruth84537952012-03-30 19:44:53 +0000293 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000294 }
John McCall70013b62010-07-15 23:40:35 +0000295
Chris Lattnere99c1102009-12-05 08:22:11 +0000296 // The initializer may differ in type from the global. Rewrite
297 // the global to match the initializer. (We have to do this
298 // because some types, like unions, can't be completely represented
299 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000300 if (GV->getType()->getElementType() != Init->getType()) {
301 llvm::GlobalVariable *OldGV = GV;
302
303 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
304 OldGV->isConstant(),
305 OldGV->getLinkage(), Init, "",
306 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000307 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000308 CGM.getContext().getTargetAddressSpace(D.getType()));
309 GV->setVisibility(OldGV->getVisibility());
Eric Christopher31ab1302011-08-23 22:38:00 +0000310
Chris Lattnere99c1102009-12-05 08:22:11 +0000311 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000312 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000313
Chris Lattnere99c1102009-12-05 08:22:11 +0000314 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000315 llvm::Constant *NewPtrForOldDecl =
316 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
317 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000318
Chris Lattnere99c1102009-12-05 08:22:11 +0000319 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000320 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000321 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000322
Chandler Carruth84537952012-03-30 19:44:53 +0000323 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
324 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000325
326 if (hasNontrivialDestruction(D.getType())) {
327 // We have a constant initializer, but a nontrivial destructor. We still
328 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000329 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000330 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000331 }
332
Chandler Carruth84537952012-03-30 19:44:53 +0000333 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000334}
335
John McCall1c9c3fd2010-10-15 04:57:14 +0000336void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000337 llvm::GlobalValue::LinkageTypes Linkage) {
Chandler Carruth84537952012-03-30 19:44:53 +0000338 llvm::Value *&DMEntry = LocalDeclMap[&D];
Craig Topper8a13c412014-05-21 05:09:00 +0000339 assert(!DMEntry && "Decl already exists in localdeclmap!");
Mike Stump11289f42009-09-09 15:08:12 +0000340
John McCallb88a5662012-03-30 21:00:39 +0000341 // Check to see if we already have a global variable for this
342 // declaration. This can happen when double-emitting function
343 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000344 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
Daniel Dunbara374e602009-02-25 19:45:19 +0000345
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000346 // Store into LocalDeclMap before generating initializer to handle
347 // circular references.
John McCallb88a5662012-03-30 21:00:39 +0000348 DMEntry = addr;
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000349
John McCall4a39ab82010-05-04 20:45:42 +0000350 // We can't have a VLA here, but we can have a pointer to a VLA,
351 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000352 // Make sure to evaluate VLA bounds now so that we have them for later.
353 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000354 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000355
John McCallb88a5662012-03-30 21:00:39 +0000356 // Save the type in case adding the initializer forces a type change.
357 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000358
Eli Benderskycb399432014-03-24 22:05:38 +0000359 llvm::GlobalVariable *var =
360 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Chris Lattnere99c1102009-12-05 08:22:11 +0000361 // If this value has an initializer, emit it.
362 if (D.getInit())
John McCallb88a5662012-03-30 21:00:39 +0000363 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000364
John McCallb88a5662012-03-30 21:00:39 +0000365 var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000366
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000367 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000368 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000369
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000370 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000371 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000372
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000373 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000374 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000375
Chandler Carruth84537952012-03-30 19:44:53 +0000376 // We may have to cast the constant because of the initializer
377 // mismatch above.
378 //
379 // FIXME: It is really dangerous to store this in the map; if anyone
380 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000381 llvm::Constant *castedAddr =
382 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCallb88a5662012-03-30 21:00:39 +0000383 DMEntry = castedAddr;
384 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000385
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000386 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000387
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000388 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000389 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000390 if (DI &&
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000391 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000392 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000393 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000394 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000395}
Mike Stump11289f42009-09-09 15:08:12 +0000396
John McCall2b7fc382010-07-13 20:32:21 +0000397namespace {
John McCall82fe67b2011-07-09 01:37:26 +0000398 struct DestroyObject : EHScopeStack::Cleanup {
399 DestroyObject(llvm::Value *addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000400 CodeGenFunction::Destroyer *destroyer,
401 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000402 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000403 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000404
John McCall82fe67b2011-07-09 01:37:26 +0000405 llvm::Value *addr;
406 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000407 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000408 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000409
Craig Topper4f12f102014-03-12 06:41:41 +0000410 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000411 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000412 bool useEHCleanupForArray =
413 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000414
415 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000416 }
417 };
418
John McCall82fe67b2011-07-09 01:37:26 +0000419 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
420 DestroyNRVOVariable(llvm::Value *addr,
421 const CXXDestructorDecl *Dtor,
422 llvm::Value *NRVOFlag)
423 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000424
425 const CXXDestructorDecl *Dtor;
426 llvm::Value *NRVOFlag;
427 llvm::Value *Loc;
428
Craig Topper4f12f102014-03-12 06:41:41 +0000429 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000430 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000431 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000432
Craig Topper8a13c412014-05-21 05:09:00 +0000433 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000434 if (NRVO) {
435 // If we exited via NRVO, we skip the destructor call.
436 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
437 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
438 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
439 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
440 CGF.EmitBlock(RunDtorBB);
441 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000442
John McCall2b7fc382010-07-13 20:32:21 +0000443 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +0000444 /*ForVirtualBase=*/false,
445 /*Delegating=*/false,
446 Loc);
John McCall2b7fc382010-07-13 20:32:21 +0000447
448 if (NRVO) CGF.EmitBlock(SkipDtorBB);
449 }
450 };
John McCall2b7fc382010-07-13 20:32:21 +0000451
John McCallcda666c2010-07-21 07:22:38 +0000452 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000453 llvm::Value *Stack;
454 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000455 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000456 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000457 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
458 CGF.Builder.CreateCall(F, V);
459 }
460 };
461
John McCall1bd25562011-06-24 23:21:27 +0000462 struct ExtendGCLifetime : EHScopeStack::Cleanup {
463 const VarDecl &Var;
464 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
465
Craig Topper4f12f102014-03-12 06:41:41 +0000466 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000467 // Compute the address of the local variable, in case it's a
468 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000469 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
470 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000471 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
472 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000473 CGF.EmitExtendGCLifetime(value);
474 }
475 };
476
John McCallcda666c2010-07-21 07:22:38 +0000477 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000478 llvm::Constant *CleanupFn;
479 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000480 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000481
John McCalla464ff92010-07-21 06:13:08 +0000482 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000483 const VarDecl *Var)
484 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000485
Craig Topper4f12f102014-03-12 06:41:41 +0000486 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000487 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
488 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000489 // Compute the address of the local variable, in case it's a byref
490 // or something.
491 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
492
John McCalla464ff92010-07-21 06:13:08 +0000493 // In some cases, the type of the function argument will be different from
494 // the type of the pointer. An example of this is
495 // void f(void* arg);
496 // __attribute__((cleanup(f))) void *g;
497 //
498 // To fix this we insert a bitcast here.
499 QualType ArgTy = FnInfo.arg_begin()->type;
500 llvm::Value *Arg =
501 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
502
503 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000504 Args.add(RValue::get(Arg),
505 CGF.getContext().getPointerType(Var.getType()));
John McCalla464ff92010-07-21 06:13:08 +0000506 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
507 }
508 };
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000509
510 /// A cleanup to call @llvm.lifetime.end.
511 class CallLifetimeEnd : public EHScopeStack::Cleanup {
512 llvm::Value *Addr;
513 llvm::Value *Size;
514 public:
515 CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
516 : Addr(addr), Size(size) {}
517
518 void Emit(CodeGenFunction &CGF, Flags flags) override {
Arnaud A. de Grandmaisonf3470cc2014-12-01 09:30:16 +0000519 llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
520 CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
521 Size, castAddr)
522 ->setDoesNotThrow();
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000523 }
524 };
John McCalla464ff92010-07-21 06:13:08 +0000525}
526
John McCall31168b02011-06-15 23:02:42 +0000527/// EmitAutoVarWithLifetime - Does the setup required for an automatic
528/// variable with lifetime.
529static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
530 llvm::Value *addr,
531 Qualifiers::ObjCLifetime lifetime) {
532 switch (lifetime) {
533 case Qualifiers::OCL_None:
534 llvm_unreachable("present but none");
535
536 case Qualifiers::OCL_ExplicitNone:
537 // nothing to do
538 break;
539
540 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000541 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000542 (var.hasAttr<ObjCPreciseLifetimeAttr>()
543 ? CodeGenFunction::destroyARCStrongPrecise
544 : CodeGenFunction::destroyARCStrongImprecise);
545
546 CleanupKind cleanupKind = CGF.getARCCleanupKind();
547 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
548 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000549 break;
550 }
551 case Qualifiers::OCL_Autoreleasing:
552 // nothing to do
553 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000554
John McCall31168b02011-06-15 23:02:42 +0000555 case Qualifiers::OCL_Weak:
556 // __weak objects always get EH cleanups; otherwise, exceptions
557 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000558 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
559 CodeGenFunction::destroyARCWeak,
560 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000561 break;
562 }
563}
564
565static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
566 if (const Expr *e = dyn_cast<Expr>(s)) {
567 // Skip the most common kinds of expressions that make
568 // hierarchy-walking expensive.
569 s = e = e->IgnoreParenCasts();
570
571 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
572 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000573 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
574 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000575 for (const auto &I : block->captures()) {
576 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000577 return true;
578 }
579 }
John McCall31168b02011-06-15 23:02:42 +0000580 }
581
582 for (Stmt::const_child_range children = s->children(); children; ++children)
Fariborz Jahanian326701e2011-06-29 20:00:16 +0000583 // children might be null; as in missing decl or conditional of an if-stmt.
584 if ((*children) && isAccessedBy(var, *children))
John McCall31168b02011-06-15 23:02:42 +0000585 return true;
586
587 return false;
588}
589
590static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
591 if (!decl) return false;
592 if (!isa<VarDecl>(decl)) return false;
593 const VarDecl *var = cast<VarDecl>(decl);
594 return isAccessedBy(*var, e);
595}
596
John McCall1553b192011-06-16 04:16:24 +0000597static void drillIntoBlockVariable(CodeGenFunction &CGF,
598 LValue &lvalue,
599 const VarDecl *var) {
600 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
601}
602
David Blaikie73ca5692014-12-09 00:32:22 +0000603void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000604 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000605 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000606 if (!lifetime) {
607 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000608 if (capturedByInit)
609 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +0000610 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000611 return;
612 }
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000613
614 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
615 init = DIE->getExpr();
616
John McCall31168b02011-06-15 23:02:42 +0000617 // If we're emitting a value with lifetime, we have to do the
618 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000619 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
620 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000621 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000622 }
623 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000624
625 // We have to maintain the illusion that the variable is
626 // zero-initialized. If the variable might be accessed in its
627 // initializer, zero-initialize before running the initializer, then
628 // actually perform the initialization with an assign.
629 bool accessedByInit = false;
630 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000631 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000632 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000633 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000634 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000635 if (capturedByInit) {
636 // We can use a simple GEP for this because it can't have been
637 // moved yet.
David Blaikie2e804282015-04-05 22:47:07 +0000638 tempLV.setAddress(Builder.CreateStructGEP(
639 nullptr, tempLV.getAddress(),
640 getByRefValueLLVMField(cast<VarDecl>(D)).second));
John McCall31168b02011-06-15 23:02:42 +0000641 }
642
Chris Lattner2192fe52011-07-18 04:24:23 +0000643 llvm::PointerType *ty
John McCall1553b192011-06-16 04:16:24 +0000644 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
John McCall31168b02011-06-15 23:02:42 +0000645 ty = cast<llvm::PointerType>(ty->getElementType());
646
647 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000648
John McCall31168b02011-06-15 23:02:42 +0000649 // If __weak, we want to use a barrier under certain conditions.
650 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000651 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000652
653 // Otherwise just do a simple store.
654 else
David Chisnallfa35df62012-01-16 17:27:18 +0000655 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000656 }
657
658 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000659 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000660
661 switch (lifetime) {
662 case Qualifiers::OCL_None:
663 llvm_unreachable("present but none");
664
665 case Qualifiers::OCL_ExplicitNone:
666 // nothing to do
667 value = EmitScalarExpr(init);
668 break;
669
670 case Qualifiers::OCL_Strong: {
671 value = EmitARCRetainScalarExpr(init);
672 break;
673 }
674
675 case Qualifiers::OCL_Weak: {
676 // No way to optimize a producing initializer into this. It's not
677 // worth optimizing for, because the value will immediately
678 // disappear in the common case.
679 value = EmitScalarExpr(init);
680
John McCall1553b192011-06-16 04:16:24 +0000681 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000682 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000683 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000684 else
John McCall1553b192011-06-16 04:16:24 +0000685 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000686 return;
687 }
688
689 case Qualifiers::OCL_Autoreleasing:
690 value = EmitARCRetainAutoreleaseScalarExpr(init);
691 break;
692 }
693
John McCall1553b192011-06-16 04:16:24 +0000694 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000695
696 // If the variable might have been accessed by its initializer, we
697 // might have to initialize with a barrier. We have to do this for
698 // both __weak and __strong, but __weak got filtered out above.
699 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000700 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000701 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000702 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000703 return;
704 }
705
David Chisnallfa35df62012-01-16 17:27:18 +0000706 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000707}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000708
John McCalld4631322011-06-17 06:42:21 +0000709/// EmitScalarInit - Initialize the given lvalue with the given object.
710void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
711 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
712 if (!lifetime)
David Chisnallfa35df62012-01-16 17:27:18 +0000713 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCalld4631322011-06-17 06:42:21 +0000714
715 switch (lifetime) {
716 case Qualifiers::OCL_None:
717 llvm_unreachable("present but none");
718
719 case Qualifiers::OCL_ExplicitNone:
720 // nothing to do
721 break;
722
723 case Qualifiers::OCL_Strong:
724 init = EmitARCRetain(lvalue.getType(), init);
725 break;
726
727 case Qualifiers::OCL_Weak:
728 // Initialize and then skip the primitive store.
729 EmitARCInitWeak(lvalue.getAddress(), init);
730 return;
731
732 case Qualifiers::OCL_Autoreleasing:
733 init = EmitARCRetainAutorelease(lvalue.getType(), init);
734 break;
735 }
736
David Chisnallfa35df62012-01-16 17:27:18 +0000737 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCalld4631322011-06-17 06:42:21 +0000738}
739
Chris Lattnerb85025f2010-12-01 02:05:19 +0000740/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
741/// non-zero parts of the specified initializer with equal or fewer than
742/// NumStores scalar stores.
743static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
744 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000745 // Zero and Undef never requires any extra stores.
746 if (isa<llvm::ConstantAggregateZero>(Init) ||
747 isa<llvm::ConstantPointerNull>(Init) ||
748 isa<llvm::UndefValue>(Init))
749 return true;
750 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
751 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
752 isa<llvm::ConstantExpr>(Init))
753 return Init->isNullValue() || NumStores--;
754
755 // See if we can emit each element.
756 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
757 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
758 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
759 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
760 return false;
761 }
762 return true;
763 }
Chris Lattner236b3572012-01-31 04:36:19 +0000764
765 if (llvm::ConstantDataSequential *CDS =
766 dyn_cast<llvm::ConstantDataSequential>(Init)) {
767 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
768 llvm::Constant *Elt = CDS->getElementAsConstant(i);
769 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
770 return false;
771 }
772 return true;
773 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000774
Chris Lattnerb85025f2010-12-01 02:05:19 +0000775 // Anything else is hard and scary.
776 return false;
777}
778
779/// emitStoresForInitAfterMemset - For inits that
780/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
781/// stores that would be required.
782static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000783 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000784 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
785 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000786
Chris Lattnere6af8862010-12-02 01:58:41 +0000787 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
788 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
789 isa<llvm::ConstantExpr>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000790 Builder.CreateStore(Init, Loc, isVolatile);
791 return;
792 }
793
794 if (llvm::ConstantDataSequential *CDS =
795 dyn_cast<llvm::ConstantDataSequential>(Init)) {
796 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
797 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000798
799 // If necessary, get a pointer to the element and emit it.
800 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000801 emitStoresForInitAfterMemset(
802 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
803 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000804 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000805 return;
806 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000807
Chris Lattnere6af8862010-12-02 01:58:41 +0000808 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
809 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000810
Chris Lattnere6af8862010-12-02 01:58:41 +0000811 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
812 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000813
814 // If necessary, get a pointer to the element and emit it.
815 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000816 emitStoresForInitAfterMemset(
817 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
818 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000819 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000820}
821
822
823/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
824/// plus some stores to initialize a local variable instead of using a memcpy
825/// from a constant global. It is beneficial to use memset if the global is all
826/// zeros, or mostly zeros and large.
827static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
828 uint64_t GlobalSize) {
829 // If a global is all zeros, always use a memset.
830 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
831
Chris Lattnerb85025f2010-12-01 02:05:19 +0000832 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
833 // do it if it will require 6 or fewer scalar stores.
834 // TODO: Should budget depends on the size? Avoiding a large global warrants
835 // plopping in more stores.
836 unsigned StoreBudget = 6;
837 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000838
839 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000840 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
841}
842
Arnaud A. de Grandmaisonf3470cc2014-12-01 09:30:16 +0000843/// Should we use the LLVM lifetime intrinsics for the given local variable?
844static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
845 unsigned Size) {
846 // For now, only in optimized builds.
847 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
848 return false;
849
850 // Limit the size of marked objects to 32 bytes. We don't want to increase
851 // compile time by marking tiny objects.
852 unsigned SizeThreshold = 32;
853
854 return Size > SizeThreshold;
855}
856
857
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000858/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000859/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000860/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000861void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
862 AutoVarEmission emission = EmitAutoVarAlloca(D);
863 EmitAutoVarInit(emission);
864 EmitAutoVarCleanups(emission);
865}
Chris Lattner03df1222007-06-02 04:53:11 +0000866
John McCallc533cb72011-02-22 06:44:22 +0000867/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000868/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +0000869CodeGenFunction::AutoVarEmission
870CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
871 QualType Ty = D.getType();
872
873 AutoVarEmission emission(D);
874
875 bool isByRef = D.hasAttr<BlocksAttr>();
876 emission.IsByRef = isByRef;
877
878 CharUnits alignment = getContext().getDeclAlign(&D);
879 emission.Alignment = alignment;
880
John McCall23c29fe2011-06-24 21:55:10 +0000881 // If the type is variably-modified, emit all the VLA sizes for it.
882 if (Ty->isVariablyModifiedType())
883 EmitVariablyModifiedType(Ty);
884
Chris Lattner03df1222007-06-02 04:53:11 +0000885 llvm::Value *DeclPtr;
Eli Friedmana682d392008-02-15 12:20:59 +0000886 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000887 bool NRVO = getLangOpts().ElideConstructors &&
888 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +0000889
Richard Smith2bcde3a2013-06-02 00:09:52 +0000890 // If this value is an array or struct with a statically determinable
891 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +0000892 //
893 // TODO: We should constant-evaluate the initializer of any variable,
894 // as long as it is initialized by a constant expression. Currently,
895 // isConstantInitializer produces wrong answers for structs with
896 // reference or bitfield members, and a few other cases, and checking
897 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +0000898 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
899 (D.isConstexpr() ||
900 ((Ty.isPODType(getContext()) ||
901 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
902 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +0000903
Rafael Espindola609f5d92013-03-26 18:41:47 +0000904 // If the variable's a const type, and it's neither an NRVO
905 // candidate nor a __block variable and has no mutable members,
906 // emit it as a global instead.
907 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
908 CGM.isTypeConstant(Ty, true)) {
909 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +0000910
Craig Topper8a13c412014-05-21 05:09:00 +0000911 emission.Address = nullptr; // signal this condition to later callbacks
Rafael Espindola609f5d92013-03-26 18:41:47 +0000912 assert(emission.wasEmittedAsGlobal());
913 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +0000914 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000915
Rafael Espindola609f5d92013-03-26 18:41:47 +0000916 // Otherwise, tell the initialization code that we're in this case.
917 emission.IsConstantAggregate = true;
918 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000919
Rafael Espindola609f5d92013-03-26 18:41:47 +0000920 // A normal fixed sized variable becomes an alloca in the entry block,
921 // unless it's an NRVO variable.
922 llvm::Type *LTy = ConvertTypeForMem(Ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000923
Rafael Espindola609f5d92013-03-26 18:41:47 +0000924 if (NRVO) {
925 // The named return value optimization: allocate this variable in the
926 // return slot, so that we can elide the copy when returning this
927 // variable (C++0x [class.copy]p34).
928 DeclPtr = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +0000929
Rafael Espindola609f5d92013-03-26 18:41:47 +0000930 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
931 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
932 // Create a flag that is used to indicate when the NRVO was applied
933 // to this variable. Set it to zero to indicate that NRVO was not
934 // applied.
935 llvm::Value *Zero = Builder.getFalse();
936 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
937 EnsureInsertPoint();
938 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +0000939
Rafael Espindola609f5d92013-03-26 18:41:47 +0000940 // Record the NRVO flag for this variable.
941 NRVOFlags[&D] = NRVOFlag;
942 emission.NRVOFlag = NRVOFlag;
Nadav Rotem1da30942013-03-23 06:43:35 +0000943 }
Douglas Gregor290c93e2010-05-15 06:46:45 +0000944 }
Chris Lattnerb781dc792008-05-08 05:58:21 +0000945 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000946 if (isByRef)
947 LTy = BuildByRefType(&D);
948
NAKAMURA Takumi215f3b72014-07-18 23:46:16 +0000949 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
950 Alloc->setName(D.getName());
Rafael Espindola609f5d92013-03-26 18:41:47 +0000951
952 CharUnits allocaAlignment = alignment;
953 if (isByRef)
954 allocaAlignment = std::max(allocaAlignment,
John McCallc8e01702013-04-16 22:48:15 +0000955 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
Rafael Espindola609f5d92013-03-26 18:41:47 +0000956 Alloc->setAlignment(allocaAlignment.getQuantity());
957 DeclPtr = Alloc;
958
959 // Emit a lifetime intrinsic if meaningful. There's no point
960 // in doing this if we don't have a valid insertion point (?).
961 uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
Arnaud A. de Grandmaisonf3470cc2014-12-01 09:30:16 +0000962 if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
963 llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
964
965 emission.SizeForLifetimeMarkers = sizeV;
966 llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
967 Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
968 ->setDoesNotThrow();
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +0000969 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000970 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +0000971 }
Chris Lattnerb781dc792008-05-08 05:58:21 +0000972 }
Chris Lattner03df1222007-06-02 04:53:11 +0000973 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000974 EnsureInsertPoint();
975
Anders Carlsson15949b32009-02-09 20:41:50 +0000976 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +0000977 // Save the stack.
John McCallad7c5c12011-02-08 08:22:06 +0000978 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +0000979
Anders Carlsson30032882008-12-12 07:38:43 +0000980 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
981 llvm::Value *V = Builder.CreateCall(F);
Mike Stump11289f42009-09-09 15:08:12 +0000982
Anders Carlsson30032882008-12-12 07:38:43 +0000983 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +0000984
985 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +0000986
John McCalla464ff92010-07-21 06:13:08 +0000987 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +0000988 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000989 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +0000990 }
Mike Stump11289f42009-09-09 15:08:12 +0000991
John McCall23c29fe2011-06-24 21:55:10 +0000992 llvm::Value *elementCount;
993 QualType elementType;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000994 std::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +0000995
Chris Lattner2192fe52011-07-18 04:24:23 +0000996 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +0000997
998 // Allocate memory for the array.
John McCall23c29fe2011-06-24 21:55:10 +0000999 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1000 vla->setAlignment(alignment.getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +00001001
John McCall23c29fe2011-06-24 21:55:10 +00001002 DeclPtr = vla;
Chris Lattner03df1222007-06-02 04:53:11 +00001003 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001004
Chris Lattner03df1222007-06-02 04:53:11 +00001005 llvm::Value *&DMEntry = LocalDeclMap[&D];
Craig Topper8a13c412014-05-21 05:09:00 +00001006 assert(!DMEntry && "Decl already exists in localdeclmap!");
Chris Lattner03df1222007-06-02 04:53:11 +00001007 DMEntry = DeclPtr;
John McCallc533cb72011-02-22 06:44:22 +00001008 emission.Address = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001009
1010 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +00001011 if (HaveInsertPoint())
1012 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001013 if (CGM.getCodeGenOpts().getDebugInfo()
1014 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001015 DI->setLocation(D.getLocation());
Rafael Espindola609f5d92013-03-26 18:41:47 +00001016 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001017 }
Devang Patel887e2152011-06-03 19:21:47 +00001018 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001019
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001020 if (D.hasAttr<AnnotateAttr>())
1021 EmitVarAnnotations(&D, emission.Address);
1022
John McCallc533cb72011-02-22 06:44:22 +00001023 return emission;
1024}
1025
1026/// Determines whether the given __block variable is potentially
1027/// captured by the given expression.
1028static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1029 // Skip the most common kinds of expressions that make
1030 // hierarchy-walking expensive.
1031 e = e->IgnoreParenCasts();
1032
1033 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1034 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +00001035 for (const auto &I : block->captures()) {
1036 if (I.getVariable() == &var)
John McCallc533cb72011-02-22 06:44:22 +00001037 return true;
1038 }
1039
1040 // No need to walk into the subexpressions.
1041 return false;
1042 }
1043
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001044 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1045 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001046 for (const auto *BI : CS->body())
1047 if (const auto *E = dyn_cast<Expr>(BI)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001048 if (isCapturedBy(var, E))
1049 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001050 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001051 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001052 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001053 for (const auto *I : DS->decls()) {
1054 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1055 const Expr *Init = VD->getInit();
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001056 if (Init && isCapturedBy(var, Init))
1057 return true;
1058 }
1059 }
1060 }
1061 else
1062 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1063 // Later, provide code to poke into statements for capture analysis.
1064 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001065 return false;
1066 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001067
John McCallc533cb72011-02-22 06:44:22 +00001068 for (Stmt::const_child_range children = e->children(); children; ++children)
1069 if (isCapturedBy(var, cast<Expr>(*children)))
1070 return true;
1071
1072 return false;
1073}
1074
Douglas Gregor82e1af22011-07-01 21:08:19 +00001075/// \brief Determine whether the given initializer is trivial in the sense
1076/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001077bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001078 if (!Init)
1079 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001080
Douglas Gregor82e1af22011-07-01 21:08:19 +00001081 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1082 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1083 if (Constructor->isTrivial() &&
1084 Constructor->isDefaultConstructor() &&
1085 !Construct->requiresZeroInitialization())
1086 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001087
Douglas Gregor82e1af22011-07-01 21:08:19 +00001088 return false;
1089}
John McCallc533cb72011-02-22 06:44:22 +00001090void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001091 assert(emission.Variable && "emission was not valid!");
1092
John McCallc533cb72011-02-22 06:44:22 +00001093 // If this was emitted as a global constant, we're done.
1094 if (emission.wasEmittedAsGlobal()) return;
1095
John McCall9e2e22f2011-02-22 07:16:58 +00001096 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001097 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001098 QualType type = D.getType();
1099
Chris Lattner07eb7332007-07-12 00:39:48 +00001100 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001101 const Expr *Init = D.getInit();
1102
1103 // If we are at an unreachable point, we don't need to emit the initializer
1104 // unless it contains a label.
1105 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001106 if (!Init || !ContainsLabel(Init)) return;
1107 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001108 }
1109
John McCall73064872011-03-31 01:59:53 +00001110 // Initialize the structure of a __block variable.
1111 if (emission.IsByRef)
1112 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001113
Douglas Gregor82e1af22011-07-01 21:08:19 +00001114 if (isTrivialInitializer(Init))
1115 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001116
John McCall73064872011-03-31 01:59:53 +00001117 CharUnits alignment = emission.Alignment;
1118
John McCallc533cb72011-02-22 06:44:22 +00001119 // Check whether this is a byref variable that's potentially
1120 // captured and moved by its own initializer. If so, we'll need to
1121 // emit the initializer first, then copy into the variable.
1122 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1123
1124 llvm::Value *Loc =
1125 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1126
Craig Topper8a13c412014-05-21 05:09:00 +00001127 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001128 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001129 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smithdafff942012-01-14 04:30:29 +00001130 constant = CGM.EmitConstantInit(D, this);
Richard Smithfddd3842011-12-30 21:15:51 +00001131 }
1132
1133 if (!constant) {
Eli Friedmana0544d62011-12-03 04:14:32 +00001134 LValue lv = MakeAddrLValue(Loc, type, alignment);
John McCall1553b192011-06-16 04:16:24 +00001135 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001136 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001137 }
John McCall91ca10f2011-03-08 09:11:50 +00001138
Richard Smith2bcde3a2013-06-02 00:09:52 +00001139 if (!emission.IsConstantAggregate) {
1140 // For simple scalar/complex initialization, store the value directly.
1141 LValue lv = MakeAddrLValue(Loc, type, alignment);
1142 lv.setNonGC(true);
1143 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1144 }
1145
John McCallc533cb72011-02-22 06:44:22 +00001146 // If this is a simple aggregate initialization, we can optimize it
1147 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001148 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001149
John McCall91ca10f2011-03-08 09:11:50 +00001150 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001151 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001152 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001153
Chris Lattner2192fe52011-07-18 04:24:23 +00001154 llvm::Type *BP = Int8PtrTy;
John McCall91ca10f2011-03-08 09:11:50 +00001155 if (Loc->getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001156 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001157
John McCall91ca10f2011-03-08 09:11:50 +00001158 // If the initializer is all or mostly zeros, codegen with memset then do
1159 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001160 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001161 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall91ca10f2011-03-08 09:11:50 +00001162 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1163 alignment.getQuantity(), isVolatile);
Benjamin Kramer29f9a002012-08-27 22:07:02 +00001164 // Zero and undef don't require a stores.
1165 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall91ca10f2011-03-08 09:11:50 +00001166 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1167 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001168 }
John McCall91ca10f2011-03-08 09:11:50 +00001169 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001170 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001171 // memcpy from the global to the alloca.
Reid Kleckner453e0562014-10-08 01:07:54 +00001172 std::string Name = getStaticDeclName(CGM, D);
John McCall91ca10f2011-03-08 09:11:50 +00001173 llvm::GlobalVariable *GV =
1174 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001175 llvm::GlobalValue::PrivateLinkage,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001176 constant, Name);
John McCall91ca10f2011-03-08 09:11:50 +00001177 GV->setAlignment(alignment.getQuantity());
Eli Friedmanb8578422011-05-27 22:32:55 +00001178 GV->setUnnamedAddr(true);
Eric Christopher31ab1302011-08-23 22:38:00 +00001179
John McCall91ca10f2011-03-08 09:11:50 +00001180 llvm::Value *SrcPtr = GV;
1181 if (SrcPtr->getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001182 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001183
1184 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1185 isVolatile);
1186 }
1187}
1188
1189/// Emit an expression as an initializer for a variable at the given
1190/// location. The expression is not necessarily the normal
1191/// initializer for the variable, and the address is not necessarily
1192/// its normal location.
1193///
1194/// \param init the initializing expression
1195/// \param var the variable to act as if we're initializing
1196/// \param loc the address to initialize; its type is a pointer
1197/// to the LLVM mapping of the variable's type
1198/// \param alignment the alignment of the address
1199/// \param capturedByInit true if the variable is a __block variable
1200/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001201void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001202 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001203 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001204
1205 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001206 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001207 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001208 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001209 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001210 return;
1211 }
1212 switch (getEvaluationKind(type)) {
1213 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001214 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001215 return;
1216 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001217 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001218 if (capturedByInit)
1219 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001220 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001221 return;
1222 }
1223 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001224 if (type->isAtomicType()) {
1225 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1226 } else {
1227 // TODO: how can we delay here if D is captured by its initializer?
1228 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001229 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001230 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001231 AggValueSlot::IsNotAliased));
John McCalla8ec7eb2013-03-07 21:37:17 +00001232 }
John McCall47fb9502013-03-07 21:37:08 +00001233 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001234 }
John McCall47fb9502013-03-07 21:37:08 +00001235 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001236}
John McCallbd309292010-07-06 01:34:17 +00001237
John McCall82fe67b2011-07-09 01:37:26 +00001238/// Enter a destroy cleanup for the given local variable.
1239void CodeGenFunction::emitAutoVarTypeCleanup(
1240 const CodeGenFunction::AutoVarEmission &emission,
1241 QualType::DestructionKind dtorKind) {
1242 assert(dtorKind != QualType::DK_none);
1243
1244 // Note that for __block variables, we want to destroy the
1245 // original stack object, not the possibly forwarded object.
1246 llvm::Value *addr = emission.getObjectAddress(*this);
1247
1248 const VarDecl *var = emission.Variable;
1249 QualType type = var->getType();
1250
1251 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001252 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001253
1254 switch (dtorKind) {
1255 case QualType::DK_none:
1256 llvm_unreachable("no cleanup for trivially-destructible variable");
1257
1258 case QualType::DK_cxx_destructor:
1259 // If there's an NRVO flag on the emission, we need a different
1260 // cleanup.
1261 if (emission.NRVOFlag) {
1262 assert(!type->isArrayType());
1263 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1264 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1265 emission.NRVOFlag);
1266 return;
1267 }
1268 break;
1269
1270 case QualType::DK_objc_strong_lifetime:
1271 // Suppress cleanups for pseudo-strong variables.
1272 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001273
John McCall82fe67b2011-07-09 01:37:26 +00001274 // Otherwise, consider whether to use an EH cleanup or not.
1275 cleanupKind = getARCCleanupKind();
1276
1277 // Use the imprecise destroyer by default.
1278 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1279 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1280 break;
1281
1282 case QualType::DK_objc_weak_lifetime:
1283 break;
1284 }
1285
1286 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001287 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001288
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001289 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001290 // is being pushed as an EH cleanup.
1291 bool useEHCleanup = (cleanupKind & EHCleanup);
1292 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1293 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001294}
1295
John McCallc533cb72011-02-22 06:44:22 +00001296void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001297 assert(emission.Variable && "emission was not valid!");
1298
John McCallc533cb72011-02-22 06:44:22 +00001299 // If this was emitted as a global constant, we're done.
1300 if (emission.wasEmittedAsGlobal()) return;
1301
John McCall8c38d352012-04-13 18:44:05 +00001302 // If we don't have an insertion point, we're done. Sema prevents
1303 // us from jumping into any of these scopes anyway.
1304 if (!HaveInsertPoint()) return;
1305
John McCall9e2e22f2011-02-22 07:16:58 +00001306 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001307
Nadav Rotem1da30942013-03-23 06:43:35 +00001308 // Make sure we call @llvm.lifetime.end. This needs to happen
1309 // *last*, so the cleanup needs to be pushed *first*.
1310 if (emission.useLifetimeMarkers()) {
1311 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1312 emission.getAllocatedAddress(),
1313 emission.getSizeForLifetimeMarkers());
1314 }
1315
John McCall82fe67b2011-07-09 01:37:26 +00001316 // Check the type for a cleanup.
1317 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1318 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001319
John McCall1bd25562011-06-24 23:21:27 +00001320 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001321 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001322 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1323 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1324 }
1325
John McCallc533cb72011-02-22 06:44:22 +00001326 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001327 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001328 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001329
John McCallc533cb72011-02-22 06:44:22 +00001330 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001331 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001332
John McCalla729c622012-02-17 03:33:10 +00001333 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001334 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001335 }
Mike Stump626aecc2009-03-05 01:23:13 +00001336
John McCallc533cb72011-02-22 06:44:22 +00001337 // If this is a block variable, call _Block_object_destroy
1338 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001339 if (emission.IsByRef)
1340 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001341}
Chris Lattner53621a52007-06-13 20:44:40 +00001342
Peter Collingbourne1425b452012-01-26 03:33:36 +00001343CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001344CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1345 switch (kind) {
1346 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001347 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001348 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001349 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001350 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001351 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001352 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001353 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001354 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001355}
1356
John McCall12cc42a2013-02-01 05:11:40 +00001357/// pushEHDestroy - Push the standard destructor for the given type as
1358/// an EH-only cleanup.
1359void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1360 llvm::Value *addr, QualType type) {
1361 assert(dtorKind && "cannot push destructor for trivial type");
1362 assert(needsEHCleanup(dtorKind));
1363
1364 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1365}
1366
1367/// pushDestroy - Push the standard destructor for the given type as
1368/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001369void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1370 llvm::Value *addr, QualType type) {
1371 assert(dtorKind && "cannot push destructor for trivial type");
1372
1373 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1374 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1375 cleanupKind & EHCleanup);
1376}
1377
John McCall82fe67b2011-07-09 01:37:26 +00001378void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001379 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001380 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001381 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1382 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001383}
1384
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001385void CodeGenFunction::pushStackRestore(CleanupKind Kind, llvm::Value *SPMem) {
1386 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1387}
1388
Richard Smith736a9472013-06-12 20:42:33 +00001389void CodeGenFunction::pushLifetimeExtendedDestroy(
1390 CleanupKind cleanupKind, llvm::Value *addr, QualType type,
1391 Destroyer *destroyer, bool useEHCleanupForArray) {
1392 assert(!isInConditionalBranch() &&
1393 "performing lifetime extension from within conditional");
1394
1395 // Push an EH-only cleanup for the object now.
1396 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1397 // around in case a temporary's destructor throws an exception.
1398 if (cleanupKind & EHCleanup)
1399 EHStack.pushCleanup<DestroyObject>(
1400 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1401 destroyer, useEHCleanupForArray);
1402
1403 // Remember that we need to push a full cleanup for the object at the
1404 // end of the full-expression.
1405 pushCleanupAfterFullExpr<DestroyObject>(
1406 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1407}
1408
John McCall178360e2011-07-11 08:38:19 +00001409/// emitDestroy - Immediately perform the destruction of the given
1410/// object.
1411///
1412/// \param addr - the address of the object; a type*
1413/// \param type - the type of the object; if an array type, all
1414/// objects are destroyed in reverse order
1415/// \param destroyer - the function to call to destroy individual
1416/// elements
1417/// \param useEHCleanupForArray - whether an EH cleanup should be
1418/// used when destroying array elements, in case one of the
1419/// destructions throws an exception
John McCall82fe67b2011-07-09 01:37:26 +00001420void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001421 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001422 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001423 const ArrayType *arrayType = getContext().getAsArrayType(type);
1424 if (!arrayType)
1425 return destroyer(*this, addr, type);
1426
1427 llvm::Value *begin = addr;
1428 llvm::Value *length = emitArrayLength(arrayType, type, begin);
John McCall97eab0a2011-07-13 08:09:46 +00001429
1430 // Normally we have to check whether the array is zero-length.
1431 bool checkZeroLength = true;
1432
1433 // But if the array length is constant, we can suppress that.
1434 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1435 // ...and if it's constant zero, we can just skip the entire thing.
1436 if (constLength->isZero()) return;
1437 checkZeroLength = false;
1438 }
1439
John McCall82fe67b2011-07-09 01:37:26 +00001440 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall97eab0a2011-07-13 08:09:46 +00001441 emitArrayDestroy(begin, end, type, destroyer,
1442 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001443}
1444
John McCall178360e2011-07-11 08:38:19 +00001445/// emitArrayDestroy - Destroys all the elements of the given array,
1446/// beginning from last to first. The array cannot be zero-length.
1447///
1448/// \param begin - a type* denoting the first element of the array
1449/// \param end - a type* denoting one past the end of the array
1450/// \param type - the element type of the array
1451/// \param destroyer - the function to call to destroy elements
1452/// \param useEHCleanup - whether to push an EH cleanup to destroy
1453/// the remaining elements in case the destruction of a single
1454/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001455void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1456 llvm::Value *end,
1457 QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001458 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001459 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001460 bool useEHCleanup) {
John McCall82fe67b2011-07-09 01:37:26 +00001461 assert(!type->isArrayType());
1462
1463 // The basic structure here is a do-while loop, because we don't
1464 // need to check for the zero-element case.
1465 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1466 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1467
John McCall97eab0a2011-07-13 08:09:46 +00001468 if (checkZeroLength) {
1469 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1470 "arraydestroy.isempty");
1471 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1472 }
1473
John McCall82fe67b2011-07-09 01:37:26 +00001474 // Enter the loop body, making that address the current address.
1475 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1476 EmitBlock(bodyBB);
1477 llvm::PHINode *elementPast =
1478 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1479 elementPast->addIncoming(end, entryBB);
1480
1481 // Shift the address back by one element.
1482 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1483 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1484 "arraydestroy.element");
1485
John McCall178360e2011-07-11 08:38:19 +00001486 if (useEHCleanup)
1487 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1488
John McCall82fe67b2011-07-09 01:37:26 +00001489 // Perform the actual destruction there.
1490 destroyer(*this, element, type);
1491
John McCall178360e2011-07-11 08:38:19 +00001492 if (useEHCleanup)
1493 PopCleanupBlock();
1494
John McCall82fe67b2011-07-09 01:37:26 +00001495 // Check whether we've reached the end.
1496 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1497 Builder.CreateCondBr(done, doneBB, bodyBB);
1498 elementPast->addIncoming(element, Builder.GetInsertBlock());
1499
1500 // Done.
1501 EmitBlock(doneBB);
1502}
1503
John McCall178360e2011-07-11 08:38:19 +00001504/// Perform partial array destruction as if in an EH cleanup. Unlike
1505/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001506static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1507 llvm::Value *begin, llvm::Value *end,
1508 QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001509 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001510 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001511 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001512 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1513 // VLAs don't require a GEP index to walk into.
1514 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001515 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001516 type = arrayType->getElementType();
1517 }
John McCall97eab0a2011-07-13 08:09:46 +00001518
1519 if (arrayDepth) {
1520 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1521
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001522 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001523 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1524 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001525 }
1526
John McCall97eab0a2011-07-13 08:09:46 +00001527 // Destroy the array. We don't ever need an EH cleanup because we
1528 // assume that we're in an EH cleanup ourselves, so a throwing
1529 // destructor causes an immediate terminate.
1530 CGF.emitArrayDestroy(begin, end, type, destroyer,
1531 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001532}
1533
John McCall82fe67b2011-07-09 01:37:26 +00001534namespace {
John McCall178360e2011-07-11 08:38:19 +00001535 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1536 /// array destroy where the end pointer is regularly determined and
1537 /// does not need to be loaded from a local.
1538 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1539 llvm::Value *ArrayBegin;
1540 llvm::Value *ArrayEnd;
1541 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001542 CodeGenFunction::Destroyer *Destroyer;
John McCall178360e2011-07-11 08:38:19 +00001543 public:
1544 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1545 QualType elementType,
1546 CodeGenFunction::Destroyer *destroyer)
1547 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
Peter Collingbourne1425b452012-01-26 03:33:36 +00001548 ElementType(elementType), Destroyer(destroyer) {}
John McCall178360e2011-07-11 08:38:19 +00001549
Craig Topper4f12f102014-03-12 06:41:41 +00001550 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001551 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1552 ElementType, Destroyer);
1553 }
1554 };
1555
1556 /// IrregularPartialArrayDestroy - a cleanup which performs a
1557 /// partial array destroy where the end pointer is irregularly
1558 /// determined and must be loaded from a local.
1559 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001560 llvm::Value *ArrayBegin;
1561 llvm::Value *ArrayEndPointer;
1562 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001563 CodeGenFunction::Destroyer *Destroyer;
John McCall82fe67b2011-07-09 01:37:26 +00001564 public:
John McCall178360e2011-07-11 08:38:19 +00001565 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1566 llvm::Value *arrayEndPointer,
1567 QualType elementType,
1568 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001569 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
Peter Collingbourne1425b452012-01-26 03:33:36 +00001570 ElementType(elementType), Destroyer(destroyer) {}
John McCall82fe67b2011-07-09 01:37:26 +00001571
Craig Topper4f12f102014-03-12 06:41:41 +00001572 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001573 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001574 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1575 ElementType, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001576 }
1577 };
1578}
1579
John McCall178360e2011-07-11 08:38:19 +00001580/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001581/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001582/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001583///
John McCall82fe67b2011-07-09 01:37:26 +00001584/// \param elementType - the immediate element type of the array;
1585/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001586void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall178360e2011-07-11 08:38:19 +00001587 llvm::Value *arrayEndPointer,
1588 QualType elementType,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001589 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001590 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1591 arrayBegin, arrayEndPointer,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001592 elementType, destroyer);
John McCall178360e2011-07-11 08:38:19 +00001593}
1594
1595/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1596/// already-constructed elements of the given array. The cleanup
1597/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001598///
John McCall178360e2011-07-11 08:38:19 +00001599/// \param elementType - the immediate element type of the array;
1600/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001601void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1602 llvm::Value *arrayEnd,
1603 QualType elementType,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001604 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001605 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001606 arrayBegin, arrayEnd,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001607 elementType, destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001608}
1609
Nadav Rotem1da30942013-03-23 06:43:35 +00001610/// Lazily declare the @llvm.lifetime.start intrinsic.
1611llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1612 if (LifetimeStartFn) return LifetimeStartFn;
1613 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1614 llvm::Intrinsic::lifetime_start);
1615 return LifetimeStartFn;
1616}
1617
1618/// Lazily declare the @llvm.lifetime.end intrinsic.
1619llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1620 if (LifetimeEndFn) return LifetimeEndFn;
1621 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1622 llvm::Intrinsic::lifetime_end);
1623 return LifetimeEndFn;
1624}
1625
John McCall31168b02011-06-15 23:02:42 +00001626namespace {
1627 /// A cleanup to perform a release of an object at the end of a
1628 /// function. This is used to balance out the incoming +1 of a
1629 /// ns_consumed argument when we can't reasonably do that just by
1630 /// not doing the initial retain for a __block argument.
1631 struct ConsumeARCParameter : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001632 ConsumeARCParameter(llvm::Value *param,
1633 ARCPreciseLifetime_t precise)
1634 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001635
1636 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001637 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001638
Craig Topper4f12f102014-03-12 06:41:41 +00001639 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001640 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001641 }
1642 };
1643}
1644
Mike Stump11289f42009-09-09 15:08:12 +00001645/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001646/// for the specified parameter and set up LocalDeclMap.
Devang Patel68a15252011-03-03 20:13:15 +00001647void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001648 bool ArgIsPointer, unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001649 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001650 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001651 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001652
1653 Arg->setName(D.getName());
1654
Adrian Prantl51936dd2013-03-14 17:53:33 +00001655 QualType Ty = D.getType();
1656
John McCall147d0212011-02-22 22:38:33 +00001657 // Use better IR generation for certain implicit parameters.
1658 if (isa<ImplicitParamDecl>(D)) {
1659 // The only implicit argument a block has is its literal.
1660 if (BlockInfo) {
1661 LocalDeclMap[&D] = Arg;
Craig Topper8a13c412014-05-21 05:09:00 +00001662 llvm::Value *LocalAddr = nullptr;
Adrian Prantl51936dd2013-03-14 17:53:33 +00001663 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Adrian Prantl0f6df002013-03-29 19:20:35 +00001664 // Allocate a stack slot to let the debug info survive the RA.
Adrian Prantl51936dd2013-03-14 17:53:33 +00001665 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1666 D.getName() + ".addr");
1667 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1668 LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1669 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1670 LocalAddr = Builder.CreateLoad(Alloc);
1671 }
John McCall147d0212011-02-22 22:38:33 +00001672
1673 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001674 if (CGM.getCodeGenOpts().getDebugInfo()
1675 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001676 DI->setLocation(D.getLocation());
David Blaikie77bbb5f2014-08-08 17:10:14 +00001677 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, ArgNo,
1678 LocalAddr, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001679 }
John McCall147d0212011-02-22 22:38:33 +00001680 }
1681
1682 return;
1683 }
1684 }
1685
Chris Lattner53621a52007-06-13 20:44:40 +00001686 llvm::Value *DeclPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001687 bool DoStore = false;
1688 bool IsScalar = hasScalarEvaluationKind(Ty);
1689 CharUnits Align = getContext().getDeclAlign(&D);
1690 // If we already have a pointer to the argument, reuse the input pointer.
1691 if (ArgIsPointer) {
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001692 // If we have a prettier pointer type at this point, bitcast to that.
1693 unsigned AS = cast<llvm::PointerType>(Arg->getType())->getAddressSpace();
1694 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
1695 DeclPtr = Arg->getType() == IRTy ? Arg : Builder.CreateBitCast(Arg, IRTy,
1696 D.getName());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001697 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00001698 // Don't push a cleanup in a thunk for a method that will also emit a
1699 // cleanup.
1700 if (!IsScalar && !CurFuncIsThunk &&
Reid Kleckner739756c2013-12-04 19:23:12 +00001701 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001702 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1703 if (RD && RD->hasNonTrivialDestructor())
1704 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001705 }
Chris Lattner53621a52007-06-13 20:44:40 +00001706 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001707 // Otherwise, create a temporary to hold the value.
Eli Friedmaneadd3e82011-11-03 20:31:28 +00001708 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1709 D.getName() + ".addr");
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001710 Alloc->setAlignment(Align.getQuantity());
Eli Friedmaneadd3e82011-11-03 20:31:28 +00001711 DeclPtr = Alloc;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001712 DoStore = true;
1713 }
Mike Stump11289f42009-09-09 15:08:12 +00001714
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001715 LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
1716 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00001717 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001718 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1719 // We honor __attribute__((ns_consumed)) for types with lifetime.
1720 // For __strong, it's handled by just skipping the initial retain;
1721 // otherwise we have to balance out the initial +1 with an extra
1722 // cleanup to do the release at the end of the function.
1723 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1724
1725 // 'self' is always formally __strong, but if this is not an
1726 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001727 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001728 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1729 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001730 assert(lt == Qualifiers::OCL_Strong);
1731 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001732 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001733 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001734 lt = Qualifiers::OCL_ExplicitNone;
1735 }
1736
1737 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001738 if (!isConsumed) {
1739 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1740 // use objc_storeStrong(&dest, value) for retaining the
1741 // object. But first, store a null into 'dest' because
1742 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001743 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001744 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1745 EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001746 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001747 }
1748 else
John McCall31168b02011-06-15 23:02:42 +00001749 // Don't use objc_retainBlock for block pointers, because we
1750 // don't want to Block_copy something just because we got it
1751 // as a parameter.
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001752 Arg = EmitARCRetainNonBlock(Arg);
1753 }
John McCall31168b02011-06-15 23:02:42 +00001754 } else {
1755 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00001756 if (isConsumed) {
1757 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1758 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1759 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1760 precise);
1761 }
John McCall31168b02011-06-15 23:02:42 +00001762
1763 if (lt == Qualifiers::OCL_Weak) {
1764 EmitARCInitWeak(DeclPtr, Arg);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001765 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001766 }
1767 }
1768
1769 // Enter the cleanup scope.
1770 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1771 }
Chris Lattner53621a52007-06-13 20:44:40 +00001772 }
1773
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001774 // Store the initial value into the alloca.
1775 if (DoStore)
1776 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1777
Chris Lattner53621a52007-06-13 20:44:40 +00001778 llvm::Value *&DMEntry = LocalDeclMap[&D];
Craig Topper8a13c412014-05-21 05:09:00 +00001779 assert(!DMEntry && "Decl already exists in localdeclmap!");
Chris Lattner53621a52007-06-13 20:44:40 +00001780 DMEntry = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001781
1782 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001783 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001784 if (CGM.getCodeGenOpts().getDebugInfo()
1785 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001786 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1787 }
1788 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001789
1790 if (D.hasAttr<AnnotateAttr>())
1791 EmitVarAnnotations(&D, DeclPtr);
Chris Lattner53621a52007-06-13 20:44:40 +00001792}