blob: 15a1a7fb5f127656fc63873b50d2e40c55bae9e5 [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:
37 case Decl::Namespace:
38 case Decl::UnresolvedUsingTypename:
39 case Decl::ClassTemplateSpecialization:
40 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000041 case Decl::VarTemplateSpecialization:
42 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000043 case Decl::TemplateTypeParm:
44 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000045 case Decl::NonTypeTemplateParm:
Douglas Gregor19043f02010-04-23 02:02:43 +000046 case Decl::CXXMethod:
47 case Decl::CXXConstructor:
48 case Decl::CXXDestructor:
49 case Decl::CXXConversion:
50 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000051 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000052 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000053 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000054 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000055 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000056 case Decl::ImplicitParam:
57 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000058 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000059 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000060 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000061 case Decl::TemplateTemplateParm:
62 case Decl::ObjCMethod:
63 case Decl::ObjCCategory:
64 case Decl::ObjCProtocol:
65 case Decl::ObjCInterface:
66 case Decl::ObjCCategoryImpl:
67 case Decl::ObjCImplementation:
68 case Decl::ObjCProperty:
69 case Decl::ObjCCompatibleAlias:
Abramo Bagnarad7340582010-06-05 05:09:32 +000070 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000071 case Decl::LinkageSpec:
72 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000073 case Decl::FileScopeAsm:
74 case Decl::Friend:
75 case Decl::FriendTemplate:
76 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000077 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000078 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000079 case Decl::UsingShadow:
David Blaikie83d382b2011-09-23 05:06:16 +000080 llvm_unreachable("Declaration should not be in declstmts!");
Chris Lattner84915fa2007-06-02 04:16:21 +000081 case Decl::Function: // void X();
Argyrios Kyrtzidis88e1b972008-10-15 00:42:39 +000082 case Decl::Record: // struct/union/class X;
Chris Lattner84915fa2007-06-02 04:16:21 +000083 case Decl::Enum: // enum X;
Mike Stump11289f42009-09-09 15:08:12 +000084 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis88e1b972008-10-15 00:42:39 +000085 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +000086 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +000087 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +000088 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +000089 case Decl::OMPThreadPrivate:
Michael Han84324352013-02-22 17:15:32 +000090 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +000091 // None of these decls require codegen support.
92 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +000093
David Blaikief121b932013-05-20 22:50:41 +000094 case Decl::NamespaceAlias:
95 if (CGDebugInfo *DI = getDebugInfo())
96 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
97 return;
David Blaikiebd483762013-05-20 04:58:53 +000098 case Decl::Using: // using X; [C++]
99 if (CGDebugInfo *DI = getDebugInfo())
100 DI->EmitUsingDecl(cast<UsingDecl>(D));
101 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000102 case Decl::UsingDirective: // using namespace X; [C++]
103 if (CGDebugInfo *DI = getDebugInfo())
104 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
105 return;
Daniel Dunbara7998072008-08-29 17:28:43 +0000106 case Decl::Var: {
107 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000108 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000109 "Should not see file-scope variables inside a function!");
John McCall1c9c3fd2010-10-15 04:57:14 +0000110 return EmitVarDecl(VD);
Chris Lattner84915fa2007-06-02 04:16:21 +0000111 }
Mike Stump11289f42009-09-09 15:08:12 +0000112
Richard Smithdda56e42011-04-15 14:24:37 +0000113 case Decl::Typedef: // typedef int X;
114 case Decl::TypeAlias: { // using X = int; [C++0x]
115 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000116 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000117
Anders Carlsson5d985f52008-12-20 21:51:53 +0000118 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000119 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000120 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000121 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000122}
Chris Lattner03df1222007-06-02 04:53:11 +0000123
John McCall1c9c3fd2010-10-15 04:57:14 +0000124/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000125/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000126void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000127 if (D.isStaticLocal()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000128 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000129 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000130
David Majnemer27d69db2014-04-28 22:17:59 +0000131 // FIXME: We need to force the emission/use of a guard variable for
132 // some variables even if we can constant-evaluate them because
133 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000134
John McCall1c9c3fd2010-10-15 04:57:14 +0000135 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000136 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000137
138 if (D.hasExternalStorage())
Lauro Ramos Venanciobada8d42008-02-16 22:30:38 +0000139 // Don't emit it now, allow it to be emitted lazily on its first use.
140 return;
Daniel Dunbar0ca16602009-04-14 02:25:56 +0000141
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000142 if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
143 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
144
145 assert(D.hasLocalStorage());
146 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000147}
148
Reid Kleckner453e0562014-10-08 01:07:54 +0000149static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
150 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000151 return CGM.getMangledName(&D).str();
152
Reid Kleckner453e0562014-10-08 01:07:54 +0000153 // If this isn't C++, we don't need a mangled name, just a pretty one.
154 assert(!D.isExternallyVisible() && "name shouldn't matter");
155 std::string ContextName;
156 const DeclContext *DC = D.getDeclContext();
157 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000158 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000159 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
160 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
161 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
162 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000163 else
David Blaikie83d382b2011-09-23 05:06:16 +0000164 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000165
Reid Kleckner453e0562014-10-08 01:07:54 +0000166 ContextName += "." + D.getNameAsString();
167 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000168}
169
Reid Kleckner453e0562014-10-08 01:07:54 +0000170llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
171 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
172 // In general, we don't always emit static var decls once before we reference
173 // them. It is possible to reference them before emitting the function that
174 // contains them, and it is possible to emit the containing function multiple
175 // times.
176 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
177 return ExistingGV;
178
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000179 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000180 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000181
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000182 // Use the label if the variable is renamed with the asm-label extension.
183 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000184 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000185 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000186 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000187 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000188
Reid Kleckner453e0562014-10-08 01:07:54 +0000189 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000190 unsigned AddrSpace =
Reid Kleckner453e0562014-10-08 01:07:54 +0000191 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000192
193 // Local address space cannot have an initializer.
194 llvm::Constant *Init = nullptr;
195 if (Ty.getAddressSpace() != LangAS::opencl_local)
196 Init = EmitNullConstant(Ty);
197 else
198 Init = llvm::UndefValue::get(LTy);
199
Anders Carlssone33eed52009-09-26 18:16:06 +0000200 llvm::GlobalVariable *GV =
Reid Kleckner453e0562014-10-08 01:07:54 +0000201 new llvm::GlobalVariable(getModule(), LTy,
Anders Carlssone33eed52009-09-26 18:16:06 +0000202 Ty.isConstant(getContext()), Linkage,
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000203 Init, Name, nullptr,
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000204 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000205 AddrSpace);
Ken Dyck160146e2010-01-27 17:10:57 +0000206 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Reid Kleckner453e0562014-10-08 01:07:54 +0000207 setGlobalVisibility(GV, &D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000208
Richard Smithfd3834f2013-04-13 02:43:54 +0000209 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000210 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000211
Hans Wennborgef2272c2014-06-18 15:55:13 +0000212 if (D.isExternallyVisible()) {
213 if (D.hasAttr<DLLImportAttr>())
214 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
215 else if (D.hasAttr<DLLExportAttr>())
216 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
217 }
218
Eli Benderskycb399432014-03-24 22:05:38 +0000219 // Make sure the result is of the correct type.
Reid Kleckner453e0562014-10-08 01:07:54 +0000220 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
221 llvm::Constant *Addr = GV;
Eli Benderskycb399432014-03-24 22:05:38 +0000222 if (AddrSpace != ExpectedAddrSpace) {
223 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
Reid Kleckner453e0562014-10-08 01:07:54 +0000224 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
Eli Benderskycb399432014-03-24 22:05:38 +0000225 }
226
Reid Kleckner453e0562014-10-08 01:07:54 +0000227 setStaticLocalDeclAddress(&D, Addr);
228
229 // Ensure that the static local gets initialized by making sure the parent
230 // function gets emitted eventually.
231 const Decl *DC = cast<Decl>(D.getDeclContext());
232
233 // We can't name blocks or captured statements directly, so try to emit their
234 // parents.
235 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
236 DC = DC->getNonClosureContext();
237 // FIXME: Ensure that global blocks get emitted.
238 if (!DC)
239 return Addr;
240 }
241
242 GlobalDecl GD;
243 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
244 GD = GlobalDecl(CD, Ctor_Base);
245 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
246 GD = GlobalDecl(DD, Dtor_Base);
247 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
248 GD = GlobalDecl(FD);
249 else {
250 // Don't do anything for Obj-C method decls or global closures. We should
251 // never defer them.
252 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
253 }
254 if (GD.getDecl())
255 (void)GetAddrOfGlobal(GD);
256
257 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000258}
259
Richard Smith6331c402012-02-13 22:16:19 +0000260/// hasNontrivialDestruction - Determine whether a type's destruction is
261/// non-trivial. If so, and the variable uses static initialization, we must
262/// register its destructor to run on exit.
263static bool hasNontrivialDestruction(QualType T) {
264 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
265 return RD && !RD->hasTrivialDestructor();
266}
267
Chandler Carruth84537952012-03-30 19:44:53 +0000268/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
269/// global variable that has already been created for it. If the initializer
270/// has a different type than GV does, this may free GV and return a different
271/// one. Otherwise it just returns GV.
272llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000273CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000274 llvm::GlobalVariable *GV) {
275 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCall70013b62010-07-15 23:40:35 +0000276
Chris Lattnere99c1102009-12-05 08:22:11 +0000277 // If constant emission failed, then this should be a C++ static
278 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000279 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000280 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000281 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall68ff0372010-09-08 01:44:27 +0000282 else if (Builder.GetInsertBlock()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000283 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000284 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000285 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000286
Chandler Carruth84537952012-03-30 19:44:53 +0000287 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000288 }
Chandler Carruth84537952012-03-30 19:44:53 +0000289 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000290 }
John McCall70013b62010-07-15 23:40:35 +0000291
Chris Lattnere99c1102009-12-05 08:22:11 +0000292 // The initializer may differ in type from the global. Rewrite
293 // the global to match the initializer. (We have to do this
294 // because some types, like unions, can't be completely represented
295 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000296 if (GV->getType()->getElementType() != Init->getType()) {
297 llvm::GlobalVariable *OldGV = GV;
298
299 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
300 OldGV->isConstant(),
301 OldGV->getLinkage(), Init, "",
302 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000303 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000304 CGM.getContext().getTargetAddressSpace(D.getType()));
305 GV->setVisibility(OldGV->getVisibility());
Eric Christopher31ab1302011-08-23 22:38:00 +0000306
Chris Lattnere99c1102009-12-05 08:22:11 +0000307 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000308 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000309
Chris Lattnere99c1102009-12-05 08:22:11 +0000310 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000311 llvm::Constant *NewPtrForOldDecl =
312 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
313 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000314
Chris Lattnere99c1102009-12-05 08:22:11 +0000315 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000316 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000317 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000318
Chandler Carruth84537952012-03-30 19:44:53 +0000319 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
320 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000321
322 if (hasNontrivialDestruction(D.getType())) {
323 // We have a constant initializer, but a nontrivial destructor. We still
324 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000325 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000326 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000327 }
328
Chandler Carruth84537952012-03-30 19:44:53 +0000329 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000330}
331
John McCall1c9c3fd2010-10-15 04:57:14 +0000332void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000333 llvm::GlobalValue::LinkageTypes Linkage) {
Chandler Carruth84537952012-03-30 19:44:53 +0000334 llvm::Value *&DMEntry = LocalDeclMap[&D];
Craig Topper8a13c412014-05-21 05:09:00 +0000335 assert(!DMEntry && "Decl already exists in localdeclmap!");
Mike Stump11289f42009-09-09 15:08:12 +0000336
John McCallb88a5662012-03-30 21:00:39 +0000337 // Check to see if we already have a global variable for this
338 // declaration. This can happen when double-emitting function
339 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000340 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
Daniel Dunbara374e602009-02-25 19:45:19 +0000341
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000342 // Store into LocalDeclMap before generating initializer to handle
343 // circular references.
John McCallb88a5662012-03-30 21:00:39 +0000344 DMEntry = addr;
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000345
John McCall4a39ab82010-05-04 20:45:42 +0000346 // We can't have a VLA here, but we can have a pointer to a VLA,
347 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000348 // Make sure to evaluate VLA bounds now so that we have them for later.
349 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000350 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000351
John McCallb88a5662012-03-30 21:00:39 +0000352 // Save the type in case adding the initializer forces a type change.
353 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000354
Eli Benderskycb399432014-03-24 22:05:38 +0000355 llvm::GlobalVariable *var =
356 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Chris Lattnere99c1102009-12-05 08:22:11 +0000357 // If this value has an initializer, emit it.
358 if (D.getInit())
John McCallb88a5662012-03-30 21:00:39 +0000359 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000360
John McCallb88a5662012-03-30 21:00:39 +0000361 var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000362
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000363 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000364 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000365
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000366 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000367 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000368
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000369 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000370 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000371
Chandler Carruth84537952012-03-30 19:44:53 +0000372 // We may have to cast the constant because of the initializer
373 // mismatch above.
374 //
375 // FIXME: It is really dangerous to store this in the map; if anyone
376 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000377 llvm::Constant *castedAddr =
378 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCallb88a5662012-03-30 21:00:39 +0000379 DMEntry = castedAddr;
380 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000381
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000382 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000383
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000384 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000385 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000386 if (DI &&
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000387 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000388 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000389 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000390 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000391}
Mike Stump11289f42009-09-09 15:08:12 +0000392
John McCall2b7fc382010-07-13 20:32:21 +0000393namespace {
John McCall82fe67b2011-07-09 01:37:26 +0000394 struct DestroyObject : EHScopeStack::Cleanup {
395 DestroyObject(llvm::Value *addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000396 CodeGenFunction::Destroyer *destroyer,
397 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000398 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000399 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000400
John McCall82fe67b2011-07-09 01:37:26 +0000401 llvm::Value *addr;
402 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000403 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000404 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000405
Craig Topper4f12f102014-03-12 06:41:41 +0000406 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000407 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000408 bool useEHCleanupForArray =
409 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000410
411 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000412 }
413 };
414
John McCall82fe67b2011-07-09 01:37:26 +0000415 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
416 DestroyNRVOVariable(llvm::Value *addr,
417 const CXXDestructorDecl *Dtor,
418 llvm::Value *NRVOFlag)
419 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000420
421 const CXXDestructorDecl *Dtor;
422 llvm::Value *NRVOFlag;
423 llvm::Value *Loc;
424
Craig Topper4f12f102014-03-12 06:41:41 +0000425 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000426 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000427 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000428
Craig Topper8a13c412014-05-21 05:09:00 +0000429 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000430 if (NRVO) {
431 // If we exited via NRVO, we skip the destructor call.
432 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
433 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
434 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
435 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
436 CGF.EmitBlock(RunDtorBB);
437 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000438
John McCall2b7fc382010-07-13 20:32:21 +0000439 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +0000440 /*ForVirtualBase=*/false,
441 /*Delegating=*/false,
442 Loc);
John McCall2b7fc382010-07-13 20:32:21 +0000443
444 if (NRVO) CGF.EmitBlock(SkipDtorBB);
445 }
446 };
John McCall2b7fc382010-07-13 20:32:21 +0000447
John McCallcda666c2010-07-21 07:22:38 +0000448 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000449 llvm::Value *Stack;
450 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000451 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000452 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000453 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
454 CGF.Builder.CreateCall(F, V);
455 }
456 };
457
John McCall1bd25562011-06-24 23:21:27 +0000458 struct ExtendGCLifetime : EHScopeStack::Cleanup {
459 const VarDecl &Var;
460 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
461
Craig Topper4f12f102014-03-12 06:41:41 +0000462 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000463 // Compute the address of the local variable, in case it's a
464 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000465 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
466 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000467 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
468 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000469 CGF.EmitExtendGCLifetime(value);
470 }
471 };
472
John McCallcda666c2010-07-21 07:22:38 +0000473 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000474 llvm::Constant *CleanupFn;
475 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000476 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000477
John McCalla464ff92010-07-21 06:13:08 +0000478 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000479 const VarDecl *Var)
480 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000481
Craig Topper4f12f102014-03-12 06:41:41 +0000482 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000483 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
484 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000485 // Compute the address of the local variable, in case it's a byref
486 // or something.
487 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
488
John McCalla464ff92010-07-21 06:13:08 +0000489 // In some cases, the type of the function argument will be different from
490 // the type of the pointer. An example of this is
491 // void f(void* arg);
492 // __attribute__((cleanup(f))) void *g;
493 //
494 // To fix this we insert a bitcast here.
495 QualType ArgTy = FnInfo.arg_begin()->type;
496 llvm::Value *Arg =
497 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
498
499 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000500 Args.add(RValue::get(Arg),
501 CGF.getContext().getPointerType(Var.getType()));
John McCalla464ff92010-07-21 06:13:08 +0000502 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
503 }
504 };
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000505
506 /// A cleanup to call @llvm.lifetime.end.
507 class CallLifetimeEnd : public EHScopeStack::Cleanup {
508 llvm::Value *Addr;
509 llvm::Value *Size;
510 public:
511 CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
512 : Addr(addr), Size(size) {}
513
514 void Emit(CodeGenFunction &CGF, Flags flags) override {
Arnaud A. de Grandmaisonf3470cc2014-12-01 09:30:16 +0000515 llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
516 CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
517 Size, castAddr)
518 ->setDoesNotThrow();
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000519 }
520 };
John McCalla464ff92010-07-21 06:13:08 +0000521}
522
John McCall31168b02011-06-15 23:02:42 +0000523/// EmitAutoVarWithLifetime - Does the setup required for an automatic
524/// variable with lifetime.
525static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
526 llvm::Value *addr,
527 Qualifiers::ObjCLifetime lifetime) {
528 switch (lifetime) {
529 case Qualifiers::OCL_None:
530 llvm_unreachable("present but none");
531
532 case Qualifiers::OCL_ExplicitNone:
533 // nothing to do
534 break;
535
536 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000537 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000538 (var.hasAttr<ObjCPreciseLifetimeAttr>()
539 ? CodeGenFunction::destroyARCStrongPrecise
540 : CodeGenFunction::destroyARCStrongImprecise);
541
542 CleanupKind cleanupKind = CGF.getARCCleanupKind();
543 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
544 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000545 break;
546 }
547 case Qualifiers::OCL_Autoreleasing:
548 // nothing to do
549 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000550
John McCall31168b02011-06-15 23:02:42 +0000551 case Qualifiers::OCL_Weak:
552 // __weak objects always get EH cleanups; otherwise, exceptions
553 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000554 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
555 CodeGenFunction::destroyARCWeak,
556 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000557 break;
558 }
559}
560
561static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
562 if (const Expr *e = dyn_cast<Expr>(s)) {
563 // Skip the most common kinds of expressions that make
564 // hierarchy-walking expensive.
565 s = e = e->IgnoreParenCasts();
566
567 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
568 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000569 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
570 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000571 for (const auto &I : block->captures()) {
572 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000573 return true;
574 }
575 }
John McCall31168b02011-06-15 23:02:42 +0000576 }
577
578 for (Stmt::const_child_range children = s->children(); children; ++children)
Fariborz Jahanian326701e2011-06-29 20:00:16 +0000579 // children might be null; as in missing decl or conditional of an if-stmt.
580 if ((*children) && isAccessedBy(var, *children))
John McCall31168b02011-06-15 23:02:42 +0000581 return true;
582
583 return false;
584}
585
586static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
587 if (!decl) return false;
588 if (!isa<VarDecl>(decl)) return false;
589 const VarDecl *var = cast<VarDecl>(decl);
590 return isAccessedBy(*var, e);
591}
592
John McCall1553b192011-06-16 04:16:24 +0000593static void drillIntoBlockVariable(CodeGenFunction &CGF,
594 LValue &lvalue,
595 const VarDecl *var) {
596 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
597}
598
David Blaikie73ca5692014-12-09 00:32:22 +0000599void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie84fe79c2014-12-30 19:39:33 +0000600 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000601 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000602 if (!lifetime) {
603 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000604 if (capturedByInit)
605 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie84fe79c2014-12-30 19:39:33 +0000606 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000607 return;
608 }
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000609
610 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
611 init = DIE->getExpr();
612
John McCall31168b02011-06-15 23:02:42 +0000613 // If we're emitting a value with lifetime, we have to do the
614 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000615 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
616 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000617 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000618 }
619 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000620
621 // We have to maintain the illusion that the variable is
622 // zero-initialized. If the variable might be accessed in its
623 // initializer, zero-initialize before running the initializer, then
624 // actually perform the initialization with an assign.
625 bool accessedByInit = false;
626 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000627 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000628 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000629 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000630 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000631 if (capturedByInit) {
632 // We can use a simple GEP for this because it can't have been
633 // moved yet.
John McCall1553b192011-06-16 04:16:24 +0000634 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
635 getByRefValueLLVMField(cast<VarDecl>(D))));
John McCall31168b02011-06-15 23:02:42 +0000636 }
637
Chris Lattner2192fe52011-07-18 04:24:23 +0000638 llvm::PointerType *ty
John McCall1553b192011-06-16 04:16:24 +0000639 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
John McCall31168b02011-06-15 23:02:42 +0000640 ty = cast<llvm::PointerType>(ty->getElementType());
641
642 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000643
John McCall31168b02011-06-15 23:02:42 +0000644 // If __weak, we want to use a barrier under certain conditions.
645 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000646 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000647
648 // Otherwise just do a simple store.
649 else
David Chisnallfa35df62012-01-16 17:27:18 +0000650 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000651 }
652
653 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000654 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000655
656 switch (lifetime) {
657 case Qualifiers::OCL_None:
658 llvm_unreachable("present but none");
659
660 case Qualifiers::OCL_ExplicitNone:
661 // nothing to do
662 value = EmitScalarExpr(init);
663 break;
664
665 case Qualifiers::OCL_Strong: {
666 value = EmitARCRetainScalarExpr(init);
667 break;
668 }
669
670 case Qualifiers::OCL_Weak: {
671 // No way to optimize a producing initializer into this. It's not
672 // worth optimizing for, because the value will immediately
673 // disappear in the common case.
674 value = EmitScalarExpr(init);
675
John McCall1553b192011-06-16 04:16:24 +0000676 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000677 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000678 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000679 else
John McCall1553b192011-06-16 04:16:24 +0000680 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000681 return;
682 }
683
684 case Qualifiers::OCL_Autoreleasing:
685 value = EmitARCRetainAutoreleaseScalarExpr(init);
686 break;
687 }
688
John McCall1553b192011-06-16 04:16:24 +0000689 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000690
691 // If the variable might have been accessed by its initializer, we
692 // might have to initialize with a barrier. We have to do this for
693 // both __weak and __strong, but __weak got filtered out above.
694 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000695 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000696 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000697 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000698 return;
699 }
700
David Chisnallfa35df62012-01-16 17:27:18 +0000701 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000702}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000703
John McCalld4631322011-06-17 06:42:21 +0000704/// EmitScalarInit - Initialize the given lvalue with the given object.
705void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
706 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
707 if (!lifetime)
David Chisnallfa35df62012-01-16 17:27:18 +0000708 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCalld4631322011-06-17 06:42:21 +0000709
710 switch (lifetime) {
711 case Qualifiers::OCL_None:
712 llvm_unreachable("present but none");
713
714 case Qualifiers::OCL_ExplicitNone:
715 // nothing to do
716 break;
717
718 case Qualifiers::OCL_Strong:
719 init = EmitARCRetain(lvalue.getType(), init);
720 break;
721
722 case Qualifiers::OCL_Weak:
723 // Initialize and then skip the primitive store.
724 EmitARCInitWeak(lvalue.getAddress(), init);
725 return;
726
727 case Qualifiers::OCL_Autoreleasing:
728 init = EmitARCRetainAutorelease(lvalue.getType(), init);
729 break;
730 }
731
David Chisnallfa35df62012-01-16 17:27:18 +0000732 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCalld4631322011-06-17 06:42:21 +0000733}
734
Chris Lattnerb85025f2010-12-01 02:05:19 +0000735/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
736/// non-zero parts of the specified initializer with equal or fewer than
737/// NumStores scalar stores.
738static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
739 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000740 // Zero and Undef never requires any extra stores.
741 if (isa<llvm::ConstantAggregateZero>(Init) ||
742 isa<llvm::ConstantPointerNull>(Init) ||
743 isa<llvm::UndefValue>(Init))
744 return true;
745 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
746 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
747 isa<llvm::ConstantExpr>(Init))
748 return Init->isNullValue() || NumStores--;
749
750 // See if we can emit each element.
751 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
752 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
753 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
754 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
755 return false;
756 }
757 return true;
758 }
Chris Lattner236b3572012-01-31 04:36:19 +0000759
760 if (llvm::ConstantDataSequential *CDS =
761 dyn_cast<llvm::ConstantDataSequential>(Init)) {
762 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
763 llvm::Constant *Elt = CDS->getElementAsConstant(i);
764 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
765 return false;
766 }
767 return true;
768 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000769
Chris Lattnerb85025f2010-12-01 02:05:19 +0000770 // Anything else is hard and scary.
771 return false;
772}
773
774/// emitStoresForInitAfterMemset - For inits that
775/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
776/// stores that would be required.
777static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000778 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000779 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
780 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000781
Chris Lattnere6af8862010-12-02 01:58:41 +0000782 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
783 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
784 isa<llvm::ConstantExpr>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000785 Builder.CreateStore(Init, Loc, isVolatile);
786 return;
787 }
788
789 if (llvm::ConstantDataSequential *CDS =
790 dyn_cast<llvm::ConstantDataSequential>(Init)) {
791 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
792 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000793
794 // If necessary, get a pointer to the element and emit it.
795 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
796 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
797 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000798 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000799 return;
800 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000801
Chris Lattnere6af8862010-12-02 01:58:41 +0000802 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
803 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000804
Chris Lattnere6af8862010-12-02 01:58:41 +0000805 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
806 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000807
808 // If necessary, get a pointer to the element and emit it.
809 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
810 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
811 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000812 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000813}
814
815
816/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
817/// plus some stores to initialize a local variable instead of using a memcpy
818/// from a constant global. It is beneficial to use memset if the global is all
819/// zeros, or mostly zeros and large.
820static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
821 uint64_t GlobalSize) {
822 // If a global is all zeros, always use a memset.
823 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
824
Chris Lattnerb85025f2010-12-01 02:05:19 +0000825 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
826 // do it if it will require 6 or fewer scalar stores.
827 // TODO: Should budget depends on the size? Avoiding a large global warrants
828 // plopping in more stores.
829 unsigned StoreBudget = 6;
830 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000831
832 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000833 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
834}
835
Arnaud A. de Grandmaisonf3470cc2014-12-01 09:30:16 +0000836/// Should we use the LLVM lifetime intrinsics for the given local variable?
837static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
838 unsigned Size) {
839 // For now, only in optimized builds.
840 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
841 return false;
842
843 // Limit the size of marked objects to 32 bytes. We don't want to increase
844 // compile time by marking tiny objects.
845 unsigned SizeThreshold = 32;
846
847 return Size > SizeThreshold;
848}
849
850
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000851/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000852/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000853/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000854void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
855 AutoVarEmission emission = EmitAutoVarAlloca(D);
856 EmitAutoVarInit(emission);
857 EmitAutoVarCleanups(emission);
858}
Chris Lattner03df1222007-06-02 04:53:11 +0000859
John McCallc533cb72011-02-22 06:44:22 +0000860/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000861/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +0000862CodeGenFunction::AutoVarEmission
863CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
864 QualType Ty = D.getType();
865
866 AutoVarEmission emission(D);
867
868 bool isByRef = D.hasAttr<BlocksAttr>();
869 emission.IsByRef = isByRef;
870
871 CharUnits alignment = getContext().getDeclAlign(&D);
872 emission.Alignment = alignment;
873
John McCall23c29fe2011-06-24 21:55:10 +0000874 // If the type is variably-modified, emit all the VLA sizes for it.
875 if (Ty->isVariablyModifiedType())
876 EmitVariablyModifiedType(Ty);
877
Chris Lattner03df1222007-06-02 04:53:11 +0000878 llvm::Value *DeclPtr;
Eli Friedmana682d392008-02-15 12:20:59 +0000879 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000880 bool NRVO = getLangOpts().ElideConstructors &&
881 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +0000882
Richard Smith2bcde3a2013-06-02 00:09:52 +0000883 // If this value is an array or struct with a statically determinable
884 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +0000885 //
886 // TODO: We should constant-evaluate the initializer of any variable,
887 // as long as it is initialized by a constant expression. Currently,
888 // isConstantInitializer produces wrong answers for structs with
889 // reference or bitfield members, and a few other cases, and checking
890 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +0000891 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
892 (D.isConstexpr() ||
893 ((Ty.isPODType(getContext()) ||
894 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
895 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +0000896
Rafael Espindola609f5d92013-03-26 18:41:47 +0000897 // If the variable's a const type, and it's neither an NRVO
898 // candidate nor a __block variable and has no mutable members,
899 // emit it as a global instead.
900 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
901 CGM.isTypeConstant(Ty, true)) {
902 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +0000903
Craig Topper8a13c412014-05-21 05:09:00 +0000904 emission.Address = nullptr; // signal this condition to later callbacks
Rafael Espindola609f5d92013-03-26 18:41:47 +0000905 assert(emission.wasEmittedAsGlobal());
906 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +0000907 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000908
Rafael Espindola609f5d92013-03-26 18:41:47 +0000909 // Otherwise, tell the initialization code that we're in this case.
910 emission.IsConstantAggregate = true;
911 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000912
Rafael Espindola609f5d92013-03-26 18:41:47 +0000913 // A normal fixed sized variable becomes an alloca in the entry block,
914 // unless it's an NRVO variable.
915 llvm::Type *LTy = ConvertTypeForMem(Ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000916
Rafael Espindola609f5d92013-03-26 18:41:47 +0000917 if (NRVO) {
918 // The named return value optimization: allocate this variable in the
919 // return slot, so that we can elide the copy when returning this
920 // variable (C++0x [class.copy]p34).
921 DeclPtr = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +0000922
Rafael Espindola609f5d92013-03-26 18:41:47 +0000923 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
924 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
925 // Create a flag that is used to indicate when the NRVO was applied
926 // to this variable. Set it to zero to indicate that NRVO was not
927 // applied.
928 llvm::Value *Zero = Builder.getFalse();
929 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
930 EnsureInsertPoint();
931 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +0000932
Rafael Espindola609f5d92013-03-26 18:41:47 +0000933 // Record the NRVO flag for this variable.
934 NRVOFlags[&D] = NRVOFlag;
935 emission.NRVOFlag = NRVOFlag;
Nadav Rotem1da30942013-03-23 06:43:35 +0000936 }
Douglas Gregor290c93e2010-05-15 06:46:45 +0000937 }
Chris Lattnerb781dc792008-05-08 05:58:21 +0000938 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000939 if (isByRef)
940 LTy = BuildByRefType(&D);
941
NAKAMURA Takumi215f3b72014-07-18 23:46:16 +0000942 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
943 Alloc->setName(D.getName());
Rafael Espindola609f5d92013-03-26 18:41:47 +0000944
945 CharUnits allocaAlignment = alignment;
946 if (isByRef)
947 allocaAlignment = std::max(allocaAlignment,
John McCallc8e01702013-04-16 22:48:15 +0000948 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
Rafael Espindola609f5d92013-03-26 18:41:47 +0000949 Alloc->setAlignment(allocaAlignment.getQuantity());
950 DeclPtr = Alloc;
951
952 // Emit a lifetime intrinsic if meaningful. There's no point
953 // in doing this if we don't have a valid insertion point (?).
954 uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
Arnaud A. de Grandmaisonf3470cc2014-12-01 09:30:16 +0000955 if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
956 llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
957
958 emission.SizeForLifetimeMarkers = sizeV;
959 llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
960 Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
961 ->setDoesNotThrow();
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +0000962 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000963 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +0000964 }
Chris Lattnerb781dc792008-05-08 05:58:21 +0000965 }
Chris Lattner03df1222007-06-02 04:53:11 +0000966 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000967 EnsureInsertPoint();
968
Anders Carlsson15949b32009-02-09 20:41:50 +0000969 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +0000970 // Save the stack.
John McCallad7c5c12011-02-08 08:22:06 +0000971 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +0000972
Anders Carlsson30032882008-12-12 07:38:43 +0000973 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
974 llvm::Value *V = Builder.CreateCall(F);
Mike Stump11289f42009-09-09 15:08:12 +0000975
Anders Carlsson30032882008-12-12 07:38:43 +0000976 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +0000977
978 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +0000979
John McCalla464ff92010-07-21 06:13:08 +0000980 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +0000981 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000982 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +0000983 }
Mike Stump11289f42009-09-09 15:08:12 +0000984
John McCall23c29fe2011-06-24 21:55:10 +0000985 llvm::Value *elementCount;
986 QualType elementType;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000987 std::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +0000988
Chris Lattner2192fe52011-07-18 04:24:23 +0000989 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +0000990
991 // Allocate memory for the array.
John McCall23c29fe2011-06-24 21:55:10 +0000992 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
993 vla->setAlignment(alignment.getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +0000994
John McCall23c29fe2011-06-24 21:55:10 +0000995 DeclPtr = vla;
Chris Lattner03df1222007-06-02 04:53:11 +0000996 }
Eli Friedmanf4084702008-12-20 23:11:59 +0000997
Chris Lattner03df1222007-06-02 04:53:11 +0000998 llvm::Value *&DMEntry = LocalDeclMap[&D];
Craig Topper8a13c412014-05-21 05:09:00 +0000999 assert(!DMEntry && "Decl already exists in localdeclmap!");
Chris Lattner03df1222007-06-02 04:53:11 +00001000 DMEntry = DeclPtr;
John McCallc533cb72011-02-22 06:44:22 +00001001 emission.Address = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001002
1003 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +00001004 if (HaveInsertPoint())
1005 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001006 if (CGM.getCodeGenOpts().getDebugInfo()
1007 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001008 DI->setLocation(D.getLocation());
Rafael Espindola609f5d92013-03-26 18:41:47 +00001009 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001010 }
Devang Patel887e2152011-06-03 19:21:47 +00001011 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001012
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001013 if (D.hasAttr<AnnotateAttr>())
1014 EmitVarAnnotations(&D, emission.Address);
1015
John McCallc533cb72011-02-22 06:44:22 +00001016 return emission;
1017}
1018
1019/// Determines whether the given __block variable is potentially
1020/// captured by the given expression.
1021static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1022 // Skip the most common kinds of expressions that make
1023 // hierarchy-walking expensive.
1024 e = e->IgnoreParenCasts();
1025
1026 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1027 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +00001028 for (const auto &I : block->captures()) {
1029 if (I.getVariable() == &var)
John McCallc533cb72011-02-22 06:44:22 +00001030 return true;
1031 }
1032
1033 // No need to walk into the subexpressions.
1034 return false;
1035 }
1036
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001037 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1038 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001039 for (const auto *BI : CS->body())
1040 if (const auto *E = dyn_cast<Expr>(BI)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001041 if (isCapturedBy(var, E))
1042 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001043 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001044 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001045 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001046 for (const auto *I : DS->decls()) {
1047 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1048 const Expr *Init = VD->getInit();
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001049 if (Init && isCapturedBy(var, Init))
1050 return true;
1051 }
1052 }
1053 }
1054 else
1055 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1056 // Later, provide code to poke into statements for capture analysis.
1057 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001058 return false;
1059 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001060
John McCallc533cb72011-02-22 06:44:22 +00001061 for (Stmt::const_child_range children = e->children(); children; ++children)
1062 if (isCapturedBy(var, cast<Expr>(*children)))
1063 return true;
1064
1065 return false;
1066}
1067
Douglas Gregor82e1af22011-07-01 21:08:19 +00001068/// \brief Determine whether the given initializer is trivial in the sense
1069/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001070bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001071 if (!Init)
1072 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001073
Douglas Gregor82e1af22011-07-01 21:08:19 +00001074 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1075 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1076 if (Constructor->isTrivial() &&
1077 Constructor->isDefaultConstructor() &&
1078 !Construct->requiresZeroInitialization())
1079 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001080
Douglas Gregor82e1af22011-07-01 21:08:19 +00001081 return false;
1082}
John McCallc533cb72011-02-22 06:44:22 +00001083void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001084 assert(emission.Variable && "emission was not valid!");
1085
John McCallc533cb72011-02-22 06:44:22 +00001086 // If this was emitted as a global constant, we're done.
1087 if (emission.wasEmittedAsGlobal()) return;
1088
John McCall9e2e22f2011-02-22 07:16:58 +00001089 const VarDecl &D = *emission.Variable;
David Blaikie84fe79c2014-12-30 19:39:33 +00001090 ApplyDebugLocation DL(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001091 QualType type = D.getType();
1092
Chris Lattner07eb7332007-07-12 00:39:48 +00001093 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001094 const Expr *Init = D.getInit();
1095
1096 // If we are at an unreachable point, we don't need to emit the initializer
1097 // unless it contains a label.
1098 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001099 if (!Init || !ContainsLabel(Init)) return;
1100 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001101 }
1102
John McCall73064872011-03-31 01:59:53 +00001103 // Initialize the structure of a __block variable.
1104 if (emission.IsByRef)
1105 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001106
Douglas Gregor82e1af22011-07-01 21:08:19 +00001107 if (isTrivialInitializer(Init))
1108 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001109
John McCall73064872011-03-31 01:59:53 +00001110 CharUnits alignment = emission.Alignment;
1111
John McCallc533cb72011-02-22 06:44:22 +00001112 // Check whether this is a byref variable that's potentially
1113 // captured and moved by its own initializer. If so, we'll need to
1114 // emit the initializer first, then copy into the variable.
1115 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1116
1117 llvm::Value *Loc =
1118 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1119
Craig Topper8a13c412014-05-21 05:09:00 +00001120 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001121 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001122 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smithdafff942012-01-14 04:30:29 +00001123 constant = CGM.EmitConstantInit(D, this);
Richard Smithfddd3842011-12-30 21:15:51 +00001124 }
1125
1126 if (!constant) {
Eli Friedmana0544d62011-12-03 04:14:32 +00001127 LValue lv = MakeAddrLValue(Loc, type, alignment);
John McCall1553b192011-06-16 04:16:24 +00001128 lv.setNonGC(true);
David Blaikie84fe79c2014-12-30 19:39:33 +00001129 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001130 }
John McCall91ca10f2011-03-08 09:11:50 +00001131
Richard Smith2bcde3a2013-06-02 00:09:52 +00001132 if (!emission.IsConstantAggregate) {
1133 // For simple scalar/complex initialization, store the value directly.
1134 LValue lv = MakeAddrLValue(Loc, type, alignment);
1135 lv.setNonGC(true);
1136 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1137 }
1138
John McCallc533cb72011-02-22 06:44:22 +00001139 // If this is a simple aggregate initialization, we can optimize it
1140 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001141 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001142
John McCall91ca10f2011-03-08 09:11:50 +00001143 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001144 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001145 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001146
Chris Lattner2192fe52011-07-18 04:24:23 +00001147 llvm::Type *BP = Int8PtrTy;
John McCall91ca10f2011-03-08 09:11:50 +00001148 if (Loc->getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001149 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001150
John McCall91ca10f2011-03-08 09:11:50 +00001151 // If the initializer is all or mostly zeros, codegen with memset then do
1152 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001153 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001154 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall91ca10f2011-03-08 09:11:50 +00001155 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1156 alignment.getQuantity(), isVolatile);
Benjamin Kramer29f9a002012-08-27 22:07:02 +00001157 // Zero and undef don't require a stores.
1158 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall91ca10f2011-03-08 09:11:50 +00001159 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1160 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001161 }
John McCall91ca10f2011-03-08 09:11:50 +00001162 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001163 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001164 // memcpy from the global to the alloca.
Reid Kleckner453e0562014-10-08 01:07:54 +00001165 std::string Name = getStaticDeclName(CGM, D);
John McCall91ca10f2011-03-08 09:11:50 +00001166 llvm::GlobalVariable *GV =
1167 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001168 llvm::GlobalValue::PrivateLinkage,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001169 constant, Name);
John McCall91ca10f2011-03-08 09:11:50 +00001170 GV->setAlignment(alignment.getQuantity());
Eli Friedmanb8578422011-05-27 22:32:55 +00001171 GV->setUnnamedAddr(true);
Eric Christopher31ab1302011-08-23 22:38:00 +00001172
John McCall91ca10f2011-03-08 09:11:50 +00001173 llvm::Value *SrcPtr = GV;
1174 if (SrcPtr->getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001175 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001176
1177 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1178 isVolatile);
1179 }
1180}
1181
1182/// Emit an expression as an initializer for a variable at the given
1183/// location. The expression is not necessarily the normal
1184/// initializer for the variable, and the address is not necessarily
1185/// its normal location.
1186///
1187/// \param init the initializing expression
1188/// \param var the variable to act as if we're initializing
1189/// \param loc the address to initialize; its type is a pointer
1190/// to the LLVM mapping of the variable's type
1191/// \param alignment the alignment of the address
1192/// \param capturedByInit true if the variable is a __block variable
1193/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001194void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie84fe79c2014-12-30 19:39:33 +00001195 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001196 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001197
1198 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001199 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001200 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001201 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie84fe79c2014-12-30 19:39:33 +00001202 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001203 return;
1204 }
1205 switch (getEvaluationKind(type)) {
1206 case TEK_Scalar:
David Blaikie84fe79c2014-12-30 19:39:33 +00001207 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001208 return;
1209 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001210 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001211 if (capturedByInit)
1212 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie84fe79c2014-12-30 19:39:33 +00001213 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001214 return;
1215 }
1216 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001217 if (type->isAtomicType()) {
1218 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1219 } else {
1220 // TODO: how can we delay here if D is captured by its initializer?
1221 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001222 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001223 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001224 AggValueSlot::IsNotAliased));
John McCalla8ec7eb2013-03-07 21:37:17 +00001225 }
John McCall47fb9502013-03-07 21:37:08 +00001226 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001227 }
John McCall47fb9502013-03-07 21:37:08 +00001228 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001229}
John McCallbd309292010-07-06 01:34:17 +00001230
John McCall82fe67b2011-07-09 01:37:26 +00001231/// Enter a destroy cleanup for the given local variable.
1232void CodeGenFunction::emitAutoVarTypeCleanup(
1233 const CodeGenFunction::AutoVarEmission &emission,
1234 QualType::DestructionKind dtorKind) {
1235 assert(dtorKind != QualType::DK_none);
1236
1237 // Note that for __block variables, we want to destroy the
1238 // original stack object, not the possibly forwarded object.
1239 llvm::Value *addr = emission.getObjectAddress(*this);
1240
1241 const VarDecl *var = emission.Variable;
1242 QualType type = var->getType();
1243
1244 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001245 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001246
1247 switch (dtorKind) {
1248 case QualType::DK_none:
1249 llvm_unreachable("no cleanup for trivially-destructible variable");
1250
1251 case QualType::DK_cxx_destructor:
1252 // If there's an NRVO flag on the emission, we need a different
1253 // cleanup.
1254 if (emission.NRVOFlag) {
1255 assert(!type->isArrayType());
1256 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1257 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1258 emission.NRVOFlag);
1259 return;
1260 }
1261 break;
1262
1263 case QualType::DK_objc_strong_lifetime:
1264 // Suppress cleanups for pseudo-strong variables.
1265 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001266
John McCall82fe67b2011-07-09 01:37:26 +00001267 // Otherwise, consider whether to use an EH cleanup or not.
1268 cleanupKind = getARCCleanupKind();
1269
1270 // Use the imprecise destroyer by default.
1271 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1272 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1273 break;
1274
1275 case QualType::DK_objc_weak_lifetime:
1276 break;
1277 }
1278
1279 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001280 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001281
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001282 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001283 // is being pushed as an EH cleanup.
1284 bool useEHCleanup = (cleanupKind & EHCleanup);
1285 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1286 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001287}
1288
John McCallc533cb72011-02-22 06:44:22 +00001289void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001290 assert(emission.Variable && "emission was not valid!");
1291
John McCallc533cb72011-02-22 06:44:22 +00001292 // If this was emitted as a global constant, we're done.
1293 if (emission.wasEmittedAsGlobal()) return;
1294
John McCall8c38d352012-04-13 18:44:05 +00001295 // If we don't have an insertion point, we're done. Sema prevents
1296 // us from jumping into any of these scopes anyway.
1297 if (!HaveInsertPoint()) return;
1298
John McCall9e2e22f2011-02-22 07:16:58 +00001299 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001300
Nadav Rotem1da30942013-03-23 06:43:35 +00001301 // Make sure we call @llvm.lifetime.end. This needs to happen
1302 // *last*, so the cleanup needs to be pushed *first*.
1303 if (emission.useLifetimeMarkers()) {
1304 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1305 emission.getAllocatedAddress(),
1306 emission.getSizeForLifetimeMarkers());
1307 }
1308
John McCall82fe67b2011-07-09 01:37:26 +00001309 // Check the type for a cleanup.
1310 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1311 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001312
John McCall1bd25562011-06-24 23:21:27 +00001313 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001314 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001315 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1316 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1317 }
1318
John McCallc533cb72011-02-22 06:44:22 +00001319 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001320 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001321 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001322
John McCallc533cb72011-02-22 06:44:22 +00001323 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001324 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001325
John McCalla729c622012-02-17 03:33:10 +00001326 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001327 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001328 }
Mike Stump626aecc2009-03-05 01:23:13 +00001329
John McCallc533cb72011-02-22 06:44:22 +00001330 // If this is a block variable, call _Block_object_destroy
1331 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001332 if (emission.IsByRef)
1333 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001334}
Chris Lattner53621a52007-06-13 20:44:40 +00001335
Peter Collingbourne1425b452012-01-26 03:33:36 +00001336CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001337CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1338 switch (kind) {
1339 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001340 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001341 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001342 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001343 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001344 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001345 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001346 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001347 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001348}
1349
John McCall12cc42a2013-02-01 05:11:40 +00001350/// pushEHDestroy - Push the standard destructor for the given type as
1351/// an EH-only cleanup.
1352void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1353 llvm::Value *addr, QualType type) {
1354 assert(dtorKind && "cannot push destructor for trivial type");
1355 assert(needsEHCleanup(dtorKind));
1356
1357 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1358}
1359
1360/// pushDestroy - Push the standard destructor for the given type as
1361/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001362void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1363 llvm::Value *addr, QualType type) {
1364 assert(dtorKind && "cannot push destructor for trivial type");
1365
1366 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1367 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1368 cleanupKind & EHCleanup);
1369}
1370
John McCall82fe67b2011-07-09 01:37:26 +00001371void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001372 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001373 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001374 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1375 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001376}
1377
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001378void CodeGenFunction::pushStackRestore(CleanupKind Kind, llvm::Value *SPMem) {
1379 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1380}
1381
Richard Smith736a9472013-06-12 20:42:33 +00001382void CodeGenFunction::pushLifetimeExtendedDestroy(
1383 CleanupKind cleanupKind, llvm::Value *addr, QualType type,
1384 Destroyer *destroyer, bool useEHCleanupForArray) {
1385 assert(!isInConditionalBranch() &&
1386 "performing lifetime extension from within conditional");
1387
1388 // Push an EH-only cleanup for the object now.
1389 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1390 // around in case a temporary's destructor throws an exception.
1391 if (cleanupKind & EHCleanup)
1392 EHStack.pushCleanup<DestroyObject>(
1393 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1394 destroyer, useEHCleanupForArray);
1395
1396 // Remember that we need to push a full cleanup for the object at the
1397 // end of the full-expression.
1398 pushCleanupAfterFullExpr<DestroyObject>(
1399 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1400}
1401
John McCall178360e2011-07-11 08:38:19 +00001402/// emitDestroy - Immediately perform the destruction of the given
1403/// object.
1404///
1405/// \param addr - the address of the object; a type*
1406/// \param type - the type of the object; if an array type, all
1407/// objects are destroyed in reverse order
1408/// \param destroyer - the function to call to destroy individual
1409/// elements
1410/// \param useEHCleanupForArray - whether an EH cleanup should be
1411/// used when destroying array elements, in case one of the
1412/// destructions throws an exception
John McCall82fe67b2011-07-09 01:37:26 +00001413void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001414 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001415 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001416 const ArrayType *arrayType = getContext().getAsArrayType(type);
1417 if (!arrayType)
1418 return destroyer(*this, addr, type);
1419
1420 llvm::Value *begin = addr;
1421 llvm::Value *length = emitArrayLength(arrayType, type, begin);
John McCall97eab0a2011-07-13 08:09:46 +00001422
1423 // Normally we have to check whether the array is zero-length.
1424 bool checkZeroLength = true;
1425
1426 // But if the array length is constant, we can suppress that.
1427 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1428 // ...and if it's constant zero, we can just skip the entire thing.
1429 if (constLength->isZero()) return;
1430 checkZeroLength = false;
1431 }
1432
John McCall82fe67b2011-07-09 01:37:26 +00001433 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall97eab0a2011-07-13 08:09:46 +00001434 emitArrayDestroy(begin, end, type, destroyer,
1435 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001436}
1437
John McCall178360e2011-07-11 08:38:19 +00001438/// emitArrayDestroy - Destroys all the elements of the given array,
1439/// beginning from last to first. The array cannot be zero-length.
1440///
1441/// \param begin - a type* denoting the first element of the array
1442/// \param end - a type* denoting one past the end of the array
1443/// \param type - the element type of the array
1444/// \param destroyer - the function to call to destroy elements
1445/// \param useEHCleanup - whether to push an EH cleanup to destroy
1446/// the remaining elements in case the destruction of a single
1447/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001448void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1449 llvm::Value *end,
1450 QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001451 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001452 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001453 bool useEHCleanup) {
John McCall82fe67b2011-07-09 01:37:26 +00001454 assert(!type->isArrayType());
1455
1456 // The basic structure here is a do-while loop, because we don't
1457 // need to check for the zero-element case.
1458 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1459 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1460
John McCall97eab0a2011-07-13 08:09:46 +00001461 if (checkZeroLength) {
1462 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1463 "arraydestroy.isempty");
1464 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1465 }
1466
John McCall82fe67b2011-07-09 01:37:26 +00001467 // Enter the loop body, making that address the current address.
1468 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1469 EmitBlock(bodyBB);
1470 llvm::PHINode *elementPast =
1471 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1472 elementPast->addIncoming(end, entryBB);
1473
1474 // Shift the address back by one element.
1475 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1476 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1477 "arraydestroy.element");
1478
John McCall178360e2011-07-11 08:38:19 +00001479 if (useEHCleanup)
1480 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1481
John McCall82fe67b2011-07-09 01:37:26 +00001482 // Perform the actual destruction there.
1483 destroyer(*this, element, type);
1484
John McCall178360e2011-07-11 08:38:19 +00001485 if (useEHCleanup)
1486 PopCleanupBlock();
1487
John McCall82fe67b2011-07-09 01:37:26 +00001488 // Check whether we've reached the end.
1489 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1490 Builder.CreateCondBr(done, doneBB, bodyBB);
1491 elementPast->addIncoming(element, Builder.GetInsertBlock());
1492
1493 // Done.
1494 EmitBlock(doneBB);
1495}
1496
John McCall178360e2011-07-11 08:38:19 +00001497/// Perform partial array destruction as if in an EH cleanup. Unlike
1498/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001499static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1500 llvm::Value *begin, llvm::Value *end,
1501 QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001502 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001503 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001504 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001505 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1506 // VLAs don't require a GEP index to walk into.
1507 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001508 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001509 type = arrayType->getElementType();
1510 }
John McCall97eab0a2011-07-13 08:09:46 +00001511
1512 if (arrayDepth) {
1513 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1514
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001515 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001516 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1517 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001518 }
1519
John McCall97eab0a2011-07-13 08:09:46 +00001520 // Destroy the array. We don't ever need an EH cleanup because we
1521 // assume that we're in an EH cleanup ourselves, so a throwing
1522 // destructor causes an immediate terminate.
1523 CGF.emitArrayDestroy(begin, end, type, destroyer,
1524 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001525}
1526
John McCall82fe67b2011-07-09 01:37:26 +00001527namespace {
John McCall178360e2011-07-11 08:38:19 +00001528 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1529 /// array destroy where the end pointer is regularly determined and
1530 /// does not need to be loaded from a local.
1531 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1532 llvm::Value *ArrayBegin;
1533 llvm::Value *ArrayEnd;
1534 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001535 CodeGenFunction::Destroyer *Destroyer;
John McCall178360e2011-07-11 08:38:19 +00001536 public:
1537 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1538 QualType elementType,
1539 CodeGenFunction::Destroyer *destroyer)
1540 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
Peter Collingbourne1425b452012-01-26 03:33:36 +00001541 ElementType(elementType), Destroyer(destroyer) {}
John McCall178360e2011-07-11 08:38:19 +00001542
Craig Topper4f12f102014-03-12 06:41:41 +00001543 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001544 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1545 ElementType, Destroyer);
1546 }
1547 };
1548
1549 /// IrregularPartialArrayDestroy - a cleanup which performs a
1550 /// partial array destroy where the end pointer is irregularly
1551 /// determined and must be loaded from a local.
1552 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001553 llvm::Value *ArrayBegin;
1554 llvm::Value *ArrayEndPointer;
1555 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001556 CodeGenFunction::Destroyer *Destroyer;
John McCall82fe67b2011-07-09 01:37:26 +00001557 public:
John McCall178360e2011-07-11 08:38:19 +00001558 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1559 llvm::Value *arrayEndPointer,
1560 QualType elementType,
1561 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001562 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
Peter Collingbourne1425b452012-01-26 03:33:36 +00001563 ElementType(elementType), Destroyer(destroyer) {}
John McCall82fe67b2011-07-09 01:37:26 +00001564
Craig Topper4f12f102014-03-12 06:41:41 +00001565 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001566 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001567 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1568 ElementType, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001569 }
1570 };
1571}
1572
John McCall178360e2011-07-11 08:38:19 +00001573/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001574/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001575/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001576///
John McCall82fe67b2011-07-09 01:37:26 +00001577/// \param elementType - the immediate element type of the array;
1578/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001579void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall178360e2011-07-11 08:38:19 +00001580 llvm::Value *arrayEndPointer,
1581 QualType elementType,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001582 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001583 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1584 arrayBegin, arrayEndPointer,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001585 elementType, destroyer);
John McCall178360e2011-07-11 08:38:19 +00001586}
1587
1588/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1589/// already-constructed elements of the given array. The cleanup
1590/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001591///
John McCall178360e2011-07-11 08:38:19 +00001592/// \param elementType - the immediate element type of the array;
1593/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001594void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1595 llvm::Value *arrayEnd,
1596 QualType elementType,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001597 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001598 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001599 arrayBegin, arrayEnd,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001600 elementType, destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001601}
1602
Nadav Rotem1da30942013-03-23 06:43:35 +00001603/// Lazily declare the @llvm.lifetime.start intrinsic.
1604llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1605 if (LifetimeStartFn) return LifetimeStartFn;
1606 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1607 llvm::Intrinsic::lifetime_start);
1608 return LifetimeStartFn;
1609}
1610
1611/// Lazily declare the @llvm.lifetime.end intrinsic.
1612llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1613 if (LifetimeEndFn) return LifetimeEndFn;
1614 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1615 llvm::Intrinsic::lifetime_end);
1616 return LifetimeEndFn;
1617}
1618
John McCall31168b02011-06-15 23:02:42 +00001619namespace {
1620 /// A cleanup to perform a release of an object at the end of a
1621 /// function. This is used to balance out the incoming +1 of a
1622 /// ns_consumed argument when we can't reasonably do that just by
1623 /// not doing the initial retain for a __block argument.
1624 struct ConsumeARCParameter : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001625 ConsumeARCParameter(llvm::Value *param,
1626 ARCPreciseLifetime_t precise)
1627 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001628
1629 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001630 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001631
Craig Topper4f12f102014-03-12 06:41:41 +00001632 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001633 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001634 }
1635 };
1636}
1637
Mike Stump11289f42009-09-09 15:08:12 +00001638/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001639/// for the specified parameter and set up LocalDeclMap.
Devang Patel68a15252011-03-03 20:13:15 +00001640void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001641 bool ArgIsPointer, unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001642 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001643 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001644 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001645
1646 Arg->setName(D.getName());
1647
Adrian Prantl51936dd2013-03-14 17:53:33 +00001648 QualType Ty = D.getType();
1649
John McCall147d0212011-02-22 22:38:33 +00001650 // Use better IR generation for certain implicit parameters.
1651 if (isa<ImplicitParamDecl>(D)) {
1652 // The only implicit argument a block has is its literal.
1653 if (BlockInfo) {
1654 LocalDeclMap[&D] = Arg;
Craig Topper8a13c412014-05-21 05:09:00 +00001655 llvm::Value *LocalAddr = nullptr;
Adrian Prantl51936dd2013-03-14 17:53:33 +00001656 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Adrian Prantl0f6df002013-03-29 19:20:35 +00001657 // Allocate a stack slot to let the debug info survive the RA.
Adrian Prantl51936dd2013-03-14 17:53:33 +00001658 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1659 D.getName() + ".addr");
1660 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1661 LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1662 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1663 LocalAddr = Builder.CreateLoad(Alloc);
1664 }
John McCall147d0212011-02-22 22:38:33 +00001665
1666 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001667 if (CGM.getCodeGenOpts().getDebugInfo()
1668 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001669 DI->setLocation(D.getLocation());
David Blaikie77bbb5f2014-08-08 17:10:14 +00001670 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, ArgNo,
1671 LocalAddr, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001672 }
John McCall147d0212011-02-22 22:38:33 +00001673 }
1674
1675 return;
1676 }
1677 }
1678
Chris Lattner53621a52007-06-13 20:44:40 +00001679 llvm::Value *DeclPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001680 bool DoStore = false;
1681 bool IsScalar = hasScalarEvaluationKind(Ty);
1682 CharUnits Align = getContext().getDeclAlign(&D);
1683 // If we already have a pointer to the argument, reuse the input pointer.
1684 if (ArgIsPointer) {
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001685 // If we have a prettier pointer type at this point, bitcast to that.
1686 unsigned AS = cast<llvm::PointerType>(Arg->getType())->getAddressSpace();
1687 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
1688 DeclPtr = Arg->getType() == IRTy ? Arg : Builder.CreateBitCast(Arg, IRTy,
1689 D.getName());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001690 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00001691 // Don't push a cleanup in a thunk for a method that will also emit a
1692 // cleanup.
1693 if (!IsScalar && !CurFuncIsThunk &&
Reid Kleckner739756c2013-12-04 19:23:12 +00001694 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001695 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1696 if (RD && RD->hasNonTrivialDestructor())
1697 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001698 }
Chris Lattner53621a52007-06-13 20:44:40 +00001699 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001700 // Otherwise, create a temporary to hold the value.
Eli Friedmaneadd3e82011-11-03 20:31:28 +00001701 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1702 D.getName() + ".addr");
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001703 Alloc->setAlignment(Align.getQuantity());
Eli Friedmaneadd3e82011-11-03 20:31:28 +00001704 DeclPtr = Alloc;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001705 DoStore = true;
1706 }
Mike Stump11289f42009-09-09 15:08:12 +00001707
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001708 LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
1709 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00001710 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001711 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1712 // We honor __attribute__((ns_consumed)) for types with lifetime.
1713 // For __strong, it's handled by just skipping the initial retain;
1714 // otherwise we have to balance out the initial +1 with an extra
1715 // cleanup to do the release at the end of the function.
1716 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1717
1718 // 'self' is always formally __strong, but if this is not an
1719 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001720 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001721 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1722 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001723 assert(lt == Qualifiers::OCL_Strong);
1724 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001725 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001726 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001727 lt = Qualifiers::OCL_ExplicitNone;
1728 }
1729
1730 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001731 if (!isConsumed) {
1732 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1733 // use objc_storeStrong(&dest, value) for retaining the
1734 // object. But first, store a null into 'dest' because
1735 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001736 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001737 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1738 EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001739 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001740 }
1741 else
John McCall31168b02011-06-15 23:02:42 +00001742 // Don't use objc_retainBlock for block pointers, because we
1743 // don't want to Block_copy something just because we got it
1744 // as a parameter.
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001745 Arg = EmitARCRetainNonBlock(Arg);
1746 }
John McCall31168b02011-06-15 23:02:42 +00001747 } else {
1748 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00001749 if (isConsumed) {
1750 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1751 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1752 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1753 precise);
1754 }
John McCall31168b02011-06-15 23:02:42 +00001755
1756 if (lt == Qualifiers::OCL_Weak) {
1757 EmitARCInitWeak(DeclPtr, Arg);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001758 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001759 }
1760 }
1761
1762 // Enter the cleanup scope.
1763 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1764 }
Chris Lattner53621a52007-06-13 20:44:40 +00001765 }
1766
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001767 // Store the initial value into the alloca.
1768 if (DoStore)
1769 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1770
Chris Lattner53621a52007-06-13 20:44:40 +00001771 llvm::Value *&DMEntry = LocalDeclMap[&D];
Craig Topper8a13c412014-05-21 05:09:00 +00001772 assert(!DMEntry && "Decl already exists in localdeclmap!");
Chris Lattner53621a52007-06-13 20:44:40 +00001773 DMEntry = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001774
1775 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001776 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001777 if (CGM.getCodeGenOpts().getDebugInfo()
1778 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001779 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1780 }
1781 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001782
1783 if (D.hasAttr<AnnotateAttr>())
1784 EmitVarAnnotations(&D, DeclPtr);
Chris Lattner53621a52007-06-13 20:44:40 +00001785}