blob: 7cf9cb2417b5cec165e71f24fb2d935dfa441128 [file] [log] [blame]
Chris Lattner84915fa2007-06-02 04:16:21 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner84915fa2007-06-02 04:16:21 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Decl nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000016#include "CGOpenCLRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CodeGenModule.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000018#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000019#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Anders Carlsson4c03d982008-08-25 01:38:19 +000021#include "clang/AST/DeclObjC.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000022#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000023#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000024#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000025#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/GlobalVariable.h"
28#include "llvm/IR/Intrinsics.h"
29#include "llvm/IR/Type.h"
Chris Lattner84915fa2007-06-02 04:16:21 +000030using namespace clang;
31using namespace CodeGen;
32
33
Chris Lattner1ad38f82007-06-09 01:20:56 +000034void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000035 switch (D.getKind()) {
Douglas Gregor19043f02010-04-23 02:02:43 +000036 case Decl::TranslationUnit:
37 case Decl::Namespace:
38 case Decl::UnresolvedUsingTypename:
39 case Decl::ClassTemplateSpecialization:
40 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000041 case Decl::VarTemplateSpecialization:
42 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000043 case Decl::TemplateTypeParm:
44 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000045 case Decl::NonTypeTemplateParm:
Douglas Gregor19043f02010-04-23 02:02:43 +000046 case Decl::CXXMethod:
47 case Decl::CXXConstructor:
48 case Decl::CXXDestructor:
49 case Decl::CXXConversion:
50 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000051 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000052 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000053 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000054 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000055 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000056 case Decl::ImplicitParam:
57 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000058 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000059 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000060 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000061 case Decl::TemplateTemplateParm:
62 case Decl::ObjCMethod:
63 case Decl::ObjCCategory:
64 case Decl::ObjCProtocol:
65 case Decl::ObjCInterface:
66 case Decl::ObjCCategoryImpl:
67 case Decl::ObjCImplementation:
68 case Decl::ObjCProperty:
69 case Decl::ObjCCompatibleAlias:
Abramo Bagnarad7340582010-06-05 05:09:32 +000070 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000071 case Decl::LinkageSpec:
72 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000073 case Decl::FileScopeAsm:
74 case Decl::Friend:
75 case Decl::FriendTemplate:
76 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000077 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000078 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000079 case Decl::UsingShadow:
David Blaikie83d382b2011-09-23 05:06:16 +000080 llvm_unreachable("Declaration should not be in declstmts!");
Chris Lattner84915fa2007-06-02 04:16:21 +000081 case Decl::Function: // void X();
Argyrios Kyrtzidis88e1b972008-10-15 00:42:39 +000082 case Decl::Record: // struct/union/class X;
Chris Lattner84915fa2007-06-02 04:16:21 +000083 case Decl::Enum: // enum X;
Mike Stump11289f42009-09-09 15:08:12 +000084 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis88e1b972008-10-15 00:42:39 +000085 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +000086 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +000087 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +000088 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +000089 case Decl::OMPThreadPrivate:
Michael Han84324352013-02-22 17:15:32 +000090 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +000091 // None of these decls require codegen support.
92 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +000093
David Blaikief121b932013-05-20 22:50:41 +000094 case Decl::NamespaceAlias:
95 if (CGDebugInfo *DI = getDebugInfo())
96 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
97 return;
David Blaikiebd483762013-05-20 04:58:53 +000098 case Decl::Using: // using X; [C++]
99 if (CGDebugInfo *DI = getDebugInfo())
100 DI->EmitUsingDecl(cast<UsingDecl>(D));
101 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000102 case Decl::UsingDirective: // using namespace X; [C++]
103 if (CGDebugInfo *DI = getDebugInfo())
104 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
105 return;
Daniel Dunbara7998072008-08-29 17:28:43 +0000106 case Decl::Var: {
107 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000108 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000109 "Should not see file-scope variables inside a function!");
John McCall1c9c3fd2010-10-15 04:57:14 +0000110 return EmitVarDecl(VD);
Chris Lattner84915fa2007-06-02 04:16:21 +0000111 }
Mike Stump11289f42009-09-09 15:08:12 +0000112
Richard Smithdda56e42011-04-15 14:24:37 +0000113 case Decl::Typedef: // typedef int X;
114 case Decl::TypeAlias: { // using X = int; [C++0x]
115 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000116 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000117
Anders Carlsson5d985f52008-12-20 21:51:53 +0000118 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000119 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000120 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000121 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000122}
Chris Lattner03df1222007-06-02 04:53:11 +0000123
John McCall1c9c3fd2010-10-15 04:57:14 +0000124/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000125/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000126void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000127 if (D.isStaticLocal()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000128 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000129 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000130
David Majnemer27d69db2014-04-28 22:17:59 +0000131 // FIXME: We need to force the emission/use of a guard variable for
132 // some variables even if we can constant-evaluate them because
133 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000134
John McCall1c9c3fd2010-10-15 04:57:14 +0000135 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000136 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000137
138 if (D.hasExternalStorage())
Lauro Ramos Venanciobada8d42008-02-16 22:30:38 +0000139 // Don't emit it now, allow it to be emitted lazily on its first use.
140 return;
Daniel Dunbar0ca16602009-04-14 02:25:56 +0000141
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000142 if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
143 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
144
145 assert(D.hasLocalStorage());
146 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000147}
148
Chris Lattnere99c1102009-12-05 08:22:11 +0000149static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
150 const char *Separator) {
151 CodeGenModule &CGM = CGF.CGM;
Richard Smith9c6890a2012-11-01 22:30:59 +0000152 if (CGF.getLangOpts().CPlusPlus) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000153 StringRef Name = CGM.getMangledName(&D);
Anders Carlssonea836bc2010-06-22 16:16:50 +0000154 return Name.str();
John McCall7ec50432010-03-19 23:29:14 +0000155 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000156
Chris Lattnere99c1102009-12-05 08:22:11 +0000157 std::string ContextName;
Fariborz Jahanian3a4ea9a2010-11-30 23:07:14 +0000158 if (!CGF.CurFuncDecl) {
159 // Better be in a block declared in global scope.
160 const NamedDecl *ND = cast<NamedDecl>(&D);
161 const DeclContext *DC = ND->getDeclContext();
Alp Toker0e64e0d2014-06-03 02:13:57 +0000162 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
163 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
Fariborz Jahanian3a4ea9a2010-11-30 23:07:14 +0000164 else
David Blaikie83d382b2011-09-23 05:06:16 +0000165 llvm_unreachable("Unknown context for block static var decl");
Fariborz Jahanian3a4ea9a2010-11-30 23:07:14 +0000166 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000167 StringRef Name = CGM.getMangledName(FD);
Anders Carlssonea836bc2010-06-22 16:16:50 +0000168 ContextName = Name.str();
John McCall7ec50432010-03-19 23:29:14 +0000169 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattnere99c1102009-12-05 08:22:11 +0000170 ContextName = CGF.CurFn->getName();
171 else
David Blaikie83d382b2011-09-23 05:06:16 +0000172 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000173
Chris Lattnere99c1102009-12-05 08:22:11 +0000174 return ContextName + Separator + D.getNameAsString();
175}
176
Eli Benderskycb399432014-03-24 22:05:38 +0000177llvm::Constant *
John McCall1c9c3fd2010-10-15 04:57:14 +0000178CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
179 const char *Separator,
180 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000181 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000182 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000183
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000184 // Use the label if the variable is renamed with the asm-label extension.
185 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000186 if (D.hasAttr<AsmLabelAttr>())
187 Name = CGM.getMangledName(&D);
188 else
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000189 Name = GetStaticDeclName(*this, D, Separator);
Nate Begemanfaae0812008-04-19 04:17:09 +0000190
Chris Lattner2192fe52011-07-18 04:24:23 +0000191 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000192 unsigned AddrSpace =
193 CGM.GetGlobalVarAddressSpace(&D, CGM.getContext().getTargetAddressSpace(Ty));
Anders Carlssone33eed52009-09-26 18:16:06 +0000194 llvm::GlobalVariable *GV =
195 new llvm::GlobalVariable(CGM.getModule(), LTy,
196 Ty.isConstant(getContext()), Linkage,
Craig Topper8a13c412014-05-21 05:09:00 +0000197 CGM.EmitNullConstant(D.getType()), Name, nullptr,
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000198 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000199 AddrSpace);
Ken Dyck160146e2010-01-27 17:10:57 +0000200 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Eli Friedman40a4bec2013-06-17 21:51:45 +0000201 CGM.setGlobalVisibility(GV, &D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000202
Richard Smithfd3834f2013-04-13 02:43:54 +0000203 if (D.getTLSKind())
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000204 CGM.setTLSMode(GV, D);
205
Eli Benderskycb399432014-03-24 22:05:38 +0000206 // Make sure the result is of the correct type.
207 unsigned ExpectedAddrSpace = CGM.getContext().getTargetAddressSpace(Ty);
208 if (AddrSpace != ExpectedAddrSpace) {
209 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
210 return llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
211 }
212
Anders Carlssone33eed52009-09-26 18:16:06 +0000213 return GV;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000214}
215
Richard Smith6331c402012-02-13 22:16:19 +0000216/// hasNontrivialDestruction - Determine whether a type's destruction is
217/// non-trivial. If so, and the variable uses static initialization, we must
218/// register its destructor to run on exit.
219static bool hasNontrivialDestruction(QualType T) {
220 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
221 return RD && !RD->hasTrivialDestructor();
222}
223
Chandler Carruth84537952012-03-30 19:44:53 +0000224/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
225/// global variable that has already been created for it. If the initializer
226/// has a different type than GV does, this may free GV and return a different
227/// one. Otherwise it just returns GV.
228llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000229CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000230 llvm::GlobalVariable *GV) {
231 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCall70013b62010-07-15 23:40:35 +0000232
Chris Lattnere99c1102009-12-05 08:22:11 +0000233 // If constant emission failed, then this should be a C++ static
234 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000235 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000236 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000237 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall68ff0372010-09-08 01:44:27 +0000238 else if (Builder.GetInsertBlock()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000239 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000240 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000241 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000242
Chandler Carruth84537952012-03-30 19:44:53 +0000243 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000244 }
Chandler Carruth84537952012-03-30 19:44:53 +0000245 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000246 }
John McCall70013b62010-07-15 23:40:35 +0000247
Chris Lattnere99c1102009-12-05 08:22:11 +0000248 // The initializer may differ in type from the global. Rewrite
249 // the global to match the initializer. (We have to do this
250 // because some types, like unions, can't be completely represented
251 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000252 if (GV->getType()->getElementType() != Init->getType()) {
253 llvm::GlobalVariable *OldGV = GV;
254
255 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
256 OldGV->isConstant(),
257 OldGV->getLinkage(), Init, "",
258 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000259 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000260 CGM.getContext().getTargetAddressSpace(D.getType()));
261 GV->setVisibility(OldGV->getVisibility());
Eric Christopher31ab1302011-08-23 22:38:00 +0000262
Chris Lattnere99c1102009-12-05 08:22:11 +0000263 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000264 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000265
Chris Lattnere99c1102009-12-05 08:22:11 +0000266 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000267 llvm::Constant *NewPtrForOldDecl =
268 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
269 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000270
Chris Lattnere99c1102009-12-05 08:22:11 +0000271 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000272 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000273 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000274
Chandler Carruth84537952012-03-30 19:44:53 +0000275 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
276 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000277
278 if (hasNontrivialDestruction(D.getType())) {
279 // We have a constant initializer, but a nontrivial destructor. We still
280 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000281 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000282 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000283 }
284
Chandler Carruth84537952012-03-30 19:44:53 +0000285 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000286}
287
John McCall1c9c3fd2010-10-15 04:57:14 +0000288void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000289 llvm::GlobalValue::LinkageTypes Linkage) {
Chandler Carruth84537952012-03-30 19:44:53 +0000290 llvm::Value *&DMEntry = LocalDeclMap[&D];
Craig Topper8a13c412014-05-21 05:09:00 +0000291 assert(!DMEntry && "Decl already exists in localdeclmap!");
Mike Stump11289f42009-09-09 15:08:12 +0000292
John McCallb88a5662012-03-30 21:00:39 +0000293 // Check to see if we already have a global variable for this
294 // declaration. This can happen when double-emitting function
295 // bodies, e.g. with complete and base constructors.
296 llvm::Constant *addr =
297 CGM.getStaticLocalDeclAddress(&D);
298
Eli Benderskycb399432014-03-24 22:05:38 +0000299 if (!addr)
300 addr = CreateStaticVarDecl(D, ".", Linkage);
Daniel Dunbara374e602009-02-25 19:45:19 +0000301
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000302 // Store into LocalDeclMap before generating initializer to handle
303 // circular references.
John McCallb88a5662012-03-30 21:00:39 +0000304 DMEntry = addr;
305 CGM.setStaticLocalDeclAddress(&D, addr);
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000306
John McCall4a39ab82010-05-04 20:45:42 +0000307 // We can't have a VLA here, but we can have a pointer to a VLA,
308 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000309 // Make sure to evaluate VLA bounds now so that we have them for later.
310 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000311 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000312
John McCallb88a5662012-03-30 21:00:39 +0000313 // Save the type in case adding the initializer forces a type change.
314 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000315
Eli Benderskycb399432014-03-24 22:05:38 +0000316 llvm::GlobalVariable *var =
317 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Chris Lattnere99c1102009-12-05 08:22:11 +0000318 // If this value has an initializer, emit it.
319 if (D.getInit())
John McCallb88a5662012-03-30 21:00:39 +0000320 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000321
John McCallb88a5662012-03-30 21:00:39 +0000322 var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000323
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000324 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000325 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000326
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000327 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000328 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000329
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000330 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000331 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000332
Chandler Carruth84537952012-03-30 19:44:53 +0000333 // We may have to cast the constant because of the initializer
334 // mismatch above.
335 //
336 // FIXME: It is really dangerous to store this in the map; if anyone
337 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000338 llvm::Constant *castedAddr =
339 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCallb88a5662012-03-30 21:00:39 +0000340 DMEntry = castedAddr;
341 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000342
343 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000344 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000345 if (DI &&
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000346 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000347 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000348 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000349 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000350}
Mike Stump11289f42009-09-09 15:08:12 +0000351
John McCall2b7fc382010-07-13 20:32:21 +0000352namespace {
John McCall82fe67b2011-07-09 01:37:26 +0000353 struct DestroyObject : EHScopeStack::Cleanup {
354 DestroyObject(llvm::Value *addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000355 CodeGenFunction::Destroyer *destroyer,
356 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000357 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000358 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000359
John McCall82fe67b2011-07-09 01:37:26 +0000360 llvm::Value *addr;
361 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000362 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000363 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000364
Craig Topper4f12f102014-03-12 06:41:41 +0000365 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000366 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000367 bool useEHCleanupForArray =
368 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000369
370 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000371 }
372 };
373
John McCall82fe67b2011-07-09 01:37:26 +0000374 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
375 DestroyNRVOVariable(llvm::Value *addr,
376 const CXXDestructorDecl *Dtor,
377 llvm::Value *NRVOFlag)
378 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000379
380 const CXXDestructorDecl *Dtor;
381 llvm::Value *NRVOFlag;
382 llvm::Value *Loc;
383
Craig Topper4f12f102014-03-12 06:41:41 +0000384 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000385 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000386 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000387
Craig Topper8a13c412014-05-21 05:09:00 +0000388 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000389 if (NRVO) {
390 // If we exited via NRVO, we skip the destructor call.
391 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
392 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
393 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
394 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
395 CGF.EmitBlock(RunDtorBB);
396 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000397
John McCall2b7fc382010-07-13 20:32:21 +0000398 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +0000399 /*ForVirtualBase=*/false,
400 /*Delegating=*/false,
401 Loc);
John McCall2b7fc382010-07-13 20:32:21 +0000402
403 if (NRVO) CGF.EmitBlock(SkipDtorBB);
404 }
405 };
John McCall2b7fc382010-07-13 20:32:21 +0000406
John McCallcda666c2010-07-21 07:22:38 +0000407 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000408 llvm::Value *Stack;
409 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000410 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000411 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000412 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
413 CGF.Builder.CreateCall(F, V);
414 }
415 };
416
John McCall1bd25562011-06-24 23:21:27 +0000417 struct ExtendGCLifetime : EHScopeStack::Cleanup {
418 const VarDecl &Var;
419 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
420
Craig Topper4f12f102014-03-12 06:41:41 +0000421 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000422 // Compute the address of the local variable, in case it's a
423 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000424 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
425 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000426 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
427 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000428 CGF.EmitExtendGCLifetime(value);
429 }
430 };
431
John McCallcda666c2010-07-21 07:22:38 +0000432 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000433 llvm::Constant *CleanupFn;
434 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000435 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000436
John McCalla464ff92010-07-21 06:13:08 +0000437 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000438 const VarDecl *Var)
439 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000440
Craig Topper4f12f102014-03-12 06:41:41 +0000441 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000442 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
443 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000444 // Compute the address of the local variable, in case it's a byref
445 // or something.
446 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
447
John McCalla464ff92010-07-21 06:13:08 +0000448 // In some cases, the type of the function argument will be different from
449 // the type of the pointer. An example of this is
450 // void f(void* arg);
451 // __attribute__((cleanup(f))) void *g;
452 //
453 // To fix this we insert a bitcast here.
454 QualType ArgTy = FnInfo.arg_begin()->type;
455 llvm::Value *Arg =
456 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
457
458 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000459 Args.add(RValue::get(Arg),
460 CGF.getContext().getPointerType(Var.getType()));
John McCalla464ff92010-07-21 06:13:08 +0000461 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
462 }
463 };
Nadav Rotem1da30942013-03-23 06:43:35 +0000464
465 /// A cleanup to call @llvm.lifetime.end.
466 class CallLifetimeEnd : public EHScopeStack::Cleanup {
467 llvm::Value *Addr;
468 llvm::Value *Size;
469 public:
470 CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
471 : Addr(addr), Size(size) {}
472
Craig Topper4f12f102014-03-12 06:41:41 +0000473 void Emit(CodeGenFunction &CGF, Flags flags) override {
Nadav Rotem1da30942013-03-23 06:43:35 +0000474 llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
475 CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
476 Size, castAddr)
477 ->setDoesNotThrow();
478 }
479 };
John McCalla464ff92010-07-21 06:13:08 +0000480}
481
John McCall31168b02011-06-15 23:02:42 +0000482/// EmitAutoVarWithLifetime - Does the setup required for an automatic
483/// variable with lifetime.
484static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
485 llvm::Value *addr,
486 Qualifiers::ObjCLifetime lifetime) {
487 switch (lifetime) {
488 case Qualifiers::OCL_None:
489 llvm_unreachable("present but none");
490
491 case Qualifiers::OCL_ExplicitNone:
492 // nothing to do
493 break;
494
495 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000496 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000497 (var.hasAttr<ObjCPreciseLifetimeAttr>()
498 ? CodeGenFunction::destroyARCStrongPrecise
499 : CodeGenFunction::destroyARCStrongImprecise);
500
501 CleanupKind cleanupKind = CGF.getARCCleanupKind();
502 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
503 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000504 break;
505 }
506 case Qualifiers::OCL_Autoreleasing:
507 // nothing to do
508 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000509
John McCall31168b02011-06-15 23:02:42 +0000510 case Qualifiers::OCL_Weak:
511 // __weak objects always get EH cleanups; otherwise, exceptions
512 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000513 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
514 CodeGenFunction::destroyARCWeak,
515 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000516 break;
517 }
518}
519
520static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
521 if (const Expr *e = dyn_cast<Expr>(s)) {
522 // Skip the most common kinds of expressions that make
523 // hierarchy-walking expensive.
524 s = e = e->IgnoreParenCasts();
525
526 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
527 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000528 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
529 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000530 for (const auto &I : block->captures()) {
531 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000532 return true;
533 }
534 }
John McCall31168b02011-06-15 23:02:42 +0000535 }
536
537 for (Stmt::const_child_range children = s->children(); children; ++children)
Fariborz Jahanian326701e2011-06-29 20:00:16 +0000538 // children might be null; as in missing decl or conditional of an if-stmt.
539 if ((*children) && isAccessedBy(var, *children))
John McCall31168b02011-06-15 23:02:42 +0000540 return true;
541
542 return false;
543}
544
545static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
546 if (!decl) return false;
547 if (!isa<VarDecl>(decl)) return false;
548 const VarDecl *var = cast<VarDecl>(decl);
549 return isAccessedBy(*var, e);
550}
551
John McCall1553b192011-06-16 04:16:24 +0000552static void drillIntoBlockVariable(CodeGenFunction &CGF,
553 LValue &lvalue,
554 const VarDecl *var) {
555 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
556}
557
John McCall31168b02011-06-15 23:02:42 +0000558void CodeGenFunction::EmitScalarInit(const Expr *init,
559 const ValueDecl *D,
John McCall1553b192011-06-16 04:16:24 +0000560 LValue lvalue,
561 bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000562 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000563 if (!lifetime) {
564 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000565 if (capturedByInit)
566 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnallfa35df62012-01-16 17:27:18 +0000567 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000568 return;
569 }
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000570
571 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
572 init = DIE->getExpr();
573
John McCall31168b02011-06-15 23:02:42 +0000574 // If we're emitting a value with lifetime, we have to do the
575 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000576 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
577 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000578 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000579 }
580 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000581
582 // We have to maintain the illusion that the variable is
583 // zero-initialized. If the variable might be accessed in its
584 // initializer, zero-initialize before running the initializer, then
585 // actually perform the initialization with an assign.
586 bool accessedByInit = false;
587 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000588 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000589 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000590 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000591 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000592 if (capturedByInit) {
593 // We can use a simple GEP for this because it can't have been
594 // moved yet.
John McCall1553b192011-06-16 04:16:24 +0000595 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
596 getByRefValueLLVMField(cast<VarDecl>(D))));
John McCall31168b02011-06-15 23:02:42 +0000597 }
598
Chris Lattner2192fe52011-07-18 04:24:23 +0000599 llvm::PointerType *ty
John McCall1553b192011-06-16 04:16:24 +0000600 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
John McCall31168b02011-06-15 23:02:42 +0000601 ty = cast<llvm::PointerType>(ty->getElementType());
602
603 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000604
John McCall31168b02011-06-15 23:02:42 +0000605 // If __weak, we want to use a barrier under certain conditions.
606 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000607 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000608
609 // Otherwise just do a simple store.
610 else
David Chisnallfa35df62012-01-16 17:27:18 +0000611 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000612 }
613
614 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000615 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000616
617 switch (lifetime) {
618 case Qualifiers::OCL_None:
619 llvm_unreachable("present but none");
620
621 case Qualifiers::OCL_ExplicitNone:
622 // nothing to do
623 value = EmitScalarExpr(init);
624 break;
625
626 case Qualifiers::OCL_Strong: {
627 value = EmitARCRetainScalarExpr(init);
628 break;
629 }
630
631 case Qualifiers::OCL_Weak: {
632 // No way to optimize a producing initializer into this. It's not
633 // worth optimizing for, because the value will immediately
634 // disappear in the common case.
635 value = EmitScalarExpr(init);
636
John McCall1553b192011-06-16 04:16:24 +0000637 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000638 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000639 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000640 else
John McCall1553b192011-06-16 04:16:24 +0000641 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000642 return;
643 }
644
645 case Qualifiers::OCL_Autoreleasing:
646 value = EmitARCRetainAutoreleaseScalarExpr(init);
647 break;
648 }
649
John McCall1553b192011-06-16 04:16:24 +0000650 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000651
652 // If the variable might have been accessed by its initializer, we
653 // might have to initialize with a barrier. We have to do this for
654 // both __weak and __strong, but __weak got filtered out above.
655 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000656 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000657 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000658 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000659 return;
660 }
661
David Chisnallfa35df62012-01-16 17:27:18 +0000662 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000663}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000664
John McCalld4631322011-06-17 06:42:21 +0000665/// EmitScalarInit - Initialize the given lvalue with the given object.
666void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
667 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
668 if (!lifetime)
David Chisnallfa35df62012-01-16 17:27:18 +0000669 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCalld4631322011-06-17 06:42:21 +0000670
671 switch (lifetime) {
672 case Qualifiers::OCL_None:
673 llvm_unreachable("present but none");
674
675 case Qualifiers::OCL_ExplicitNone:
676 // nothing to do
677 break;
678
679 case Qualifiers::OCL_Strong:
680 init = EmitARCRetain(lvalue.getType(), init);
681 break;
682
683 case Qualifiers::OCL_Weak:
684 // Initialize and then skip the primitive store.
685 EmitARCInitWeak(lvalue.getAddress(), init);
686 return;
687
688 case Qualifiers::OCL_Autoreleasing:
689 init = EmitARCRetainAutorelease(lvalue.getType(), init);
690 break;
691 }
692
David Chisnallfa35df62012-01-16 17:27:18 +0000693 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCalld4631322011-06-17 06:42:21 +0000694}
695
Chris Lattnerb85025f2010-12-01 02:05:19 +0000696/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
697/// non-zero parts of the specified initializer with equal or fewer than
698/// NumStores scalar stores.
699static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
700 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000701 // Zero and Undef never requires any extra stores.
702 if (isa<llvm::ConstantAggregateZero>(Init) ||
703 isa<llvm::ConstantPointerNull>(Init) ||
704 isa<llvm::UndefValue>(Init))
705 return true;
706 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
707 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
708 isa<llvm::ConstantExpr>(Init))
709 return Init->isNullValue() || NumStores--;
710
711 // See if we can emit each element.
712 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
713 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
714 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
715 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
716 return false;
717 }
718 return true;
719 }
Chris Lattner236b3572012-01-31 04:36:19 +0000720
721 if (llvm::ConstantDataSequential *CDS =
722 dyn_cast<llvm::ConstantDataSequential>(Init)) {
723 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
724 llvm::Constant *Elt = CDS->getElementAsConstant(i);
725 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
726 return false;
727 }
728 return true;
729 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000730
Chris Lattnerb85025f2010-12-01 02:05:19 +0000731 // Anything else is hard and scary.
732 return false;
733}
734
735/// emitStoresForInitAfterMemset - For inits that
736/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
737/// stores that would be required.
738static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000739 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000740 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
741 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000742
Chris Lattnere6af8862010-12-02 01:58:41 +0000743 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
744 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
745 isa<llvm::ConstantExpr>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000746 Builder.CreateStore(Init, Loc, isVolatile);
747 return;
748 }
749
750 if (llvm::ConstantDataSequential *CDS =
751 dyn_cast<llvm::ConstantDataSequential>(Init)) {
752 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
753 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000754
755 // If necessary, get a pointer to the element and emit it.
756 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
757 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
758 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000759 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000760 return;
761 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000762
Chris Lattnere6af8862010-12-02 01:58:41 +0000763 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
764 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000765
Chris Lattnere6af8862010-12-02 01:58:41 +0000766 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
767 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000768
769 // If necessary, get a pointer to the element and emit it.
770 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
771 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
772 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000773 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000774}
775
776
777/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
778/// plus some stores to initialize a local variable instead of using a memcpy
779/// from a constant global. It is beneficial to use memset if the global is all
780/// zeros, or mostly zeros and large.
781static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
782 uint64_t GlobalSize) {
783 // If a global is all zeros, always use a memset.
784 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
785
Chris Lattnerb85025f2010-12-01 02:05:19 +0000786 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
787 // do it if it will require 6 or fewer scalar stores.
788 // TODO: Should budget depends on the size? Avoiding a large global warrants
789 // plopping in more stores.
790 unsigned StoreBudget = 6;
791 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000792
793 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000794 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
795}
796
Nadav Rotem1da30942013-03-23 06:43:35 +0000797/// Should we use the LLVM lifetime intrinsics for the given local variable?
798static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
799 unsigned Size) {
Alexey Samsonov262f05b2013-04-02 13:19:46 +0000800 // Always emit lifetime markers in -fsanitize=use-after-scope mode.
801 if (CGF.getLangOpts().Sanitize.UseAfterScope)
802 return true;
Nadav Rotem1da30942013-03-23 06:43:35 +0000803 // For now, only in optimized builds.
804 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
805 return false;
806
807 // Limit the size of marked objects to 32 bytes. We don't want to increase
808 // compile time by marking tiny objects.
809 unsigned SizeThreshold = 32;
810
811 return Size > SizeThreshold;
812}
813
Chris Lattnerb85025f2010-12-01 02:05:19 +0000814
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000815/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000816/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000817/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000818void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
819 AutoVarEmission emission = EmitAutoVarAlloca(D);
820 EmitAutoVarInit(emission);
821 EmitAutoVarCleanups(emission);
822}
Chris Lattner03df1222007-06-02 04:53:11 +0000823
John McCallc533cb72011-02-22 06:44:22 +0000824/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000825/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +0000826CodeGenFunction::AutoVarEmission
827CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
828 QualType Ty = D.getType();
829
830 AutoVarEmission emission(D);
831
832 bool isByRef = D.hasAttr<BlocksAttr>();
833 emission.IsByRef = isByRef;
834
835 CharUnits alignment = getContext().getDeclAlign(&D);
836 emission.Alignment = alignment;
837
John McCall23c29fe2011-06-24 21:55:10 +0000838 // If the type is variably-modified, emit all the VLA sizes for it.
839 if (Ty->isVariablyModifiedType())
840 EmitVariablyModifiedType(Ty);
841
Chris Lattner03df1222007-06-02 04:53:11 +0000842 llvm::Value *DeclPtr;
Eli Friedmana682d392008-02-15 12:20:59 +0000843 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000844 bool NRVO = getLangOpts().ElideConstructors &&
845 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +0000846
Richard Smith2bcde3a2013-06-02 00:09:52 +0000847 // If this value is an array or struct with a statically determinable
848 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +0000849 //
850 // TODO: We should constant-evaluate the initializer of any variable,
851 // as long as it is initialized by a constant expression. Currently,
852 // isConstantInitializer produces wrong answers for structs with
853 // reference or bitfield members, and a few other cases, and checking
854 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +0000855 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
856 (D.isConstexpr() ||
857 ((Ty.isPODType(getContext()) ||
858 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
859 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +0000860
Rafael Espindola609f5d92013-03-26 18:41:47 +0000861 // If the variable's a const type, and it's neither an NRVO
862 // candidate nor a __block variable and has no mutable members,
863 // emit it as a global instead.
864 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
865 CGM.isTypeConstant(Ty, true)) {
866 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +0000867
Craig Topper8a13c412014-05-21 05:09:00 +0000868 emission.Address = nullptr; // signal this condition to later callbacks
Rafael Espindola609f5d92013-03-26 18:41:47 +0000869 assert(emission.wasEmittedAsGlobal());
870 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +0000871 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000872
Rafael Espindola609f5d92013-03-26 18:41:47 +0000873 // Otherwise, tell the initialization code that we're in this case.
874 emission.IsConstantAggregate = true;
875 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000876
Rafael Espindola609f5d92013-03-26 18:41:47 +0000877 // A normal fixed sized variable becomes an alloca in the entry block,
878 // unless it's an NRVO variable.
879 llvm::Type *LTy = ConvertTypeForMem(Ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000880
Rafael Espindola609f5d92013-03-26 18:41:47 +0000881 if (NRVO) {
882 // The named return value optimization: allocate this variable in the
883 // return slot, so that we can elide the copy when returning this
884 // variable (C++0x [class.copy]p34).
885 DeclPtr = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +0000886
Rafael Espindola609f5d92013-03-26 18:41:47 +0000887 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
888 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
889 // Create a flag that is used to indicate when the NRVO was applied
890 // to this variable. Set it to zero to indicate that NRVO was not
891 // applied.
892 llvm::Value *Zero = Builder.getFalse();
893 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
894 EnsureInsertPoint();
895 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +0000896
Rafael Espindola609f5d92013-03-26 18:41:47 +0000897 // Record the NRVO flag for this variable.
898 NRVOFlags[&D] = NRVOFlag;
899 emission.NRVOFlag = NRVOFlag;
Nadav Rotem1da30942013-03-23 06:43:35 +0000900 }
Douglas Gregor290c93e2010-05-15 06:46:45 +0000901 }
Chris Lattnerb781dc792008-05-08 05:58:21 +0000902 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000903 if (isByRef)
904 LTy = BuildByRefType(&D);
905
906 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
907 Alloc->setName(D.getName());
908
909 CharUnits allocaAlignment = alignment;
910 if (isByRef)
911 allocaAlignment = std::max(allocaAlignment,
John McCallc8e01702013-04-16 22:48:15 +0000912 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
Rafael Espindola609f5d92013-03-26 18:41:47 +0000913 Alloc->setAlignment(allocaAlignment.getQuantity());
914 DeclPtr = Alloc;
915
916 // Emit a lifetime intrinsic if meaningful. There's no point
917 // in doing this if we don't have a valid insertion point (?).
918 uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
919 if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
920 llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
921
922 emission.SizeForLifetimeMarkers = sizeV;
923 llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
924 Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
925 ->setDoesNotThrow();
926 } else {
927 assert(!emission.useLifetimeMarkers());
928 }
Chris Lattnerb781dc792008-05-08 05:58:21 +0000929 }
Chris Lattner03df1222007-06-02 04:53:11 +0000930 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000931 EnsureInsertPoint();
932
Anders Carlsson15949b32009-02-09 20:41:50 +0000933 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +0000934 // Save the stack.
John McCallad7c5c12011-02-08 08:22:06 +0000935 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +0000936
Anders Carlsson30032882008-12-12 07:38:43 +0000937 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
938 llvm::Value *V = Builder.CreateCall(F);
Mike Stump11289f42009-09-09 15:08:12 +0000939
Anders Carlsson30032882008-12-12 07:38:43 +0000940 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +0000941
942 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +0000943
John McCalla464ff92010-07-21 06:13:08 +0000944 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +0000945 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000946 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +0000947 }
Mike Stump11289f42009-09-09 15:08:12 +0000948
John McCall23c29fe2011-06-24 21:55:10 +0000949 llvm::Value *elementCount;
950 QualType elementType;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000951 std::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +0000952
Chris Lattner2192fe52011-07-18 04:24:23 +0000953 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +0000954
955 // Allocate memory for the array.
John McCall23c29fe2011-06-24 21:55:10 +0000956 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
957 vla->setAlignment(alignment.getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +0000958
John McCall23c29fe2011-06-24 21:55:10 +0000959 DeclPtr = vla;
Chris Lattner03df1222007-06-02 04:53:11 +0000960 }
Eli Friedmanf4084702008-12-20 23:11:59 +0000961
Chris Lattner03df1222007-06-02 04:53:11 +0000962 llvm::Value *&DMEntry = LocalDeclMap[&D];
Craig Topper8a13c412014-05-21 05:09:00 +0000963 assert(!DMEntry && "Decl already exists in localdeclmap!");
Chris Lattner03df1222007-06-02 04:53:11 +0000964 DMEntry = DeclPtr;
John McCallc533cb72011-02-22 06:44:22 +0000965 emission.Address = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +0000966
967 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +0000968 if (HaveInsertPoint())
969 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000970 if (CGM.getCodeGenOpts().getDebugInfo()
971 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +0000972 DI->setLocation(D.getLocation());
Rafael Espindola609f5d92013-03-26 18:41:47 +0000973 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +0000974 }
Devang Patel887e2152011-06-03 19:21:47 +0000975 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +0000976
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000977 if (D.hasAttr<AnnotateAttr>())
978 EmitVarAnnotations(&D, emission.Address);
979
John McCallc533cb72011-02-22 06:44:22 +0000980 return emission;
981}
982
983/// Determines whether the given __block variable is potentially
984/// captured by the given expression.
985static bool isCapturedBy(const VarDecl &var, const Expr *e) {
986 // Skip the most common kinds of expressions that make
987 // hierarchy-walking expensive.
988 e = e->IgnoreParenCasts();
989
990 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
991 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000992 for (const auto &I : block->captures()) {
993 if (I.getVariable() == &var)
John McCallc533cb72011-02-22 06:44:22 +0000994 return true;
995 }
996
997 // No need to walk into the subexpressions.
998 return false;
999 }
1000
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001001 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1002 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001003 for (const auto *BI : CS->body())
1004 if (const auto *E = dyn_cast<Expr>(BI)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001005 if (isCapturedBy(var, E))
1006 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001007 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001008 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001009 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001010 for (const auto *I : DS->decls()) {
1011 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1012 const Expr *Init = VD->getInit();
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001013 if (Init && isCapturedBy(var, Init))
1014 return true;
1015 }
1016 }
1017 }
1018 else
1019 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1020 // Later, provide code to poke into statements for capture analysis.
1021 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001022 return false;
1023 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001024
John McCallc533cb72011-02-22 06:44:22 +00001025 for (Stmt::const_child_range children = e->children(); children; ++children)
1026 if (isCapturedBy(var, cast<Expr>(*children)))
1027 return true;
1028
1029 return false;
1030}
1031
Douglas Gregor82e1af22011-07-01 21:08:19 +00001032/// \brief Determine whether the given initializer is trivial in the sense
1033/// that it requires no code to be generated.
1034static bool isTrivialInitializer(const Expr *Init) {
1035 if (!Init)
1036 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001037
Douglas Gregor82e1af22011-07-01 21:08:19 +00001038 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1039 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1040 if (Constructor->isTrivial() &&
1041 Constructor->isDefaultConstructor() &&
1042 !Construct->requiresZeroInitialization())
1043 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001044
Douglas Gregor82e1af22011-07-01 21:08:19 +00001045 return false;
1046}
John McCallc533cb72011-02-22 06:44:22 +00001047void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001048 assert(emission.Variable && "emission was not valid!");
1049
John McCallc533cb72011-02-22 06:44:22 +00001050 // If this was emitted as a global constant, we're done.
1051 if (emission.wasEmittedAsGlobal()) return;
1052
John McCall9e2e22f2011-02-22 07:16:58 +00001053 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001054 QualType type = D.getType();
1055
Chris Lattner07eb7332007-07-12 00:39:48 +00001056 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001057 const Expr *Init = D.getInit();
1058
1059 // If we are at an unreachable point, we don't need to emit the initializer
1060 // unless it contains a label.
1061 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001062 if (!Init || !ContainsLabel(Init)) return;
1063 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001064 }
1065
John McCall73064872011-03-31 01:59:53 +00001066 // Initialize the structure of a __block variable.
1067 if (emission.IsByRef)
1068 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001069
Douglas Gregor82e1af22011-07-01 21:08:19 +00001070 if (isTrivialInitializer(Init))
1071 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001072
John McCall73064872011-03-31 01:59:53 +00001073 CharUnits alignment = emission.Alignment;
1074
John McCallc533cb72011-02-22 06:44:22 +00001075 // Check whether this is a byref variable that's potentially
1076 // captured and moved by its own initializer. If so, we'll need to
1077 // emit the initializer first, then copy into the variable.
1078 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1079
1080 llvm::Value *Loc =
1081 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1082
Craig Topper8a13c412014-05-21 05:09:00 +00001083 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001084 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001085 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smithdafff942012-01-14 04:30:29 +00001086 constant = CGM.EmitConstantInit(D, this);
Richard Smithfddd3842011-12-30 21:15:51 +00001087 }
1088
1089 if (!constant) {
Eli Friedmana0544d62011-12-03 04:14:32 +00001090 LValue lv = MakeAddrLValue(Loc, type, alignment);
John McCall1553b192011-06-16 04:16:24 +00001091 lv.setNonGC(true);
1092 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1093 }
John McCall91ca10f2011-03-08 09:11:50 +00001094
Richard Smith2bcde3a2013-06-02 00:09:52 +00001095 if (!emission.IsConstantAggregate) {
1096 // For simple scalar/complex initialization, store the value directly.
1097 LValue lv = MakeAddrLValue(Loc, type, alignment);
1098 lv.setNonGC(true);
1099 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1100 }
1101
John McCallc533cb72011-02-22 06:44:22 +00001102 // If this is a simple aggregate initialization, we can optimize it
1103 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001104 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001105
John McCall91ca10f2011-03-08 09:11:50 +00001106 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001107 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001108 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001109
Chris Lattner2192fe52011-07-18 04:24:23 +00001110 llvm::Type *BP = Int8PtrTy;
John McCall91ca10f2011-03-08 09:11:50 +00001111 if (Loc->getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001112 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001113
John McCall91ca10f2011-03-08 09:11:50 +00001114 // If the initializer is all or mostly zeros, codegen with memset then do
1115 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001116 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001117 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall91ca10f2011-03-08 09:11:50 +00001118 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1119 alignment.getQuantity(), isVolatile);
Benjamin Kramer29f9a002012-08-27 22:07:02 +00001120 // Zero and undef don't require a stores.
1121 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall91ca10f2011-03-08 09:11:50 +00001122 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1123 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001124 }
John McCall91ca10f2011-03-08 09:11:50 +00001125 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001126 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001127 // memcpy from the global to the alloca.
1128 std::string Name = GetStaticDeclName(*this, D, ".");
1129 llvm::GlobalVariable *GV =
1130 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001131 llvm::GlobalValue::PrivateLinkage,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001132 constant, Name);
John McCall91ca10f2011-03-08 09:11:50 +00001133 GV->setAlignment(alignment.getQuantity());
Eli Friedmanb8578422011-05-27 22:32:55 +00001134 GV->setUnnamedAddr(true);
Eric Christopher31ab1302011-08-23 22:38:00 +00001135
John McCall91ca10f2011-03-08 09:11:50 +00001136 llvm::Value *SrcPtr = GV;
1137 if (SrcPtr->getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001138 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001139
1140 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1141 isVolatile);
1142 }
1143}
1144
1145/// Emit an expression as an initializer for a variable at the given
1146/// location. The expression is not necessarily the normal
1147/// initializer for the variable, and the address is not necessarily
1148/// its normal location.
1149///
1150/// \param init the initializing expression
1151/// \param var the variable to act as if we're initializing
1152/// \param loc the address to initialize; its type is a pointer
1153/// to the LLVM mapping of the variable's type
1154/// \param alignment the alignment of the address
1155/// \param capturedByInit true if the variable is a __block variable
1156/// whose address is potentially changed by the initializer
1157void CodeGenFunction::EmitExprAsInit(const Expr *init,
John McCall31168b02011-06-15 23:02:42 +00001158 const ValueDecl *D,
John McCall1553b192011-06-16 04:16:24 +00001159 LValue lvalue,
John McCall91ca10f2011-03-08 09:11:50 +00001160 bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001161 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001162
1163 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001164 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001165 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001166 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnallfa35df62012-01-16 17:27:18 +00001167 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001168 return;
1169 }
1170 switch (getEvaluationKind(type)) {
1171 case TEK_Scalar:
John McCall1553b192011-06-16 04:16:24 +00001172 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001173 return;
1174 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001175 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001176 if (capturedByInit)
1177 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall47fb9502013-03-07 21:37:08 +00001178 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1179 return;
1180 }
1181 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001182 if (type->isAtomicType()) {
1183 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1184 } else {
1185 // TODO: how can we delay here if D is captured by its initializer?
1186 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001187 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001188 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001189 AggValueSlot::IsNotAliased));
John McCalla8ec7eb2013-03-07 21:37:17 +00001190 }
John McCall47fb9502013-03-07 21:37:08 +00001191 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001192 }
John McCall47fb9502013-03-07 21:37:08 +00001193 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001194}
John McCallbd309292010-07-06 01:34:17 +00001195
John McCall82fe67b2011-07-09 01:37:26 +00001196/// Enter a destroy cleanup for the given local variable.
1197void CodeGenFunction::emitAutoVarTypeCleanup(
1198 const CodeGenFunction::AutoVarEmission &emission,
1199 QualType::DestructionKind dtorKind) {
1200 assert(dtorKind != QualType::DK_none);
1201
1202 // Note that for __block variables, we want to destroy the
1203 // original stack object, not the possibly forwarded object.
1204 llvm::Value *addr = emission.getObjectAddress(*this);
1205
1206 const VarDecl *var = emission.Variable;
1207 QualType type = var->getType();
1208
1209 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001210 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001211
1212 switch (dtorKind) {
1213 case QualType::DK_none:
1214 llvm_unreachable("no cleanup for trivially-destructible variable");
1215
1216 case QualType::DK_cxx_destructor:
1217 // If there's an NRVO flag on the emission, we need a different
1218 // cleanup.
1219 if (emission.NRVOFlag) {
1220 assert(!type->isArrayType());
1221 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1222 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1223 emission.NRVOFlag);
1224 return;
1225 }
1226 break;
1227
1228 case QualType::DK_objc_strong_lifetime:
1229 // Suppress cleanups for pseudo-strong variables.
1230 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001231
John McCall82fe67b2011-07-09 01:37:26 +00001232 // Otherwise, consider whether to use an EH cleanup or not.
1233 cleanupKind = getARCCleanupKind();
1234
1235 // Use the imprecise destroyer by default.
1236 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1237 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1238 break;
1239
1240 case QualType::DK_objc_weak_lifetime:
1241 break;
1242 }
1243
1244 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001245 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001246
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001247 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001248 // is being pushed as an EH cleanup.
1249 bool useEHCleanup = (cleanupKind & EHCleanup);
1250 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1251 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001252}
1253
John McCallc533cb72011-02-22 06:44:22 +00001254void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001255 assert(emission.Variable && "emission was not valid!");
1256
John McCallc533cb72011-02-22 06:44:22 +00001257 // If this was emitted as a global constant, we're done.
1258 if (emission.wasEmittedAsGlobal()) return;
1259
John McCall8c38d352012-04-13 18:44:05 +00001260 // If we don't have an insertion point, we're done. Sema prevents
1261 // us from jumping into any of these scopes anyway.
1262 if (!HaveInsertPoint()) return;
1263
John McCall9e2e22f2011-02-22 07:16:58 +00001264 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001265
Nadav Rotem1da30942013-03-23 06:43:35 +00001266 // Make sure we call @llvm.lifetime.end. This needs to happen
1267 // *last*, so the cleanup needs to be pushed *first*.
1268 if (emission.useLifetimeMarkers()) {
1269 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1270 emission.getAllocatedAddress(),
1271 emission.getSizeForLifetimeMarkers());
1272 }
1273
John McCall82fe67b2011-07-09 01:37:26 +00001274 // Check the type for a cleanup.
1275 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1276 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001277
John McCall1bd25562011-06-24 23:21:27 +00001278 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001279 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001280 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1281 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1282 }
1283
John McCallc533cb72011-02-22 06:44:22 +00001284 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001285 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001286 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001287
John McCallc533cb72011-02-22 06:44:22 +00001288 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001289 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001290
John McCalla729c622012-02-17 03:33:10 +00001291 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001292 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001293 }
Mike Stump626aecc2009-03-05 01:23:13 +00001294
John McCallc533cb72011-02-22 06:44:22 +00001295 // If this is a block variable, call _Block_object_destroy
1296 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001297 if (emission.IsByRef)
1298 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001299}
Chris Lattner53621a52007-06-13 20:44:40 +00001300
Peter Collingbourne1425b452012-01-26 03:33:36 +00001301CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001302CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1303 switch (kind) {
1304 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001305 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001306 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001307 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001308 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001309 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001310 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001311 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001312 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001313}
1314
John McCall12cc42a2013-02-01 05:11:40 +00001315/// pushEHDestroy - Push the standard destructor for the given type as
1316/// an EH-only cleanup.
1317void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1318 llvm::Value *addr, QualType type) {
1319 assert(dtorKind && "cannot push destructor for trivial type");
1320 assert(needsEHCleanup(dtorKind));
1321
1322 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1323}
1324
1325/// pushDestroy - Push the standard destructor for the given type as
1326/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001327void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1328 llvm::Value *addr, QualType type) {
1329 assert(dtorKind && "cannot push destructor for trivial type");
1330
1331 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1332 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1333 cleanupKind & EHCleanup);
1334}
1335
John McCall82fe67b2011-07-09 01:37:26 +00001336void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001337 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001338 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001339 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1340 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001341}
1342
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001343void CodeGenFunction::pushStackRestore(CleanupKind Kind, llvm::Value *SPMem) {
1344 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1345}
1346
Richard Smith736a9472013-06-12 20:42:33 +00001347void CodeGenFunction::pushLifetimeExtendedDestroy(
1348 CleanupKind cleanupKind, llvm::Value *addr, QualType type,
1349 Destroyer *destroyer, bool useEHCleanupForArray) {
1350 assert(!isInConditionalBranch() &&
1351 "performing lifetime extension from within conditional");
1352
1353 // Push an EH-only cleanup for the object now.
1354 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1355 // around in case a temporary's destructor throws an exception.
1356 if (cleanupKind & EHCleanup)
1357 EHStack.pushCleanup<DestroyObject>(
1358 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1359 destroyer, useEHCleanupForArray);
1360
1361 // Remember that we need to push a full cleanup for the object at the
1362 // end of the full-expression.
1363 pushCleanupAfterFullExpr<DestroyObject>(
1364 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1365}
1366
John McCall178360e2011-07-11 08:38:19 +00001367/// emitDestroy - Immediately perform the destruction of the given
1368/// object.
1369///
1370/// \param addr - the address of the object; a type*
1371/// \param type - the type of the object; if an array type, all
1372/// objects are destroyed in reverse order
1373/// \param destroyer - the function to call to destroy individual
1374/// elements
1375/// \param useEHCleanupForArray - whether an EH cleanup should be
1376/// used when destroying array elements, in case one of the
1377/// destructions throws an exception
John McCall82fe67b2011-07-09 01:37:26 +00001378void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001379 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001380 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001381 const ArrayType *arrayType = getContext().getAsArrayType(type);
1382 if (!arrayType)
1383 return destroyer(*this, addr, type);
1384
1385 llvm::Value *begin = addr;
1386 llvm::Value *length = emitArrayLength(arrayType, type, begin);
John McCall97eab0a2011-07-13 08:09:46 +00001387
1388 // Normally we have to check whether the array is zero-length.
1389 bool checkZeroLength = true;
1390
1391 // But if the array length is constant, we can suppress that.
1392 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1393 // ...and if it's constant zero, we can just skip the entire thing.
1394 if (constLength->isZero()) return;
1395 checkZeroLength = false;
1396 }
1397
John McCall82fe67b2011-07-09 01:37:26 +00001398 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall97eab0a2011-07-13 08:09:46 +00001399 emitArrayDestroy(begin, end, type, destroyer,
1400 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001401}
1402
John McCall178360e2011-07-11 08:38:19 +00001403/// emitArrayDestroy - Destroys all the elements of the given array,
1404/// beginning from last to first. The array cannot be zero-length.
1405///
1406/// \param begin - a type* denoting the first element of the array
1407/// \param end - a type* denoting one past the end of the array
1408/// \param type - the element type of the array
1409/// \param destroyer - the function to call to destroy elements
1410/// \param useEHCleanup - whether to push an EH cleanup to destroy
1411/// the remaining elements in case the destruction of a single
1412/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001413void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1414 llvm::Value *end,
1415 QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001416 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001417 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001418 bool useEHCleanup) {
John McCall82fe67b2011-07-09 01:37:26 +00001419 assert(!type->isArrayType());
1420
1421 // The basic structure here is a do-while loop, because we don't
1422 // need to check for the zero-element case.
1423 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1424 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1425
John McCall97eab0a2011-07-13 08:09:46 +00001426 if (checkZeroLength) {
1427 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1428 "arraydestroy.isempty");
1429 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1430 }
1431
John McCall82fe67b2011-07-09 01:37:26 +00001432 // Enter the loop body, making that address the current address.
1433 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1434 EmitBlock(bodyBB);
1435 llvm::PHINode *elementPast =
1436 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1437 elementPast->addIncoming(end, entryBB);
1438
1439 // Shift the address back by one element.
1440 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1441 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1442 "arraydestroy.element");
1443
John McCall178360e2011-07-11 08:38:19 +00001444 if (useEHCleanup)
1445 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1446
John McCall82fe67b2011-07-09 01:37:26 +00001447 // Perform the actual destruction there.
1448 destroyer(*this, element, type);
1449
John McCall178360e2011-07-11 08:38:19 +00001450 if (useEHCleanup)
1451 PopCleanupBlock();
1452
John McCall82fe67b2011-07-09 01:37:26 +00001453 // Check whether we've reached the end.
1454 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1455 Builder.CreateCondBr(done, doneBB, bodyBB);
1456 elementPast->addIncoming(element, Builder.GetInsertBlock());
1457
1458 // Done.
1459 EmitBlock(doneBB);
1460}
1461
John McCall178360e2011-07-11 08:38:19 +00001462/// Perform partial array destruction as if in an EH cleanup. Unlike
1463/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001464static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1465 llvm::Value *begin, llvm::Value *end,
1466 QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001467 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001468 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001469 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001470 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1471 // VLAs don't require a GEP index to walk into.
1472 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001473 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001474 type = arrayType->getElementType();
1475 }
John McCall97eab0a2011-07-13 08:09:46 +00001476
1477 if (arrayDepth) {
1478 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1479
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001480 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001481 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1482 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001483 }
1484
John McCall97eab0a2011-07-13 08:09:46 +00001485 // Destroy the array. We don't ever need an EH cleanup because we
1486 // assume that we're in an EH cleanup ourselves, so a throwing
1487 // destructor causes an immediate terminate.
1488 CGF.emitArrayDestroy(begin, end, type, destroyer,
1489 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001490}
1491
John McCall82fe67b2011-07-09 01:37:26 +00001492namespace {
John McCall178360e2011-07-11 08:38:19 +00001493 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1494 /// array destroy where the end pointer is regularly determined and
1495 /// does not need to be loaded from a local.
1496 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1497 llvm::Value *ArrayBegin;
1498 llvm::Value *ArrayEnd;
1499 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001500 CodeGenFunction::Destroyer *Destroyer;
John McCall178360e2011-07-11 08:38:19 +00001501 public:
1502 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1503 QualType elementType,
1504 CodeGenFunction::Destroyer *destroyer)
1505 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
Peter Collingbourne1425b452012-01-26 03:33:36 +00001506 ElementType(elementType), Destroyer(destroyer) {}
John McCall178360e2011-07-11 08:38:19 +00001507
Craig Topper4f12f102014-03-12 06:41:41 +00001508 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001509 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1510 ElementType, Destroyer);
1511 }
1512 };
1513
1514 /// IrregularPartialArrayDestroy - a cleanup which performs a
1515 /// partial array destroy where the end pointer is irregularly
1516 /// determined and must be loaded from a local.
1517 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001518 llvm::Value *ArrayBegin;
1519 llvm::Value *ArrayEndPointer;
1520 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001521 CodeGenFunction::Destroyer *Destroyer;
John McCall82fe67b2011-07-09 01:37:26 +00001522 public:
John McCall178360e2011-07-11 08:38:19 +00001523 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1524 llvm::Value *arrayEndPointer,
1525 QualType elementType,
1526 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001527 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
Peter Collingbourne1425b452012-01-26 03:33:36 +00001528 ElementType(elementType), Destroyer(destroyer) {}
John McCall82fe67b2011-07-09 01:37:26 +00001529
Craig Topper4f12f102014-03-12 06:41:41 +00001530 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001531 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001532 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1533 ElementType, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001534 }
1535 };
1536}
1537
John McCall178360e2011-07-11 08:38:19 +00001538/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001539/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001540/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001541///
John McCall82fe67b2011-07-09 01:37:26 +00001542/// \param elementType - the immediate element type of the array;
1543/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001544void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall178360e2011-07-11 08:38:19 +00001545 llvm::Value *arrayEndPointer,
1546 QualType elementType,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001547 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001548 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1549 arrayBegin, arrayEndPointer,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001550 elementType, destroyer);
John McCall178360e2011-07-11 08:38:19 +00001551}
1552
1553/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1554/// already-constructed elements of the given array. The cleanup
1555/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001556///
John McCall178360e2011-07-11 08:38:19 +00001557/// \param elementType - the immediate element type of the array;
1558/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001559void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1560 llvm::Value *arrayEnd,
1561 QualType elementType,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001562 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001563 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001564 arrayBegin, arrayEnd,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001565 elementType, destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001566}
1567
Nadav Rotem1da30942013-03-23 06:43:35 +00001568/// Lazily declare the @llvm.lifetime.start intrinsic.
1569llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1570 if (LifetimeStartFn) return LifetimeStartFn;
1571 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1572 llvm::Intrinsic::lifetime_start);
1573 return LifetimeStartFn;
1574}
1575
1576/// Lazily declare the @llvm.lifetime.end intrinsic.
1577llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1578 if (LifetimeEndFn) return LifetimeEndFn;
1579 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1580 llvm::Intrinsic::lifetime_end);
1581 return LifetimeEndFn;
1582}
1583
John McCall31168b02011-06-15 23:02:42 +00001584namespace {
1585 /// A cleanup to perform a release of an object at the end of a
1586 /// function. This is used to balance out the incoming +1 of a
1587 /// ns_consumed argument when we can't reasonably do that just by
1588 /// not doing the initial retain for a __block argument.
1589 struct ConsumeARCParameter : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001590 ConsumeARCParameter(llvm::Value *param,
1591 ARCPreciseLifetime_t precise)
1592 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001593
1594 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001595 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001596
Craig Topper4f12f102014-03-12 06:41:41 +00001597 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001598 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001599 }
1600 };
1601}
1602
Mike Stump11289f42009-09-09 15:08:12 +00001603/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001604/// for the specified parameter and set up LocalDeclMap.
Devang Patel68a15252011-03-03 20:13:15 +00001605void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001606 bool ArgIsPointer, unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001607 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001608 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001609 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001610
1611 Arg->setName(D.getName());
1612
Adrian Prantl51936dd2013-03-14 17:53:33 +00001613 QualType Ty = D.getType();
1614
John McCall147d0212011-02-22 22:38:33 +00001615 // Use better IR generation for certain implicit parameters.
1616 if (isa<ImplicitParamDecl>(D)) {
1617 // The only implicit argument a block has is its literal.
1618 if (BlockInfo) {
1619 LocalDeclMap[&D] = Arg;
Craig Topper8a13c412014-05-21 05:09:00 +00001620 llvm::Value *LocalAddr = nullptr;
Adrian Prantl51936dd2013-03-14 17:53:33 +00001621 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Adrian Prantl0f6df002013-03-29 19:20:35 +00001622 // Allocate a stack slot to let the debug info survive the RA.
Adrian Prantl51936dd2013-03-14 17:53:33 +00001623 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1624 D.getName() + ".addr");
1625 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1626 LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1627 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1628 LocalAddr = Builder.CreateLoad(Alloc);
1629 }
John McCall147d0212011-02-22 22:38:33 +00001630
1631 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001632 if (CGM.getCodeGenOpts().getDebugInfo()
1633 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001634 DI->setLocation(D.getLocation());
Adrian Prantl51936dd2013-03-14 17:53:33 +00001635 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, LocalAddr, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001636 }
John McCall147d0212011-02-22 22:38:33 +00001637 }
1638
1639 return;
1640 }
1641 }
1642
Chris Lattner53621a52007-06-13 20:44:40 +00001643 llvm::Value *DeclPtr;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001644 bool DoStore = false;
1645 bool IsScalar = hasScalarEvaluationKind(Ty);
1646 CharUnits Align = getContext().getDeclAlign(&D);
1647 // If we already have a pointer to the argument, reuse the input pointer.
1648 if (ArgIsPointer) {
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001649 // If we have a prettier pointer type at this point, bitcast to that.
1650 unsigned AS = cast<llvm::PointerType>(Arg->getType())->getAddressSpace();
1651 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
1652 DeclPtr = Arg->getType() == IRTy ? Arg : Builder.CreateBitCast(Arg, IRTy,
1653 D.getName());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001654 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001655 if (!IsScalar &&
Reid Kleckner739756c2013-12-04 19:23:12 +00001656 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001657 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1658 if (RD && RD->hasNonTrivialDestructor())
1659 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001660 }
Chris Lattner53621a52007-06-13 20:44:40 +00001661 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001662 // Otherwise, create a temporary to hold the value.
Eli Friedmaneadd3e82011-11-03 20:31:28 +00001663 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1664 D.getName() + ".addr");
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001665 Alloc->setAlignment(Align.getQuantity());
Eli Friedmaneadd3e82011-11-03 20:31:28 +00001666 DeclPtr = Alloc;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001667 DoStore = true;
1668 }
Mike Stump11289f42009-09-09 15:08:12 +00001669
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001670 LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
1671 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00001672 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001673 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1674 // We honor __attribute__((ns_consumed)) for types with lifetime.
1675 // For __strong, it's handled by just skipping the initial retain;
1676 // otherwise we have to balance out the initial +1 with an extra
1677 // cleanup to do the release at the end of the function.
1678 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1679
1680 // 'self' is always formally __strong, but if this is not an
1681 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001682 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001683 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1684 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001685 assert(lt == Qualifiers::OCL_Strong);
1686 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001687 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001688 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001689 lt = Qualifiers::OCL_ExplicitNone;
1690 }
1691
1692 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001693 if (!isConsumed) {
1694 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1695 // use objc_storeStrong(&dest, value) for retaining the
1696 // object. But first, store a null into 'dest' because
1697 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001698 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001699 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1700 EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001701 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001702 }
1703 else
John McCall31168b02011-06-15 23:02:42 +00001704 // Don't use objc_retainBlock for block pointers, because we
1705 // don't want to Block_copy something just because we got it
1706 // as a parameter.
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001707 Arg = EmitARCRetainNonBlock(Arg);
1708 }
John McCall31168b02011-06-15 23:02:42 +00001709 } else {
1710 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00001711 if (isConsumed) {
1712 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1713 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1714 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1715 precise);
1716 }
John McCall31168b02011-06-15 23:02:42 +00001717
1718 if (lt == Qualifiers::OCL_Weak) {
1719 EmitARCInitWeak(DeclPtr, Arg);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001720 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001721 }
1722 }
1723
1724 // Enter the cleanup scope.
1725 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1726 }
Chris Lattner53621a52007-06-13 20:44:40 +00001727 }
1728
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001729 // Store the initial value into the alloca.
1730 if (DoStore)
1731 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1732
Chris Lattner53621a52007-06-13 20:44:40 +00001733 llvm::Value *&DMEntry = LocalDeclMap[&D];
Craig Topper8a13c412014-05-21 05:09:00 +00001734 assert(!DMEntry && "Decl already exists in localdeclmap!");
Chris Lattner53621a52007-06-13 20:44:40 +00001735 DMEntry = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001736
1737 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001738 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001739 if (CGM.getCodeGenOpts().getDebugInfo()
1740 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001741 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1742 }
1743 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001744
1745 if (D.hasAttr<AnnotateAttr>())
1746 EmitVarAnnotations(&D, DeclPtr);
Chris Lattner53621a52007-06-13 20:44:40 +00001747}