blob: 8543ca8eef46d35148d36310e0f70d1e43450310 [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
Sanjiv Gupta18de6242008-05-30 10:30:31 +000014#include "CGDebugInfo.h"
Chris Lattner84915fa2007-06-02 04:16:21 +000015#include "CodeGenFunction.h"
Anders Carlssonf94cd1f2007-10-17 00:52:43 +000016#include "CodeGenModule.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000017#include "CGOpenCLRuntime.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"
Chandler Carruth85098242010-06-15 23:19:56 +000024#include "clang/Frontend/CodeGenOptions.h"
Anders Carlssonf94cd1f2007-10-17 00:52:43 +000025#include "llvm/GlobalVariable.h"
Anders Carlsson30032882008-12-12 07:38:43 +000026#include "llvm/Intrinsics.h"
Mike Stump97d01d52009-03-04 03:23:46 +000027#include "llvm/Target/TargetData.h"
Chris Lattner53621a52007-06-13 20:44:40 +000028#include "llvm/Type.h"
Chris Lattner84915fa2007-06-02 04:16:21 +000029using namespace clang;
30using namespace CodeGen;
31
32
Chris Lattner1ad38f82007-06-09 01:20:56 +000033void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000034 switch (D.getKind()) {
Douglas Gregor19043f02010-04-23 02:02:43 +000035 case Decl::TranslationUnit:
36 case Decl::Namespace:
37 case Decl::UnresolvedUsingTypename:
38 case Decl::ClassTemplateSpecialization:
39 case Decl::ClassTemplatePartialSpecialization:
40 case Decl::TemplateTypeParm:
41 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000042 case Decl::NonTypeTemplateParm:
Douglas Gregor19043f02010-04-23 02:02:43 +000043 case Decl::CXXMethod:
44 case Decl::CXXConstructor:
45 case Decl::CXXDestructor:
46 case Decl::CXXConversion:
47 case Decl::Field:
Francois Pichetdf946c32010-11-21 06:49:41 +000048 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000049 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000050 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000051 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000052 case Decl::ImplicitParam:
53 case Decl::ClassTemplate:
54 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000055 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000056 case Decl::TemplateTemplateParm:
57 case Decl::ObjCMethod:
58 case Decl::ObjCCategory:
59 case Decl::ObjCProtocol:
60 case Decl::ObjCInterface:
61 case Decl::ObjCCategoryImpl:
62 case Decl::ObjCImplementation:
63 case Decl::ObjCProperty:
64 case Decl::ObjCCompatibleAlias:
Abramo Bagnarad7340582010-06-05 05:09:32 +000065 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000066 case Decl::LinkageSpec:
67 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000068 case Decl::FileScopeAsm:
69 case Decl::Friend:
70 case Decl::FriendTemplate:
71 case Decl::Block:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000072 case Decl::ClassScopeFunctionSpecialization:
David Blaikie83d382b2011-09-23 05:06:16 +000073 llvm_unreachable("Declaration should not be in declstmts!");
Chris Lattner84915fa2007-06-02 04:16:21 +000074 case Decl::Function: // void X();
Argyrios Kyrtzidis88e1b972008-10-15 00:42:39 +000075 case Decl::Record: // struct/union/class X;
Chris Lattner84915fa2007-06-02 04:16:21 +000076 case Decl::Enum: // enum X;
Mike Stump11289f42009-09-09 15:08:12 +000077 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis88e1b972008-10-15 00:42:39 +000078 case Decl::CXXRecord: // struct/union/class X; [C++]
Daniel Dunbar785406b2009-11-23 00:07:06 +000079 case Decl::Using: // using X; [C++]
80 case Decl::UsingShadow:
81 case Decl::UsingDirective: // using namespace X; [C++]
Douglas Gregor19043f02010-04-23 02:02:43 +000082 case Decl::NamespaceAlias:
Anders Carlssonce2cd012009-12-03 17:26:31 +000083 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +000084 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +000085 case Decl::Import:
Chris Lattner84915fa2007-06-02 04:16:21 +000086 // None of these decls require codegen support.
87 return;
Mike Stump11289f42009-09-09 15:08:12 +000088
Daniel Dunbara7998072008-08-29 17:28:43 +000089 case Decl::Var: {
90 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +000091 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +000092 "Should not see file-scope variables inside a function!");
John McCall1c9c3fd2010-10-15 04:57:14 +000093 return EmitVarDecl(VD);
Chris Lattner84915fa2007-06-02 04:16:21 +000094 }
Mike Stump11289f42009-09-09 15:08:12 +000095
Richard Smithdda56e42011-04-15 14:24:37 +000096 case Decl::Typedef: // typedef int X;
97 case Decl::TypeAlias: { // using X = int; [C++0x]
98 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +000099 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000100
Anders Carlsson5d985f52008-12-20 21:51:53 +0000101 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000102 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000103 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000104 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000105}
Chris Lattner03df1222007-06-02 04:53:11 +0000106
John McCall1c9c3fd2010-10-15 04:57:14 +0000107/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000108/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000109void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Chris Lattner03df1222007-06-02 04:53:11 +0000110 switch (D.getStorageClass()) {
John McCall8e7d6562010-08-26 03:08:43 +0000111 case SC_None:
112 case SC_Auto:
113 case SC_Register:
John McCall1c9c3fd2010-10-15 04:57:14 +0000114 return EmitAutoVarDecl(D);
John McCall8e7d6562010-08-26 03:08:43 +0000115 case SC_Static: {
Eric Christopher31ab1302011-08-23 22:38:00 +0000116 llvm::GlobalValue::LinkageTypes Linkage =
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000117 llvm::GlobalValue::InternalLinkage;
118
John McCall7cb02202010-05-25 04:30:21 +0000119 // If the function definition has some sort of weak linkage, its
120 // static variables should also be weak so that they get properly
121 // uniqued. We can't do this in C, though, because there's no
122 // standard way to agree on which variables are the same (i.e.
123 // there's no mangling).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000124 if (getContext().getLangOpts().CPlusPlus)
John McCall7cb02202010-05-25 04:30:21 +0000125 if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
126 Linkage = CurFn->getLinkage();
Eric Christopher31ab1302011-08-23 22:38:00 +0000127
John McCall1c9c3fd2010-10-15 04:57:14 +0000128 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000129 }
John McCall8e7d6562010-08-26 03:08:43 +0000130 case SC_Extern:
131 case SC_PrivateExtern:
Lauro Ramos Venanciobada8d42008-02-16 22:30:38 +0000132 // Don't emit it now, allow it to be emitted lazily on its first use.
133 return;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000134 case SC_OpenCLWorkGroupLocal:
135 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
Chris Lattner03df1222007-06-02 04:53:11 +0000136 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +0000137
David Blaikie83d382b2011-09-23 05:06:16 +0000138 llvm_unreachable("Unknown storage class");
Chris Lattner03df1222007-06-02 04:53:11 +0000139}
140
Chris Lattnere99c1102009-12-05 08:22:11 +0000141static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
142 const char *Separator) {
143 CodeGenModule &CGM = CGF.CGM;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000144 if (CGF.getContext().getLangOpts().CPlusPlus) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000145 StringRef Name = CGM.getMangledName(&D);
Anders Carlssonea836bc2010-06-22 16:16:50 +0000146 return Name.str();
John McCall7ec50432010-03-19 23:29:14 +0000147 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000148
Chris Lattnere99c1102009-12-05 08:22:11 +0000149 std::string ContextName;
Fariborz Jahanian3a4ea9a2010-11-30 23:07:14 +0000150 if (!CGF.CurFuncDecl) {
151 // Better be in a block declared in global scope.
152 const NamedDecl *ND = cast<NamedDecl>(&D);
153 const DeclContext *DC = ND->getDeclContext();
154 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
155 MangleBuffer Name;
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000156 CGM.getBlockMangledName(GlobalDecl(), Name, BD);
Fariborz Jahanian3a4ea9a2010-11-30 23:07:14 +0000157 ContextName = Name.getString();
158 }
159 else
David Blaikie83d382b2011-09-23 05:06:16 +0000160 llvm_unreachable("Unknown context for block static var decl");
Fariborz Jahanian3a4ea9a2010-11-30 23:07:14 +0000161 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000162 StringRef Name = CGM.getMangledName(FD);
Anders Carlssonea836bc2010-06-22 16:16:50 +0000163 ContextName = Name.str();
John McCall7ec50432010-03-19 23:29:14 +0000164 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattnere99c1102009-12-05 08:22:11 +0000165 ContextName = CGF.CurFn->getName();
166 else
David Blaikie83d382b2011-09-23 05:06:16 +0000167 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000168
Chris Lattnere99c1102009-12-05 08:22:11 +0000169 return ContextName + Separator + D.getNameAsString();
170}
171
Chandler Carruth84537952012-03-30 19:44:53 +0000172llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000173CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
174 const char *Separator,
175 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000176 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000177 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000178
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000179 // Use the label if the variable is renamed with the asm-label extension.
180 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000181 if (D.hasAttr<AsmLabelAttr>())
182 Name = CGM.getMangledName(&D);
183 else
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000184 Name = GetStaticDeclName(*this, D, Separator);
Nate Begemanfaae0812008-04-19 04:17:09 +0000185
Chris Lattner2192fe52011-07-18 04:24:23 +0000186 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Anders Carlssone33eed52009-09-26 18:16:06 +0000187 llvm::GlobalVariable *GV =
188 new llvm::GlobalVariable(CGM.getModule(), LTy,
189 Ty.isConstant(getContext()), Linkage,
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000190 CGM.EmitNullConstant(D.getType()), Name, 0,
191 llvm::GlobalVariable::NotThreadLocal,
Chandler Carruth84537952012-03-30 19:44:53 +0000192 CGM.getContext().getTargetAddressSpace(Ty));
Ken Dyck160146e2010-01-27 17:10:57 +0000193 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
John McCall8e7cb6d2010-11-02 21:04:24 +0000194 if (Linkage != llvm::GlobalValue::InternalLinkage)
195 GV->setVisibility(CurFn->getVisibility());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000196
197 if (D.isThreadSpecified())
198 CGM.setTLSMode(GV, D);
199
Anders Carlssone33eed52009-09-26 18:16:06 +0000200 return GV;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000201}
202
Richard Smith6331c402012-02-13 22:16:19 +0000203/// hasNontrivialDestruction - Determine whether a type's destruction is
204/// non-trivial. If so, and the variable uses static initialization, we must
205/// register its destructor to run on exit.
206static bool hasNontrivialDestruction(QualType T) {
207 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
208 return RD && !RD->hasTrivialDestructor();
209}
210
Chandler Carruth84537952012-03-30 19:44:53 +0000211/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
212/// global variable that has already been created for it. If the initializer
213/// has a different type than GV does, this may free GV and return a different
214/// one. Otherwise it just returns GV.
215llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000216CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000217 llvm::GlobalVariable *GV) {
218 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCall70013b62010-07-15 23:40:35 +0000219
Chris Lattnere99c1102009-12-05 08:22:11 +0000220 // If constant emission failed, then this should be a C++ static
221 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000222 if (!Init) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000223 if (!getContext().getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000224 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall68ff0372010-09-08 01:44:27 +0000225 else if (Builder.GetInsertBlock()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000226 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000227 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000228 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000229
Chandler Carruth84537952012-03-30 19:44:53 +0000230 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000231 }
Chandler Carruth84537952012-03-30 19:44:53 +0000232 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000233 }
John McCall70013b62010-07-15 23:40:35 +0000234
Chris Lattnere99c1102009-12-05 08:22:11 +0000235 // The initializer may differ in type from the global. Rewrite
236 // the global to match the initializer. (We have to do this
237 // because some types, like unions, can't be completely represented
238 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000239 if (GV->getType()->getElementType() != Init->getType()) {
240 llvm::GlobalVariable *OldGV = GV;
241
242 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
243 OldGV->isConstant(),
244 OldGV->getLinkage(), Init, "",
245 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000246 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000247 CGM.getContext().getTargetAddressSpace(D.getType()));
248 GV->setVisibility(OldGV->getVisibility());
Eric Christopher31ab1302011-08-23 22:38:00 +0000249
Chris Lattnere99c1102009-12-05 08:22:11 +0000250 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000251 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000252
Chris Lattnere99c1102009-12-05 08:22:11 +0000253 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000254 llvm::Constant *NewPtrForOldDecl =
255 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
256 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000257
Chris Lattnere99c1102009-12-05 08:22:11 +0000258 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000259 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000260 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000261
Chandler Carruth84537952012-03-30 19:44:53 +0000262 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
263 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000264
265 if (hasNontrivialDestruction(D.getType())) {
266 // We have a constant initializer, but a nontrivial destructor. We still
267 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000268 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000269 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000270 }
271
Chandler Carruth84537952012-03-30 19:44:53 +0000272 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000273}
274
John McCall1c9c3fd2010-10-15 04:57:14 +0000275void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000276 llvm::GlobalValue::LinkageTypes Linkage) {
Chandler Carruth84537952012-03-30 19:44:53 +0000277 llvm::Value *&DMEntry = LocalDeclMap[&D];
278 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
Mike Stump11289f42009-09-09 15:08:12 +0000279
John McCallb88a5662012-03-30 21:00:39 +0000280 // Check to see if we already have a global variable for this
281 // declaration. This can happen when double-emitting function
282 // bodies, e.g. with complete and base constructors.
283 llvm::Constant *addr =
284 CGM.getStaticLocalDeclAddress(&D);
285
286 llvm::GlobalVariable *var;
287 if (addr) {
288 var = cast<llvm::GlobalVariable>(addr->stripPointerCasts());
289 } else {
290 addr = var = CreateStaticVarDecl(D, ".", Linkage);
291 }
Daniel Dunbara374e602009-02-25 19:45:19 +0000292
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000293 // Store into LocalDeclMap before generating initializer to handle
294 // circular references.
John McCallb88a5662012-03-30 21:00:39 +0000295 DMEntry = addr;
296 CGM.setStaticLocalDeclAddress(&D, addr);
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000297
John McCall4a39ab82010-05-04 20:45:42 +0000298 // We can't have a VLA here, but we can have a pointer to a VLA,
299 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000300 // Make sure to evaluate VLA bounds now so that we have them for later.
301 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000302 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000303
John McCallb88a5662012-03-30 21:00:39 +0000304 // Save the type in case adding the initializer forces a type change.
305 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000306
Chris Lattnere99c1102009-12-05 08:22:11 +0000307 // If this value has an initializer, emit it.
308 if (D.getInit())
John McCallb88a5662012-03-30 21:00:39 +0000309 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000310
John McCallb88a5662012-03-30 21:00:39 +0000311 var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000312
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000313 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000314 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000315
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000316 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000317 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000318
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000319 if (D.hasAttr<UsedAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000320 CGM.AddUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000321
Chandler Carruth84537952012-03-30 19:44:53 +0000322 // We may have to cast the constant because of the initializer
323 // mismatch above.
324 //
325 // FIXME: It is really dangerous to store this in the map; if anyone
326 // RAUW's the GV uses of this constant will be invalid.
John McCallb88a5662012-03-30 21:00:39 +0000327 llvm::Constant *castedAddr = llvm::ConstantExpr::getBitCast(var, expectedType);
328 DMEntry = castedAddr;
329 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000330
331 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000332 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000333 if (DI &&
334 CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000335 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000336 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000337 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000338}
Mike Stump11289f42009-09-09 15:08:12 +0000339
John McCall2b7fc382010-07-13 20:32:21 +0000340namespace {
John McCall82fe67b2011-07-09 01:37:26 +0000341 struct DestroyObject : EHScopeStack::Cleanup {
342 DestroyObject(llvm::Value *addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000343 CodeGenFunction::Destroyer *destroyer,
344 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000345 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000346 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000347
John McCall82fe67b2011-07-09 01:37:26 +0000348 llvm::Value *addr;
349 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000350 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000351 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000352
John McCall30317fd2011-07-12 20:27:29 +0000353 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall178360e2011-07-11 08:38:19 +0000354 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000355 bool useEHCleanupForArray =
356 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000357
358 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000359 }
360 };
361
John McCall82fe67b2011-07-09 01:37:26 +0000362 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
363 DestroyNRVOVariable(llvm::Value *addr,
364 const CXXDestructorDecl *Dtor,
365 llvm::Value *NRVOFlag)
366 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000367
368 const CXXDestructorDecl *Dtor;
369 llvm::Value *NRVOFlag;
370 llvm::Value *Loc;
371
John McCall30317fd2011-07-12 20:27:29 +0000372 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2b7fc382010-07-13 20:32:21 +0000373 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000374 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000375
376 llvm::BasicBlock *SkipDtorBB = 0;
377 if (NRVO) {
378 // If we exited via NRVO, we skip the destructor call.
379 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
380 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
381 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
382 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
383 CGF.EmitBlock(RunDtorBB);
384 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000385
John McCall2b7fc382010-07-13 20:32:21 +0000386 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
387 /*ForVirtualBase=*/false, Loc);
388
389 if (NRVO) CGF.EmitBlock(SkipDtorBB);
390 }
391 };
John McCall2b7fc382010-07-13 20:32:21 +0000392
John McCallcda666c2010-07-21 07:22:38 +0000393 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000394 llvm::Value *Stack;
395 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
John McCall30317fd2011-07-12 20:27:29 +0000396 void Emit(CodeGenFunction &CGF, Flags flags) {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000397 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000398 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
399 CGF.Builder.CreateCall(F, V);
400 }
401 };
402
John McCall1bd25562011-06-24 23:21:27 +0000403 struct ExtendGCLifetime : EHScopeStack::Cleanup {
404 const VarDecl &Var;
405 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
406
John McCall30317fd2011-07-12 20:27:29 +0000407 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1bd25562011-06-24 23:21:27 +0000408 // Compute the address of the local variable, in case it's a
409 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000410 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
411 Var.getType(), VK_LValue, SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000412 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
413 CGF.EmitExtendGCLifetime(value);
414 }
415 };
416
John McCallcda666c2010-07-21 07:22:38 +0000417 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000418 llvm::Constant *CleanupFn;
419 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000420 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000421
John McCalla464ff92010-07-21 06:13:08 +0000422 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000423 const VarDecl *Var)
424 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000425
John McCall30317fd2011-07-12 20:27:29 +0000426 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall113bee02012-03-10 09:33:50 +0000427 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
428 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000429 // Compute the address of the local variable, in case it's a byref
430 // or something.
431 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
432
John McCalla464ff92010-07-21 06:13:08 +0000433 // In some cases, the type of the function argument will be different from
434 // the type of the pointer. An example of this is
435 // void f(void* arg);
436 // __attribute__((cleanup(f))) void *g;
437 //
438 // To fix this we insert a bitcast here.
439 QualType ArgTy = FnInfo.arg_begin()->type;
440 llvm::Value *Arg =
441 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
442
443 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000444 Args.add(RValue::get(Arg),
445 CGF.getContext().getPointerType(Var.getType()));
John McCalla464ff92010-07-21 06:13:08 +0000446 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
447 }
448 };
John McCalla464ff92010-07-21 06:13:08 +0000449}
450
John McCall31168b02011-06-15 23:02:42 +0000451/// EmitAutoVarWithLifetime - Does the setup required for an automatic
452/// variable with lifetime.
453static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
454 llvm::Value *addr,
455 Qualifiers::ObjCLifetime lifetime) {
456 switch (lifetime) {
457 case Qualifiers::OCL_None:
458 llvm_unreachable("present but none");
459
460 case Qualifiers::OCL_ExplicitNone:
461 // nothing to do
462 break;
463
464 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000465 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000466 (var.hasAttr<ObjCPreciseLifetimeAttr>()
467 ? CodeGenFunction::destroyARCStrongPrecise
468 : CodeGenFunction::destroyARCStrongImprecise);
469
470 CleanupKind cleanupKind = CGF.getARCCleanupKind();
471 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
472 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000473 break;
474 }
475 case Qualifiers::OCL_Autoreleasing:
476 // nothing to do
477 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000478
John McCall31168b02011-06-15 23:02:42 +0000479 case Qualifiers::OCL_Weak:
480 // __weak objects always get EH cleanups; otherwise, exceptions
481 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000482 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
483 CodeGenFunction::destroyARCWeak,
484 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000485 break;
486 }
487}
488
489static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
490 if (const Expr *e = dyn_cast<Expr>(s)) {
491 // Skip the most common kinds of expressions that make
492 // hierarchy-walking expensive.
493 s = e = e->IgnoreParenCasts();
494
495 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
496 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000497 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
498 const BlockDecl *block = be->getBlockDecl();
499 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
500 e = block->capture_end(); i != e; ++i) {
501 if (i->getVariable() == &var)
502 return true;
503 }
504 }
John McCall31168b02011-06-15 23:02:42 +0000505 }
506
507 for (Stmt::const_child_range children = s->children(); children; ++children)
Fariborz Jahanian326701e2011-06-29 20:00:16 +0000508 // children might be null; as in missing decl or conditional of an if-stmt.
509 if ((*children) && isAccessedBy(var, *children))
John McCall31168b02011-06-15 23:02:42 +0000510 return true;
511
512 return false;
513}
514
515static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
516 if (!decl) return false;
517 if (!isa<VarDecl>(decl)) return false;
518 const VarDecl *var = cast<VarDecl>(decl);
519 return isAccessedBy(*var, e);
520}
521
John McCall1553b192011-06-16 04:16:24 +0000522static void drillIntoBlockVariable(CodeGenFunction &CGF,
523 LValue &lvalue,
524 const VarDecl *var) {
525 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
526}
527
John McCall31168b02011-06-15 23:02:42 +0000528void CodeGenFunction::EmitScalarInit(const Expr *init,
529 const ValueDecl *D,
John McCall1553b192011-06-16 04:16:24 +0000530 LValue lvalue,
531 bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000532 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000533 if (!lifetime) {
534 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000535 if (capturedByInit)
536 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnallfa35df62012-01-16 17:27:18 +0000537 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000538 return;
539 }
540
541 // If we're emitting a value with lifetime, we have to do the
542 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000543 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
544 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000545 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000546 }
547 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000548
549 // We have to maintain the illusion that the variable is
550 // zero-initialized. If the variable might be accessed in its
551 // initializer, zero-initialize before running the initializer, then
552 // actually perform the initialization with an assign.
553 bool accessedByInit = false;
554 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000555 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000556 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000557 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000558 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000559 if (capturedByInit) {
560 // We can use a simple GEP for this because it can't have been
561 // moved yet.
John McCall1553b192011-06-16 04:16:24 +0000562 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
563 getByRefValueLLVMField(cast<VarDecl>(D))));
John McCall31168b02011-06-15 23:02:42 +0000564 }
565
Chris Lattner2192fe52011-07-18 04:24:23 +0000566 llvm::PointerType *ty
John McCall1553b192011-06-16 04:16:24 +0000567 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
John McCall31168b02011-06-15 23:02:42 +0000568 ty = cast<llvm::PointerType>(ty->getElementType());
569
570 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000571
John McCall31168b02011-06-15 23:02:42 +0000572 // If __weak, we want to use a barrier under certain conditions.
573 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000574 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000575
576 // Otherwise just do a simple store.
577 else
David Chisnallfa35df62012-01-16 17:27:18 +0000578 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000579 }
580
581 // Emit the initializer.
582 llvm::Value *value = 0;
583
584 switch (lifetime) {
585 case Qualifiers::OCL_None:
586 llvm_unreachable("present but none");
587
588 case Qualifiers::OCL_ExplicitNone:
589 // nothing to do
590 value = EmitScalarExpr(init);
591 break;
592
593 case Qualifiers::OCL_Strong: {
594 value = EmitARCRetainScalarExpr(init);
595 break;
596 }
597
598 case Qualifiers::OCL_Weak: {
599 // No way to optimize a producing initializer into this. It's not
600 // worth optimizing for, because the value will immediately
601 // disappear in the common case.
602 value = EmitScalarExpr(init);
603
John McCall1553b192011-06-16 04:16:24 +0000604 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000605 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000606 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000607 else
John McCall1553b192011-06-16 04:16:24 +0000608 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000609 return;
610 }
611
612 case Qualifiers::OCL_Autoreleasing:
613 value = EmitARCRetainAutoreleaseScalarExpr(init);
614 break;
615 }
616
John McCall1553b192011-06-16 04:16:24 +0000617 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000618
619 // If the variable might have been accessed by its initializer, we
620 // might have to initialize with a barrier. We have to do this for
621 // both __weak and __strong, but __weak got filtered out above.
622 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
John McCall1553b192011-06-16 04:16:24 +0000623 llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
David Chisnallfa35df62012-01-16 17:27:18 +0000624 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000625 EmitARCRelease(oldValue, /*precise*/ false);
626 return;
627 }
628
David Chisnallfa35df62012-01-16 17:27:18 +0000629 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000630}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000631
John McCalld4631322011-06-17 06:42:21 +0000632/// EmitScalarInit - Initialize the given lvalue with the given object.
633void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
634 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
635 if (!lifetime)
David Chisnallfa35df62012-01-16 17:27:18 +0000636 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCalld4631322011-06-17 06:42:21 +0000637
638 switch (lifetime) {
639 case Qualifiers::OCL_None:
640 llvm_unreachable("present but none");
641
642 case Qualifiers::OCL_ExplicitNone:
643 // nothing to do
644 break;
645
646 case Qualifiers::OCL_Strong:
647 init = EmitARCRetain(lvalue.getType(), init);
648 break;
649
650 case Qualifiers::OCL_Weak:
651 // Initialize and then skip the primitive store.
652 EmitARCInitWeak(lvalue.getAddress(), init);
653 return;
654
655 case Qualifiers::OCL_Autoreleasing:
656 init = EmitARCRetainAutorelease(lvalue.getType(), init);
657 break;
658 }
659
David Chisnallfa35df62012-01-16 17:27:18 +0000660 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCalld4631322011-06-17 06:42:21 +0000661}
662
Chris Lattnerb85025f2010-12-01 02:05:19 +0000663/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
664/// non-zero parts of the specified initializer with equal or fewer than
665/// NumStores scalar stores.
666static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
667 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000668 // Zero and Undef never requires any extra stores.
669 if (isa<llvm::ConstantAggregateZero>(Init) ||
670 isa<llvm::ConstantPointerNull>(Init) ||
671 isa<llvm::UndefValue>(Init))
672 return true;
673 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
674 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
675 isa<llvm::ConstantExpr>(Init))
676 return Init->isNullValue() || NumStores--;
677
678 // See if we can emit each element.
679 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
680 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
681 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
682 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
683 return false;
684 }
685 return true;
686 }
Chris Lattner236b3572012-01-31 04:36:19 +0000687
688 if (llvm::ConstantDataSequential *CDS =
689 dyn_cast<llvm::ConstantDataSequential>(Init)) {
690 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
691 llvm::Constant *Elt = CDS->getElementAsConstant(i);
692 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
693 return false;
694 }
695 return true;
696 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000697
Chris Lattnerb85025f2010-12-01 02:05:19 +0000698 // Anything else is hard and scary.
699 return false;
700}
701
702/// emitStoresForInitAfterMemset - For inits that
703/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
704/// stores that would be required.
705static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000706 bool isVolatile, CGBuilderTy &Builder) {
Chris Lattner236b3572012-01-31 04:36:19 +0000707 // Zero doesn't require a store.
708 if (Init->isNullValue() || isa<llvm::UndefValue>(Init))
Chris Lattnere6af8862010-12-02 01:58:41 +0000709 return;
Eric Christopher31ab1302011-08-23 22:38:00 +0000710
Chris Lattnere6af8862010-12-02 01:58:41 +0000711 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
712 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
713 isa<llvm::ConstantExpr>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000714 Builder.CreateStore(Init, Loc, isVolatile);
715 return;
716 }
717
718 if (llvm::ConstantDataSequential *CDS =
719 dyn_cast<llvm::ConstantDataSequential>(Init)) {
720 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
721 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000722
723 // If necessary, get a pointer to the element and emit it.
724 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
725 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
726 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000727 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000728 return;
729 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000730
Chris Lattnere6af8862010-12-02 01:58:41 +0000731 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
732 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000733
Chris Lattnere6af8862010-12-02 01:58:41 +0000734 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
735 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000736
737 // If necessary, get a pointer to the element and emit it.
738 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
739 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
740 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000741 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000742}
743
744
745/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
746/// plus some stores to initialize a local variable instead of using a memcpy
747/// from a constant global. It is beneficial to use memset if the global is all
748/// zeros, or mostly zeros and large.
749static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
750 uint64_t GlobalSize) {
751 // If a global is all zeros, always use a memset.
752 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
753
754
755 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
756 // do it if it will require 6 or fewer scalar stores.
757 // TODO: Should budget depends on the size? Avoiding a large global warrants
758 // plopping in more stores.
759 unsigned StoreBudget = 6;
760 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000761
762 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000763 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
764}
765
766
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000767/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000768/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000769/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000770void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
771 AutoVarEmission emission = EmitAutoVarAlloca(D);
772 EmitAutoVarInit(emission);
773 EmitAutoVarCleanups(emission);
774}
Chris Lattner03df1222007-06-02 04:53:11 +0000775
John McCallc533cb72011-02-22 06:44:22 +0000776/// EmitAutoVarAlloca - Emit the alloca and debug information for a
777/// local variable. Does not emit initalization or destruction.
778CodeGenFunction::AutoVarEmission
779CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
780 QualType Ty = D.getType();
781
782 AutoVarEmission emission(D);
783
784 bool isByRef = D.hasAttr<BlocksAttr>();
785 emission.IsByRef = isByRef;
786
787 CharUnits alignment = getContext().getDeclAlign(&D);
788 emission.Alignment = alignment;
789
John McCall23c29fe2011-06-24 21:55:10 +0000790 // If the type is variably-modified, emit all the VLA sizes for it.
791 if (Ty->isVariablyModifiedType())
792 EmitVariablyModifiedType(Ty);
793
Chris Lattner03df1222007-06-02 04:53:11 +0000794 llvm::Value *DeclPtr;
Eli Friedmana682d392008-02-15 12:20:59 +0000795 if (Ty->isConstantSizeType()) {
Chris Lattnerb781dc792008-05-08 05:58:21 +0000796 if (!Target.useGlobalsForAutomaticVariables()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000797 bool NRVO = getContext().getLangOpts().ElideConstructors &&
John McCallc533cb72011-02-22 06:44:22 +0000798 D.isNRVOVariable();
799
800 // If this value is a POD array or struct with a statically
Richard Smithd572f822011-12-02 00:30:33 +0000801 // determinable constant initializer, there are optimizations we can do.
802 //
Richard Smithe070fd22012-02-17 06:48:11 +0000803 // TODO: We should constant-evaluate the initializer of any variable,
Richard Smithd572f822011-12-02 00:30:33 +0000804 // as long as it is initialized by a constant expression. Currently,
805 // isConstantInitializer produces wrong answers for structs with
806 // reference or bitfield members, and a few other cases, and checking
807 // for POD-ness protects us from some of these.
John McCallc533cb72011-02-22 06:44:22 +0000808 if (D.getInit() &&
Eric Christopher31ab1302011-08-23 22:38:00 +0000809 (Ty->isArrayType() || Ty->isRecordType()) &&
John McCall31168b02011-06-15 23:02:42 +0000810 (Ty.isPODType(getContext()) ||
811 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
John McCall8b0f4ff2010-08-02 21:13:48 +0000812 D.getInit()->isConstantInitializer(getContext(), false)) {
John McCallc533cb72011-02-22 06:44:22 +0000813
814 // If the variable's a const type, and it's neither an NRVO
Richard Smithd572f822011-12-02 00:30:33 +0000815 // candidate nor a __block variable and has no mutable members,
816 // emit it as a global instead.
Richard Smithe070fd22012-02-17 06:48:11 +0000817 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
818 CGM.isTypeConstant(Ty, true)) {
819 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +0000820
Richard Smithe070fd22012-02-17 06:48:11 +0000821 emission.Address = 0; // signal this condition to later callbacks
822 assert(emission.wasEmittedAsGlobal());
823 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +0000824 }
John McCallc533cb72011-02-22 06:44:22 +0000825
826 // Otherwise, tell the initialization code that we're in this case.
827 emission.IsConstantAggregate = true;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +0000828 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000829
Douglas Gregor290c93e2010-05-15 06:46:45 +0000830 // A normal fixed sized variable becomes an alloca in the entry block,
831 // unless it's an NRVO variable.
Chris Lattner2192fe52011-07-18 04:24:23 +0000832 llvm::Type *LTy = ConvertTypeForMem(Ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000833
Douglas Gregor290c93e2010-05-15 06:46:45 +0000834 if (NRVO) {
835 // The named return value optimization: allocate this variable in the
836 // return slot, so that we can elide the copy when returning this
837 // variable (C++0x [class.copy]p34).
838 DeclPtr = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +0000839
Douglas Gregor9154b5d2010-05-17 15:52:46 +0000840 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
841 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
842 // Create a flag that is used to indicate when the NRVO was applied
Eric Christopher31ab1302011-08-23 22:38:00 +0000843 // to this variable. Set it to zero to indicate that NRVO was not
Douglas Gregor9154b5d2010-05-17 15:52:46 +0000844 // applied.
Chris Lattner46a7ad72010-12-01 01:47:15 +0000845 llvm::Value *Zero = Builder.getFalse();
John McCallc533cb72011-02-22 06:44:22 +0000846 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
Nick Lewycky8d222622011-02-16 23:59:08 +0000847 EnsureInsertPoint();
Douglas Gregor9154b5d2010-05-17 15:52:46 +0000848 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +0000849
Douglas Gregor9154b5d2010-05-17 15:52:46 +0000850 // Record the NRVO flag for this variable.
851 NRVOFlags[&D] = NRVOFlag;
John McCallc533cb72011-02-22 06:44:22 +0000852 emission.NRVOFlag = NRVOFlag;
Douglas Gregor9154b5d2010-05-17 15:52:46 +0000853 }
854 }
Douglas Gregor290c93e2010-05-15 06:46:45 +0000855 } else {
856 if (isByRef)
857 LTy = BuildByRefType(&D);
Eric Christopher31ab1302011-08-23 22:38:00 +0000858
Douglas Gregor290c93e2010-05-15 06:46:45 +0000859 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
Benjamin Kramer3df1a2d2011-11-29 14:46:55 +0000860 Alloc->setName(D.getName());
Mike Stump11289f42009-09-09 15:08:12 +0000861
John McCallc533cb72011-02-22 06:44:22 +0000862 CharUnits allocaAlignment = alignment;
Douglas Gregor290c93e2010-05-15 06:46:45 +0000863 if (isByRef)
Eric Christopher31ab1302011-08-23 22:38:00 +0000864 allocaAlignment = std::max(allocaAlignment,
Ken Dyck9a648692011-01-18 02:01:14 +0000865 getContext().toCharUnitsFromBits(Target.getPointerAlign(0)));
John McCallc533cb72011-02-22 06:44:22 +0000866 Alloc->setAlignment(allocaAlignment.getQuantity());
Douglas Gregor290c93e2010-05-15 06:46:45 +0000867 DeclPtr = Alloc;
868 }
Chris Lattnerb781dc792008-05-08 05:58:21 +0000869 } else {
870 // Targets that don't support recursion emit locals as globals.
871 const char *Class =
John McCall8e7d6562010-08-26 03:08:43 +0000872 D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
John McCall1c9c3fd2010-10-15 04:57:14 +0000873 DeclPtr = CreateStaticVarDecl(D, Class,
874 llvm::GlobalValue::InternalLinkage);
Chris Lattnerb781dc792008-05-08 05:58:21 +0000875 }
Chris Lattner03df1222007-06-02 04:53:11 +0000876 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000877 EnsureInsertPoint();
878
Anders Carlsson15949b32009-02-09 20:41:50 +0000879 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +0000880 // Save the stack.
John McCallad7c5c12011-02-08 08:22:06 +0000881 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +0000882
Anders Carlsson30032882008-12-12 07:38:43 +0000883 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
884 llvm::Value *V = Builder.CreateCall(F);
Mike Stump11289f42009-09-09 15:08:12 +0000885
Anders Carlsson30032882008-12-12 07:38:43 +0000886 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +0000887
888 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +0000889
John McCalla464ff92010-07-21 06:13:08 +0000890 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +0000891 // FIXME: in general circumstances, this should be an EH cleanup.
John McCallcda666c2010-07-21 07:22:38 +0000892 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +0000893 }
Mike Stump11289f42009-09-09 15:08:12 +0000894
John McCall23c29fe2011-06-24 21:55:10 +0000895 llvm::Value *elementCount;
896 QualType elementType;
897 llvm::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +0000898
Chris Lattner2192fe52011-07-18 04:24:23 +0000899 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +0000900
901 // Allocate memory for the array.
John McCall23c29fe2011-06-24 21:55:10 +0000902 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
903 vla->setAlignment(alignment.getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +0000904
John McCall23c29fe2011-06-24 21:55:10 +0000905 DeclPtr = vla;
Chris Lattner03df1222007-06-02 04:53:11 +0000906 }
Eli Friedmanf4084702008-12-20 23:11:59 +0000907
Chris Lattner03df1222007-06-02 04:53:11 +0000908 llvm::Value *&DMEntry = LocalDeclMap[&D];
909 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
910 DMEntry = DeclPtr;
John McCallc533cb72011-02-22 06:44:22 +0000911 emission.Address = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +0000912
913 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +0000914 if (HaveInsertPoint())
915 if (CGDebugInfo *DI = getDebugInfo()) {
Alexey Samsonov74a38682012-05-04 07:39:27 +0000916 if (CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) {
917 DI->setLocation(D.getLocation());
918 if (Target.useGlobalsForAutomaticVariables()) {
919 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr),
920 &D);
921 } else
922 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
923 }
Devang Patel887e2152011-06-03 19:21:47 +0000924 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +0000925
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000926 if (D.hasAttr<AnnotateAttr>())
927 EmitVarAnnotations(&D, emission.Address);
928
John McCallc533cb72011-02-22 06:44:22 +0000929 return emission;
930}
931
932/// Determines whether the given __block variable is potentially
933/// captured by the given expression.
934static bool isCapturedBy(const VarDecl &var, const Expr *e) {
935 // Skip the most common kinds of expressions that make
936 // hierarchy-walking expensive.
937 e = e->IgnoreParenCasts();
938
939 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
940 const BlockDecl *block = be->getBlockDecl();
941 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
942 e = block->capture_end(); i != e; ++i) {
943 if (i->getVariable() == &var)
944 return true;
945 }
946
947 // No need to walk into the subexpressions.
948 return false;
949 }
950
Fariborz Jahanian797f1e22011-08-23 16:47:15 +0000951 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
952 const CompoundStmt *CS = SE->getSubStmt();
Eric Christopherd28d1072011-08-23 23:44:09 +0000953 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
954 BE = CS->body_end(); BI != BE; ++BI)
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +0000955 if (Expr *E = dyn_cast<Expr>((*BI))) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +0000956 if (isCapturedBy(var, E))
957 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +0000958 }
959 else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
960 // special case declarations
961 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
962 I != E; ++I) {
963 if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
964 Expr *Init = VD->getInit();
965 if (Init && isCapturedBy(var, Init))
966 return true;
967 }
968 }
969 }
970 else
971 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
972 // Later, provide code to poke into statements for capture analysis.
973 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +0000974 return false;
975 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000976
John McCallc533cb72011-02-22 06:44:22 +0000977 for (Stmt::const_child_range children = e->children(); children; ++children)
978 if (isCapturedBy(var, cast<Expr>(*children)))
979 return true;
980
981 return false;
982}
983
Douglas Gregor82e1af22011-07-01 21:08:19 +0000984/// \brief Determine whether the given initializer is trivial in the sense
985/// that it requires no code to be generated.
986static bool isTrivialInitializer(const Expr *Init) {
987 if (!Init)
988 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +0000989
Douglas Gregor82e1af22011-07-01 21:08:19 +0000990 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
991 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
992 if (Constructor->isTrivial() &&
993 Constructor->isDefaultConstructor() &&
994 !Construct->requiresZeroInitialization())
995 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +0000996
Douglas Gregor82e1af22011-07-01 21:08:19 +0000997 return false;
998}
John McCallc533cb72011-02-22 06:44:22 +0000999void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001000 assert(emission.Variable && "emission was not valid!");
1001
John McCallc533cb72011-02-22 06:44:22 +00001002 // If this was emitted as a global constant, we're done.
1003 if (emission.wasEmittedAsGlobal()) return;
1004
John McCall9e2e22f2011-02-22 07:16:58 +00001005 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001006 QualType type = D.getType();
1007
Chris Lattner07eb7332007-07-12 00:39:48 +00001008 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001009 const Expr *Init = D.getInit();
1010
1011 // If we are at an unreachable point, we don't need to emit the initializer
1012 // unless it contains a label.
1013 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001014 if (!Init || !ContainsLabel(Init)) return;
1015 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001016 }
1017
John McCall73064872011-03-31 01:59:53 +00001018 // Initialize the structure of a __block variable.
1019 if (emission.IsByRef)
1020 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001021
Douglas Gregor82e1af22011-07-01 21:08:19 +00001022 if (isTrivialInitializer(Init))
1023 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001024
John McCall73064872011-03-31 01:59:53 +00001025 CharUnits alignment = emission.Alignment;
1026
John McCallc533cb72011-02-22 06:44:22 +00001027 // Check whether this is a byref variable that's potentially
1028 // captured and moved by its own initializer. If so, we'll need to
1029 // emit the initializer first, then copy into the variable.
1030 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1031
1032 llvm::Value *Loc =
1033 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1034
Richard Smithfddd3842011-12-30 21:15:51 +00001035 llvm::Constant *constant = 0;
1036 if (emission.IsConstantAggregate) {
1037 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smithdafff942012-01-14 04:30:29 +00001038 constant = CGM.EmitConstantInit(D, this);
Richard Smithfddd3842011-12-30 21:15:51 +00001039 }
1040
1041 if (!constant) {
Eli Friedmana0544d62011-12-03 04:14:32 +00001042 LValue lv = MakeAddrLValue(Loc, type, alignment);
John McCall1553b192011-06-16 04:16:24 +00001043 lv.setNonGC(true);
1044 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1045 }
John McCall91ca10f2011-03-08 09:11:50 +00001046
John McCallc533cb72011-02-22 06:44:22 +00001047 // If this is a simple aggregate initialization, we can optimize it
1048 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001049 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001050
John McCall91ca10f2011-03-08 09:11:50 +00001051 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001052 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001053 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001054
Chris Lattner2192fe52011-07-18 04:24:23 +00001055 llvm::Type *BP = Int8PtrTy;
John McCall91ca10f2011-03-08 09:11:50 +00001056 if (Loc->getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001057 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001058
John McCall91ca10f2011-03-08 09:11:50 +00001059 // If the initializer is all or mostly zeros, codegen with memset then do
1060 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001061 if (shouldUseMemSetPlusStoresToInitialize(constant,
John McCall91ca10f2011-03-08 09:11:50 +00001062 CGM.getTargetData().getTypeAllocSize(constant->getType()))) {
1063 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1064 alignment.getQuantity(), isVolatile);
1065 if (!constant->isNullValue()) {
1066 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1067 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001068 }
John McCall91ca10f2011-03-08 09:11:50 +00001069 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001070 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001071 // memcpy from the global to the alloca.
1072 std::string Name = GetStaticDeclName(*this, D, ".");
1073 llvm::GlobalVariable *GV =
1074 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001075 llvm::GlobalValue::PrivateLinkage,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001076 constant, Name);
John McCall91ca10f2011-03-08 09:11:50 +00001077 GV->setAlignment(alignment.getQuantity());
Eli Friedmanb8578422011-05-27 22:32:55 +00001078 GV->setUnnamedAddr(true);
Eric Christopher31ab1302011-08-23 22:38:00 +00001079
John McCall91ca10f2011-03-08 09:11:50 +00001080 llvm::Value *SrcPtr = GV;
1081 if (SrcPtr->getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001082 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001083
1084 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1085 isVolatile);
1086 }
1087}
1088
1089/// Emit an expression as an initializer for a variable at the given
1090/// location. The expression is not necessarily the normal
1091/// initializer for the variable, and the address is not necessarily
1092/// its normal location.
1093///
1094/// \param init the initializing expression
1095/// \param var the variable to act as if we're initializing
1096/// \param loc the address to initialize; its type is a pointer
1097/// to the LLVM mapping of the variable's type
1098/// \param alignment the alignment of the address
1099/// \param capturedByInit true if the variable is a __block variable
1100/// whose address is potentially changed by the initializer
1101void CodeGenFunction::EmitExprAsInit(const Expr *init,
John McCall31168b02011-06-15 23:02:42 +00001102 const ValueDecl *D,
John McCall1553b192011-06-16 04:16:24 +00001103 LValue lvalue,
John McCall91ca10f2011-03-08 09:11:50 +00001104 bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001105 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001106
1107 if (type->isReferenceType()) {
John McCall1553b192011-06-16 04:16:24 +00001108 RValue rvalue = EmitReferenceBindingToExpr(init, D);
Eric Christopher31ab1302011-08-23 22:38:00 +00001109 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001110 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnallfa35df62012-01-16 17:27:18 +00001111 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCallc533cb72011-02-22 06:44:22 +00001112 } else if (!hasAggregateLLVMType(type)) {
John McCall1553b192011-06-16 04:16:24 +00001113 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCallc533cb72011-02-22 06:44:22 +00001114 } else if (type->isAnyComplexType()) {
John McCall91ca10f2011-03-08 09:11:50 +00001115 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001116 if (capturedByInit)
1117 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1118 StoreComplexToAddr(complex, lvalue.getAddress(), lvalue.isVolatile());
John McCallc533cb72011-02-22 06:44:22 +00001119 } else {
1120 // TODO: how can we delay here if D is captured by its initializer?
John McCall8d6fc952011-08-25 20:40:09 +00001121 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001122 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001123 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001124 AggValueSlot::IsNotAliased));
Sebastian Redld026dc42012-02-19 16:03:09 +00001125 MaybeEmitStdInitializerListCleanup(lvalue.getAddress(), init);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001126 }
John McCallc533cb72011-02-22 06:44:22 +00001127}
John McCallbd309292010-07-06 01:34:17 +00001128
John McCall82fe67b2011-07-09 01:37:26 +00001129/// Enter a destroy cleanup for the given local variable.
1130void CodeGenFunction::emitAutoVarTypeCleanup(
1131 const CodeGenFunction::AutoVarEmission &emission,
1132 QualType::DestructionKind dtorKind) {
1133 assert(dtorKind != QualType::DK_none);
1134
1135 // Note that for __block variables, we want to destroy the
1136 // original stack object, not the possibly forwarded object.
1137 llvm::Value *addr = emission.getObjectAddress(*this);
1138
1139 const VarDecl *var = emission.Variable;
1140 QualType type = var->getType();
1141
1142 CleanupKind cleanupKind = NormalAndEHCleanup;
1143 CodeGenFunction::Destroyer *destroyer = 0;
1144
1145 switch (dtorKind) {
1146 case QualType::DK_none:
1147 llvm_unreachable("no cleanup for trivially-destructible variable");
1148
1149 case QualType::DK_cxx_destructor:
1150 // If there's an NRVO flag on the emission, we need a different
1151 // cleanup.
1152 if (emission.NRVOFlag) {
1153 assert(!type->isArrayType());
1154 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1155 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1156 emission.NRVOFlag);
1157 return;
1158 }
1159 break;
1160
1161 case QualType::DK_objc_strong_lifetime:
1162 // Suppress cleanups for pseudo-strong variables.
1163 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001164
John McCall82fe67b2011-07-09 01:37:26 +00001165 // Otherwise, consider whether to use an EH cleanup or not.
1166 cleanupKind = getARCCleanupKind();
1167
1168 // Use the imprecise destroyer by default.
1169 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1170 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1171 break;
1172
1173 case QualType::DK_objc_weak_lifetime:
1174 break;
1175 }
1176
1177 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001178 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001179
1180 // Use an EH cleanup in array destructors iff the destructor itself
1181 // is being pushed as an EH cleanup.
1182 bool useEHCleanup = (cleanupKind & EHCleanup);
1183 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1184 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001185}
1186
John McCallc533cb72011-02-22 06:44:22 +00001187void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001188 assert(emission.Variable && "emission was not valid!");
1189
John McCallc533cb72011-02-22 06:44:22 +00001190 // If this was emitted as a global constant, we're done.
1191 if (emission.wasEmittedAsGlobal()) return;
1192
John McCall8c38d352012-04-13 18:44:05 +00001193 // If we don't have an insertion point, we're done. Sema prevents
1194 // us from jumping into any of these scopes anyway.
1195 if (!HaveInsertPoint()) return;
1196
John McCall9e2e22f2011-02-22 07:16:58 +00001197 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001198
John McCall82fe67b2011-07-09 01:37:26 +00001199 // Check the type for a cleanup.
1200 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1201 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001202
John McCall1bd25562011-06-24 23:21:27 +00001203 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001204 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001205 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1206 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1207 }
1208
John McCallc533cb72011-02-22 06:44:22 +00001209 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001210 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001211 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001212
John McCallc533cb72011-02-22 06:44:22 +00001213 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001214 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001215
John McCalla729c622012-02-17 03:33:10 +00001216 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001217 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001218 }
Mike Stump626aecc2009-03-05 01:23:13 +00001219
John McCallc533cb72011-02-22 06:44:22 +00001220 // If this is a block variable, call _Block_object_destroy
1221 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001222 if (emission.IsByRef)
1223 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001224}
Chris Lattner53621a52007-06-13 20:44:40 +00001225
Peter Collingbourne1425b452012-01-26 03:33:36 +00001226CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001227CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1228 switch (kind) {
1229 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001230 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001231 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001232 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001233 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001234 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001235 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001236 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001237 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001238}
1239
John McCall4bd0fb12011-07-12 16:41:08 +00001240/// pushDestroy - Push the standard destructor for the given type.
1241void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1242 llvm::Value *addr, QualType type) {
1243 assert(dtorKind && "cannot push destructor for trivial type");
1244
1245 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1246 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1247 cleanupKind & EHCleanup);
1248}
1249
John McCall82fe67b2011-07-09 01:37:26 +00001250void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001251 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001252 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001253 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1254 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001255}
1256
John McCall178360e2011-07-11 08:38:19 +00001257/// emitDestroy - Immediately perform the destruction of the given
1258/// object.
1259///
1260/// \param addr - the address of the object; a type*
1261/// \param type - the type of the object; if an array type, all
1262/// objects are destroyed in reverse order
1263/// \param destroyer - the function to call to destroy individual
1264/// elements
1265/// \param useEHCleanupForArray - whether an EH cleanup should be
1266/// used when destroying array elements, in case one of the
1267/// destructions throws an exception
John McCall82fe67b2011-07-09 01:37:26 +00001268void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001269 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001270 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001271 const ArrayType *arrayType = getContext().getAsArrayType(type);
1272 if (!arrayType)
1273 return destroyer(*this, addr, type);
1274
1275 llvm::Value *begin = addr;
1276 llvm::Value *length = emitArrayLength(arrayType, type, begin);
John McCall97eab0a2011-07-13 08:09:46 +00001277
1278 // Normally we have to check whether the array is zero-length.
1279 bool checkZeroLength = true;
1280
1281 // But if the array length is constant, we can suppress that.
1282 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1283 // ...and if it's constant zero, we can just skip the entire thing.
1284 if (constLength->isZero()) return;
1285 checkZeroLength = false;
1286 }
1287
John McCall82fe67b2011-07-09 01:37:26 +00001288 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall97eab0a2011-07-13 08:09:46 +00001289 emitArrayDestroy(begin, end, type, destroyer,
1290 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001291}
1292
John McCall178360e2011-07-11 08:38:19 +00001293/// emitArrayDestroy - Destroys all the elements of the given array,
1294/// beginning from last to first. The array cannot be zero-length.
1295///
1296/// \param begin - a type* denoting the first element of the array
1297/// \param end - a type* denoting one past the end of the array
1298/// \param type - the element type of the array
1299/// \param destroyer - the function to call to destroy elements
1300/// \param useEHCleanup - whether to push an EH cleanup to destroy
1301/// the remaining elements in case the destruction of a single
1302/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001303void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1304 llvm::Value *end,
1305 QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001306 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001307 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001308 bool useEHCleanup) {
John McCall82fe67b2011-07-09 01:37:26 +00001309 assert(!type->isArrayType());
1310
1311 // The basic structure here is a do-while loop, because we don't
1312 // need to check for the zero-element case.
1313 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1314 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1315
John McCall97eab0a2011-07-13 08:09:46 +00001316 if (checkZeroLength) {
1317 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1318 "arraydestroy.isempty");
1319 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1320 }
1321
John McCall82fe67b2011-07-09 01:37:26 +00001322 // Enter the loop body, making that address the current address.
1323 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1324 EmitBlock(bodyBB);
1325 llvm::PHINode *elementPast =
1326 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1327 elementPast->addIncoming(end, entryBB);
1328
1329 // Shift the address back by one element.
1330 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1331 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1332 "arraydestroy.element");
1333
John McCall178360e2011-07-11 08:38:19 +00001334 if (useEHCleanup)
1335 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1336
John McCall82fe67b2011-07-09 01:37:26 +00001337 // Perform the actual destruction there.
1338 destroyer(*this, element, type);
1339
John McCall178360e2011-07-11 08:38:19 +00001340 if (useEHCleanup)
1341 PopCleanupBlock();
1342
John McCall82fe67b2011-07-09 01:37:26 +00001343 // Check whether we've reached the end.
1344 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1345 Builder.CreateCondBr(done, doneBB, bodyBB);
1346 elementPast->addIncoming(element, Builder.GetInsertBlock());
1347
1348 // Done.
1349 EmitBlock(doneBB);
1350}
1351
John McCall178360e2011-07-11 08:38:19 +00001352/// Perform partial array destruction as if in an EH cleanup. Unlike
1353/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001354static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1355 llvm::Value *begin, llvm::Value *end,
1356 QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001357 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001358 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001359 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001360 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1361 // VLAs don't require a GEP index to walk into.
1362 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001363 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001364 type = arrayType->getElementType();
1365 }
John McCall97eab0a2011-07-13 08:09:46 +00001366
1367 if (arrayDepth) {
1368 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1369
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001370 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001371 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1372 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001373 }
1374
John McCall97eab0a2011-07-13 08:09:46 +00001375 // Destroy the array. We don't ever need an EH cleanup because we
1376 // assume that we're in an EH cleanup ourselves, so a throwing
1377 // destructor causes an immediate terminate.
1378 CGF.emitArrayDestroy(begin, end, type, destroyer,
1379 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001380}
1381
John McCall82fe67b2011-07-09 01:37:26 +00001382namespace {
John McCall178360e2011-07-11 08:38:19 +00001383 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1384 /// array destroy where the end pointer is regularly determined and
1385 /// does not need to be loaded from a local.
1386 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1387 llvm::Value *ArrayBegin;
1388 llvm::Value *ArrayEnd;
1389 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001390 CodeGenFunction::Destroyer *Destroyer;
John McCall178360e2011-07-11 08:38:19 +00001391 public:
1392 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1393 QualType elementType,
1394 CodeGenFunction::Destroyer *destroyer)
1395 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
Peter Collingbourne1425b452012-01-26 03:33:36 +00001396 ElementType(elementType), Destroyer(destroyer) {}
John McCall178360e2011-07-11 08:38:19 +00001397
John McCall30317fd2011-07-12 20:27:29 +00001398 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall178360e2011-07-11 08:38:19 +00001399 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1400 ElementType, Destroyer);
1401 }
1402 };
1403
1404 /// IrregularPartialArrayDestroy - a cleanup which performs a
1405 /// partial array destroy where the end pointer is irregularly
1406 /// determined and must be loaded from a local.
1407 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001408 llvm::Value *ArrayBegin;
1409 llvm::Value *ArrayEndPointer;
1410 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001411 CodeGenFunction::Destroyer *Destroyer;
John McCall82fe67b2011-07-09 01:37:26 +00001412 public:
John McCall178360e2011-07-11 08:38:19 +00001413 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1414 llvm::Value *arrayEndPointer,
1415 QualType elementType,
1416 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001417 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
Peter Collingbourne1425b452012-01-26 03:33:36 +00001418 ElementType(elementType), Destroyer(destroyer) {}
John McCall82fe67b2011-07-09 01:37:26 +00001419
John McCall30317fd2011-07-12 20:27:29 +00001420 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall82fe67b2011-07-09 01:37:26 +00001421 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001422 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1423 ElementType, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001424 }
1425 };
1426}
1427
John McCall178360e2011-07-11 08:38:19 +00001428/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001429/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001430/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001431///
John McCall82fe67b2011-07-09 01:37:26 +00001432/// \param elementType - the immediate element type of the array;
1433/// possibly still an array type
1434/// \param array - a value of type elementType*
1435/// \param destructionKind - the kind of destruction required
1436/// \param initializedElementCount - a value of type size_t* holding
1437/// the number of successfully-constructed elements
John McCall4bd0fb12011-07-12 16:41:08 +00001438void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall178360e2011-07-11 08:38:19 +00001439 llvm::Value *arrayEndPointer,
1440 QualType elementType,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001441 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001442 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1443 arrayBegin, arrayEndPointer,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001444 elementType, destroyer);
John McCall178360e2011-07-11 08:38:19 +00001445}
1446
1447/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1448/// already-constructed elements of the given array. The cleanup
1449/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001450///
John McCall178360e2011-07-11 08:38:19 +00001451/// \param elementType - the immediate element type of the array;
1452/// possibly still an array type
1453/// \param array - a value of type elementType*
1454/// \param destructionKind - the kind of destruction required
1455/// \param initializedElementCount - a value of type size_t* holding
1456/// the number of successfully-constructed elements
1457void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1458 llvm::Value *arrayEnd,
1459 QualType elementType,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001460 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001461 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001462 arrayBegin, arrayEnd,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001463 elementType, destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001464}
1465
John McCall31168b02011-06-15 23:02:42 +00001466namespace {
1467 /// A cleanup to perform a release of an object at the end of a
1468 /// function. This is used to balance out the incoming +1 of a
1469 /// ns_consumed argument when we can't reasonably do that just by
1470 /// not doing the initial retain for a __block argument.
1471 struct ConsumeARCParameter : EHScopeStack::Cleanup {
1472 ConsumeARCParameter(llvm::Value *param) : Param(param) {}
1473
1474 llvm::Value *Param;
1475
John McCall30317fd2011-07-12 20:27:29 +00001476 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +00001477 CGF.EmitARCRelease(Param, /*precise*/ false);
1478 }
1479 };
1480}
1481
Mike Stump11289f42009-09-09 15:08:12 +00001482/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001483/// for the specified parameter and set up LocalDeclMap.
Devang Patel68a15252011-03-03 20:13:15 +00001484void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1485 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001486 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001487 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001488 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001489
1490 Arg->setName(D.getName());
1491
1492 // Use better IR generation for certain implicit parameters.
1493 if (isa<ImplicitParamDecl>(D)) {
1494 // The only implicit argument a block has is its literal.
1495 if (BlockInfo) {
1496 LocalDeclMap[&D] = Arg;
1497
1498 if (CGDebugInfo *DI = getDebugInfo()) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001499 if (CGM.getCodeGenOpts().DebugInfo >=
1500 CodeGenOptions::LimitedDebugInfo) {
1501 DI->setLocation(D.getLocation());
1502 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, Builder);
1503 }
John McCall147d0212011-02-22 22:38:33 +00001504 }
1505
1506 return;
1507 }
1508 }
1509
Chris Lattnerfc4379f2008-04-06 23:10:54 +00001510 QualType Ty = D.getType();
Mike Stump11289f42009-09-09 15:08:12 +00001511
Chris Lattner53621a52007-06-13 20:44:40 +00001512 llvm::Value *DeclPtr;
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001513 // If this is an aggregate or variable sized value, reuse the input pointer.
1514 if (!Ty->isConstantSizeType() ||
1515 CodeGenFunction::hasAggregateLLVMType(Ty)) {
Chris Lattner53621a52007-06-13 20:44:40 +00001516 DeclPtr = Arg;
Chris Lattner53621a52007-06-13 20:44:40 +00001517 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001518 // Otherwise, create a temporary to hold the value.
Eli Friedmaneadd3e82011-11-03 20:31:28 +00001519 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1520 D.getName() + ".addr");
1521 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1522 DeclPtr = Alloc;
Mike Stump11289f42009-09-09 15:08:12 +00001523
John McCall31168b02011-06-15 23:02:42 +00001524 bool doStore = true;
1525
1526 Qualifiers qs = Ty.getQualifiers();
1527
1528 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1529 // We honor __attribute__((ns_consumed)) for types with lifetime.
1530 // For __strong, it's handled by just skipping the initial retain;
1531 // otherwise we have to balance out the initial +1 with an extra
1532 // cleanup to do the release at the end of the function.
1533 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1534
1535 // 'self' is always formally __strong, but if this is not an
1536 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001537 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001538 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1539 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001540 assert(lt == Qualifiers::OCL_Strong);
1541 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001542 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001543 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001544 lt = Qualifiers::OCL_ExplicitNone;
1545 }
1546
1547 if (lt == Qualifiers::OCL_Strong) {
1548 if (!isConsumed)
1549 // Don't use objc_retainBlock for block pointers, because we
1550 // don't want to Block_copy something just because we got it
1551 // as a parameter.
1552 Arg = EmitARCRetainNonBlock(Arg);
1553 } else {
1554 // Push the cleanup for a consumed parameter.
1555 if (isConsumed)
1556 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg);
1557
1558 if (lt == Qualifiers::OCL_Weak) {
1559 EmitARCInitWeak(DeclPtr, Arg);
Chad Rosier1d9cdb62012-02-18 01:20:35 +00001560 doStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001561 }
1562 }
1563
1564 // Enter the cleanup scope.
1565 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1566 }
1567
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001568 // Store the initial value into the alloca.
John McCall55e1fbc2011-06-25 02:11:03 +00001569 if (doStore) {
1570 LValue lv = MakeAddrLValue(DeclPtr, Ty,
Eli Friedmana0544d62011-12-03 04:14:32 +00001571 getContext().getDeclAlign(&D));
David Chisnallfa35df62012-01-16 17:27:18 +00001572 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
John McCall55e1fbc2011-06-25 02:11:03 +00001573 }
Chris Lattner53621a52007-06-13 20:44:40 +00001574 }
1575
1576 llvm::Value *&DMEntry = LocalDeclMap[&D];
1577 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1578 DMEntry = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001579
1580 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001581 if (CGDebugInfo *DI = getDebugInfo()) {
1582 if (CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) {
1583 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1584 }
1585 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001586
1587 if (D.hasAttr<AnnotateAttr>())
1588 EmitVarAnnotations(&D, DeclPtr);
Chris Lattner53621a52007-06-13 20:44:40 +00001589}