blob: 96aa8c68e004c9c4351e31095519a46f4a78f7a8 [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"
David Majnemerdc012fa2015-04-22 21:38:15 +000015#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CGDebugInfo.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000017#include "CGOpenCLRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CodeGenModule.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000019#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000020#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/Decl.h"
Anders Carlsson4c03d982008-08-25 01:38:19 +000022#include "clang/AST/DeclObjC.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000023#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000024#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000025#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000026#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000027#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/GlobalVariable.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Type.h"
Chris Lattner84915fa2007-06-02 04:16:21 +000031using namespace clang;
32using namespace CodeGen;
33
34
Chris Lattner1ad38f82007-06-09 01:20:56 +000035void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000036 switch (D.getKind()) {
Douglas Gregor19043f02010-04-23 02:02:43 +000037 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +000038 case Decl::ExternCContext:
Douglas Gregor19043f02010-04-23 02:02:43 +000039 case Decl::Namespace:
40 case Decl::UnresolvedUsingTypename:
41 case Decl::ClassTemplateSpecialization:
42 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000043 case Decl::VarTemplateSpecialization:
44 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000045 case Decl::TemplateTypeParm:
46 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000047 case Decl::NonTypeTemplateParm:
Douglas Gregor19043f02010-04-23 02:02:43 +000048 case Decl::CXXMethod:
49 case Decl::CXXConstructor:
50 case Decl::CXXDestructor:
51 case Decl::CXXConversion:
52 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000053 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000054 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000055 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000056 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000057 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000058 case Decl::ImplicitParam:
59 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000060 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000061 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000062 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000063 case Decl::TemplateTemplateParm:
64 case Decl::ObjCMethod:
65 case Decl::ObjCCategory:
66 case Decl::ObjCProtocol:
67 case Decl::ObjCInterface:
68 case Decl::ObjCCategoryImpl:
69 case Decl::ObjCImplementation:
70 case Decl::ObjCProperty:
71 case Decl::ObjCCompatibleAlias:
Abramo Bagnarad7340582010-06-05 05:09:32 +000072 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000073 case Decl::LinkageSpec:
74 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000075 case Decl::FileScopeAsm:
76 case Decl::Friend:
77 case Decl::FriendTemplate:
78 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000079 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000080 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000081 case Decl::UsingShadow:
Douglas Gregor85f3f952015-07-07 03:57:15 +000082 case Decl::ObjCTypeParam:
David Blaikie83d382b2011-09-23 05:06:16 +000083 llvm_unreachable("Declaration should not be in declstmts!");
Chris Lattner84915fa2007-06-02 04:16:21 +000084 case Decl::Function: // void X();
David Blaikiebe822ed2015-07-01 18:07:22 +000085 case Decl::Record: // struct/union/class X;
Chris Lattner84915fa2007-06-02 04:16:21 +000086 case Decl::Enum: // enum X;
Mike Stump11289f42009-09-09 15:08:12 +000087 case Decl::EnumConstant: // enum ? { X = ? }
David Blaikiebe822ed2015-07-01 18:07:22 +000088 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +000089 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +000090 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +000091 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +000092 case Decl::OMPThreadPrivate:
Michael Han84324352013-02-22 17:15:32 +000093 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +000094 // None of these decls require codegen support.
95 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +000096
David Blaikief121b932013-05-20 22:50:41 +000097 case Decl::NamespaceAlias:
98 if (CGDebugInfo *DI = getDebugInfo())
99 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
100 return;
David Blaikiebd483762013-05-20 04:58:53 +0000101 case Decl::Using: // using X; [C++]
102 if (CGDebugInfo *DI = getDebugInfo())
103 DI->EmitUsingDecl(cast<UsingDecl>(D));
104 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000105 case Decl::UsingDirective: // using namespace X; [C++]
106 if (CGDebugInfo *DI = getDebugInfo())
107 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
108 return;
Daniel Dunbara7998072008-08-29 17:28:43 +0000109 case Decl::Var: {
110 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000111 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000112 "Should not see file-scope variables inside a function!");
John McCall1c9c3fd2010-10-15 04:57:14 +0000113 return EmitVarDecl(VD);
Chris Lattner84915fa2007-06-02 04:16:21 +0000114 }
Mike Stump11289f42009-09-09 15:08:12 +0000115
Richard Smithdda56e42011-04-15 14:24:37 +0000116 case Decl::Typedef: // typedef int X;
117 case Decl::TypeAlias: { // using X = int; [C++0x]
118 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000119 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000120
Anders Carlsson5d985f52008-12-20 21:51:53 +0000121 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000122 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000123 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000124 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000125}
Chris Lattner03df1222007-06-02 04:53:11 +0000126
John McCall1c9c3fd2010-10-15 04:57:14 +0000127/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000128/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000129void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000130 if (D.isStaticLocal()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000131 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000132 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000133
David Majnemer27d69db2014-04-28 22:17:59 +0000134 // FIXME: We need to force the emission/use of a guard variable for
135 // some variables even if we can constant-evaluate them because
136 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000137
John McCall1c9c3fd2010-10-15 04:57:14 +0000138 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000139 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000140
141 if (D.hasExternalStorage())
Lauro Ramos Venanciobada8d42008-02-16 22:30:38 +0000142 // Don't emit it now, allow it to be emitted lazily on its first use.
143 return;
Daniel Dunbar0ca16602009-04-14 02:25:56 +0000144
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000145 if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
146 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
147
148 assert(D.hasLocalStorage());
149 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000150}
151
Reid Kleckner453e0562014-10-08 01:07:54 +0000152static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
153 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000154 return CGM.getMangledName(&D).str();
155
Reid Kleckner453e0562014-10-08 01:07:54 +0000156 // If this isn't C++, we don't need a mangled name, just a pretty one.
157 assert(!D.isExternallyVisible() && "name shouldn't matter");
158 std::string ContextName;
159 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000160 if (auto *CD = dyn_cast<CapturedDecl>(DC))
161 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000162 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000163 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000164 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
165 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
166 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
167 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000168 else
David Blaikie83d382b2011-09-23 05:06:16 +0000169 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000170
Reid Kleckner453e0562014-10-08 01:07:54 +0000171 ContextName += "." + D.getNameAsString();
172 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000173}
174
Reid Kleckner453e0562014-10-08 01:07:54 +0000175llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
176 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
177 // In general, we don't always emit static var decls once before we reference
178 // them. It is possible to reference them before emitting the function that
179 // contains them, and it is possible to emit the containing function multiple
180 // times.
181 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
182 return ExistingGV;
183
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000184 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000185 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000186
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000187 // Use the label if the variable is renamed with the asm-label extension.
188 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000189 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000190 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000191 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000192 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000193
Reid Kleckner453e0562014-10-08 01:07:54 +0000194 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000195 unsigned AddrSpace =
Reid Kleckner453e0562014-10-08 01:07:54 +0000196 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000197
198 // Local address space cannot have an initializer.
199 llvm::Constant *Init = nullptr;
200 if (Ty.getAddressSpace() != LangAS::opencl_local)
201 Init = EmitNullConstant(Ty);
202 else
203 Init = llvm::UndefValue::get(LTy);
204
Anders Carlssone33eed52009-09-26 18:16:06 +0000205 llvm::GlobalVariable *GV =
Reid Kleckner453e0562014-10-08 01:07:54 +0000206 new llvm::GlobalVariable(getModule(), LTy,
Anders Carlssone33eed52009-09-26 18:16:06 +0000207 Ty.isConstant(getContext()), Linkage,
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000208 Init, Name, nullptr,
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000209 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000210 AddrSpace);
Ken Dyck160146e2010-01-27 17:10:57 +0000211 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Reid Kleckner453e0562014-10-08 01:07:54 +0000212 setGlobalVisibility(GV, &D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000213
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000214 if (supportsCOMDAT() && GV->isWeakForLinker())
215 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000216
Richard Smithfd3834f2013-04-13 02:43:54 +0000217 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000218 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000219
Hans Wennborgef2272c2014-06-18 15:55:13 +0000220 if (D.isExternallyVisible()) {
221 if (D.hasAttr<DLLImportAttr>())
222 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
223 else if (D.hasAttr<DLLExportAttr>())
224 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
225 }
226
Eli Benderskycb399432014-03-24 22:05:38 +0000227 // Make sure the result is of the correct type.
Reid Kleckner453e0562014-10-08 01:07:54 +0000228 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
229 llvm::Constant *Addr = GV;
Eli Benderskycb399432014-03-24 22:05:38 +0000230 if (AddrSpace != ExpectedAddrSpace) {
231 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
Reid Kleckner453e0562014-10-08 01:07:54 +0000232 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
Eli Benderskycb399432014-03-24 22:05:38 +0000233 }
234
Reid Kleckner453e0562014-10-08 01:07:54 +0000235 setStaticLocalDeclAddress(&D, Addr);
236
237 // Ensure that the static local gets initialized by making sure the parent
238 // function gets emitted eventually.
239 const Decl *DC = cast<Decl>(D.getDeclContext());
240
241 // We can't name blocks or captured statements directly, so try to emit their
242 // parents.
243 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
244 DC = DC->getNonClosureContext();
245 // FIXME: Ensure that global blocks get emitted.
246 if (!DC)
247 return Addr;
248 }
249
250 GlobalDecl GD;
251 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
252 GD = GlobalDecl(CD, Ctor_Base);
253 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
254 GD = GlobalDecl(DD, Dtor_Base);
255 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
256 GD = GlobalDecl(FD);
257 else {
258 // Don't do anything for Obj-C method decls or global closures. We should
259 // never defer them.
260 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
261 }
262 if (GD.getDecl())
263 (void)GetAddrOfGlobal(GD);
264
265 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000266}
267
Richard Smith6331c402012-02-13 22:16:19 +0000268/// hasNontrivialDestruction - Determine whether a type's destruction is
269/// non-trivial. If so, and the variable uses static initialization, we must
270/// register its destructor to run on exit.
271static bool hasNontrivialDestruction(QualType T) {
272 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
273 return RD && !RD->hasTrivialDestructor();
274}
275
Chandler Carruth84537952012-03-30 19:44:53 +0000276/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
277/// global variable that has already been created for it. If the initializer
278/// has a different type than GV does, this may free GV and return a different
279/// one. Otherwise it just returns GV.
280llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000281CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000282 llvm::GlobalVariable *GV) {
283 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCall70013b62010-07-15 23:40:35 +0000284
Chris Lattnere99c1102009-12-05 08:22:11 +0000285 // If constant emission failed, then this should be a C++ static
286 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000287 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000288 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000289 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall68ff0372010-09-08 01:44:27 +0000290 else if (Builder.GetInsertBlock()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000291 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000292 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000293 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000294
Chandler Carruth84537952012-03-30 19:44:53 +0000295 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000296 }
Chandler Carruth84537952012-03-30 19:44:53 +0000297 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000298 }
John McCall70013b62010-07-15 23:40:35 +0000299
Chris Lattnere99c1102009-12-05 08:22:11 +0000300 // The initializer may differ in type from the global. Rewrite
301 // the global to match the initializer. (We have to do this
302 // because some types, like unions, can't be completely represented
303 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000304 if (GV->getType()->getElementType() != Init->getType()) {
305 llvm::GlobalVariable *OldGV = GV;
306
307 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
308 OldGV->isConstant(),
309 OldGV->getLinkage(), Init, "",
310 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000311 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000312 CGM.getContext().getTargetAddressSpace(D.getType()));
313 GV->setVisibility(OldGV->getVisibility());
Eric Christopher31ab1302011-08-23 22:38:00 +0000314
Chris Lattnere99c1102009-12-05 08:22:11 +0000315 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000316 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000317
Chris Lattnere99c1102009-12-05 08:22:11 +0000318 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000319 llvm::Constant *NewPtrForOldDecl =
320 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
321 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000322
Chris Lattnere99c1102009-12-05 08:22:11 +0000323 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000324 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000325 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000326
Chandler Carruth84537952012-03-30 19:44:53 +0000327 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
328 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000329
330 if (hasNontrivialDestruction(D.getType())) {
331 // We have a constant initializer, but a nontrivial destructor. We still
332 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000333 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000334 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000335 }
336
Chandler Carruth84537952012-03-30 19:44:53 +0000337 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000338}
339
John McCall1c9c3fd2010-10-15 04:57:14 +0000340void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000341 llvm::GlobalValue::LinkageTypes Linkage) {
Chandler Carruth84537952012-03-30 19:44:53 +0000342 llvm::Value *&DMEntry = LocalDeclMap[&D];
Craig Topper8a13c412014-05-21 05:09:00 +0000343 assert(!DMEntry && "Decl already exists in localdeclmap!");
Mike Stump11289f42009-09-09 15:08:12 +0000344
John McCallb88a5662012-03-30 21:00:39 +0000345 // Check to see if we already have a global variable for this
346 // declaration. This can happen when double-emitting function
347 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000348 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
Daniel Dunbara374e602009-02-25 19:45:19 +0000349
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000350 // Store into LocalDeclMap before generating initializer to handle
351 // circular references.
John McCallb88a5662012-03-30 21:00:39 +0000352 DMEntry = addr;
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000353
John McCall4a39ab82010-05-04 20:45:42 +0000354 // We can't have a VLA here, but we can have a pointer to a VLA,
355 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000356 // Make sure to evaluate VLA bounds now so that we have them for later.
357 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000358 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000359
John McCallb88a5662012-03-30 21:00:39 +0000360 // Save the type in case adding the initializer forces a type change.
361 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000362
Eli Benderskycb399432014-03-24 22:05:38 +0000363 llvm::GlobalVariable *var =
364 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Chris Lattnere99c1102009-12-05 08:22:11 +0000365 // If this value has an initializer, emit it.
366 if (D.getInit())
John McCallb88a5662012-03-30 21:00:39 +0000367 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000368
John McCallb88a5662012-03-30 21:00:39 +0000369 var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000370
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000371 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000372 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000373
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000374 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000375 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000376
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000377 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000378 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000379
Chandler Carruth84537952012-03-30 19:44:53 +0000380 // We may have to cast the constant because of the initializer
381 // mismatch above.
382 //
383 // FIXME: It is really dangerous to store this in the map; if anyone
384 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000385 llvm::Constant *castedAddr =
386 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCallb88a5662012-03-30 21:00:39 +0000387 DMEntry = castedAddr;
388 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000389
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000390 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000391
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000392 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000393 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000394 if (DI &&
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000395 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000396 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000397 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000398 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000399}
Mike Stump11289f42009-09-09 15:08:12 +0000400
John McCall2b7fc382010-07-13 20:32:21 +0000401namespace {
John McCall82fe67b2011-07-09 01:37:26 +0000402 struct DestroyObject : EHScopeStack::Cleanup {
403 DestroyObject(llvm::Value *addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000404 CodeGenFunction::Destroyer *destroyer,
405 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000406 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000407 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000408
John McCall82fe67b2011-07-09 01:37:26 +0000409 llvm::Value *addr;
410 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000411 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000412 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000413
Craig Topper4f12f102014-03-12 06:41:41 +0000414 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000415 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000416 bool useEHCleanupForArray =
417 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000418
419 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000420 }
421 };
422
John McCall82fe67b2011-07-09 01:37:26 +0000423 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
424 DestroyNRVOVariable(llvm::Value *addr,
425 const CXXDestructorDecl *Dtor,
426 llvm::Value *NRVOFlag)
427 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000428
429 const CXXDestructorDecl *Dtor;
430 llvm::Value *NRVOFlag;
431 llvm::Value *Loc;
432
Craig Topper4f12f102014-03-12 06:41:41 +0000433 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000434 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000435 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000436
Craig Topper8a13c412014-05-21 05:09:00 +0000437 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000438 if (NRVO) {
439 // If we exited via NRVO, we skip the destructor call.
440 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
441 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
442 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
443 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
444 CGF.EmitBlock(RunDtorBB);
445 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000446
John McCall2b7fc382010-07-13 20:32:21 +0000447 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +0000448 /*ForVirtualBase=*/false,
449 /*Delegating=*/false,
450 Loc);
John McCall2b7fc382010-07-13 20:32:21 +0000451
452 if (NRVO) CGF.EmitBlock(SkipDtorBB);
453 }
454 };
John McCall2b7fc382010-07-13 20:32:21 +0000455
John McCallcda666c2010-07-21 07:22:38 +0000456 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000457 llvm::Value *Stack;
458 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000459 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000460 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000461 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
462 CGF.Builder.CreateCall(F, V);
463 }
464 };
465
John McCall1bd25562011-06-24 23:21:27 +0000466 struct ExtendGCLifetime : EHScopeStack::Cleanup {
467 const VarDecl &Var;
468 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
469
Craig Topper4f12f102014-03-12 06:41:41 +0000470 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000471 // Compute the address of the local variable, in case it's a
472 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000473 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
474 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000475 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
476 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000477 CGF.EmitExtendGCLifetime(value);
478 }
479 };
480
John McCallcda666c2010-07-21 07:22:38 +0000481 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000482 llvm::Constant *CleanupFn;
483 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000484 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000485
John McCalla464ff92010-07-21 06:13:08 +0000486 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000487 const VarDecl *Var)
488 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000489
Craig Topper4f12f102014-03-12 06:41:41 +0000490 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000491 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
492 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000493 // Compute the address of the local variable, in case it's a byref
494 // or something.
495 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
496
John McCalla464ff92010-07-21 06:13:08 +0000497 // In some cases, the type of the function argument will be different from
498 // the type of the pointer. An example of this is
499 // void f(void* arg);
500 // __attribute__((cleanup(f))) void *g;
501 //
502 // To fix this we insert a bitcast here.
503 QualType ArgTy = FnInfo.arg_begin()->type;
504 llvm::Value *Arg =
505 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
506
507 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000508 Args.add(RValue::get(Arg),
509 CGF.getContext().getPointerType(Var.getType()));
John McCalla464ff92010-07-21 06:13:08 +0000510 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
511 }
512 };
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000513
514 /// A cleanup to call @llvm.lifetime.end.
515 class CallLifetimeEnd : public EHScopeStack::Cleanup {
516 llvm::Value *Addr;
517 llvm::Value *Size;
518 public:
519 CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
520 : Addr(addr), Size(size) {}
521
522 void Emit(CodeGenFunction &CGF, Flags flags) override {
David Majnemerdc012fa2015-04-22 21:38:15 +0000523 CGF.EmitLifetimeEnd(Size, Addr);
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000524 }
525 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000526}
John McCalla464ff92010-07-21 06:13:08 +0000527
John McCall31168b02011-06-15 23:02:42 +0000528/// EmitAutoVarWithLifetime - Does the setup required for an automatic
529/// variable with lifetime.
530static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
531 llvm::Value *addr,
532 Qualifiers::ObjCLifetime lifetime) {
533 switch (lifetime) {
534 case Qualifiers::OCL_None:
535 llvm_unreachable("present but none");
536
537 case Qualifiers::OCL_ExplicitNone:
538 // nothing to do
539 break;
540
541 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000542 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000543 (var.hasAttr<ObjCPreciseLifetimeAttr>()
544 ? CodeGenFunction::destroyARCStrongPrecise
545 : CodeGenFunction::destroyARCStrongImprecise);
546
547 CleanupKind cleanupKind = CGF.getARCCleanupKind();
548 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
549 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000550 break;
551 }
552 case Qualifiers::OCL_Autoreleasing:
553 // nothing to do
554 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000555
John McCall31168b02011-06-15 23:02:42 +0000556 case Qualifiers::OCL_Weak:
557 // __weak objects always get EH cleanups; otherwise, exceptions
558 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000559 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
560 CodeGenFunction::destroyARCWeak,
561 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000562 break;
563 }
564}
565
566static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
567 if (const Expr *e = dyn_cast<Expr>(s)) {
568 // Skip the most common kinds of expressions that make
569 // hierarchy-walking expensive.
570 s = e = e->IgnoreParenCasts();
571
572 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
573 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000574 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
575 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000576 for (const auto &I : block->captures()) {
577 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000578 return true;
579 }
580 }
John McCall31168b02011-06-15 23:02:42 +0000581 }
582
Benjamin Kramer642f1732015-07-02 21:03:14 +0000583 for (const Stmt *SubStmt : s->children())
584 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
585 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000586 return true;
587
588 return false;
589}
590
591static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
592 if (!decl) return false;
593 if (!isa<VarDecl>(decl)) return false;
594 const VarDecl *var = cast<VarDecl>(decl);
595 return isAccessedBy(*var, e);
596}
597
John McCall1553b192011-06-16 04:16:24 +0000598static void drillIntoBlockVariable(CodeGenFunction &CGF,
599 LValue &lvalue,
600 const VarDecl *var) {
601 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
602}
603
David Blaikie73ca5692014-12-09 00:32:22 +0000604void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000605 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000606 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000607 if (!lifetime) {
608 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000609 if (capturedByInit)
610 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +0000611 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000612 return;
613 }
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000614
615 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
616 init = DIE->getExpr();
617
John McCall31168b02011-06-15 23:02:42 +0000618 // If we're emitting a value with lifetime, we have to do the
619 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000620 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
621 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000622 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000623 }
624 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000625
626 // We have to maintain the illusion that the variable is
627 // zero-initialized. If the variable might be accessed in its
628 // initializer, zero-initialize before running the initializer, then
629 // actually perform the initialization with an assign.
630 bool accessedByInit = false;
631 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000632 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000633 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000634 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000635 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000636 if (capturedByInit) {
637 // We can use a simple GEP for this because it can't have been
638 // moved yet.
David Blaikie2e804282015-04-05 22:47:07 +0000639 tempLV.setAddress(Builder.CreateStructGEP(
640 nullptr, tempLV.getAddress(),
641 getByRefValueLLVMField(cast<VarDecl>(D)).second));
John McCall31168b02011-06-15 23:02:42 +0000642 }
643
Chris Lattner2192fe52011-07-18 04:24:23 +0000644 llvm::PointerType *ty
John McCall1553b192011-06-16 04:16:24 +0000645 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
John McCall31168b02011-06-15 23:02:42 +0000646 ty = cast<llvm::PointerType>(ty->getElementType());
647
648 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000649
John McCall31168b02011-06-15 23:02:42 +0000650 // If __weak, we want to use a barrier under certain conditions.
651 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000652 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000653
654 // Otherwise just do a simple store.
655 else
David Chisnallfa35df62012-01-16 17:27:18 +0000656 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000657 }
658
659 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000660 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000661
662 switch (lifetime) {
663 case Qualifiers::OCL_None:
664 llvm_unreachable("present but none");
665
666 case Qualifiers::OCL_ExplicitNone:
667 // nothing to do
668 value = EmitScalarExpr(init);
669 break;
670
671 case Qualifiers::OCL_Strong: {
672 value = EmitARCRetainScalarExpr(init);
673 break;
674 }
675
676 case Qualifiers::OCL_Weak: {
677 // No way to optimize a producing initializer into this. It's not
678 // worth optimizing for, because the value will immediately
679 // disappear in the common case.
680 value = EmitScalarExpr(init);
681
John McCall1553b192011-06-16 04:16:24 +0000682 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000683 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000684 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000685 else
John McCall1553b192011-06-16 04:16:24 +0000686 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000687 return;
688 }
689
690 case Qualifiers::OCL_Autoreleasing:
691 value = EmitARCRetainAutoreleaseScalarExpr(init);
692 break;
693 }
694
John McCall1553b192011-06-16 04:16:24 +0000695 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000696
697 // If the variable might have been accessed by its initializer, we
698 // might have to initialize with a barrier. We have to do this for
699 // both __weak and __strong, but __weak got filtered out above.
700 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000701 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000702 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000703 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000704 return;
705 }
706
David Chisnallfa35df62012-01-16 17:27:18 +0000707 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000708}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000709
John McCalld4631322011-06-17 06:42:21 +0000710/// EmitScalarInit - Initialize the given lvalue with the given object.
711void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
712 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
713 if (!lifetime)
David Chisnallfa35df62012-01-16 17:27:18 +0000714 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCalld4631322011-06-17 06:42:21 +0000715
716 switch (lifetime) {
717 case Qualifiers::OCL_None:
718 llvm_unreachable("present but none");
719
720 case Qualifiers::OCL_ExplicitNone:
721 // nothing to do
722 break;
723
724 case Qualifiers::OCL_Strong:
725 init = EmitARCRetain(lvalue.getType(), init);
726 break;
727
728 case Qualifiers::OCL_Weak:
729 // Initialize and then skip the primitive store.
730 EmitARCInitWeak(lvalue.getAddress(), init);
731 return;
732
733 case Qualifiers::OCL_Autoreleasing:
734 init = EmitARCRetainAutorelease(lvalue.getType(), init);
735 break;
736 }
737
David Chisnallfa35df62012-01-16 17:27:18 +0000738 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCalld4631322011-06-17 06:42:21 +0000739}
740
Chris Lattnerb85025f2010-12-01 02:05:19 +0000741/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
742/// non-zero parts of the specified initializer with equal or fewer than
743/// NumStores scalar stores.
744static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
745 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000746 // Zero and Undef never requires any extra stores.
747 if (isa<llvm::ConstantAggregateZero>(Init) ||
748 isa<llvm::ConstantPointerNull>(Init) ||
749 isa<llvm::UndefValue>(Init))
750 return true;
751 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
752 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
753 isa<llvm::ConstantExpr>(Init))
754 return Init->isNullValue() || NumStores--;
755
756 // See if we can emit each element.
757 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
758 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
759 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
760 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
761 return false;
762 }
763 return true;
764 }
Chris Lattner236b3572012-01-31 04:36:19 +0000765
766 if (llvm::ConstantDataSequential *CDS =
767 dyn_cast<llvm::ConstantDataSequential>(Init)) {
768 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
769 llvm::Constant *Elt = CDS->getElementAsConstant(i);
770 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
771 return false;
772 }
773 return true;
774 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000775
Chris Lattnerb85025f2010-12-01 02:05:19 +0000776 // Anything else is hard and scary.
777 return false;
778}
779
780/// emitStoresForInitAfterMemset - For inits that
781/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
782/// stores that would be required.
783static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000784 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000785 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
786 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000787
Chris Lattnere6af8862010-12-02 01:58:41 +0000788 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
789 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
790 isa<llvm::ConstantExpr>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000791 Builder.CreateStore(Init, Loc, isVolatile);
792 return;
793 }
794
795 if (llvm::ConstantDataSequential *CDS =
796 dyn_cast<llvm::ConstantDataSequential>(Init)) {
797 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
798 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000799
800 // If necessary, get a pointer to the element and emit it.
801 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000802 emitStoresForInitAfterMemset(
803 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
804 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000805 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000806 return;
807 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000808
Chris Lattnere6af8862010-12-02 01:58:41 +0000809 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
810 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000811
Chris Lattnere6af8862010-12-02 01:58:41 +0000812 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
813 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000814
815 // If necessary, get a pointer to the element and emit it.
816 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000817 emitStoresForInitAfterMemset(
818 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
819 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000820 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000821}
822
823
824/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
825/// plus some stores to initialize a local variable instead of using a memcpy
826/// from a constant global. It is beneficial to use memset if the global is all
827/// zeros, or mostly zeros and large.
828static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
829 uint64_t GlobalSize) {
830 // If a global is all zeros, always use a memset.
831 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
832
Chris Lattnerb85025f2010-12-01 02:05:19 +0000833 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
834 // do it if it will require 6 or fewer scalar stores.
835 // TODO: Should budget depends on the size? Avoiding a large global warrants
836 // plopping in more stores.
837 unsigned StoreBudget = 6;
838 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000839
840 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000841 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
842}
843
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000844/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000845/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000846/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000847void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
848 AutoVarEmission emission = EmitAutoVarAlloca(D);
849 EmitAutoVarInit(emission);
850 EmitAutoVarCleanups(emission);
851}
Chris Lattner03df1222007-06-02 04:53:11 +0000852
David Majnemerdc012fa2015-04-22 21:38:15 +0000853/// Emit a lifetime.begin marker if some criteria are satisfied.
854/// \return a pointer to the temporary size Value if a marker was emitted, null
855/// otherwise
856llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
857 llvm::Value *Addr) {
858 // For now, only in optimized builds.
859 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
860 return nullptr;
861
Reid Kleckner1ef49212015-04-23 18:07:13 +0000862 // Disable lifetime markers in msan builds.
863 // FIXME: Remove this when msan works with lifetime markers.
864 if (getLangOpts().Sanitize.has(SanitizerKind::Memory))
865 return nullptr;
866
David Majnemerdc012fa2015-04-22 21:38:15 +0000867 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000868 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
869 llvm::CallInst *C =
870 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000871 C->setDoesNotThrow();
872 return SizeV;
873}
874
875void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000876 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
877 llvm::CallInst *C =
878 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000879 C->setDoesNotThrow();
880}
881
John McCallc533cb72011-02-22 06:44:22 +0000882/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000883/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +0000884CodeGenFunction::AutoVarEmission
885CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
886 QualType Ty = D.getType();
887
888 AutoVarEmission emission(D);
889
890 bool isByRef = D.hasAttr<BlocksAttr>();
891 emission.IsByRef = isByRef;
892
893 CharUnits alignment = getContext().getDeclAlign(&D);
894 emission.Alignment = alignment;
895
John McCall23c29fe2011-06-24 21:55:10 +0000896 // If the type is variably-modified, emit all the VLA sizes for it.
897 if (Ty->isVariablyModifiedType())
898 EmitVariablyModifiedType(Ty);
899
Chris Lattner03df1222007-06-02 04:53:11 +0000900 llvm::Value *DeclPtr;
Eli Friedmana682d392008-02-15 12:20:59 +0000901 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000902 bool NRVO = getLangOpts().ElideConstructors &&
903 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +0000904
Richard Smith2bcde3a2013-06-02 00:09:52 +0000905 // If this value is an array or struct with a statically determinable
906 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +0000907 //
908 // TODO: We should constant-evaluate the initializer of any variable,
909 // as long as it is initialized by a constant expression. Currently,
910 // isConstantInitializer produces wrong answers for structs with
911 // reference or bitfield members, and a few other cases, and checking
912 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +0000913 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
914 (D.isConstexpr() ||
915 ((Ty.isPODType(getContext()) ||
916 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
917 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +0000918
Rafael Espindola609f5d92013-03-26 18:41:47 +0000919 // If the variable's a const type, and it's neither an NRVO
920 // candidate nor a __block variable and has no mutable members,
921 // emit it as a global instead.
922 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
923 CGM.isTypeConstant(Ty, true)) {
924 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +0000925
Craig Topper8a13c412014-05-21 05:09:00 +0000926 emission.Address = nullptr; // signal this condition to later callbacks
Rafael Espindola609f5d92013-03-26 18:41:47 +0000927 assert(emission.wasEmittedAsGlobal());
928 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +0000929 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000930
Rafael Espindola609f5d92013-03-26 18:41:47 +0000931 // Otherwise, tell the initialization code that we're in this case.
932 emission.IsConstantAggregate = true;
933 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000934
Rafael Espindola609f5d92013-03-26 18:41:47 +0000935 // A normal fixed sized variable becomes an alloca in the entry block,
936 // unless it's an NRVO variable.
937 llvm::Type *LTy = ConvertTypeForMem(Ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000938
Rafael Espindola609f5d92013-03-26 18:41:47 +0000939 if (NRVO) {
940 // The named return value optimization: allocate this variable in the
941 // return slot, so that we can elide the copy when returning this
942 // variable (C++0x [class.copy]p34).
943 DeclPtr = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +0000944
Rafael Espindola609f5d92013-03-26 18:41:47 +0000945 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
946 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
947 // Create a flag that is used to indicate when the NRVO was applied
948 // to this variable. Set it to zero to indicate that NRVO was not
949 // applied.
950 llvm::Value *Zero = Builder.getFalse();
951 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
952 EnsureInsertPoint();
953 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +0000954
Rafael Espindola609f5d92013-03-26 18:41:47 +0000955 // Record the NRVO flag for this variable.
956 NRVOFlags[&D] = NRVOFlag;
957 emission.NRVOFlag = NRVOFlag;
Nadav Rotem1da30942013-03-23 06:43:35 +0000958 }
Douglas Gregor290c93e2010-05-15 06:46:45 +0000959 }
Chris Lattnerb781dc792008-05-08 05:58:21 +0000960 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000961 if (isByRef)
962 LTy = BuildByRefType(&D);
963
NAKAMURA Takumi215f3b72014-07-18 23:46:16 +0000964 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
965 Alloc->setName(D.getName());
Rafael Espindola609f5d92013-03-26 18:41:47 +0000966
967 CharUnits allocaAlignment = alignment;
968 if (isByRef)
969 allocaAlignment = std::max(allocaAlignment,
John McCallc8e01702013-04-16 22:48:15 +0000970 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
Rafael Espindola609f5d92013-03-26 18:41:47 +0000971 Alloc->setAlignment(allocaAlignment.getQuantity());
972 DeclPtr = Alloc;
973
974 // Emit a lifetime intrinsic if meaningful. There's no point
975 // in doing this if we don't have a valid insertion point (?).
976 uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
David Majnemerdc012fa2015-04-22 21:38:15 +0000977 if (HaveInsertPoint()) {
978 emission.SizeForLifetimeMarkers = EmitLifetimeStart(size, Alloc);
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +0000979 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000980 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +0000981 }
Chris Lattnerb781dc792008-05-08 05:58:21 +0000982 }
Chris Lattner03df1222007-06-02 04:53:11 +0000983 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000984 EnsureInsertPoint();
985
Anders Carlsson15949b32009-02-09 20:41:50 +0000986 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +0000987 // Save the stack.
John McCallad7c5c12011-02-08 08:22:06 +0000988 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +0000989
Anders Carlsson30032882008-12-12 07:38:43 +0000990 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +0000991 llvm::Value *V = Builder.CreateCall(F);
Mike Stump11289f42009-09-09 15:08:12 +0000992
Anders Carlsson30032882008-12-12 07:38:43 +0000993 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +0000994
995 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +0000996
John McCalla464ff92010-07-21 06:13:08 +0000997 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +0000998 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000999 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001000 }
Mike Stump11289f42009-09-09 15:08:12 +00001001
John McCall23c29fe2011-06-24 21:55:10 +00001002 llvm::Value *elementCount;
1003 QualType elementType;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001004 std::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +00001005
Chris Lattner2192fe52011-07-18 04:24:23 +00001006 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +00001007
1008 // Allocate memory for the array.
John McCall23c29fe2011-06-24 21:55:10 +00001009 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1010 vla->setAlignment(alignment.getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +00001011
John McCall23c29fe2011-06-24 21:55:10 +00001012 DeclPtr = vla;
Chris Lattner03df1222007-06-02 04:53:11 +00001013 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001014
Chris Lattner03df1222007-06-02 04:53:11 +00001015 llvm::Value *&DMEntry = LocalDeclMap[&D];
Craig Topper8a13c412014-05-21 05:09:00 +00001016 assert(!DMEntry && "Decl already exists in localdeclmap!");
Chris Lattner03df1222007-06-02 04:53:11 +00001017 DMEntry = DeclPtr;
John McCallc533cb72011-02-22 06:44:22 +00001018 emission.Address = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001019
1020 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +00001021 if (HaveInsertPoint())
1022 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001023 if (CGM.getCodeGenOpts().getDebugInfo()
1024 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001025 DI->setLocation(D.getLocation());
Rafael Espindola609f5d92013-03-26 18:41:47 +00001026 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001027 }
Devang Patel887e2152011-06-03 19:21:47 +00001028 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001029
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001030 if (D.hasAttr<AnnotateAttr>())
1031 EmitVarAnnotations(&D, emission.Address);
1032
John McCallc533cb72011-02-22 06:44:22 +00001033 return emission;
1034}
1035
1036/// Determines whether the given __block variable is potentially
1037/// captured by the given expression.
1038static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1039 // Skip the most common kinds of expressions that make
1040 // hierarchy-walking expensive.
1041 e = e->IgnoreParenCasts();
1042
1043 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1044 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +00001045 for (const auto &I : block->captures()) {
1046 if (I.getVariable() == &var)
John McCallc533cb72011-02-22 06:44:22 +00001047 return true;
1048 }
1049
1050 // No need to walk into the subexpressions.
1051 return false;
1052 }
1053
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001054 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1055 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001056 for (const auto *BI : CS->body())
1057 if (const auto *E = dyn_cast<Expr>(BI)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001058 if (isCapturedBy(var, E))
1059 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001060 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001061 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001062 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001063 for (const auto *I : DS->decls()) {
1064 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1065 const Expr *Init = VD->getInit();
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001066 if (Init && isCapturedBy(var, Init))
1067 return true;
1068 }
1069 }
1070 }
1071 else
1072 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1073 // Later, provide code to poke into statements for capture analysis.
1074 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001075 return false;
1076 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001077
Benjamin Kramer642f1732015-07-02 21:03:14 +00001078 for (const Stmt *SubStmt : e->children())
1079 if (isCapturedBy(var, cast<Expr>(SubStmt)))
John McCallc533cb72011-02-22 06:44:22 +00001080 return true;
1081
1082 return false;
1083}
1084
Douglas Gregor82e1af22011-07-01 21:08:19 +00001085/// \brief Determine whether the given initializer is trivial in the sense
1086/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001087bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001088 if (!Init)
1089 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001090
Douglas Gregor82e1af22011-07-01 21:08:19 +00001091 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1092 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1093 if (Constructor->isTrivial() &&
1094 Constructor->isDefaultConstructor() &&
1095 !Construct->requiresZeroInitialization())
1096 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001097
Douglas Gregor82e1af22011-07-01 21:08:19 +00001098 return false;
1099}
John McCallc533cb72011-02-22 06:44:22 +00001100void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001101 assert(emission.Variable && "emission was not valid!");
1102
John McCallc533cb72011-02-22 06:44:22 +00001103 // If this was emitted as a global constant, we're done.
1104 if (emission.wasEmittedAsGlobal()) return;
1105
John McCall9e2e22f2011-02-22 07:16:58 +00001106 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001107 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001108 QualType type = D.getType();
1109
Chris Lattner07eb7332007-07-12 00:39:48 +00001110 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001111 const Expr *Init = D.getInit();
1112
1113 // If we are at an unreachable point, we don't need to emit the initializer
1114 // unless it contains a label.
1115 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001116 if (!Init || !ContainsLabel(Init)) return;
1117 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001118 }
1119
John McCall73064872011-03-31 01:59:53 +00001120 // Initialize the structure of a __block variable.
1121 if (emission.IsByRef)
1122 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001123
Douglas Gregor82e1af22011-07-01 21:08:19 +00001124 if (isTrivialInitializer(Init))
1125 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001126
John McCall73064872011-03-31 01:59:53 +00001127 CharUnits alignment = emission.Alignment;
1128
John McCallc533cb72011-02-22 06:44:22 +00001129 // Check whether this is a byref variable that's potentially
1130 // captured and moved by its own initializer. If so, we'll need to
1131 // emit the initializer first, then copy into the variable.
1132 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1133
1134 llvm::Value *Loc =
1135 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1136
Craig Topper8a13c412014-05-21 05:09:00 +00001137 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001138 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001139 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smithdafff942012-01-14 04:30:29 +00001140 constant = CGM.EmitConstantInit(D, this);
Richard Smithfddd3842011-12-30 21:15:51 +00001141 }
1142
1143 if (!constant) {
Eli Friedmana0544d62011-12-03 04:14:32 +00001144 LValue lv = MakeAddrLValue(Loc, type, alignment);
John McCall1553b192011-06-16 04:16:24 +00001145 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001146 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001147 }
John McCall91ca10f2011-03-08 09:11:50 +00001148
Richard Smith2bcde3a2013-06-02 00:09:52 +00001149 if (!emission.IsConstantAggregate) {
1150 // For simple scalar/complex initialization, store the value directly.
1151 LValue lv = MakeAddrLValue(Loc, type, alignment);
1152 lv.setNonGC(true);
1153 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1154 }
1155
John McCallc533cb72011-02-22 06:44:22 +00001156 // If this is a simple aggregate initialization, we can optimize it
1157 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001158 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001159
John McCall91ca10f2011-03-08 09:11:50 +00001160 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001161 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001162 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001163
Chris Lattner2192fe52011-07-18 04:24:23 +00001164 llvm::Type *BP = Int8PtrTy;
John McCall91ca10f2011-03-08 09:11:50 +00001165 if (Loc->getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001166 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001167
John McCall91ca10f2011-03-08 09:11:50 +00001168 // If the initializer is all or mostly zeros, codegen with memset then do
1169 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001170 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001171 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall91ca10f2011-03-08 09:11:50 +00001172 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1173 alignment.getQuantity(), isVolatile);
Benjamin Kramer29f9a002012-08-27 22:07:02 +00001174 // Zero and undef don't require a stores.
1175 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall91ca10f2011-03-08 09:11:50 +00001176 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1177 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001178 }
John McCall91ca10f2011-03-08 09:11:50 +00001179 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001180 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001181 // memcpy from the global to the alloca.
Reid Kleckner453e0562014-10-08 01:07:54 +00001182 std::string Name = getStaticDeclName(CGM, D);
John McCall91ca10f2011-03-08 09:11:50 +00001183 llvm::GlobalVariable *GV =
1184 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001185 llvm::GlobalValue::PrivateLinkage,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001186 constant, Name);
John McCall91ca10f2011-03-08 09:11:50 +00001187 GV->setAlignment(alignment.getQuantity());
Eli Friedmanb8578422011-05-27 22:32:55 +00001188 GV->setUnnamedAddr(true);
Eric Christopher31ab1302011-08-23 22:38:00 +00001189
John McCall91ca10f2011-03-08 09:11:50 +00001190 llvm::Value *SrcPtr = GV;
1191 if (SrcPtr->getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001192 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001193
1194 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1195 isVolatile);
1196 }
1197}
1198
1199/// Emit an expression as an initializer for a variable at the given
1200/// location. The expression is not necessarily the normal
1201/// initializer for the variable, and the address is not necessarily
1202/// its normal location.
1203///
1204/// \param init the initializing expression
1205/// \param var the variable to act as if we're initializing
1206/// \param loc the address to initialize; its type is a pointer
1207/// to the LLVM mapping of the variable's type
1208/// \param alignment the alignment of the address
1209/// \param capturedByInit true if the variable is a __block variable
1210/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001211void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001212 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001213 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001214
1215 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001216 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001217 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001218 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001219 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001220 return;
1221 }
1222 switch (getEvaluationKind(type)) {
1223 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001224 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001225 return;
1226 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001227 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001228 if (capturedByInit)
1229 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001230 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001231 return;
1232 }
1233 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001234 if (type->isAtomicType()) {
1235 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1236 } else {
1237 // TODO: how can we delay here if D is captured by its initializer?
1238 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001239 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001240 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001241 AggValueSlot::IsNotAliased));
John McCalla8ec7eb2013-03-07 21:37:17 +00001242 }
John McCall47fb9502013-03-07 21:37:08 +00001243 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001244 }
John McCall47fb9502013-03-07 21:37:08 +00001245 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001246}
John McCallbd309292010-07-06 01:34:17 +00001247
John McCall82fe67b2011-07-09 01:37:26 +00001248/// Enter a destroy cleanup for the given local variable.
1249void CodeGenFunction::emitAutoVarTypeCleanup(
1250 const CodeGenFunction::AutoVarEmission &emission,
1251 QualType::DestructionKind dtorKind) {
1252 assert(dtorKind != QualType::DK_none);
1253
1254 // Note that for __block variables, we want to destroy the
1255 // original stack object, not the possibly forwarded object.
1256 llvm::Value *addr = emission.getObjectAddress(*this);
1257
1258 const VarDecl *var = emission.Variable;
1259 QualType type = var->getType();
1260
1261 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001262 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001263
1264 switch (dtorKind) {
1265 case QualType::DK_none:
1266 llvm_unreachable("no cleanup for trivially-destructible variable");
1267
1268 case QualType::DK_cxx_destructor:
1269 // If there's an NRVO flag on the emission, we need a different
1270 // cleanup.
1271 if (emission.NRVOFlag) {
1272 assert(!type->isArrayType());
1273 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1274 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1275 emission.NRVOFlag);
1276 return;
1277 }
1278 break;
1279
1280 case QualType::DK_objc_strong_lifetime:
1281 // Suppress cleanups for pseudo-strong variables.
1282 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001283
John McCall82fe67b2011-07-09 01:37:26 +00001284 // Otherwise, consider whether to use an EH cleanup or not.
1285 cleanupKind = getARCCleanupKind();
1286
1287 // Use the imprecise destroyer by default.
1288 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1289 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1290 break;
1291
1292 case QualType::DK_objc_weak_lifetime:
1293 break;
1294 }
1295
1296 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001297 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001298
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001299 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001300 // is being pushed as an EH cleanup.
1301 bool useEHCleanup = (cleanupKind & EHCleanup);
1302 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1303 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001304}
1305
John McCallc533cb72011-02-22 06:44:22 +00001306void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001307 assert(emission.Variable && "emission was not valid!");
1308
John McCallc533cb72011-02-22 06:44:22 +00001309 // If this was emitted as a global constant, we're done.
1310 if (emission.wasEmittedAsGlobal()) return;
1311
John McCall8c38d352012-04-13 18:44:05 +00001312 // If we don't have an insertion point, we're done. Sema prevents
1313 // us from jumping into any of these scopes anyway.
1314 if (!HaveInsertPoint()) return;
1315
John McCall9e2e22f2011-02-22 07:16:58 +00001316 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001317
Nadav Rotem1da30942013-03-23 06:43:35 +00001318 // Make sure we call @llvm.lifetime.end. This needs to happen
1319 // *last*, so the cleanup needs to be pushed *first*.
1320 if (emission.useLifetimeMarkers()) {
1321 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1322 emission.getAllocatedAddress(),
1323 emission.getSizeForLifetimeMarkers());
David Majnemerdc012fa2015-04-22 21:38:15 +00001324 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
1325 cleanup.setLifetimeMarker();
Nadav Rotem1da30942013-03-23 06:43:35 +00001326 }
1327
John McCall82fe67b2011-07-09 01:37:26 +00001328 // Check the type for a cleanup.
1329 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1330 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001331
John McCall1bd25562011-06-24 23:21:27 +00001332 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001333 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001334 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1335 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1336 }
1337
John McCallc533cb72011-02-22 06:44:22 +00001338 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001339 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001340 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001341
John McCallc533cb72011-02-22 06:44:22 +00001342 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001343 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001344
John McCalla729c622012-02-17 03:33:10 +00001345 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001346 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001347 }
Mike Stump626aecc2009-03-05 01:23:13 +00001348
John McCallc533cb72011-02-22 06:44:22 +00001349 // If this is a block variable, call _Block_object_destroy
1350 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001351 if (emission.IsByRef)
1352 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001353}
Chris Lattner53621a52007-06-13 20:44:40 +00001354
Peter Collingbourne1425b452012-01-26 03:33:36 +00001355CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001356CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1357 switch (kind) {
1358 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001359 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001360 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001361 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001362 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001363 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001364 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001365 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001366 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001367}
1368
John McCall12cc42a2013-02-01 05:11:40 +00001369/// pushEHDestroy - Push the standard destructor for the given type as
1370/// an EH-only cleanup.
1371void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1372 llvm::Value *addr, QualType type) {
1373 assert(dtorKind && "cannot push destructor for trivial type");
1374 assert(needsEHCleanup(dtorKind));
1375
1376 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1377}
1378
1379/// pushDestroy - Push the standard destructor for the given type as
1380/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001381void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1382 llvm::Value *addr, QualType type) {
1383 assert(dtorKind && "cannot push destructor for trivial type");
1384
1385 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1386 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1387 cleanupKind & EHCleanup);
1388}
1389
John McCall82fe67b2011-07-09 01:37:26 +00001390void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001391 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001392 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001393 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1394 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001395}
1396
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001397void CodeGenFunction::pushStackRestore(CleanupKind Kind, llvm::Value *SPMem) {
1398 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1399}
1400
Richard Smith736a9472013-06-12 20:42:33 +00001401void CodeGenFunction::pushLifetimeExtendedDestroy(
1402 CleanupKind cleanupKind, llvm::Value *addr, QualType type,
1403 Destroyer *destroyer, bool useEHCleanupForArray) {
1404 assert(!isInConditionalBranch() &&
1405 "performing lifetime extension from within conditional");
1406
1407 // Push an EH-only cleanup for the object now.
1408 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1409 // around in case a temporary's destructor throws an exception.
1410 if (cleanupKind & EHCleanup)
1411 EHStack.pushCleanup<DestroyObject>(
1412 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1413 destroyer, useEHCleanupForArray);
1414
1415 // Remember that we need to push a full cleanup for the object at the
1416 // end of the full-expression.
1417 pushCleanupAfterFullExpr<DestroyObject>(
1418 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1419}
1420
John McCall178360e2011-07-11 08:38:19 +00001421/// emitDestroy - Immediately perform the destruction of the given
1422/// object.
1423///
1424/// \param addr - the address of the object; a type*
1425/// \param type - the type of the object; if an array type, all
1426/// objects are destroyed in reverse order
1427/// \param destroyer - the function to call to destroy individual
1428/// elements
1429/// \param useEHCleanupForArray - whether an EH cleanup should be
1430/// used when destroying array elements, in case one of the
1431/// destructions throws an exception
John McCall82fe67b2011-07-09 01:37:26 +00001432void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001433 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001434 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001435 const ArrayType *arrayType = getContext().getAsArrayType(type);
1436 if (!arrayType)
1437 return destroyer(*this, addr, type);
1438
1439 llvm::Value *begin = addr;
1440 llvm::Value *length = emitArrayLength(arrayType, type, begin);
John McCall97eab0a2011-07-13 08:09:46 +00001441
1442 // Normally we have to check whether the array is zero-length.
1443 bool checkZeroLength = true;
1444
1445 // But if the array length is constant, we can suppress that.
1446 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1447 // ...and if it's constant zero, we can just skip the entire thing.
1448 if (constLength->isZero()) return;
1449 checkZeroLength = false;
1450 }
1451
John McCall82fe67b2011-07-09 01:37:26 +00001452 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall97eab0a2011-07-13 08:09:46 +00001453 emitArrayDestroy(begin, end, type, destroyer,
1454 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001455}
1456
John McCall178360e2011-07-11 08:38:19 +00001457/// emitArrayDestroy - Destroys all the elements of the given array,
1458/// beginning from last to first. The array cannot be zero-length.
1459///
1460/// \param begin - a type* denoting the first element of the array
1461/// \param end - a type* denoting one past the end of the array
1462/// \param type - the element type of the array
1463/// \param destroyer - the function to call to destroy elements
1464/// \param useEHCleanup - whether to push an EH cleanup to destroy
1465/// the remaining elements in case the destruction of a single
1466/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001467void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1468 llvm::Value *end,
1469 QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001470 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001471 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001472 bool useEHCleanup) {
John McCall82fe67b2011-07-09 01:37:26 +00001473 assert(!type->isArrayType());
1474
1475 // The basic structure here is a do-while loop, because we don't
1476 // need to check for the zero-element case.
1477 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1478 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1479
John McCall97eab0a2011-07-13 08:09:46 +00001480 if (checkZeroLength) {
1481 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1482 "arraydestroy.isempty");
1483 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1484 }
1485
John McCall82fe67b2011-07-09 01:37:26 +00001486 // Enter the loop body, making that address the current address.
1487 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1488 EmitBlock(bodyBB);
1489 llvm::PHINode *elementPast =
1490 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1491 elementPast->addIncoming(end, entryBB);
1492
1493 // Shift the address back by one element.
1494 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1495 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1496 "arraydestroy.element");
1497
John McCall178360e2011-07-11 08:38:19 +00001498 if (useEHCleanup)
1499 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1500
John McCall82fe67b2011-07-09 01:37:26 +00001501 // Perform the actual destruction there.
1502 destroyer(*this, element, type);
1503
John McCall178360e2011-07-11 08:38:19 +00001504 if (useEHCleanup)
1505 PopCleanupBlock();
1506
John McCall82fe67b2011-07-09 01:37:26 +00001507 // Check whether we've reached the end.
1508 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1509 Builder.CreateCondBr(done, doneBB, bodyBB);
1510 elementPast->addIncoming(element, Builder.GetInsertBlock());
1511
1512 // Done.
1513 EmitBlock(doneBB);
1514}
1515
John McCall178360e2011-07-11 08:38:19 +00001516/// Perform partial array destruction as if in an EH cleanup. Unlike
1517/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001518static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1519 llvm::Value *begin, llvm::Value *end,
1520 QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001521 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001522 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001523 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001524 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1525 // VLAs don't require a GEP index to walk into.
1526 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001527 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001528 type = arrayType->getElementType();
1529 }
John McCall97eab0a2011-07-13 08:09:46 +00001530
1531 if (arrayDepth) {
1532 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1533
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001534 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001535 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1536 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001537 }
1538
John McCall97eab0a2011-07-13 08:09:46 +00001539 // Destroy the array. We don't ever need an EH cleanup because we
1540 // assume that we're in an EH cleanup ourselves, so a throwing
1541 // destructor causes an immediate terminate.
1542 CGF.emitArrayDestroy(begin, end, type, destroyer,
1543 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001544}
1545
John McCall82fe67b2011-07-09 01:37:26 +00001546namespace {
John McCall178360e2011-07-11 08:38:19 +00001547 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1548 /// array destroy where the end pointer is regularly determined and
1549 /// does not need to be loaded from a local.
1550 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1551 llvm::Value *ArrayBegin;
1552 llvm::Value *ArrayEnd;
1553 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001554 CodeGenFunction::Destroyer *Destroyer;
John McCall178360e2011-07-11 08:38:19 +00001555 public:
1556 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1557 QualType elementType,
1558 CodeGenFunction::Destroyer *destroyer)
1559 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
Peter Collingbourne1425b452012-01-26 03:33:36 +00001560 ElementType(elementType), Destroyer(destroyer) {}
John McCall178360e2011-07-11 08:38:19 +00001561
Craig Topper4f12f102014-03-12 06:41:41 +00001562 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001563 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1564 ElementType, Destroyer);
1565 }
1566 };
1567
1568 /// IrregularPartialArrayDestroy - a cleanup which performs a
1569 /// partial array destroy where the end pointer is irregularly
1570 /// determined and must be loaded from a local.
1571 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001572 llvm::Value *ArrayBegin;
1573 llvm::Value *ArrayEndPointer;
1574 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001575 CodeGenFunction::Destroyer *Destroyer;
John McCall82fe67b2011-07-09 01:37:26 +00001576 public:
John McCall178360e2011-07-11 08:38:19 +00001577 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1578 llvm::Value *arrayEndPointer,
1579 QualType elementType,
1580 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001581 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
Peter Collingbourne1425b452012-01-26 03:33:36 +00001582 ElementType(elementType), Destroyer(destroyer) {}
John McCall82fe67b2011-07-09 01:37:26 +00001583
Craig Topper4f12f102014-03-12 06:41:41 +00001584 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001585 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001586 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1587 ElementType, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001588 }
1589 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001590}
John McCall82fe67b2011-07-09 01:37:26 +00001591
John McCall178360e2011-07-11 08:38:19 +00001592/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001593/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001594/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001595///
John McCall82fe67b2011-07-09 01:37:26 +00001596/// \param elementType - the immediate element type of the array;
1597/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001598void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall178360e2011-07-11 08:38:19 +00001599 llvm::Value *arrayEndPointer,
1600 QualType elementType,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001601 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001602 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1603 arrayBegin, arrayEndPointer,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001604 elementType, destroyer);
John McCall178360e2011-07-11 08:38:19 +00001605}
1606
1607/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1608/// already-constructed elements of the given array. The cleanup
1609/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001610///
John McCall178360e2011-07-11 08:38:19 +00001611/// \param elementType - the immediate element type of the array;
1612/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001613void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1614 llvm::Value *arrayEnd,
1615 QualType elementType,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001616 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001617 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001618 arrayBegin, arrayEnd,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001619 elementType, destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001620}
1621
Nadav Rotem1da30942013-03-23 06:43:35 +00001622/// Lazily declare the @llvm.lifetime.start intrinsic.
1623llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1624 if (LifetimeStartFn) return LifetimeStartFn;
1625 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1626 llvm::Intrinsic::lifetime_start);
1627 return LifetimeStartFn;
1628}
1629
1630/// Lazily declare the @llvm.lifetime.end intrinsic.
1631llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1632 if (LifetimeEndFn) return LifetimeEndFn;
1633 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1634 llvm::Intrinsic::lifetime_end);
1635 return LifetimeEndFn;
1636}
1637
John McCall31168b02011-06-15 23:02:42 +00001638namespace {
1639 /// A cleanup to perform a release of an object at the end of a
1640 /// function. This is used to balance out the incoming +1 of a
1641 /// ns_consumed argument when we can't reasonably do that just by
1642 /// not doing the initial retain for a __block argument.
1643 struct ConsumeARCParameter : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001644 ConsumeARCParameter(llvm::Value *param,
1645 ARCPreciseLifetime_t precise)
1646 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001647
1648 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001649 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001650
Craig Topper4f12f102014-03-12 06:41:41 +00001651 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001652 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001653 }
1654 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001655}
John McCall31168b02011-06-15 23:02:42 +00001656
Mike Stump11289f42009-09-09 15:08:12 +00001657/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001658/// for the specified parameter and set up LocalDeclMap.
Devang Patel68a15252011-03-03 20:13:15 +00001659void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001660 bool ArgIsPointer, unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001661 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001662 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001663 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001664
1665 Arg->setName(D.getName());
1666
Adrian Prantl51936dd2013-03-14 17:53:33 +00001667 QualType Ty = D.getType();
1668
John McCall147d0212011-02-22 22:38:33 +00001669 // Use better IR generation for certain implicit parameters.
1670 if (isa<ImplicitParamDecl>(D)) {
1671 // The only implicit argument a block has is its literal.
1672 if (BlockInfo) {
1673 LocalDeclMap[&D] = Arg;
Craig Topper8a13c412014-05-21 05:09:00 +00001674 llvm::Value *LocalAddr = nullptr;
Adrian Prantl51936dd2013-03-14 17:53:33 +00001675 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Adrian Prantl0f6df002013-03-29 19:20:35 +00001676 // Allocate a stack slot to let the debug info survive the RA.
Adrian Prantl51936dd2013-03-14 17:53:33 +00001677 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1678 D.getName() + ".addr");
1679 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1680 LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1681 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1682 LocalAddr = Builder.CreateLoad(Alloc);
1683 }
John McCall147d0212011-02-22 22:38:33 +00001684
1685 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001686 if (CGM.getCodeGenOpts().getDebugInfo()
1687 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001688 DI->setLocation(D.getLocation());
David Blaikie77bbb5f2014-08-08 17:10:14 +00001689 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, ArgNo,
1690 LocalAddr, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001691 }
John McCall147d0212011-02-22 22:38:33 +00001692 }
1693
1694 return;
1695 }
1696 }
1697
Chris Lattner53621a52007-06-13 20:44:40 +00001698 llvm::Value *DeclPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001699 bool DoStore = false;
1700 bool IsScalar = hasScalarEvaluationKind(Ty);
1701 CharUnits Align = getContext().getDeclAlign(&D);
1702 // If we already have a pointer to the argument, reuse the input pointer.
1703 if (ArgIsPointer) {
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001704 // If we have a prettier pointer type at this point, bitcast to that.
1705 unsigned AS = cast<llvm::PointerType>(Arg->getType())->getAddressSpace();
1706 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
1707 DeclPtr = Arg->getType() == IRTy ? Arg : Builder.CreateBitCast(Arg, IRTy,
1708 D.getName());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001709 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00001710 // Don't push a cleanup in a thunk for a method that will also emit a
1711 // cleanup.
1712 if (!IsScalar && !CurFuncIsThunk &&
Reid Kleckner739756c2013-12-04 19:23:12 +00001713 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001714 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1715 if (RD && RD->hasNonTrivialDestructor())
1716 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001717 }
Chris Lattner53621a52007-06-13 20:44:40 +00001718 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001719 // Otherwise, create a temporary to hold the value.
Eli Friedmaneadd3e82011-11-03 20:31:28 +00001720 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1721 D.getName() + ".addr");
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001722 Alloc->setAlignment(Align.getQuantity());
Eli Friedmaneadd3e82011-11-03 20:31:28 +00001723 DeclPtr = Alloc;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001724 DoStore = true;
1725 }
Mike Stump11289f42009-09-09 15:08:12 +00001726
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001727 LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
1728 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00001729 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001730 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1731 // We honor __attribute__((ns_consumed)) for types with lifetime.
1732 // For __strong, it's handled by just skipping the initial retain;
1733 // otherwise we have to balance out the initial +1 with an extra
1734 // cleanup to do the release at the end of the function.
1735 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1736
1737 // 'self' is always formally __strong, but if this is not an
1738 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001739 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001740 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1741 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001742 assert(lt == Qualifiers::OCL_Strong);
1743 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001744 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001745 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001746 lt = Qualifiers::OCL_ExplicitNone;
1747 }
1748
1749 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001750 if (!isConsumed) {
1751 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1752 // use objc_storeStrong(&dest, value) for retaining the
1753 // object. But first, store a null into 'dest' because
1754 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001755 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001756 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1757 EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001758 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001759 }
1760 else
John McCall31168b02011-06-15 23:02:42 +00001761 // Don't use objc_retainBlock for block pointers, because we
1762 // don't want to Block_copy something just because we got it
1763 // as a parameter.
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001764 Arg = EmitARCRetainNonBlock(Arg);
1765 }
John McCall31168b02011-06-15 23:02:42 +00001766 } else {
1767 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00001768 if (isConsumed) {
1769 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1770 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1771 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1772 precise);
1773 }
John McCall31168b02011-06-15 23:02:42 +00001774
1775 if (lt == Qualifiers::OCL_Weak) {
1776 EmitARCInitWeak(DeclPtr, Arg);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001777 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001778 }
1779 }
1780
1781 // Enter the cleanup scope.
1782 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1783 }
Chris Lattner53621a52007-06-13 20:44:40 +00001784 }
1785
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001786 // Store the initial value into the alloca.
1787 if (DoStore)
1788 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1789
Chris Lattner53621a52007-06-13 20:44:40 +00001790 llvm::Value *&DMEntry = LocalDeclMap[&D];
Craig Topper8a13c412014-05-21 05:09:00 +00001791 assert(!DMEntry && "Decl already exists in localdeclmap!");
Chris Lattner53621a52007-06-13 20:44:40 +00001792 DMEntry = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001793
1794 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001795 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001796 if (CGM.getCodeGenOpts().getDebugInfo()
1797 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001798 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1799 }
1800 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001801
1802 if (D.hasAttr<AnnotateAttr>())
1803 EmitVarAnnotations(&D, DeclPtr);
Chris Lattner53621a52007-06-13 20:44:40 +00001804}