blob: a11861c3e7ffe72e8815595e90b952cec7e800ab [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:
54 case Decl::TemplateTemplateParm:
55 case Decl::ObjCMethod:
56 case Decl::ObjCCategory:
57 case Decl::ObjCProtocol:
58 case Decl::ObjCInterface:
59 case Decl::ObjCCategoryImpl:
60 case Decl::ObjCImplementation:
61 case Decl::ObjCProperty:
62 case Decl::ObjCCompatibleAlias:
Abramo Bagnarad7340582010-06-05 05:09:32 +000063 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000064 case Decl::LinkageSpec:
65 case Decl::ObjCPropertyImpl:
66 case Decl::ObjCClass:
67 case Decl::ObjCForwardProtocol:
68 case Decl::FileScopeAsm:
69 case Decl::Friend:
70 case Decl::FriendTemplate:
71 case Decl::Block:
72
73 assert(0 && "Declaration not 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 Lattner84915fa2007-06-02 04:16:21 +000084 // None of these decls require codegen support.
85 return;
Mike Stump11289f42009-09-09 15:08:12 +000086
Daniel Dunbara7998072008-08-29 17:28:43 +000087 case Decl::Var: {
88 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +000089 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +000090 "Should not see file-scope variables inside a function!");
John McCall1c9c3fd2010-10-15 04:57:14 +000091 return EmitVarDecl(VD);
Chris Lattner84915fa2007-06-02 04:16:21 +000092 }
Mike Stump11289f42009-09-09 15:08:12 +000093
Anders Carlsson5d985f52008-12-20 21:51:53 +000094 case Decl::Typedef: { // typedef int X;
95 const TypedefDecl &TD = cast<TypedefDecl>(D);
96 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +000097
Anders Carlsson5d985f52008-12-20 21:51:53 +000098 if (Ty->isVariablyModifiedType())
99 EmitVLASize(Ty);
100 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000101 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000102}
Chris Lattner03df1222007-06-02 04:53:11 +0000103
John McCall1c9c3fd2010-10-15 04:57:14 +0000104/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000105/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000106void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000107 if (D.hasAttr<AsmLabelAttr>())
Fariborz Jahanianed308a92009-03-30 20:32:06 +0000108 CGM.ErrorUnsupported(&D, "__asm__");
Mike Stump11289f42009-09-09 15:08:12 +0000109
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: {
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000116 llvm::GlobalValue::LinkageTypes Linkage =
117 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).
124 if (getContext().getLangOptions().CPlusPlus)
125 if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
126 Linkage = CurFn->getLinkage();
Anders Carlssoncee2d2f2010-02-07 02:03:08 +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;
Chris Lattner03df1222007-06-02 04:53:11 +0000134 }
Daniel Dunbar0ca16602009-04-14 02:25:56 +0000135
136 assert(0 && "Unknown storage class");
Chris Lattner03df1222007-06-02 04:53:11 +0000137}
138
Chris Lattnere99c1102009-12-05 08:22:11 +0000139static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
140 const char *Separator) {
141 CodeGenModule &CGM = CGF.CGM;
John McCall7ec50432010-03-19 23:29:14 +0000142 if (CGF.getContext().getLangOptions().CPlusPlus) {
Anders Carlssonea836bc2010-06-22 16:16:50 +0000143 llvm::StringRef Name = CGM.getMangledName(&D);
144 return Name.str();
John McCall7ec50432010-03-19 23:29:14 +0000145 }
Chris Lattnere99c1102009-12-05 08:22:11 +0000146
147 std::string ContextName;
Fariborz Jahanian3a4ea9a2010-11-30 23:07:14 +0000148 if (!CGF.CurFuncDecl) {
149 // Better be in a block declared in global scope.
150 const NamedDecl *ND = cast<NamedDecl>(&D);
151 const DeclContext *DC = ND->getDeclContext();
152 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
153 MangleBuffer Name;
154 CGM.getMangledName(GlobalDecl(), Name, BD);
155 ContextName = Name.getString();
156 }
157 else
158 assert(0 && "Unknown context for block static var decl");
159 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
Anders Carlssonea836bc2010-06-22 16:16:50 +0000160 llvm::StringRef Name = CGM.getMangledName(FD);
161 ContextName = Name.str();
John McCall7ec50432010-03-19 23:29:14 +0000162 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattnere99c1102009-12-05 08:22:11 +0000163 ContextName = CGF.CurFn->getName();
164 else
Fariborz Jahanian3a4ea9a2010-11-30 23:07:14 +0000165 assert(0 && "Unknown context for static var decl");
Chris Lattnere99c1102009-12-05 08:22:11 +0000166
167 return ContextName + Separator + D.getNameAsString();
168}
169
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000170llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000171CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
172 const char *Separator,
173 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000174 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000175 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000176
Chris Lattnere99c1102009-12-05 08:22:11 +0000177 std::string Name = GetStaticDeclName(*this, D, Separator);
Nate Begemanfaae0812008-04-19 04:17:09 +0000178
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000179 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Anders Carlssone33eed52009-09-26 18:16:06 +0000180 llvm::GlobalVariable *GV =
181 new llvm::GlobalVariable(CGM.getModule(), LTy,
182 Ty.isConstant(getContext()), Linkage,
183 CGM.EmitNullConstant(D.getType()), Name, 0,
184 D.isThreadSpecified(), Ty.getAddressSpace());
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(),
Chris Lattnere99c1102009-12-05 08:22:11 +0000227 D.getType().getAddressSpace());
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())
261 EmitVLASize(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());
294 const llvm::Type *LPtrTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000295 llvm::PointerType::get(LTy, D.getType().getAddressSpace());
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
Anders Carlsson0168f4b2009-09-12 02:14:24 +0000306unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
307 assert(ByRefValueInfo.count(VD) && "Did not find value!");
308
309 return ByRefValueInfo.find(VD)->second.second;
310}
311
Mike Stump97d01d52009-03-04 03:23:46 +0000312/// BuildByRefType - This routine changes a __block variable declared as T x
313/// into:
314///
315/// struct {
316/// void *__isa;
317/// void *__forwarding;
318/// int32_t __flags;
319/// int32_t __size;
Mike Stump2114d7c2009-09-22 02:12:52 +0000320/// void *__copy_helper; // only if needed
321/// void *__destroy_helper; // only if needed
322/// char padding[X]; // only if needed
Mike Stump97d01d52009-03-04 03:23:46 +0000323/// T x;
324/// } x
325///
Anders Carlsson71d1d922009-09-09 02:51:03 +0000326const llvm::Type *CodeGenFunction::BuildByRefType(const ValueDecl *D) {
Anders Carlsson0168f4b2009-09-12 02:14:24 +0000327 std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
328 if (Info.first)
329 return Info.first;
330
Anders Carlsson71d1d922009-09-09 02:51:03 +0000331 QualType Ty = D->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000332
Anders Carlssonf8e94f22009-09-12 02:44:18 +0000333 std::vector<const llvm::Type *> Types;
Anders Carlsson10f2c102009-09-10 01:32:12 +0000334
Benjamin Kramerabd5b902009-10-13 10:07:13 +0000335 const llvm::PointerType *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlssonf8e94f22009-09-12 02:44:18 +0000336
Anders Carlsson10f2c102009-09-10 01:32:12 +0000337 llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(VMContext);
338
Anders Carlssonf8e94f22009-09-12 02:44:18 +0000339 // void *__isa;
340 Types.push_back(Int8PtrTy);
341
342 // void *__forwarding;
343 Types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
344
345 // int32_t __flags;
Chris Lattner5e016ae2010-06-27 07:15:29 +0000346 Types.push_back(Int32Ty);
Anders Carlssonf8e94f22009-09-12 02:44:18 +0000347
348 // int32_t __size;
Chris Lattner5e016ae2010-06-27 07:15:29 +0000349 Types.push_back(Int32Ty);
Anders Carlssonf8e94f22009-09-12 02:44:18 +0000350
351 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
352 if (HasCopyAndDispose) {
353 /// void *__copy_helper;
354 Types.push_back(Int8PtrTy);
355
356 /// void *__destroy_helper;
357 Types.push_back(Int8PtrTy);
Mike Stump97d01d52009-03-04 03:23:46 +0000358 }
Anders Carlssonf8e94f22009-09-12 02:44:18 +0000359
360 bool Packed = false;
Ken Dyck160146e2010-01-27 17:10:57 +0000361 CharUnits Align = getContext().getDeclAlign(D);
362 if (Align > CharUnits::fromQuantity(Target.getPointerAlign(0) / 8)) {
Anders Carlssonf8e94f22009-09-12 02:44:18 +0000363 // We have to insert padding.
364
365 // The struct above has 2 32-bit integers.
366 unsigned CurrentOffsetInBytes = 4 * 2;
367
368 // And either 2 or 4 pointers.
369 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
370 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
371
372 // Align the offset.
373 unsigned AlignedOffsetInBytes =
Ken Dyck160146e2010-01-27 17:10:57 +0000374 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
Anders Carlssonf8e94f22009-09-12 02:44:18 +0000375
376 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
Anders Carlssonccbabc92009-09-13 17:55:13 +0000377 if (NumPaddingBytes > 0) {
378 const llvm::Type *Ty = llvm::Type::getInt8Ty(VMContext);
Mike Stump70197d52009-10-21 00:42:55 +0000379 // FIXME: We need a sema error for alignment larger than the minimum of
380 // the maximal stack alignmint and the alignment of malloc on the system.
Anders Carlssonccbabc92009-09-13 17:55:13 +0000381 if (NumPaddingBytes > 1)
382 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
Anders Carlssonf8e94f22009-09-12 02:44:18 +0000383
Anders Carlssonccbabc92009-09-13 17:55:13 +0000384 Types.push_back(Ty);
Anders Carlssonf8e94f22009-09-12 02:44:18 +0000385
Anders Carlssonccbabc92009-09-13 17:55:13 +0000386 // We want a packed struct.
387 Packed = true;
388 }
Anders Carlssonf8e94f22009-09-12 02:44:18 +0000389 }
390
391 // T x;
Fariborz Jahanian087206d2010-09-03 23:07:53 +0000392 Types.push_back(ConvertTypeForMem(Ty));
Anders Carlsson0168f4b2009-09-12 02:14:24 +0000393
Anders Carlssonf8e94f22009-09-12 02:44:18 +0000394 const llvm::Type *T = llvm::StructType::get(VMContext, Types, Packed);
Anders Carlsson10f2c102009-09-10 01:32:12 +0000395
396 cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
397 CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(),
398 ByRefTypeHolder.get());
399
Anders Carlsson0168f4b2009-09-12 02:14:24 +0000400 Info.first = ByRefTypeHolder.get();
Anders Carlssonf8e94f22009-09-12 02:44:18 +0000401
402 Info.second = Types.size() - 1;
Anders Carlsson0168f4b2009-09-12 02:14:24 +0000403
404 return Info.first;
Mike Stump97d01d52009-03-04 03:23:46 +0000405}
406
John McCall2b7fc382010-07-13 20:32:21 +0000407namespace {
John McCallcda666c2010-07-21 07:22:38 +0000408 struct CallArrayDtor : EHScopeStack::Cleanup {
John McCall2b7fc382010-07-13 20:32:21 +0000409 CallArrayDtor(const CXXDestructorDecl *Dtor,
410 const ConstantArrayType *Type,
411 llvm::Value *Loc)
412 : Dtor(Dtor), Type(Type), Loc(Loc) {}
413
414 const CXXDestructorDecl *Dtor;
415 const ConstantArrayType *Type;
416 llvm::Value *Loc;
417
418 void Emit(CodeGenFunction &CGF, bool IsForEH) {
419 QualType BaseElementTy = CGF.getContext().getBaseElementType(Type);
420 const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
421 BasePtr = llvm::PointerType::getUnqual(BasePtr);
422 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(Loc, BasePtr);
423 CGF.EmitCXXAggrDestructorCall(Dtor, Type, BaseAddrPtr);
424 }
425 };
426
John McCallcda666c2010-07-21 07:22:38 +0000427 struct CallVarDtor : EHScopeStack::Cleanup {
John McCall2b7fc382010-07-13 20:32:21 +0000428 CallVarDtor(const CXXDestructorDecl *Dtor,
429 llvm::Value *NRVOFlag,
430 llvm::Value *Loc)
431 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(Loc) {}
432
433 const CXXDestructorDecl *Dtor;
434 llvm::Value *NRVOFlag;
435 llvm::Value *Loc;
436
437 void Emit(CodeGenFunction &CGF, bool IsForEH) {
438 // Along the exceptions path we always execute the dtor.
439 bool NRVO = !IsForEH && NRVOFlag;
440
441 llvm::BasicBlock *SkipDtorBB = 0;
442 if (NRVO) {
443 // If we exited via NRVO, we skip the destructor call.
444 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
445 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
446 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
447 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
448 CGF.EmitBlock(RunDtorBB);
449 }
450
451 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
452 /*ForVirtualBase=*/false, Loc);
453
454 if (NRVO) CGF.EmitBlock(SkipDtorBB);
455 }
456 };
457}
458
John McCalla464ff92010-07-21 06:13:08 +0000459namespace {
John McCallcda666c2010-07-21 07:22:38 +0000460 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000461 llvm::Value *Stack;
462 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
463 void Emit(CodeGenFunction &CGF, bool IsForEH) {
464 llvm::Value *V = CGF.Builder.CreateLoad(Stack, "tmp");
465 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
466 CGF.Builder.CreateCall(F, V);
467 }
468 };
469
John McCallcda666c2010-07-21 07:22:38 +0000470 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000471 llvm::Constant *CleanupFn;
472 const CGFunctionInfo &FnInfo;
473 llvm::Value *Addr;
474 const VarDecl &Var;
475
476 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
477 llvm::Value *Addr, const VarDecl *Var)
478 : CleanupFn(CleanupFn), FnInfo(*Info), Addr(Addr), Var(*Var) {}
479
480 void Emit(CodeGenFunction &CGF, bool IsForEH) {
481 // In some cases, the type of the function argument will be different from
482 // the type of the pointer. An example of this is
483 // void f(void* arg);
484 // __attribute__((cleanup(f))) void *g;
485 //
486 // To fix this we insert a bitcast here.
487 QualType ArgTy = FnInfo.arg_begin()->type;
488 llvm::Value *Arg =
489 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
490
491 CallArgList Args;
492 Args.push_back(std::make_pair(RValue::get(Arg),
493 CGF.getContext().getPointerType(Var.getType())));
494 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
495 }
496 };
497
John McCallcda666c2010-07-21 07:22:38 +0000498 struct CallBlockRelease : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000499 llvm::Value *Addr;
500 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
501
502 void Emit(CodeGenFunction &CGF, bool IsForEH) {
503 llvm::Value *V = CGF.Builder.CreateStructGEP(Addr, 1, "forwarding");
504 V = CGF.Builder.CreateLoad(V);
505 CGF.BuildBlockRelease(V);
506 }
507 };
508}
509
Chris Lattnerb85025f2010-12-01 02:05:19 +0000510
511/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
512/// non-zero parts of the specified initializer with equal or fewer than
513/// NumStores scalar stores.
514static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
515 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000516 // Zero and Undef never requires any extra stores.
517 if (isa<llvm::ConstantAggregateZero>(Init) ||
518 isa<llvm::ConstantPointerNull>(Init) ||
519 isa<llvm::UndefValue>(Init))
520 return true;
521 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
522 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
523 isa<llvm::ConstantExpr>(Init))
524 return Init->isNullValue() || NumStores--;
525
526 // See if we can emit each element.
527 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
528 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
529 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
530 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
531 return false;
532 }
533 return true;
534 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000535
536 // Anything else is hard and scary.
537 return false;
538}
539
540/// emitStoresForInitAfterMemset - For inits that
541/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
542/// stores that would be required.
543static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
544 CGBuilderTy &Builder) {
545 // Zero doesn't require any stores.
Chris Lattnere6af8862010-12-02 01:58:41 +0000546 if (isa<llvm::ConstantAggregateZero>(Init) ||
547 isa<llvm::ConstantPointerNull>(Init) ||
548 isa<llvm::UndefValue>(Init))
549 return;
Chris Lattnerb85025f2010-12-01 02:05:19 +0000550
Chris Lattnere6af8862010-12-02 01:58:41 +0000551 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
552 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
553 isa<llvm::ConstantExpr>(Init)) {
554 if (!Init->isNullValue())
555 Builder.CreateStore(Init, Loc);
556 return;
557 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000558
Chris Lattnere6af8862010-12-02 01:58:41 +0000559 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
560 "Unknown value type!");
561
562 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
563 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
564 if (Elt->isNullValue()) continue;
565
566 // Otherwise, get a pointer to the element and emit it.
567 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
568 Builder);
569 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000570}
571
572
573/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
574/// plus some stores to initialize a local variable instead of using a memcpy
575/// from a constant global. It is beneficial to use memset if the global is all
576/// zeros, or mostly zeros and large.
577static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
578 uint64_t GlobalSize) {
579 // If a global is all zeros, always use a memset.
580 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
581
582
583 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
584 // do it if it will require 6 or fewer scalar stores.
585 // TODO: Should budget depends on the size? Avoiding a large global warrants
586 // plopping in more stores.
587 unsigned StoreBudget = 6;
588 uint64_t SizeLimit = 32;
589
590 return GlobalSize > SizeLimit &&
591 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
592}
593
594
John McCall1c9c3fd2010-10-15 04:57:14 +0000595/// EmitLocalVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000596/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000597/// These turn into simple stack objects, or GlobalValues depending on target.
John McCall1c9c3fd2010-10-15 04:57:14 +0000598void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D,
599 SpecialInitFn *SpecialInit) {
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000600 QualType Ty = D.getType();
Daniel Dunbar03816342010-08-21 02:24:36 +0000601 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000602 bool isByRef = D.hasAttr<BlocksAttr>();
Mike Stump626aecc2009-03-05 01:23:13 +0000603 bool needsDispose = false;
Ken Dyck160146e2010-01-27 17:10:57 +0000604 CharUnits Align = CharUnits::Zero();
Chris Lattnere99c1102009-12-05 08:22:11 +0000605 bool IsSimpleConstantInitializer = false;
Chris Lattner03df1222007-06-02 04:53:11 +0000606
Douglas Gregor290c93e2010-05-15 06:46:45 +0000607 bool NRVO = false;
Douglas Gregor9154b5d2010-05-17 15:52:46 +0000608 llvm::Value *NRVOFlag = 0;
Chris Lattner03df1222007-06-02 04:53:11 +0000609 llvm::Value *DeclPtr;
Eli Friedmana682d392008-02-15 12:20:59 +0000610 if (Ty->isConstantSizeType()) {
Chris Lattnerb781dc792008-05-08 05:58:21 +0000611 if (!Target.useGlobalsForAutomaticVariables()) {
Douglas Gregor290c93e2010-05-15 06:46:45 +0000612 NRVO = getContext().getLangOptions().ElideConstructors &&
613 D.isNRVOVariable();
Chris Lattnerffcd06ea2009-12-05 06:49:57 +0000614 // If this value is an array or struct, is POD, and if the initializer is
Douglas Gregor290c93e2010-05-15 06:46:45 +0000615 // a staticly determinable constant, try to optimize it (unless the NRVO
616 // is already optimizing this).
John McCall8b0f4ff2010-08-02 21:13:48 +0000617 if (!NRVO && D.getInit() && !isByRef &&
Chris Lattnerffcd06ea2009-12-05 06:49:57 +0000618 (Ty->isArrayType() || Ty->isRecordType()) &&
619 Ty->isPODType() &&
John McCall8b0f4ff2010-08-02 21:13:48 +0000620 D.getInit()->isConstantInitializer(getContext(), false)) {
Chris Lattnerffcd06ea2009-12-05 06:49:57 +0000621 // If this variable is marked 'const', emit the value as a global.
622 if (CGM.getCodeGenOpts().MergeAllConstants &&
623 Ty.isConstant(getContext())) {
John McCall1c9c3fd2010-10-15 04:57:14 +0000624 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
Tanya Lattnerf9d41df2009-11-04 01:18:09 +0000625 return;
626 }
Chris Lattnere99c1102009-12-05 08:22:11 +0000627
628 IsSimpleConstantInitializer = true;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +0000629 }
630
Douglas Gregor290c93e2010-05-15 06:46:45 +0000631 // A normal fixed sized variable becomes an alloca in the entry block,
632 // unless it's an NRVO variable.
Eli Friedman3efa41a2009-03-04 04:25:14 +0000633 const llvm::Type *LTy = ConvertTypeForMem(Ty);
Douglas Gregor290c93e2010-05-15 06:46:45 +0000634
635 if (NRVO) {
636 // The named return value optimization: allocate this variable in the
637 // return slot, so that we can elide the copy when returning this
638 // variable (C++0x [class.copy]p34).
639 DeclPtr = ReturnValue;
Douglas Gregor9154b5d2010-05-17 15:52:46 +0000640
641 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
642 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
643 // Create a flag that is used to indicate when the NRVO was applied
644 // to this variable. Set it to zero to indicate that NRVO was not
645 // applied.
Chris Lattner46a7ad72010-12-01 01:47:15 +0000646 llvm::Value *Zero = Builder.getFalse();
647 NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
Douglas Gregor9154b5d2010-05-17 15:52:46 +0000648 Builder.CreateStore(Zero, NRVOFlag);
649
650 // Record the NRVO flag for this variable.
651 NRVOFlags[&D] = NRVOFlag;
652 }
653 }
Douglas Gregor290c93e2010-05-15 06:46:45 +0000654 } else {
655 if (isByRef)
656 LTy = BuildByRefType(&D);
657
658 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
659 Alloc->setName(D.getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +0000660
Douglas Gregor290c93e2010-05-15 06:46:45 +0000661 Align = getContext().getDeclAlign(&D);
662 if (isByRef)
663 Align = std::max(Align,
664 CharUnits::fromQuantity(Target.getPointerAlign(0) / 8));
665 Alloc->setAlignment(Align.getQuantity());
666 DeclPtr = Alloc;
667 }
Chris Lattnerb781dc792008-05-08 05:58:21 +0000668 } else {
669 // Targets that don't support recursion emit locals as globals.
670 const char *Class =
John McCall8e7d6562010-08-26 03:08:43 +0000671 D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
John McCall1c9c3fd2010-10-15 04:57:14 +0000672 DeclPtr = CreateStaticVarDecl(D, Class,
673 llvm::GlobalValue::InternalLinkage);
Chris Lattnerb781dc792008-05-08 05:58:21 +0000674 }
Mike Stump11289f42009-09-09 15:08:12 +0000675
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000676 // FIXME: Can this happen?
Anders Carlsson8a01b792008-12-20 20:46:34 +0000677 if (Ty->isVariablyModifiedType())
678 EmitVLASize(Ty);
Chris Lattner03df1222007-06-02 04:53:11 +0000679 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000680 EnsureInsertPoint();
681
Anders Carlsson15949b32009-02-09 20:41:50 +0000682 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +0000683 // Save the stack.
Benjamin Kramerabd5b902009-10-13 10:07:13 +0000684 const llvm::Type *LTy = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson30032882008-12-12 07:38:43 +0000685 llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +0000686
Anders Carlsson30032882008-12-12 07:38:43 +0000687 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
688 llvm::Value *V = Builder.CreateCall(F);
Mike Stump11289f42009-09-09 15:08:12 +0000689
Anders Carlsson30032882008-12-12 07:38:43 +0000690 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +0000691
692 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +0000693
John McCalla464ff92010-07-21 06:13:08 +0000694 // Push a cleanup block and restore the stack there.
John McCallcda666c2010-07-21 07:22:38 +0000695 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +0000696 }
Mike Stump11289f42009-09-09 15:08:12 +0000697
Anders Carlsson30032882008-12-12 07:38:43 +0000698 // Get the element type.
Mike Stump11289f42009-09-09 15:08:12 +0000699 const llvm::Type *LElemTy = ConvertTypeForMem(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +0000700 const llvm::Type *LElemPtrTy =
Daniel Dunbara94e3d12010-08-21 02:17:08 +0000701 llvm::PointerType::get(LElemTy, Ty.getAddressSpace());
Anders Carlsson30032882008-12-12 07:38:43 +0000702
Anders Carlsson8a01b792008-12-20 20:46:34 +0000703 llvm::Value *VLASize = EmitVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +0000704
705 // Allocate memory for the array.
Anders Carlssone33eed52009-09-26 18:16:06 +0000706 llvm::AllocaInst *VLA =
707 Builder.CreateAlloca(llvm::Type::getInt8Ty(VMContext), VLASize, "vla");
Ken Dyck160146e2010-01-27 17:10:57 +0000708 VLA->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +0000709
Eli Friedmanf4084702008-12-20 23:11:59 +0000710 DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
Chris Lattner03df1222007-06-02 04:53:11 +0000711 }
Eli Friedmanf4084702008-12-20 23:11:59 +0000712
Chris Lattner03df1222007-06-02 04:53:11 +0000713 llvm::Value *&DMEntry = LocalDeclMap[&D];
714 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
715 DMEntry = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +0000716
717 // Emit debug info for local var declaration.
Anders Carlsson63784f42009-02-13 08:11:52 +0000718 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar669521c2009-07-19 07:03:11 +0000719 assert(HaveInsertPoint() && "Unexpected unreachable point!");
Mike Stump11289f42009-09-09 15:08:12 +0000720
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000721 DI->setLocation(D.getLocation());
Sanjiv Gupta47e29612009-05-22 13:54:25 +0000722 if (Target.useGlobalsForAutomaticVariables()) {
723 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
Mike Stump97d01d52009-03-04 03:23:46 +0000724 } else
725 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Sanjiv Gupta18de6242008-05-30 10:30:31 +0000726 }
727
Chris Lattner07eb7332007-07-12 00:39:48 +0000728 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000729 const Expr *Init = D.getInit();
730
731 // If we are at an unreachable point, we don't need to emit the initializer
732 // unless it contains a label.
733 if (!HaveInsertPoint()) {
734 if (!ContainsLabel(Init))
735 Init = 0;
736 else
737 EnsureInsertPoint();
738 }
739
Mike Stump97d01d52009-03-04 03:23:46 +0000740 if (isByRef) {
Benjamin Kramerabd5b902009-10-13 10:07:13 +0000741 const llvm::PointerType *PtrToInt8Ty = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump97d01d52009-03-04 03:23:46 +0000742
Daniel Dunbarb6adc432009-07-19 06:58:07 +0000743 EnsureInsertPoint();
Mike Stump97d01d52009-03-04 03:23:46 +0000744 llvm::Value *isa_field = Builder.CreateStructGEP(DeclPtr, 0);
745 llvm::Value *forwarding_field = Builder.CreateStructGEP(DeclPtr, 1);
746 llvm::Value *flags_field = Builder.CreateStructGEP(DeclPtr, 2);
747 llvm::Value *size_field = Builder.CreateStructGEP(DeclPtr, 3);
748 llvm::Value *V;
749 int flag = 0;
750 int flags = 0;
751
Mike Stump90d8daf2009-03-07 06:04:31 +0000752 needsDispose = true;
Mike Stump4446dcf2009-03-05 08:32:30 +0000753
Mike Stump97d01d52009-03-04 03:23:46 +0000754 if (Ty->isBlockPointerType()) {
755 flag |= BLOCK_FIELD_IS_BLOCK;
756 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +0000757 } else if (getContext().isObjCNSObjectType(Ty) ||
758 Ty->isObjCObjectPointerType()) {
Mike Stump97d01d52009-03-04 03:23:46 +0000759 flag |= BLOCK_FIELD_IS_OBJECT;
Mike Stumpfbe25dd2009-03-06 04:53:30 +0000760 flags |= BLOCK_HAS_COPY_DISPOSE;
Mike Stump97d01d52009-03-04 03:23:46 +0000761 }
Mike Stump90d8daf2009-03-07 06:04:31 +0000762
763 // FIXME: Someone double check this.
764 if (Ty.isObjCGCWeak())
765 flag |= BLOCK_FIELD_IS_WEAK;
Mike Stump97d01d52009-03-04 03:23:46 +0000766
767 int isa = 0;
Chris Lattnerb85025f2010-12-01 02:05:19 +0000768 if (flag & BLOCK_FIELD_IS_WEAK)
Mike Stump97d01d52009-03-04 03:23:46 +0000769 isa = 1;
Chris Lattner46a7ad72010-12-01 01:47:15 +0000770 V = Builder.CreateIntToPtr(Builder.getInt32(isa), PtrToInt8Ty, "isa");
Mike Stump97d01d52009-03-04 03:23:46 +0000771 Builder.CreateStore(V, isa_field);
772
Anders Carlsson10f2c102009-09-10 01:32:12 +0000773 Builder.CreateStore(DeclPtr, forwarding_field);
Mike Stump97d01d52009-03-04 03:23:46 +0000774
Chris Lattner46a7ad72010-12-01 01:47:15 +0000775 Builder.CreateStore(Builder.getInt32(flags), flags_field);
Mike Stump97d01d52009-03-04 03:23:46 +0000776
Mike Stump4446dcf2009-03-05 08:32:30 +0000777 const llvm::Type *V1;
778 V1 = cast<llvm::PointerType>(DeclPtr->getType())->getElementType();
Chris Lattner46a7ad72010-12-01 01:47:15 +0000779 V = Builder.getInt32(CGM.GetTargetTypeStoreSize(V1).getQuantity());
Mike Stump97d01d52009-03-04 03:23:46 +0000780 Builder.CreateStore(V, size_field);
781
782 if (flags & BLOCK_HAS_COPY_DISPOSE) {
Fariborz Jahanian9db7b8b2010-11-15 19:19:38 +0000783 SynthesizeCopyDisposeHelpers = true;
Mike Stump97d01d52009-03-04 03:23:46 +0000784 llvm::Value *copy_helper = Builder.CreateStructGEP(DeclPtr, 4);
Ken Dyck160146e2010-01-27 17:10:57 +0000785 Builder.CreateStore(BuildbyrefCopyHelper(DeclPtr->getType(), flag,
786 Align.getQuantity()),
Mike Stumpf89230d2009-03-06 06:12:24 +0000787 copy_helper);
Mike Stump97d01d52009-03-04 03:23:46 +0000788
Mike Stumpfbe25dd2009-03-06 04:53:30 +0000789 llvm::Value *destroy_helper = Builder.CreateStructGEP(DeclPtr, 5);
Mike Stumpcbc2bca2009-06-05 23:26:36 +0000790 Builder.CreateStore(BuildbyrefDestroyHelper(DeclPtr->getType(), flag,
Ken Dyck160146e2010-01-27 17:10:57 +0000791 Align.getQuantity()),
Mike Stumpfbe25dd2009-03-06 04:53:30 +0000792 destroy_helper);
Chris Lattner9de95272007-08-26 05:13:54 +0000793 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000794 }
Anders Carlssoncadb9a62009-02-07 23:51:38 +0000795
John McCallbd309292010-07-06 01:34:17 +0000796 if (SpecialInit) {
797 SpecialInit(*this, D, DeclPtr);
798 } else if (Init) {
Fariborz Jahanianc6140732010-03-12 21:40:43 +0000799 llvm::Value *Loc = DeclPtr;
800 if (isByRef)
801 Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D),
802 D.getNameAsString());
803
Daniel Dunbara94e3d12010-08-21 02:17:08 +0000804 bool isVolatile = getContext().getCanonicalType(Ty).isVolatileQualified();
Fariborz Jahanianc6140732010-03-12 21:40:43 +0000805
806 // If the initializer was a simple constant initializer, we can optimize it
807 // in various ways.
808 if (IsSimpleConstantInitializer) {
Daniel Dunbara94e3d12010-08-21 02:17:08 +0000809 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), Ty,this);
Fariborz Jahanianc6140732010-03-12 21:40:43 +0000810 assert(Init != 0 && "Wasn't a simple constant init?");
811
Chris Lattner46a7ad72010-12-01 01:47:15 +0000812 llvm::Value *AlignVal = Builder.getInt32(Align.getQuantity());
Fariborz Jahanianc6140732010-03-12 21:40:43 +0000813 llvm::Value *SizeVal =
Chris Lattner46a7ad72010-12-01 01:47:15 +0000814 llvm::ConstantInt::get(CGF.IntPtrTy,
Fariborz Jahanianc6140732010-03-12 21:40:43 +0000815 getContext().getTypeSizeInChars(Ty).getQuantity());
816
817 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Fariborz Jahanianc6140732010-03-12 21:40:43 +0000818
Chris Lattner46a7ad72010-12-01 01:47:15 +0000819 llvm::Value *NotVolatile = Builder.getFalse();
Mon P Wangcc2ab0c2010-04-04 03:10:52 +0000820
Chris Lattnerb85025f2010-12-01 02:05:19 +0000821 // If the initializer is all or mostly zeros, codegen with memset then do
822 // a few stores afterward.
823 if (shouldUseMemSetPlusStoresToInitialize(Init,
824 CGM.getTargetData().getTypeAllocSize(Init->getType()))) {
825 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
826 llvm::Value *MemSetDest = Loc;
827 if (MemSetDest->getType() != BP)
828 MemSetDest = Builder.CreateBitCast(MemSetDest, BP, "tmp");
829
830 Builder.CreateCall5(CGM.getMemSetFn(BP, SizeVal->getType()),
831 MemSetDest, Builder.getInt8(0), SizeVal, AlignVal,
832 NotVolatile);
833 emitStoresForInitAfterMemset(Init, Loc, Builder);
834
Fariborz Jahanianc6140732010-03-12 21:40:43 +0000835 } else {
836 // Otherwise, create a temporary global with the initializer then
837 // memcpy from the global to the alloca.
838 std::string Name = GetStaticDeclName(*this, D, ".");
839 llvm::GlobalVariable *GV =
840 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), true,
841 llvm::GlobalValue::InternalLinkage,
842 Init, Name, 0, false, 0);
843 GV->setAlignment(Align.getQuantity());
844
845 llvm::Value *SrcPtr = GV;
846 if (SrcPtr->getType() != BP)
847 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
Mon P Wangcc2ab0c2010-04-04 03:10:52 +0000848
Chris Lattnerb85025f2010-12-01 02:05:19 +0000849 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
850 if (Loc->getType() != BP)
851 Loc = Builder.CreateBitCast(Loc, BP, "tmp");
852
Mon P Wangcc2ab0c2010-04-04 03:10:52 +0000853 Builder.CreateCall5(CGM.getMemCpyFn(Loc->getType(), SrcPtr->getType(),
854 SizeVal->getType()),
855 Loc, SrcPtr, SizeVal, AlignVal, NotVolatile);
Fariborz Jahanianc6140732010-03-12 21:40:43 +0000856 }
857 } else if (Ty->isReferenceType()) {
Anders Carlsson04775f82010-06-26 16:35:32 +0000858 RValue RV = EmitReferenceBindingToExpr(Init, &D);
Daniel Dunbar03816342010-08-21 02:24:36 +0000859 EmitStoreOfScalar(RV.getScalarVal(), Loc, false, Alignment, Ty);
Fariborz Jahanianc6140732010-03-12 21:40:43 +0000860 } else if (!hasAggregateLLVMType(Init->getType())) {
861 llvm::Value *V = EmitScalarExpr(Init);
Daniel Dunbar03816342010-08-21 02:24:36 +0000862 EmitStoreOfScalar(V, Loc, isVolatile, Alignment, Ty);
Fariborz Jahanianc6140732010-03-12 21:40:43 +0000863 } else if (Init->getType()->isAnyComplexType()) {
864 EmitComplexExprIntoAddr(Init, Loc, isVolatile);
865 } else {
John McCall7a626f62010-09-15 10:14:12 +0000866 EmitAggExpr(Init, AggValueSlot::forAddr(Loc, isVolatile, true));
Fariborz Jahanianc6140732010-03-12 21:40:43 +0000867 }
868 }
John McCallbd309292010-07-06 01:34:17 +0000869
Fariborz Jahanian18c06232009-08-03 20:20:07 +0000870 // Handle CXX destruction of variables.
Fariborz Jahaniand44bdb22009-08-03 20:51:29 +0000871 QualType DtorTy(Ty);
Douglas Gregor4ef1d402009-11-09 22:08:55 +0000872 while (const ArrayType *Array = getContext().getAsArrayType(DtorTy))
Fariborz Jahanianc9076fe2009-10-29 16:22:54 +0000873 DtorTy = getContext().getBaseElementType(Array);
Fariborz Jahaniand44bdb22009-08-03 20:51:29 +0000874 if (const RecordType *RT = DtorTy->getAs<RecordType>())
Douglas Gregor290c93e2010-05-15 06:46:45 +0000875 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregor17012562010-05-15 16:39:56 +0000876 if (!ClassDecl->hasTrivialDestructor()) {
Douglas Gregor9154b5d2010-05-17 15:52:46 +0000877 // Note: We suppress the destructor call when the corresponding NRVO
878 // flag has been set.
Douglas Gregor290c93e2010-05-15 06:46:45 +0000879 llvm::Value *Loc = DeclPtr;
880 if (isByRef)
881 Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D),
882 D.getNameAsString());
883
Douglas Gregorbac74902010-07-01 14:13:13 +0000884 const CXXDestructorDecl *D = ClassDecl->getDestructor();
Fariborz Jahanian18c06232009-08-03 20:20:07 +0000885 assert(D && "EmitLocalBlockVarDecl - destructor is nul");
Fariborz Jahanianc9076fe2009-10-29 16:22:54 +0000886
Fariborz Jahanianc9076fe2009-10-29 16:22:54 +0000887 if (const ConstantArrayType *Array =
888 getContext().getAsConstantArrayType(Ty)) {
John McCallcda666c2010-07-21 07:22:38 +0000889 EHStack.pushCleanup<CallArrayDtor>(NormalAndEHCleanup,
890 D, Array, Loc);
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000891 } else {
John McCallcda666c2010-07-21 07:22:38 +0000892 EHStack.pushCleanup<CallVarDtor>(NormalAndEHCleanup,
893 D, NRVOFlag, Loc);
Fariborz Jahanian09cc10f2009-11-04 17:57:40 +0000894 }
Fariborz Jahanian18c06232009-08-03 20:20:07 +0000895 }
896 }
Mike Stump11289f42009-09-09 15:08:12 +0000897
Anders Carlssoncadb9a62009-02-07 23:51:38 +0000898 // Handle the cleanup attribute
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000899 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +0000900 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000901
Anders Carlssonecf9bf02009-09-10 23:43:36 +0000902 llvm::Constant* F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +0000903 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +0000904
Anders Carlsson6f5c1562009-04-26 00:34:20 +0000905 const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
John McCallcda666c2010-07-21 07:22:38 +0000906 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup,
907 F, &Info, DeclPtr, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +0000908 }
Mike Stump626aecc2009-03-05 01:23:13 +0000909
John McCall775f9f92010-07-22 21:25:44 +0000910 // If this is a block variable, clean it up.
John McCalla464ff92010-07-21 06:13:08 +0000911 if (needsDispose && CGM.getLangOptions().getGCMode() != LangOptions::GCOnly)
John McCall569eafc2010-10-06 18:56:43 +0000912 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, DeclPtr);
Chris Lattner03df1222007-06-02 04:53:11 +0000913}
Chris Lattner53621a52007-06-13 20:44:40 +0000914
Mike Stump11289f42009-09-09 15:08:12 +0000915/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +0000916/// for the specified parameter and set up LocalDeclMap.
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000917void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) {
918 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +0000919 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000920 "Invalid argument to EmitParmDecl");
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000921 QualType Ty = D.getType();
Mike Stump53f9ded2009-11-03 23:25:48 +0000922 CanQualType CTy = getContext().getCanonicalType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +0000923
Chris Lattner53621a52007-06-13 20:44:40 +0000924 llvm::Value *DeclPtr;
Daniel Dunbar3d33fab2010-02-08 22:53:07 +0000925 // If this is an aggregate or variable sized value, reuse the input pointer.
926 if (!Ty->isConstantSizeType() ||
927 CodeGenFunction::hasAggregateLLVMType(Ty)) {
Chris Lattner53621a52007-06-13 20:44:40 +0000928 DeclPtr = Arg;
Chris Lattner53621a52007-06-13 20:44:40 +0000929 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +0000930 // Otherwise, create a temporary to hold the value.
Daniel Dunbara7566f12010-02-09 02:48:28 +0000931 DeclPtr = CreateMemTemp(Ty, D.getName() + ".addr");
Mike Stump11289f42009-09-09 15:08:12 +0000932
Daniel Dunbar3d33fab2010-02-08 22:53:07 +0000933 // Store the initial value into the alloca.
Daniel Dunbar03816342010-08-21 02:24:36 +0000934 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
935 EmitStoreOfScalar(Arg, DeclPtr, CTy.isVolatileQualified(), Alignment, Ty);
Chris Lattner53621a52007-06-13 20:44:40 +0000936 }
Daniel Dunbar3d33fab2010-02-08 22:53:07 +0000937 Arg->setName(D.getName());
Chris Lattner53621a52007-06-13 20:44:40 +0000938
939 llvm::Value *&DMEntry = LocalDeclMap[&D];
940 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
941 DMEntry = DeclPtr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +0000942
943 // Emit debug info for param declaration.
Devang Patel3028a432009-10-09 22:06:15 +0000944 if (CGDebugInfo *DI = getDebugInfo()) {
945 DI->setLocation(D.getLocation());
Chris Lattneraffb3732008-11-10 06:08:34 +0000946 DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder);
Devang Patel3028a432009-10-09 22:06:15 +0000947 }
Chris Lattner53621a52007-06-13 20:44:40 +0000948}