blob: ae9753b03df34a535aced4b70710f57a3b62c115 [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"
Daniel Dunbarad319a72008-08-11 05:00:27 +000017#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/Decl.h"
Anders Carlsson4c03d982008-08-25 01:38:19 +000020#include "clang/AST/DeclObjC.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000021#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000022#include "clang/Basic/TargetInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000023#include "clang/Frontend/CodeGenOptions.h"
Anders Carlssonf94cd1f2007-10-17 00:52:43 +000024#include "llvm/GlobalVariable.h"
Anders Carlsson30032882008-12-12 07:38:43 +000025#include "llvm/Intrinsics.h"
Mike Stump97d01d52009-03-04 03:23:46 +000026#include "llvm/Target/TargetData.h"
Chris Lattner53621a52007-06-13 20:44:40 +000027#include "llvm/Type.h"
Chris Lattner84915fa2007-06-02 04:16:21 +000028using namespace clang;
29using namespace CodeGen;
30
31
Chris Lattner1ad38f82007-06-09 01:20:56 +000032void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000033 switch (D.getKind()) {
Douglas Gregor19043f02010-04-23 02:02:43 +000034 case Decl::TranslationUnit:
35 case Decl::Namespace:
36 case Decl::UnresolvedUsingTypename:
37 case Decl::ClassTemplateSpecialization:
38 case Decl::ClassTemplatePartialSpecialization:
39 case Decl::TemplateTypeParm:
40 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000041 case Decl::NonTypeTemplateParm:
Douglas Gregor19043f02010-04-23 02:02:43 +000042 case Decl::CXXMethod:
43 case Decl::CXXConstructor:
44 case Decl::CXXDestructor:
45 case Decl::CXXConversion:
46 case Decl::Field:
Francois Pichetdf946c32010-11-21 06:49:41 +000047 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000048 case Decl::ObjCIvar:
49 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000050 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000051 case Decl::ImplicitParam:
52 case Decl::ClassTemplate:
53 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000054 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000055 case Decl::TemplateTemplateParm:
56 case Decl::ObjCMethod:
57 case Decl::ObjCCategory:
58 case Decl::ObjCProtocol:
59 case Decl::ObjCInterface:
60 case Decl::ObjCCategoryImpl:
61 case Decl::ObjCImplementation:
62 case Decl::ObjCProperty:
63 case Decl::ObjCCompatibleAlias:
Abramo Bagnarad7340582010-06-05 05:09:32 +000064 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000065 case Decl::LinkageSpec:
66 case Decl::ObjCPropertyImpl:
67 case Decl::ObjCClass:
68 case Decl::ObjCForwardProtocol:
69 case Decl::FileScopeAsm:
70 case Decl::Friend:
71 case Decl::FriendTemplate:
72 case Decl::Block:
Devang Patel095421b2011-04-05 20:28:21 +000073 assert(0 && "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;
Chris Lattner84915fa2007-06-02 04:16:21 +000085 // None of these decls require codegen support.
86 return;
Mike Stump11289f42009-09-09 15:08:12 +000087
Daniel Dunbara7998072008-08-29 17:28:43 +000088 case Decl::Var: {
89 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +000090 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +000091 "Should not see file-scope variables inside a function!");
John McCall1c9c3fd2010-10-15 04:57:14 +000092 return EmitVarDecl(VD);
Chris Lattner84915fa2007-06-02 04:16:21 +000093 }
Mike Stump11289f42009-09-09 15:08:12 +000094
Richard Smithdda56e42011-04-15 14:24:37 +000095 case Decl::Typedef: // typedef int X;
96 case Decl::TypeAlias: { // using X = int; [C++0x]
97 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +000098 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +000099
Anders Carlsson5d985f52008-12-20 21:51:53 +0000100 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000101 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000102 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000103 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000104}
Chris Lattner03df1222007-06-02 04:53:11 +0000105
John McCall1c9c3fd2010-10-15 04:57:14 +0000106/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000107/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000108void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Chris Lattner03df1222007-06-02 04:53:11 +0000109 switch (D.getStorageClass()) {
John McCall8e7d6562010-08-26 03:08:43 +0000110 case SC_None:
111 case SC_Auto:
112 case SC_Register:
John McCall1c9c3fd2010-10-15 04:57:14 +0000113 return EmitAutoVarDecl(D);
John McCall8e7d6562010-08-26 03:08:43 +0000114 case SC_Static: {
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000115 llvm::GlobalValue::LinkageTypes Linkage =
116 llvm::GlobalValue::InternalLinkage;
117
John McCall7cb02202010-05-25 04:30:21 +0000118 // If the function definition has some sort of weak linkage, its
119 // static variables should also be weak so that they get properly
120 // uniqued. We can't do this in C, though, because there's no
121 // standard way to agree on which variables are the same (i.e.
122 // there's no mangling).
123 if (getContext().getLangOptions().CPlusPlus)
124 if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
125 Linkage = CurFn->getLinkage();
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000126
John McCall1c9c3fd2010-10-15 04:57:14 +0000127 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000128 }
John McCall8e7d6562010-08-26 03:08:43 +0000129 case SC_Extern:
130 case SC_PrivateExtern:
Lauro Ramos Venanciobada8d42008-02-16 22:30:38 +0000131 // Don't emit it now, allow it to be emitted lazily on its first use.
132 return;
Chris Lattner03df1222007-06-02 04:53:11 +0000133 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +0000134
135 assert(0 && "Unknown storage class");
Chris Lattner03df1222007-06-02 04:53:11 +0000136}
137
Chris Lattnere99c1102009-12-05 08:22:11 +0000138static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
139 const char *Separator) {
140 CodeGenModule &CGM = CGF.CGM;
John McCall7ec50432010-03-19 23:29:14 +0000141 if (CGF.getContext().getLangOptions().CPlusPlus) {
Anders Carlssonea836bc2010-06-22 16:16:50 +0000142 llvm::StringRef Name = CGM.getMangledName(&D);
143 return Name.str();
John McCall7ec50432010-03-19 23:29:14 +0000144 }
Chris Lattnere99c1102009-12-05 08:22:11 +0000145
146 std::string ContextName;
Fariborz Jahanian3a4ea9a2010-11-30 23:07:14 +0000147 if (!CGF.CurFuncDecl) {
148 // Better be in a block declared in global scope.
149 const NamedDecl *ND = cast<NamedDecl>(&D);
150 const DeclContext *DC = ND->getDeclContext();
151 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
152 MangleBuffer Name;
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000153 CGM.getBlockMangledName(GlobalDecl(), Name, BD);
Fariborz Jahanian3a4ea9a2010-11-30 23:07:14 +0000154 ContextName = Name.getString();
155 }
156 else
157 assert(0 && "Unknown context for block static var decl");
158 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
Anders Carlssonea836bc2010-06-22 16:16:50 +0000159 llvm::StringRef Name = CGM.getMangledName(FD);
160 ContextName = Name.str();
John McCall7ec50432010-03-19 23:29:14 +0000161 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattnere99c1102009-12-05 08:22:11 +0000162 ContextName = CGF.CurFn->getName();
163 else
Fariborz Jahanian3a4ea9a2010-11-30 23:07:14 +0000164 assert(0 && "Unknown context for static var decl");
Chris Lattnere99c1102009-12-05 08:22:11 +0000165
166 return ContextName + Separator + D.getNameAsString();
167}
168
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000169llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000170CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
171 const char *Separator,
172 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000173 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000174 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000175
Chris Lattnere99c1102009-12-05 08:22:11 +0000176 std::string Name = GetStaticDeclName(*this, D, Separator);
Nate Begemanfaae0812008-04-19 04:17:09 +0000177
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000178 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Anders Carlssone33eed52009-09-26 18:16:06 +0000179 llvm::GlobalVariable *GV =
180 new llvm::GlobalVariable(CGM.getModule(), LTy,
181 Ty.isConstant(getContext()), Linkage,
182 CGM.EmitNullConstant(D.getType()), Name, 0,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000183 D.isThreadSpecified(),
184 CGM.getContext().getTargetAddressSpace(Ty));
Ken Dyck160146e2010-01-27 17:10:57 +0000185 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
John McCall8e7cb6d2010-11-02 21:04:24 +0000186 if (Linkage != llvm::GlobalValue::InternalLinkage)
187 GV->setVisibility(CurFn->getVisibility());
Anders Carlssone33eed52009-09-26 18:16:06 +0000188 return GV;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000189}
190
John McCall1c9c3fd2010-10-15 04:57:14 +0000191/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
Chris Lattnere99c1102009-12-05 08:22:11 +0000192/// global variable that has already been created for it. If the initializer
193/// has a different type than GV does, this may free GV and return a different
194/// one. Otherwise it just returns GV.
195llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000196CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
197 llvm::GlobalVariable *GV) {
Chris Lattnere99c1102009-12-05 08:22:11 +0000198 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this);
John McCall70013b62010-07-15 23:40:35 +0000199
Chris Lattnere99c1102009-12-05 08:22:11 +0000200 // If constant emission failed, then this should be a C++ static
201 // initializer.
202 if (!Init) {
203 if (!getContext().getLangOptions().CPlusPlus)
204 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall68ff0372010-09-08 01:44:27 +0000205 else if (Builder.GetInsertBlock()) {
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000206 // Since we have a static initializer, this global variable can't
207 // be constant.
208 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000209
John McCallcdf7ef52010-11-06 09:44:32 +0000210 EmitCXXGuardedInit(D, GV);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000211 }
Chris Lattnere99c1102009-12-05 08:22:11 +0000212 return GV;
213 }
John McCall70013b62010-07-15 23:40:35 +0000214
Chris Lattnere99c1102009-12-05 08:22:11 +0000215 // The initializer may differ in type from the global. Rewrite
216 // the global to match the initializer. (We have to do this
217 // because some types, like unions, can't be completely represented
218 // in the LLVM type system.)
John McCall56f57582010-09-03 18:58:50 +0000219 if (GV->getType()->getElementType() != Init->getType()) {
Chris Lattnere99c1102009-12-05 08:22:11 +0000220 llvm::GlobalVariable *OldGV = GV;
221
222 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
223 OldGV->isConstant(),
224 OldGV->getLinkage(), Init, "",
John McCall8e7cb6d2010-11-02 21:04:24 +0000225 /*InsertBefore*/ OldGV,
226 D.isThreadSpecified(),
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000227 CGM.getContext().getTargetAddressSpace(D.getType()));
John McCall8e7cb6d2010-11-02 21:04:24 +0000228 GV->setVisibility(OldGV->getVisibility());
Chris Lattnere99c1102009-12-05 08:22:11 +0000229
230 // Steal the name of the old global
231 GV->takeName(OldGV);
232
233 // Replace all uses of the old global with the new global
234 llvm::Constant *NewPtrForOldDecl =
235 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
236 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
237
238 // Erase the old global, since it is no longer used.
239 OldGV->eraseFromParent();
240 }
241
242 GV->setInitializer(Init);
243 return GV;
244}
245
John McCall1c9c3fd2010-10-15 04:57:14 +0000246void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000247 llvm::GlobalValue::LinkageTypes Linkage) {
Daniel Dunbara374e602009-02-25 19:45:19 +0000248 llvm::Value *&DMEntry = LocalDeclMap[&D];
249 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
Mike Stump11289f42009-09-09 15:08:12 +0000250
John McCall1c9c3fd2010-10-15 04:57:14 +0000251 llvm::GlobalVariable *GV = CreateStaticVarDecl(D, ".", Linkage);
Daniel Dunbara374e602009-02-25 19:45:19 +0000252
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000253 // Store into LocalDeclMap before generating initializer to handle
254 // circular references.
255 DMEntry = GV;
256
John McCall4a39ab82010-05-04 20:45:42 +0000257 // We can't have a VLA here, but we can have a pointer to a VLA,
258 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000259 // Make sure to evaluate VLA bounds now so that we have them for later.
260 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000261 EmitVariablyModifiedType(D.getType());
Fariborz Jahanian366a9482010-09-07 23:26:17 +0000262
263 // Local static block variables must be treated as globals as they may be
264 // referenced in their RHS initializer block-literal expresion.
265 CGM.setStaticLocalDeclAddress(&D, GV);
Eli Friedmanbc633be2009-04-20 03:54:15 +0000266
Chris Lattnere99c1102009-12-05 08:22:11 +0000267 // If this value has an initializer, emit it.
268 if (D.getInit())
John McCall1c9c3fd2010-10-15 04:57:14 +0000269 GV = AddInitializerToStaticVarDecl(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +0000270
Chris Lattner4d941092010-03-10 23:59:59 +0000271 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
272
Daniel Dunbar53bf7412009-02-12 23:32:54 +0000273 // FIXME: Merge attribute handling.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000274 if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
Nate Begemanfaae0812008-04-19 04:17:09 +0000275 SourceManager &SM = CGM.getContext().getSourceManager();
276 llvm::Constant *Ann =
Mike Stump11289f42009-09-09 15:08:12 +0000277 CGM.EmitAnnotateAttr(GV, AA,
Chris Lattner8a425862009-01-16 07:36:28 +0000278 SM.getInstantiationLineNumber(D.getLocation()));
Nate Begemanfaae0812008-04-19 04:17:09 +0000279 CGM.AddAnnotation(Ann);
280 }
281
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000282 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
Daniel Dunbar53bf7412009-02-12 23:32:54 +0000283 GV->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000284
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000285 if (D.hasAttr<UsedAttr>())
Daniel Dunbar128a1382009-02-13 22:08:43 +0000286 CGM.AddUsedGlobal(GV);
287
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000288 // We may have to cast the constant because of the initializer
289 // mismatch above.
290 //
291 // FIXME: It is really dangerous to store this in the map; if anyone
292 // RAUW's the GV uses of this constant will be invalid.
Eli Friedmanc98a7ad2008-06-08 01:23:18 +0000293 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000294 const llvm::Type *LPtrTy =
295 LTy->getPointerTo(CGM.getContext().getTargetAddressSpace(D.getType()));
Owen Andersonade90fd2009-07-29 18:54:39 +0000296 DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000297
298 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000299 CGDebugInfo *DI = getDebugInfo();
Mike Stumpf5a5c4f2009-02-20 00:19:45 +0000300 if (DI) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000301 DI->setLocation(D.getLocation());
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000302 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
303 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000304}
Mike Stump11289f42009-09-09 15:08:12 +0000305
John McCall2b7fc382010-07-13 20:32:21 +0000306namespace {
John McCall82fe67b2011-07-09 01:37:26 +0000307 struct DestroyObject : EHScopeStack::Cleanup {
308 DestroyObject(llvm::Value *addr, QualType type,
309 CodeGenFunction::Destroyer *destroyer)
310 : addr(addr), type(type), destroyer(*destroyer) {}
John McCall2b7fc382010-07-13 20:32:21 +0000311
John McCall82fe67b2011-07-09 01:37:26 +0000312 llvm::Value *addr;
313 QualType type;
314 CodeGenFunction::Destroyer &destroyer;
John McCall2b7fc382010-07-13 20:32:21 +0000315
316 void Emit(CodeGenFunction &CGF, bool IsForEH) {
John McCall82fe67b2011-07-09 01:37:26 +0000317 CGF.emitDestroy(addr, type, destroyer);
John McCall2b7fc382010-07-13 20:32:21 +0000318 }
319 };
320
John McCall82fe67b2011-07-09 01:37:26 +0000321 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
322 DestroyNRVOVariable(llvm::Value *addr,
323 const CXXDestructorDecl *Dtor,
324 llvm::Value *NRVOFlag)
325 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000326
327 const CXXDestructorDecl *Dtor;
328 llvm::Value *NRVOFlag;
329 llvm::Value *Loc;
330
331 void Emit(CodeGenFunction &CGF, bool IsForEH) {
332 // Along the exceptions path we always execute the dtor.
333 bool NRVO = !IsForEH && NRVOFlag;
334
335 llvm::BasicBlock *SkipDtorBB = 0;
336 if (NRVO) {
337 // If we exited via NRVO, we skip the destructor call.
338 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
339 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
340 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
341 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
342 CGF.EmitBlock(RunDtorBB);
343 }
344
345 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
346 /*ForVirtualBase=*/false, Loc);
347
348 if (NRVO) CGF.EmitBlock(SkipDtorBB);
349 }
350 };
John McCall2b7fc382010-07-13 20:32:21 +0000351
John McCallcda666c2010-07-21 07:22:38 +0000352 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000353 llvm::Value *Stack;
354 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
355 void Emit(CodeGenFunction &CGF, bool IsForEH) {
356 llvm::Value *V = CGF.Builder.CreateLoad(Stack, "tmp");
357 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
358 CGF.Builder.CreateCall(F, V);
359 }
360 };
361
John McCall1bd25562011-06-24 23:21:27 +0000362 struct ExtendGCLifetime : EHScopeStack::Cleanup {
363 const VarDecl &Var;
364 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
365
366 void Emit(CodeGenFunction &CGF, bool forEH) {
367 // Compute the address of the local variable, in case it's a
368 // byref or something.
369 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue,
370 SourceLocation());
371 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
372 CGF.EmitExtendGCLifetime(value);
373 }
374 };
375
John McCallcda666c2010-07-21 07:22:38 +0000376 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000377 llvm::Constant *CleanupFn;
378 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000379 const VarDecl &Var;
380
381 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000382 const VarDecl *Var)
383 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000384
385 void Emit(CodeGenFunction &CGF, bool IsForEH) {
John McCallc533cb72011-02-22 06:44:22 +0000386 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue,
387 SourceLocation());
388 // Compute the address of the local variable, in case it's a byref
389 // or something.
390 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
391
John McCalla464ff92010-07-21 06:13:08 +0000392 // In some cases, the type of the function argument will be different from
393 // the type of the pointer. An example of this is
394 // void f(void* arg);
395 // __attribute__((cleanup(f))) void *g;
396 //
397 // To fix this we insert a bitcast here.
398 QualType ArgTy = FnInfo.arg_begin()->type;
399 llvm::Value *Arg =
400 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
401
402 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000403 Args.add(RValue::get(Arg),
404 CGF.getContext().getPointerType(Var.getType()));
John McCalla464ff92010-07-21 06:13:08 +0000405 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
406 }
407 };
John McCalla464ff92010-07-21 06:13:08 +0000408}
409
John McCall31168b02011-06-15 23:02:42 +0000410/// EmitAutoVarWithLifetime - Does the setup required for an automatic
411/// variable with lifetime.
412static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
413 llvm::Value *addr,
414 Qualifiers::ObjCLifetime lifetime) {
415 switch (lifetime) {
416 case Qualifiers::OCL_None:
417 llvm_unreachable("present but none");
418
419 case Qualifiers::OCL_ExplicitNone:
420 // nothing to do
421 break;
422
423 case Qualifiers::OCL_Strong: {
424 CGF.PushARCReleaseCleanup(CGF.getARCCleanupKind(),
425 var.getType(), addr,
426 var.hasAttr<ObjCPreciseLifetimeAttr>());
427 break;
428 }
429 case Qualifiers::OCL_Autoreleasing:
430 // nothing to do
431 break;
432
433 case Qualifiers::OCL_Weak:
434 // __weak objects always get EH cleanups; otherwise, exceptions
435 // could cause really nasty crashes instead of mere leaks.
436 CGF.PushARCWeakReleaseCleanup(NormalAndEHCleanup, var.getType(), addr);
437 break;
438 }
439}
440
441static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
442 if (const Expr *e = dyn_cast<Expr>(s)) {
443 // Skip the most common kinds of expressions that make
444 // hierarchy-walking expensive.
445 s = e = e->IgnoreParenCasts();
446
447 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
448 return (ref->getDecl() == &var);
449 }
450
451 for (Stmt::const_child_range children = s->children(); children; ++children)
Fariborz Jahanian326701e2011-06-29 20:00:16 +0000452 // children might be null; as in missing decl or conditional of an if-stmt.
453 if ((*children) && isAccessedBy(var, *children))
John McCall31168b02011-06-15 23:02:42 +0000454 return true;
455
456 return false;
457}
458
459static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
460 if (!decl) return false;
461 if (!isa<VarDecl>(decl)) return false;
462 const VarDecl *var = cast<VarDecl>(decl);
463 return isAccessedBy(*var, e);
464}
465
John McCall1553b192011-06-16 04:16:24 +0000466static void drillIntoBlockVariable(CodeGenFunction &CGF,
467 LValue &lvalue,
468 const VarDecl *var) {
469 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
470}
471
John McCall31168b02011-06-15 23:02:42 +0000472void CodeGenFunction::EmitScalarInit(const Expr *init,
473 const ValueDecl *D,
John McCall1553b192011-06-16 04:16:24 +0000474 LValue lvalue,
475 bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000476 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000477 if (!lifetime) {
478 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000479 if (capturedByInit)
480 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall55e1fbc2011-06-25 02:11:03 +0000481 EmitStoreThroughLValue(RValue::get(value), lvalue);
John McCall31168b02011-06-15 23:02:42 +0000482 return;
483 }
484
485 // If we're emitting a value with lifetime, we have to do the
486 // initialization *before* we leave the cleanup scopes.
487 CodeGenFunction::RunCleanupsScope Scope(*this);
488 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init))
489 init = ewc->getSubExpr();
490
491 // We have to maintain the illusion that the variable is
492 // zero-initialized. If the variable might be accessed in its
493 // initializer, zero-initialize before running the initializer, then
494 // actually perform the initialization with an assign.
495 bool accessedByInit = false;
496 if (lifetime != Qualifiers::OCL_ExplicitNone)
497 accessedByInit = isAccessedBy(D, init);
498 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000499 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000500 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000501 if (capturedByInit) {
502 // We can use a simple GEP for this because it can't have been
503 // moved yet.
John McCall1553b192011-06-16 04:16:24 +0000504 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
505 getByRefValueLLVMField(cast<VarDecl>(D))));
John McCall31168b02011-06-15 23:02:42 +0000506 }
507
John McCall1553b192011-06-16 04:16:24 +0000508 const llvm::PointerType *ty
509 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
John McCall31168b02011-06-15 23:02:42 +0000510 ty = cast<llvm::PointerType>(ty->getElementType());
511
512 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
513
514 // If __weak, we want to use a barrier under certain conditions.
515 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000516 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000517
518 // Otherwise just do a simple store.
519 else
John McCall1553b192011-06-16 04:16:24 +0000520 EmitStoreOfScalar(zero, tempLV);
John McCall31168b02011-06-15 23:02:42 +0000521 }
522
523 // Emit the initializer.
524 llvm::Value *value = 0;
525
526 switch (lifetime) {
527 case Qualifiers::OCL_None:
528 llvm_unreachable("present but none");
529
530 case Qualifiers::OCL_ExplicitNone:
531 // nothing to do
532 value = EmitScalarExpr(init);
533 break;
534
535 case Qualifiers::OCL_Strong: {
536 value = EmitARCRetainScalarExpr(init);
537 break;
538 }
539
540 case Qualifiers::OCL_Weak: {
541 // No way to optimize a producing initializer into this. It's not
542 // worth optimizing for, because the value will immediately
543 // disappear in the common case.
544 value = EmitScalarExpr(init);
545
John McCall1553b192011-06-16 04:16:24 +0000546 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000547 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000548 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000549 else
John McCall1553b192011-06-16 04:16:24 +0000550 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000551 return;
552 }
553
554 case Qualifiers::OCL_Autoreleasing:
555 value = EmitARCRetainAutoreleaseScalarExpr(init);
556 break;
557 }
558
John McCall1553b192011-06-16 04:16:24 +0000559 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000560
561 // If the variable might have been accessed by its initializer, we
562 // might have to initialize with a barrier. We have to do this for
563 // both __weak and __strong, but __weak got filtered out above.
564 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
John McCall1553b192011-06-16 04:16:24 +0000565 llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
566 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +0000567 EmitARCRelease(oldValue, /*precise*/ false);
568 return;
569 }
570
John McCall1553b192011-06-16 04:16:24 +0000571 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +0000572}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000573
John McCalld4631322011-06-17 06:42:21 +0000574/// EmitScalarInit - Initialize the given lvalue with the given object.
575void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
576 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
577 if (!lifetime)
John McCall55e1fbc2011-06-25 02:11:03 +0000578 return EmitStoreThroughLValue(RValue::get(init), lvalue);
John McCalld4631322011-06-17 06:42:21 +0000579
580 switch (lifetime) {
581 case Qualifiers::OCL_None:
582 llvm_unreachable("present but none");
583
584 case Qualifiers::OCL_ExplicitNone:
585 // nothing to do
586 break;
587
588 case Qualifiers::OCL_Strong:
589 init = EmitARCRetain(lvalue.getType(), init);
590 break;
591
592 case Qualifiers::OCL_Weak:
593 // Initialize and then skip the primitive store.
594 EmitARCInitWeak(lvalue.getAddress(), init);
595 return;
596
597 case Qualifiers::OCL_Autoreleasing:
598 init = EmitARCRetainAutorelease(lvalue.getType(), init);
599 break;
600 }
601
602 EmitStoreOfScalar(init, lvalue);
603}
604
Chris Lattnerb85025f2010-12-01 02:05:19 +0000605/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
606/// non-zero parts of the specified initializer with equal or fewer than
607/// NumStores scalar stores.
608static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
609 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000610 // Zero and Undef never requires any extra stores.
611 if (isa<llvm::ConstantAggregateZero>(Init) ||
612 isa<llvm::ConstantPointerNull>(Init) ||
613 isa<llvm::UndefValue>(Init))
614 return true;
615 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
616 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
617 isa<llvm::ConstantExpr>(Init))
618 return Init->isNullValue() || NumStores--;
619
620 // See if we can emit each element.
621 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
622 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
623 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
624 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
625 return false;
626 }
627 return true;
628 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000629
630 // Anything else is hard and scary.
631 return false;
632}
633
634/// emitStoresForInitAfterMemset - For inits that
635/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
636/// stores that would be required.
637static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000638 bool isVolatile, CGBuilderTy &Builder) {
Chris Lattnerb85025f2010-12-01 02:05:19 +0000639 // Zero doesn't require any stores.
Chris Lattnere6af8862010-12-02 01:58:41 +0000640 if (isa<llvm::ConstantAggregateZero>(Init) ||
641 isa<llvm::ConstantPointerNull>(Init) ||
642 isa<llvm::UndefValue>(Init))
643 return;
Chris Lattnerb85025f2010-12-01 02:05:19 +0000644
Chris Lattnere6af8862010-12-02 01:58:41 +0000645 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
646 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
647 isa<llvm::ConstantExpr>(Init)) {
648 if (!Init->isNullValue())
John McCallc533cb72011-02-22 06:44:22 +0000649 Builder.CreateStore(Init, Loc, isVolatile);
Chris Lattnere6af8862010-12-02 01:58:41 +0000650 return;
651 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000652
Chris Lattnere6af8862010-12-02 01:58:41 +0000653 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
654 "Unknown value type!");
655
656 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
657 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
658 if (Elt->isNullValue()) continue;
659
660 // Otherwise, get a pointer to the element and emit it.
661 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
John McCallc533cb72011-02-22 06:44:22 +0000662 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000663 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000664}
665
666
667/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
668/// plus some stores to initialize a local variable instead of using a memcpy
669/// from a constant global. It is beneficial to use memset if the global is all
670/// zeros, or mostly zeros and large.
671static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
672 uint64_t GlobalSize) {
673 // If a global is all zeros, always use a memset.
674 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
675
676
677 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
678 // do it if it will require 6 or fewer scalar stores.
679 // TODO: Should budget depends on the size? Avoiding a large global warrants
680 // plopping in more stores.
681 unsigned StoreBudget = 6;
682 uint64_t SizeLimit = 32;
683
684 return GlobalSize > SizeLimit &&
685 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
686}
687
688
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000689/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000690/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000691/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000692void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
693 AutoVarEmission emission = EmitAutoVarAlloca(D);
694 EmitAutoVarInit(emission);
695 EmitAutoVarCleanups(emission);
696}
Chris Lattner03df1222007-06-02 04:53:11 +0000697
John McCallc533cb72011-02-22 06:44:22 +0000698/// EmitAutoVarAlloca - Emit the alloca and debug information for a
699/// local variable. Does not emit initalization or destruction.
700CodeGenFunction::AutoVarEmission
701CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
702 QualType Ty = D.getType();
703
704 AutoVarEmission emission(D);
705
706 bool isByRef = D.hasAttr<BlocksAttr>();
707 emission.IsByRef = isByRef;
708
709 CharUnits alignment = getContext().getDeclAlign(&D);
710 emission.Alignment = alignment;
711
John McCall23c29fe2011-06-24 21:55:10 +0000712 // If the type is variably-modified, emit all the VLA sizes for it.
713 if (Ty->isVariablyModifiedType())
714 EmitVariablyModifiedType(Ty);
715
Chris Lattner03df1222007-06-02 04:53:11 +0000716 llvm::Value *DeclPtr;
Eli Friedmana682d392008-02-15 12:20:59 +0000717 if (Ty->isConstantSizeType()) {
Chris Lattnerb781dc792008-05-08 05:58:21 +0000718 if (!Target.useGlobalsForAutomaticVariables()) {
John McCallc533cb72011-02-22 06:44:22 +0000719 bool NRVO = getContext().getLangOptions().ElideConstructors &&
720 D.isNRVOVariable();
721
722 // If this value is a POD array or struct with a statically
723 // determinable constant initializer, there are optimizations we
724 // can do.
725 // TODO: we can potentially constant-evaluate non-POD structs and
726 // arrays as long as the initialization is trivial (e.g. if they
727 // have a non-trivial destructor, but not a non-trivial constructor).
728 if (D.getInit() &&
John McCall31168b02011-06-15 23:02:42 +0000729 (Ty->isArrayType() || Ty->isRecordType()) &&
730 (Ty.isPODType(getContext()) ||
731 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
John McCall8b0f4ff2010-08-02 21:13:48 +0000732 D.getInit()->isConstantInitializer(getContext(), false)) {
John McCallc533cb72011-02-22 06:44:22 +0000733
734 // If the variable's a const type, and it's neither an NRVO
735 // candidate nor a __block variable, emit it as a global instead.
736 if (CGM.getCodeGenOpts().MergeAllConstants && Ty.isConstQualified() &&
737 !NRVO && !isByRef) {
Douglas Gregor19da4e42011-03-06 23:28:21 +0000738 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +0000739
740 emission.Address = 0; // signal this condition to later callbacks
741 assert(emission.wasEmittedAsGlobal());
742 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +0000743 }
John McCallc533cb72011-02-22 06:44:22 +0000744
745 // Otherwise, tell the initialization code that we're in this case.
746 emission.IsConstantAggregate = true;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +0000747 }
748
Douglas Gregor290c93e2010-05-15 06:46:45 +0000749 // A normal fixed sized variable becomes an alloca in the entry block,
750 // unless it's an NRVO variable.
Eli Friedman3efa41a2009-03-04 04:25:14 +0000751 const llvm::Type *LTy = ConvertTypeForMem(Ty);
Douglas Gregor290c93e2010-05-15 06:46:45 +0000752
753 if (NRVO) {
754 // The named return value optimization: allocate this variable in the
755 // return slot, so that we can elide the copy when returning this
756 // variable (C++0x [class.copy]p34).
757 DeclPtr = ReturnValue;
Douglas Gregor9154b5d2010-05-17 15:52:46 +0000758
759 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
760 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
761 // Create a flag that is used to indicate when the NRVO was applied
762 // to this variable. Set it to zero to indicate that NRVO was not
763 // applied.
Chris Lattner46a7ad72010-12-01 01:47:15 +0000764 llvm::Value *Zero = Builder.getFalse();
John McCallc533cb72011-02-22 06:44:22 +0000765 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
Nick Lewycky8d222622011-02-16 23:59:08 +0000766 EnsureInsertPoint();
Douglas Gregor9154b5d2010-05-17 15:52:46 +0000767 Builder.CreateStore(Zero, NRVOFlag);
768
769 // Record the NRVO flag for this variable.
770 NRVOFlags[&D] = NRVOFlag;
John McCallc533cb72011-02-22 06:44:22 +0000771 emission.NRVOFlag = NRVOFlag;
Douglas Gregor9154b5d2010-05-17 15:52:46 +0000772 }
773 }
Douglas Gregor290c93e2010-05-15 06:46:45 +0000774 } else {
775 if (isByRef)
776 LTy = BuildByRefType(&D);
777
778 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
779 Alloc->setName(D.getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +0000780
John McCallc533cb72011-02-22 06:44:22 +0000781 CharUnits allocaAlignment = alignment;
Douglas Gregor290c93e2010-05-15 06:46:45 +0000782 if (isByRef)
John McCallc533cb72011-02-22 06:44:22 +0000783 allocaAlignment = std::max(allocaAlignment,
Ken Dyck9a648692011-01-18 02:01:14 +0000784 getContext().toCharUnitsFromBits(Target.getPointerAlign(0)));
John McCallc533cb72011-02-22 06:44:22 +0000785 Alloc->setAlignment(allocaAlignment.getQuantity());
Douglas Gregor290c93e2010-05-15 06:46:45 +0000786 DeclPtr = Alloc;
787 }
Chris Lattnerb781dc792008-05-08 05:58:21 +0000788 } else {
789 // Targets that don't support recursion emit locals as globals.
790 const char *Class =
John McCall8e7d6562010-08-26 03:08:43 +0000791 D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
John McCall1c9c3fd2010-10-15 04:57:14 +0000792 DeclPtr = CreateStaticVarDecl(D, Class,
793 llvm::GlobalValue::InternalLinkage);
Chris Lattnerb781dc792008-05-08 05:58:21 +0000794 }
Chris Lattner03df1222007-06-02 04:53:11 +0000795 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000796 EnsureInsertPoint();
797
Anders Carlsson15949b32009-02-09 20:41:50 +0000798 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +0000799 // Save the stack.
John McCallad7c5c12011-02-08 08:22:06 +0000800 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +0000801
Anders Carlsson30032882008-12-12 07:38:43 +0000802 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
803 llvm::Value *V = Builder.CreateCall(F);
Mike Stump11289f42009-09-09 15:08:12 +0000804
Anders Carlsson30032882008-12-12 07:38:43 +0000805 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +0000806
807 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +0000808
John McCalla464ff92010-07-21 06:13:08 +0000809 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +0000810 // FIXME: in general circumstances, this should be an EH cleanup.
John McCallcda666c2010-07-21 07:22:38 +0000811 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +0000812 }
Mike Stump11289f42009-09-09 15:08:12 +0000813
John McCall23c29fe2011-06-24 21:55:10 +0000814 llvm::Value *elementCount;
815 QualType elementType;
816 llvm::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +0000817
John McCall23c29fe2011-06-24 21:55:10 +0000818 const llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +0000819
820 // Allocate memory for the array.
John McCall23c29fe2011-06-24 21:55:10 +0000821 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
822 vla->setAlignment(alignment.getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +0000823
John McCall23c29fe2011-06-24 21:55:10 +0000824 DeclPtr = vla;
Chris Lattner03df1222007-06-02 04:53:11 +0000825 }
Eli Friedmanf4084702008-12-20 23:11:59 +0000826
Chris Lattner03df1222007-06-02 04:53:11 +0000827 llvm::Value *&DMEntry = LocalDeclMap[&D];
828 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
829 DMEntry = DeclPtr;
John McCallc533cb72011-02-22 06:44:22 +0000830 emission.Address = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +0000831
832 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +0000833 if (HaveInsertPoint())
834 if (CGDebugInfo *DI = getDebugInfo()) {
835 DI->setLocation(D.getLocation());
Devang Patel887e2152011-06-03 19:21:47 +0000836 if (Target.useGlobalsForAutomaticVariables()) {
837 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
838 } else
839 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
840 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +0000841
John McCallc533cb72011-02-22 06:44:22 +0000842 return emission;
843}
844
845/// Determines whether the given __block variable is potentially
846/// captured by the given expression.
847static bool isCapturedBy(const VarDecl &var, const Expr *e) {
848 // Skip the most common kinds of expressions that make
849 // hierarchy-walking expensive.
850 e = e->IgnoreParenCasts();
851
852 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
853 const BlockDecl *block = be->getBlockDecl();
854 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
855 e = block->capture_end(); i != e; ++i) {
856 if (i->getVariable() == &var)
857 return true;
858 }
859
860 // No need to walk into the subexpressions.
861 return false;
862 }
863
864 for (Stmt::const_child_range children = e->children(); children; ++children)
865 if (isCapturedBy(var, cast<Expr>(*children)))
866 return true;
867
868 return false;
869}
870
Douglas Gregor82e1af22011-07-01 21:08:19 +0000871/// \brief Determine whether the given initializer is trivial in the sense
872/// that it requires no code to be generated.
873static bool isTrivialInitializer(const Expr *Init) {
874 if (!Init)
875 return true;
876
877 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
878 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
879 if (Constructor->isTrivial() &&
880 Constructor->isDefaultConstructor() &&
881 !Construct->requiresZeroInitialization())
882 return true;
883
884 return false;
885}
John McCallc533cb72011-02-22 06:44:22 +0000886void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +0000887 assert(emission.Variable && "emission was not valid!");
888
John McCallc533cb72011-02-22 06:44:22 +0000889 // If this was emitted as a global constant, we're done.
890 if (emission.wasEmittedAsGlobal()) return;
891
John McCall9e2e22f2011-02-22 07:16:58 +0000892 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +0000893 QualType type = D.getType();
894
Chris Lattner07eb7332007-07-12 00:39:48 +0000895 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000896 const Expr *Init = D.getInit();
897
898 // If we are at an unreachable point, we don't need to emit the initializer
899 // unless it contains a label.
900 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +0000901 if (!Init || !ContainsLabel(Init)) return;
902 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000903 }
904
John McCall73064872011-03-31 01:59:53 +0000905 // Initialize the structure of a __block variable.
906 if (emission.IsByRef)
907 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +0000908
Douglas Gregor82e1af22011-07-01 21:08:19 +0000909 if (isTrivialInitializer(Init))
910 return;
911
Mon P Wangcc2ab0c2010-04-04 03:10:52 +0000912
John McCall73064872011-03-31 01:59:53 +0000913 CharUnits alignment = emission.Alignment;
914
John McCallc533cb72011-02-22 06:44:22 +0000915 // Check whether this is a byref variable that's potentially
916 // captured and moved by its own initializer. If so, we'll need to
917 // emit the initializer first, then copy into the variable.
918 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
919
920 llvm::Value *Loc =
921 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
922
John McCall1553b192011-06-16 04:16:24 +0000923 if (!emission.IsConstantAggregate) {
924 LValue lv = MakeAddrLValue(Loc, type, alignment.getQuantity());
925 lv.setNonGC(true);
926 return EmitExprAsInit(Init, &D, lv, capturedByInit);
927 }
John McCall91ca10f2011-03-08 09:11:50 +0000928
John McCallc533cb72011-02-22 06:44:22 +0000929 // If this is a simple aggregate initialization, we can optimize it
930 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +0000931 assert(!capturedByInit && "constant init contains a capturing block?");
John McCallc533cb72011-02-22 06:44:22 +0000932
John McCall91ca10f2011-03-08 09:11:50 +0000933 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +0000934
John McCall91ca10f2011-03-08 09:11:50 +0000935 llvm::Constant *constant = CGM.EmitConstantExpr(D.getInit(), type, this);
936 assert(constant != 0 && "Wasn't a simple constant init?");
John McCallc533cb72011-02-22 06:44:22 +0000937
John McCall91ca10f2011-03-08 09:11:50 +0000938 llvm::Value *SizeVal =
939 llvm::ConstantInt::get(IntPtrTy,
940 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +0000941
John McCall91ca10f2011-03-08 09:11:50 +0000942 const llvm::Type *BP = Int8PtrTy;
943 if (Loc->getType() != BP)
944 Loc = Builder.CreateBitCast(Loc, BP, "tmp");
Mon P Wangcc2ab0c2010-04-04 03:10:52 +0000945
John McCall91ca10f2011-03-08 09:11:50 +0000946 // If the initializer is all or mostly zeros, codegen with memset then do
947 // a few stores afterward.
948 if (shouldUseMemSetPlusStoresToInitialize(constant,
949 CGM.getTargetData().getTypeAllocSize(constant->getType()))) {
950 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
951 alignment.getQuantity(), isVolatile);
952 if (!constant->isNullValue()) {
953 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
954 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +0000955 }
John McCall91ca10f2011-03-08 09:11:50 +0000956 } else {
957 // Otherwise, create a temporary global with the initializer then
958 // memcpy from the global to the alloca.
959 std::string Name = GetStaticDeclName(*this, D, ".");
960 llvm::GlobalVariable *GV =
961 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
962 llvm::GlobalValue::InternalLinkage,
963 constant, Name, 0, false, 0);
964 GV->setAlignment(alignment.getQuantity());
Eli Friedmanb8578422011-05-27 22:32:55 +0000965 GV->setUnnamedAddr(true);
John McCall91ca10f2011-03-08 09:11:50 +0000966
967 llvm::Value *SrcPtr = GV;
968 if (SrcPtr->getType() != BP)
969 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
970
971 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
972 isVolatile);
973 }
974}
975
976/// Emit an expression as an initializer for a variable at the given
977/// location. The expression is not necessarily the normal
978/// initializer for the variable, and the address is not necessarily
979/// its normal location.
980///
981/// \param init the initializing expression
982/// \param var the variable to act as if we're initializing
983/// \param loc the address to initialize; its type is a pointer
984/// to the LLVM mapping of the variable's type
985/// \param alignment the alignment of the address
986/// \param capturedByInit true if the variable is a __block variable
987/// whose address is potentially changed by the initializer
988void CodeGenFunction::EmitExprAsInit(const Expr *init,
John McCall31168b02011-06-15 23:02:42 +0000989 const ValueDecl *D,
John McCall1553b192011-06-16 04:16:24 +0000990 LValue lvalue,
John McCall91ca10f2011-03-08 09:11:50 +0000991 bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +0000992 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +0000993
994 if (type->isReferenceType()) {
John McCall1553b192011-06-16 04:16:24 +0000995 RValue rvalue = EmitReferenceBindingToExpr(init, D);
John McCall31168b02011-06-15 23:02:42 +0000996 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +0000997 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall55e1fbc2011-06-25 02:11:03 +0000998 EmitStoreThroughLValue(rvalue, lvalue);
John McCallc533cb72011-02-22 06:44:22 +0000999 } else if (!hasAggregateLLVMType(type)) {
John McCall1553b192011-06-16 04:16:24 +00001000 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCallc533cb72011-02-22 06:44:22 +00001001 } else if (type->isAnyComplexType()) {
John McCall91ca10f2011-03-08 09:11:50 +00001002 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001003 if (capturedByInit)
1004 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1005 StoreComplexToAddr(complex, lvalue.getAddress(), lvalue.isVolatile());
John McCallc533cb72011-02-22 06:44:22 +00001006 } else {
1007 // TODO: how can we delay here if D is captured by its initializer?
John McCall1553b192011-06-16 04:16:24 +00001008 EmitAggExpr(init, AggValueSlot::forLValue(lvalue, true, false));
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001009 }
John McCallc533cb72011-02-22 06:44:22 +00001010}
John McCallbd309292010-07-06 01:34:17 +00001011
John McCall82fe67b2011-07-09 01:37:26 +00001012/// Enter a destroy cleanup for the given local variable.
1013void CodeGenFunction::emitAutoVarTypeCleanup(
1014 const CodeGenFunction::AutoVarEmission &emission,
1015 QualType::DestructionKind dtorKind) {
1016 assert(dtorKind != QualType::DK_none);
1017
1018 // Note that for __block variables, we want to destroy the
1019 // original stack object, not the possibly forwarded object.
1020 llvm::Value *addr = emission.getObjectAddress(*this);
1021
1022 const VarDecl *var = emission.Variable;
1023 QualType type = var->getType();
1024
1025 CleanupKind cleanupKind = NormalAndEHCleanup;
1026 CodeGenFunction::Destroyer *destroyer = 0;
1027
1028 switch (dtorKind) {
1029 case QualType::DK_none:
1030 llvm_unreachable("no cleanup for trivially-destructible variable");
1031
1032 case QualType::DK_cxx_destructor:
1033 // If there's an NRVO flag on the emission, we need a different
1034 // cleanup.
1035 if (emission.NRVOFlag) {
1036 assert(!type->isArrayType());
1037 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1038 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1039 emission.NRVOFlag);
1040 return;
1041 }
1042 break;
1043
1044 case QualType::DK_objc_strong_lifetime:
1045 // Suppress cleanups for pseudo-strong variables.
1046 if (var->isARCPseudoStrong()) return;
1047
1048 // Otherwise, consider whether to use an EH cleanup or not.
1049 cleanupKind = getARCCleanupKind();
1050
1051 // Use the imprecise destroyer by default.
1052 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1053 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1054 break;
1055
1056 case QualType::DK_objc_weak_lifetime:
1057 break;
1058 }
1059
1060 // If we haven't chosen a more specific destroyer, use the default.
1061 if (!destroyer) destroyer = &getDestroyer(dtorKind);
1062 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer);
1063}
1064
John McCallc533cb72011-02-22 06:44:22 +00001065void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001066 assert(emission.Variable && "emission was not valid!");
1067
John McCallc533cb72011-02-22 06:44:22 +00001068 // If this was emitted as a global constant, we're done.
1069 if (emission.wasEmittedAsGlobal()) return;
1070
John McCall9e2e22f2011-02-22 07:16:58 +00001071 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001072
John McCall82fe67b2011-07-09 01:37:26 +00001073 // Check the type for a cleanup.
1074 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1075 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001076
John McCall1bd25562011-06-24 23:21:27 +00001077 // In GC mode, honor objc_precise_lifetime.
1078 if (getLangOptions().getGCMode() != LangOptions::NonGC &&
1079 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1080 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1081 }
1082
John McCallc533cb72011-02-22 06:44:22 +00001083 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001084 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001085 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001086
John McCallc533cb72011-02-22 06:44:22 +00001087 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001088 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001089
Anders Carlsson6f5c1562009-04-26 00:34:20 +00001090 const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
John McCallc533cb72011-02-22 06:44:22 +00001091 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001092 }
Mike Stump626aecc2009-03-05 01:23:13 +00001093
John McCallc533cb72011-02-22 06:44:22 +00001094 // If this is a block variable, call _Block_object_destroy
1095 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001096 if (emission.IsByRef)
1097 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001098}
Chris Lattner53621a52007-06-13 20:44:40 +00001099
John McCall82fe67b2011-07-09 01:37:26 +00001100CodeGenFunction::Destroyer &
1101CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
John McCallc2f00012011-07-09 09:09:00 +00001102 // This is surprisingly compiler-dependent. GCC 4.2 can't bind
1103 // references to functions directly in returns, and using '*&foo'
1104 // confuses MSVC. Luckily, the following code pattern works in both.
1105 Destroyer *destroyer = 0;
John McCall82fe67b2011-07-09 01:37:26 +00001106 switch (kind) {
1107 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001108 case QualType::DK_cxx_destructor:
1109 destroyer = &destroyCXXObject;
1110 break;
1111 case QualType::DK_objc_strong_lifetime:
1112 destroyer = &destroyARCStrongPrecise;
1113 break;
1114 case QualType::DK_objc_weak_lifetime:
1115 destroyer = &destroyARCWeak;
1116 break;
John McCall82fe67b2011-07-09 01:37:26 +00001117 }
John McCallc2f00012011-07-09 09:09:00 +00001118 return *destroyer;
John McCall82fe67b2011-07-09 01:37:26 +00001119}
1120
1121void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
1122 QualType type, Destroyer &destroyer) {
1123 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer);
1124}
1125
1126void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
1127 Destroyer &destroyer) {
1128 const ArrayType *arrayType = getContext().getAsArrayType(type);
1129 if (!arrayType)
1130 return destroyer(*this, addr, type);
1131
1132 llvm::Value *begin = addr;
1133 llvm::Value *length = emitArrayLength(arrayType, type, begin);
1134 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1135 emitArrayDestroy(begin, end, type, destroyer);
1136}
1137
1138void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1139 llvm::Value *end,
1140 QualType type,
1141 Destroyer &destroyer) {
1142 assert(!type->isArrayType());
1143
1144 // The basic structure here is a do-while loop, because we don't
1145 // need to check for the zero-element case.
1146 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1147 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1148
1149 // Enter the loop body, making that address the current address.
1150 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1151 EmitBlock(bodyBB);
1152 llvm::PHINode *elementPast =
1153 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1154 elementPast->addIncoming(end, entryBB);
1155
1156 // Shift the address back by one element.
1157 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1158 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1159 "arraydestroy.element");
1160
1161 // Perform the actual destruction there.
1162 destroyer(*this, element, type);
1163
1164 // Check whether we've reached the end.
1165 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1166 Builder.CreateCondBr(done, doneBB, bodyBB);
1167 elementPast->addIncoming(element, Builder.GetInsertBlock());
1168
1169 // Done.
1170 EmitBlock(doneBB);
1171}
1172
1173namespace {
1174 class PartialArrayDestroy : public EHScopeStack::Cleanup {
1175 llvm::Value *ArrayBegin;
1176 llvm::Value *ArrayEndPointer;
1177 QualType ElementType;
1178 CodeGenFunction::Destroyer &Destroyer;
1179 public:
1180 PartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEndPointer,
1181 QualType elementType,
1182 CodeGenFunction::Destroyer *destroyer)
1183 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1184 ElementType(elementType), Destroyer(*destroyer) {}
1185
1186 void Emit(CodeGenFunction &CGF, bool isForEH) {
1187 llvm::Value *arrayBegin = ArrayBegin;
1188 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1189
1190 // It's possible for the count to be zero here, so we're going
1191 // to need a check. For the sake of prettier IR, we just want
1192 // to jump to the end of the array destroy loop. This assumes
1193 // the structure of the IR generated by emitArrayDestroy, but
1194 // that assumption is pretty reliable.
1195 llvm::Value *earlyTest =
1196 CGF.Builder.CreateICmpEQ(arrayBegin, arrayEnd, "pad.isempty");
1197
1198 llvm::BasicBlock *nextBB = CGF.createBasicBlock("pad.arraydestroy");
1199
1200 // For now, use a conditional branch with both successors the
1201 // same. We'll patch this later.
1202 llvm::BranchInst *br =
1203 CGF.Builder.CreateCondBr(earlyTest, nextBB, nextBB);
1204 CGF.EmitBlock(nextBB);
1205
1206 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1207
1208 // If the element type is itself an array, drill down.
1209 QualType type = ElementType;
1210 llvm::SmallVector<llvm::Value*,4> gepIndices;
1211 gepIndices.push_back(zero);
1212 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1213 // VLAs don't require a GEP index to walk into.
1214 if (!isa<VariableArrayType>(arrayType))
1215 gepIndices.push_back(zero);
1216 type = arrayType->getElementType();
1217 }
1218 if (gepIndices.size() != 1) {
1219 arrayBegin =
1220 CGF.Builder.CreateInBoundsGEP(arrayBegin, gepIndices.begin(),
1221 gepIndices.end(), "pad.arraybegin");
1222 arrayEnd =
1223 CGF.Builder.CreateInBoundsGEP(arrayEnd, gepIndices.begin(),
1224 gepIndices.end(), "pad.arrayend");
1225 }
1226
1227 CGF.emitArrayDestroy(arrayBegin, arrayEnd, type, Destroyer);
1228
1229 // Set the conditional branch's 'false' successor to doneBB.
1230 llvm::BasicBlock *doneBB = CGF.Builder.GetInsertBlock();
1231 assert(CGF.Builder.GetInsertPoint() == doneBB->begin());
1232 br->setSuccessor(1, doneBB);
1233 }
1234 };
1235}
1236
1237/// pushPartialArrayCleanup - Push a cleanup to destroy
1238/// already-constructed elements of the given array. The cleanup
1239/// may be popped with DeactivateCleanupBlock.
1240///
1241/// \param elementType - the immediate element type of the array;
1242/// possibly still an array type
1243/// \param array - a value of type elementType*
1244/// \param destructionKind - the kind of destruction required
1245/// \param initializedElementCount - a value of type size_t* holding
1246/// the number of successfully-constructed elements
1247void CodeGenFunction::pushPartialArrayCleanup(llvm::Value *array,
1248 QualType elementType,
1249 Destroyer &destroyer,
1250 llvm::Value *arrayEndPointer) {
1251 // FIXME: can this be in a conditional expression?
1252 EHStack.pushCleanup<PartialArrayDestroy>(EHCleanup, array, arrayEndPointer,
1253 elementType, &destroyer);
1254}
1255
John McCall31168b02011-06-15 23:02:42 +00001256namespace {
1257 /// A cleanup to perform a release of an object at the end of a
1258 /// function. This is used to balance out the incoming +1 of a
1259 /// ns_consumed argument when we can't reasonably do that just by
1260 /// not doing the initial retain for a __block argument.
1261 struct ConsumeARCParameter : EHScopeStack::Cleanup {
1262 ConsumeARCParameter(llvm::Value *param) : Param(param) {}
1263
1264 llvm::Value *Param;
1265
1266 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1267 CGF.EmitARCRelease(Param, /*precise*/ false);
1268 }
1269 };
1270}
1271
Mike Stump11289f42009-09-09 15:08:12 +00001272/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001273/// for the specified parameter and set up LocalDeclMap.
Devang Patel68a15252011-03-03 20:13:15 +00001274void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1275 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001276 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001277 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001278 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001279
1280 Arg->setName(D.getName());
1281
1282 // Use better IR generation for certain implicit parameters.
1283 if (isa<ImplicitParamDecl>(D)) {
1284 // The only implicit argument a block has is its literal.
1285 if (BlockInfo) {
1286 LocalDeclMap[&D] = Arg;
1287
1288 if (CGDebugInfo *DI = getDebugInfo()) {
1289 DI->setLocation(D.getLocation());
1290 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, Builder);
1291 }
1292
1293 return;
1294 }
1295 }
1296
Chris Lattnerfc4379f2008-04-06 23:10:54 +00001297 QualType Ty = D.getType();
Mike Stump11289f42009-09-09 15:08:12 +00001298
Chris Lattner53621a52007-06-13 20:44:40 +00001299 llvm::Value *DeclPtr;
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001300 // If this is an aggregate or variable sized value, reuse the input pointer.
1301 if (!Ty->isConstantSizeType() ||
1302 CodeGenFunction::hasAggregateLLVMType(Ty)) {
Chris Lattner53621a52007-06-13 20:44:40 +00001303 DeclPtr = Arg;
Chris Lattner53621a52007-06-13 20:44:40 +00001304 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001305 // Otherwise, create a temporary to hold the value.
Daniel Dunbara7566f12010-02-09 02:48:28 +00001306 DeclPtr = CreateMemTemp(Ty, D.getName() + ".addr");
Mike Stump11289f42009-09-09 15:08:12 +00001307
John McCall31168b02011-06-15 23:02:42 +00001308 bool doStore = true;
1309
1310 Qualifiers qs = Ty.getQualifiers();
1311
1312 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1313 // We honor __attribute__((ns_consumed)) for types with lifetime.
1314 // For __strong, it's handled by just skipping the initial retain;
1315 // otherwise we have to balance out the initial +1 with an extra
1316 // cleanup to do the release at the end of the function.
1317 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1318
1319 // 'self' is always formally __strong, but if this is not an
1320 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001321 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001322 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1323 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001324 assert(lt == Qualifiers::OCL_Strong);
1325 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001326 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001327 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001328 lt = Qualifiers::OCL_ExplicitNone;
1329 }
1330
1331 if (lt == Qualifiers::OCL_Strong) {
1332 if (!isConsumed)
1333 // Don't use objc_retainBlock for block pointers, because we
1334 // don't want to Block_copy something just because we got it
1335 // as a parameter.
1336 Arg = EmitARCRetainNonBlock(Arg);
1337 } else {
1338 // Push the cleanup for a consumed parameter.
1339 if (isConsumed)
1340 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg);
1341
1342 if (lt == Qualifiers::OCL_Weak) {
1343 EmitARCInitWeak(DeclPtr, Arg);
1344 doStore = false; // The weak init is a store, no need to do two
1345 }
1346 }
1347
1348 // Enter the cleanup scope.
1349 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1350 }
1351
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001352 // Store the initial value into the alloca.
John McCall55e1fbc2011-06-25 02:11:03 +00001353 if (doStore) {
1354 LValue lv = MakeAddrLValue(DeclPtr, Ty,
1355 getContext().getDeclAlign(&D).getQuantity());
1356 EmitStoreOfScalar(Arg, lv);
1357 }
Chris Lattner53621a52007-06-13 20:44:40 +00001358 }
1359
1360 llvm::Value *&DMEntry = LocalDeclMap[&D];
1361 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1362 DMEntry = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001363
1364 // Emit debug info for param declaration.
Devang Patel7bf741a2011-06-15 17:57:08 +00001365 if (CGDebugInfo *DI = getDebugInfo())
Devang Patel68a15252011-03-03 20:13:15 +00001366 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
Chris Lattner53621a52007-06-13 20:44:40 +00001367}