blob: 9490769407d90666928e261f5f824e34f4ab8aa8 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Decl nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Sanjiv Guptacc9b1632008-05-30 10:30:31 +000014#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "CodeGenFunction.h"
Anders Carlsson1a86b332007-10-17 00:52:43 +000016#include "CodeGenModule.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000017#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/Decl.h"
Anders Carlsson19567ee2008-08-25 01:38:19 +000020#include "clang/AST/DeclObjC.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner2621fd12008-05-08 05:58:21 +000022#include "clang/Basic/TargetInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000023#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson1a86b332007-10-17 00:52:43 +000024#include "llvm/GlobalVariable.h"
Anders Carlsson5d463152008-12-12 07:38:43 +000025#include "llvm/Intrinsics.h"
Mike Stumpdab514f2009-03-04 03:23:46 +000026#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/Type.h"
28using namespace clang;
29using namespace CodeGen;
30
31
32void CodeGenFunction::EmitDecl(const Decl &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +000033 switch (D.getKind()) {
Douglas Gregor08688ac2010-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:
Sean Hunt9a555912010-05-30 07:21:58 +000041 case Decl::NonTypeTemplateParm:
Douglas Gregor08688ac2010-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 Pichet41f5e662010-11-21 06:49:41 +000047 case Decl::IndirectField:
Douglas Gregor08688ac2010-04-23 02:02:43 +000048 case Decl::ObjCIvar:
49 case Decl::ObjCAtDefsField:
Chris Lattneraa9fc462007-10-08 21:37:32 +000050 case Decl::ParmVar:
Douglas Gregor08688ac2010-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 Bagnara6206d532010-06-05 05:09:32 +000063 case Decl::AccessSpec:
Douglas Gregor08688ac2010-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!");
Reid Spencer5f016e22007-07-11 17:01:13 +000074 case Decl::Function: // void X();
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000075 case Decl::Record: // struct/union/class X;
Reid Spencer5f016e22007-07-11 17:01:13 +000076 case Decl::Enum: // enum X;
Mike Stump1eb44332009-09-09 15:08:12 +000077 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000078 case Decl::CXXRecord: // struct/union/class X; [C++]
Daniel Dunbarfa133a12009-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 Gregor08688ac2010-04-23 02:02:43 +000082 case Decl::NamespaceAlias:
Anders Carlsson7b0ca3f2009-12-03 17:26:31 +000083 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Reid Spencer5f016e22007-07-11 17:01:13 +000084 // None of these decls require codegen support.
85 return;
Mike Stump1eb44332009-09-09 15:08:12 +000086
Daniel Dunbar662174c82008-08-29 17:28:43 +000087 case Decl::Var: {
88 const VarDecl &VD = cast<VarDecl>(D);
John McCallb6bbcc92010-10-15 04:57:14 +000089 assert(VD.isLocalVarDecl() &&
Daniel Dunbar662174c82008-08-29 17:28:43 +000090 "Should not see file-scope variables inside a function!");
John McCallb6bbcc92010-10-15 04:57:14 +000091 return EmitVarDecl(VD);
Reid Spencer5f016e22007-07-11 17:01:13 +000092 }
Mike Stump1eb44332009-09-09 15:08:12 +000093
Anders Carlssonfcdbb932008-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 Stump1eb44332009-09-09 15:08:12 +000097
Anders Carlssonfcdbb932008-12-20 21:51:53 +000098 if (Ty->isVariablyModifiedType())
99 EmitVLASize(Ty);
100 }
Daniel Dunbar662174c82008-08-29 17:28:43 +0000101 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000102}
103
John McCallb6bbcc92010-10-15 04:57:14 +0000104/// EmitVarDecl - This method handles emission of any variable declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000105/// inside a function, including static vars etc.
John McCallb6bbcc92010-10-15 04:57:14 +0000106void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000107 if (D.hasAttr<AsmLabelAttr>())
Fariborz Jahanianba8639d2009-03-30 20:32:06 +0000108 CGM.ErrorUnsupported(&D, "__asm__");
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Reid Spencer5f016e22007-07-11 17:01:13 +0000110 switch (D.getStorageClass()) {
John McCalld931b082010-08-26 03:08:43 +0000111 case SC_None:
112 case SC_Auto:
113 case SC_Register:
John McCallb6bbcc92010-10-15 04:57:14 +0000114 return EmitAutoVarDecl(D);
John McCalld931b082010-08-26 03:08:43 +0000115 case SC_Static: {
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000116 llvm::GlobalValue::LinkageTypes Linkage =
117 llvm::GlobalValue::InternalLinkage;
118
John McCall8b242332010-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 Carlssonf6b89a12010-02-07 02:03:08 +0000127
John McCallb6bbcc92010-10-15 04:57:14 +0000128 return EmitStaticVarDecl(D, Linkage);
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000129 }
John McCalld931b082010-08-26 03:08:43 +0000130 case SC_Extern:
131 case SC_PrivateExtern:
Lauro Ramos Venanciofea90b82008-02-16 22:30:38 +0000132 // Don't emit it now, allow it to be emitted lazily on its first use.
133 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000134 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000135
136 assert(0 && "Unknown storage class");
Reid Spencer5f016e22007-07-11 17:01:13 +0000137}
138
Chris Lattner761acc12009-12-05 08:22:11 +0000139static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
140 const char *Separator) {
141 CodeGenModule &CGM = CGF.CGM;
John McCallf746aa62010-03-19 23:29:14 +0000142 if (CGF.getContext().getLangOptions().CPlusPlus) {
Anders Carlsson9a20d552010-06-22 16:16:50 +0000143 llvm::StringRef Name = CGM.getMangledName(&D);
144 return Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000145 }
Chris Lattner761acc12009-12-05 08:22:11 +0000146
147 std::string ContextName;
Fariborz Jahanianfaa5bfc2010-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 Carlsson9a20d552010-06-22 16:16:50 +0000160 llvm::StringRef Name = CGM.getMangledName(FD);
161 ContextName = Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000162 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattner761acc12009-12-05 08:22:11 +0000163 ContextName = CGF.CurFn->getName();
164 else
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000165 assert(0 && "Unknown context for static var decl");
Chris Lattner761acc12009-12-05 08:22:11 +0000166
167 return ContextName + Separator + D.getNameAsString();
168}
169
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000170llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000171CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
172 const char *Separator,
173 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000174 QualType Ty = D.getType();
Eli Friedman3c2b3172008-02-15 12:20:59 +0000175 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000176
Chris Lattner761acc12009-12-05 08:22:11 +0000177 std::string Name = GetStaticDeclName(*this, D, Separator);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000178
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000179 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Anders Carlsson41f8a132009-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 Dyck8b752f12010-01-27 17:10:57 +0000185 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
John McCall112c9672010-11-02 21:04:24 +0000186 if (Linkage != llvm::GlobalValue::InternalLinkage)
187 GV->setVisibility(CurFn->getVisibility());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000188 return GV;
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000189}
190
John McCallb6bbcc92010-10-15 04:57:14 +0000191/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
Chris Lattner761acc12009-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 McCallb6bbcc92010-10-15 04:57:14 +0000196CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
197 llvm::GlobalVariable *GV) {
Chris Lattner761acc12009-12-05 08:22:11 +0000198 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this);
John McCallbf40cb52010-07-15 23:40:35 +0000199
Chris Lattner761acc12009-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 McCall5cd91b52010-09-08 01:44:27 +0000205 else if (Builder.GetInsertBlock()) {
Anders Carlsson071c8102010-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 McCall5cd91b52010-09-08 01:44:27 +0000209
John McCall3030eb82010-11-06 09:44:32 +0000210 EmitCXXGuardedInit(D, GV);
Anders Carlsson071c8102010-01-26 04:02:23 +0000211 }
Chris Lattner761acc12009-12-05 08:22:11 +0000212 return GV;
213 }
John McCallbf40cb52010-07-15 23:40:35 +0000214
Chris Lattner761acc12009-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 McCall9c20fa92010-09-03 18:58:50 +0000219 if (GV->getType()->getElementType() != Init->getType()) {
Chris Lattner761acc12009-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 McCall112c9672010-11-02 21:04:24 +0000225 /*InsertBefore*/ OldGV,
226 D.isThreadSpecified(),
Chris Lattner761acc12009-12-05 08:22:11 +0000227 D.getType().getAddressSpace());
John McCall112c9672010-11-02 21:04:24 +0000228 GV->setVisibility(OldGV->getVisibility());
Chris Lattner761acc12009-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 McCallb6bbcc92010-10-15 04:57:14 +0000246void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000247 llvm::GlobalValue::LinkageTypes Linkage) {
Daniel Dunbara985b312009-02-25 19:45:19 +0000248 llvm::Value *&DMEntry = LocalDeclMap[&D];
249 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
Mike Stump1eb44332009-09-09 15:08:12 +0000250
John McCallb6bbcc92010-10-15 04:57:14 +0000251 llvm::GlobalVariable *GV = CreateStaticVarDecl(D, ".", Linkage);
Daniel Dunbara985b312009-02-25 19:45:19 +0000252
Daniel Dunbare5731f82009-02-25 20:08:33 +0000253 // Store into LocalDeclMap before generating initializer to handle
254 // circular references.
255 DMEntry = GV;
256
John McCallfe67f3b2010-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 Friedmanc62aad82009-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 Jahanian09349142010-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 Friedmanc62aad82009-04-20 03:54:15 +0000266
Chris Lattner761acc12009-12-05 08:22:11 +0000267 // If this value has an initializer, emit it.
268 if (D.getInit())
John McCallb6bbcc92010-10-15 04:57:14 +0000269 GV = AddInitializerToStaticVarDecl(D, GV);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000270
Chris Lattner0af95232010-03-10 23:59:59 +0000271 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
272
Daniel Dunbar30510ab2009-02-12 23:32:54 +0000273 // FIXME: Merge attribute handling.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000274 if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000275 SourceManager &SM = CGM.getContext().getSourceManager();
276 llvm::Constant *Ann =
Mike Stump1eb44332009-09-09 15:08:12 +0000277 CGM.EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000278 SM.getInstantiationLineNumber(D.getLocation()));
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000279 CGM.AddAnnotation(Ann);
280 }
281
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000282 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
Daniel Dunbar30510ab2009-02-12 23:32:54 +0000283 GV->setSection(SA->getName());
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000285 if (D.hasAttr<UsedAttr>())
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000286 CGM.AddUsedGlobal(GV);
287
Daniel Dunbare5731f82009-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 Friedman26590522008-06-08 01:23:18 +0000293 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
Chris Lattnerc0f31fd2010-12-02 04:27:29 +0000294 const llvm::Type *LPtrTy = LTy->getPointerTo(D.getType().getAddressSpace());
Owen Anderson3c4972d2009-07-29 18:54:39 +0000295 DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000296
297 // Emit global variable debug descriptor for static vars.
Anders Carlssone896d982009-02-13 08:11:52 +0000298 CGDebugInfo *DI = getDebugInfo();
Mike Stump4451bd92009-02-20 00:19:45 +0000299 if (DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000300 DI->setLocation(D.getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000301 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
302 }
Anders Carlsson1a86b332007-10-17 00:52:43 +0000303}
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000305unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
306 assert(ByRefValueInfo.count(VD) && "Did not find value!");
307
308 return ByRefValueInfo.find(VD)->second.second;
309}
310
Mike Stumpdab514f2009-03-04 03:23:46 +0000311/// BuildByRefType - This routine changes a __block variable declared as T x
312/// into:
313///
314/// struct {
315/// void *__isa;
316/// void *__forwarding;
317/// int32_t __flags;
318/// int32_t __size;
Mike Stump39605b42009-09-22 02:12:52 +0000319/// void *__copy_helper; // only if needed
320/// void *__destroy_helper; // only if needed
321/// char padding[X]; // only if needed
Mike Stumpdab514f2009-03-04 03:23:46 +0000322/// T x;
323/// } x
324///
Anders Carlsson9ad55132009-09-09 02:51:03 +0000325const llvm::Type *CodeGenFunction::BuildByRefType(const ValueDecl *D) {
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000326 std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
327 if (Info.first)
328 return Info.first;
329
Anders Carlsson9ad55132009-09-09 02:51:03 +0000330 QualType Ty = D->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Anders Carlsson18be84c2009-09-12 02:44:18 +0000332 std::vector<const llvm::Type *> Types;
Anders Carlsson36043862009-09-10 01:32:12 +0000333
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000334 const llvm::PointerType *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson18be84c2009-09-12 02:44:18 +0000335
Anders Carlsson36043862009-09-10 01:32:12 +0000336 llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(VMContext);
337
Anders Carlsson18be84c2009-09-12 02:44:18 +0000338 // void *__isa;
339 Types.push_back(Int8PtrTy);
340
341 // void *__forwarding;
342 Types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
343
344 // int32_t __flags;
Chris Lattner77b89b82010-06-27 07:15:29 +0000345 Types.push_back(Int32Ty);
Anders Carlsson18be84c2009-09-12 02:44:18 +0000346
347 // int32_t __size;
Chris Lattner77b89b82010-06-27 07:15:29 +0000348 Types.push_back(Int32Ty);
Anders Carlsson18be84c2009-09-12 02:44:18 +0000349
350 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
351 if (HasCopyAndDispose) {
352 /// void *__copy_helper;
353 Types.push_back(Int8PtrTy);
354
355 /// void *__destroy_helper;
356 Types.push_back(Int8PtrTy);
Mike Stumpdab514f2009-03-04 03:23:46 +0000357 }
Anders Carlsson18be84c2009-09-12 02:44:18 +0000358
359 bool Packed = false;
Ken Dyck8b752f12010-01-27 17:10:57 +0000360 CharUnits Align = getContext().getDeclAlign(D);
361 if (Align > CharUnits::fromQuantity(Target.getPointerAlign(0) / 8)) {
Anders Carlsson18be84c2009-09-12 02:44:18 +0000362 // We have to insert padding.
363
364 // The struct above has 2 32-bit integers.
365 unsigned CurrentOffsetInBytes = 4 * 2;
366
367 // And either 2 or 4 pointers.
368 CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
369 CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
370
371 // Align the offset.
372 unsigned AlignedOffsetInBytes =
Ken Dyck8b752f12010-01-27 17:10:57 +0000373 llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
Anders Carlsson18be84c2009-09-12 02:44:18 +0000374
375 unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
Anders Carlssone0c88222009-09-13 17:55:13 +0000376 if (NumPaddingBytes > 0) {
377 const llvm::Type *Ty = llvm::Type::getInt8Ty(VMContext);
Mike Stump04c688a2009-10-21 00:42:55 +0000378 // FIXME: We need a sema error for alignment larger than the minimum of
379 // the maximal stack alignmint and the alignment of malloc on the system.
Anders Carlssone0c88222009-09-13 17:55:13 +0000380 if (NumPaddingBytes > 1)
381 Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
Anders Carlsson18be84c2009-09-12 02:44:18 +0000382
Anders Carlssone0c88222009-09-13 17:55:13 +0000383 Types.push_back(Ty);
Anders Carlsson18be84c2009-09-12 02:44:18 +0000384
Anders Carlssone0c88222009-09-13 17:55:13 +0000385 // We want a packed struct.
386 Packed = true;
387 }
Anders Carlsson18be84c2009-09-12 02:44:18 +0000388 }
389
390 // T x;
Fariborz Jahanian469a20d2010-09-03 23:07:53 +0000391 Types.push_back(ConvertTypeForMem(Ty));
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000392
Anders Carlsson18be84c2009-09-12 02:44:18 +0000393 const llvm::Type *T = llvm::StructType::get(VMContext, Types, Packed);
Anders Carlsson36043862009-09-10 01:32:12 +0000394
395 cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
396 CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(),
397 ByRefTypeHolder.get());
398
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000399 Info.first = ByRefTypeHolder.get();
Anders Carlsson18be84c2009-09-12 02:44:18 +0000400
401 Info.second = Types.size() - 1;
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000402
403 return Info.first;
Mike Stumpdab514f2009-03-04 03:23:46 +0000404}
405
John McCallda65ea82010-07-13 20:32:21 +0000406namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000407 struct CallArrayDtor : EHScopeStack::Cleanup {
John McCallda65ea82010-07-13 20:32:21 +0000408 CallArrayDtor(const CXXDestructorDecl *Dtor,
409 const ConstantArrayType *Type,
410 llvm::Value *Loc)
411 : Dtor(Dtor), Type(Type), Loc(Loc) {}
412
413 const CXXDestructorDecl *Dtor;
414 const ConstantArrayType *Type;
415 llvm::Value *Loc;
416
417 void Emit(CodeGenFunction &CGF, bool IsForEH) {
418 QualType BaseElementTy = CGF.getContext().getBaseElementType(Type);
419 const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
420 BasePtr = llvm::PointerType::getUnqual(BasePtr);
421 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(Loc, BasePtr);
422 CGF.EmitCXXAggrDestructorCall(Dtor, Type, BaseAddrPtr);
423 }
424 };
425
John McCall1f0fca52010-07-21 07:22:38 +0000426 struct CallVarDtor : EHScopeStack::Cleanup {
John McCallda65ea82010-07-13 20:32:21 +0000427 CallVarDtor(const CXXDestructorDecl *Dtor,
428 llvm::Value *NRVOFlag,
429 llvm::Value *Loc)
430 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(Loc) {}
431
432 const CXXDestructorDecl *Dtor;
433 llvm::Value *NRVOFlag;
434 llvm::Value *Loc;
435
436 void Emit(CodeGenFunction &CGF, bool IsForEH) {
437 // Along the exceptions path we always execute the dtor.
438 bool NRVO = !IsForEH && NRVOFlag;
439
440 llvm::BasicBlock *SkipDtorBB = 0;
441 if (NRVO) {
442 // If we exited via NRVO, we skip the destructor call.
443 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
444 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
445 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
446 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
447 CGF.EmitBlock(RunDtorBB);
448 }
449
450 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
451 /*ForVirtualBase=*/false, Loc);
452
453 if (NRVO) CGF.EmitBlock(SkipDtorBB);
454 }
455 };
456}
457
John McCalld8715092010-07-21 06:13:08 +0000458namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000459 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000460 llvm::Value *Stack;
461 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
462 void Emit(CodeGenFunction &CGF, bool IsForEH) {
463 llvm::Value *V = CGF.Builder.CreateLoad(Stack, "tmp");
464 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
465 CGF.Builder.CreateCall(F, V);
466 }
467 };
468
John McCall1f0fca52010-07-21 07:22:38 +0000469 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000470 llvm::Constant *CleanupFn;
471 const CGFunctionInfo &FnInfo;
472 llvm::Value *Addr;
473 const VarDecl &Var;
474
475 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
476 llvm::Value *Addr, const VarDecl *Var)
477 : CleanupFn(CleanupFn), FnInfo(*Info), Addr(Addr), Var(*Var) {}
478
479 void Emit(CodeGenFunction &CGF, bool IsForEH) {
480 // In some cases, the type of the function argument will be different from
481 // the type of the pointer. An example of this is
482 // void f(void* arg);
483 // __attribute__((cleanup(f))) void *g;
484 //
485 // To fix this we insert a bitcast here.
486 QualType ArgTy = FnInfo.arg_begin()->type;
487 llvm::Value *Arg =
488 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
489
490 CallArgList Args;
491 Args.push_back(std::make_pair(RValue::get(Arg),
492 CGF.getContext().getPointerType(Var.getType())));
493 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
494 }
495 };
496
John McCall1f0fca52010-07-21 07:22:38 +0000497 struct CallBlockRelease : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000498 llvm::Value *Addr;
499 CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
500
501 void Emit(CodeGenFunction &CGF, bool IsForEH) {
502 llvm::Value *V = CGF.Builder.CreateStructGEP(Addr, 1, "forwarding");
503 V = CGF.Builder.CreateLoad(V);
504 CGF.BuildBlockRelease(V);
505 }
506 };
507}
508
Chris Lattner94cd0112010-12-01 02:05:19 +0000509
510/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
511/// non-zero parts of the specified initializer with equal or fewer than
512/// NumStores scalar stores.
513static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
514 unsigned &NumStores) {
Chris Lattner70b02942010-12-02 01:58:41 +0000515 // Zero and Undef never requires any extra stores.
516 if (isa<llvm::ConstantAggregateZero>(Init) ||
517 isa<llvm::ConstantPointerNull>(Init) ||
518 isa<llvm::UndefValue>(Init))
519 return true;
520 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
521 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
522 isa<llvm::ConstantExpr>(Init))
523 return Init->isNullValue() || NumStores--;
524
525 // See if we can emit each element.
526 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
527 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
528 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
529 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
530 return false;
531 }
532 return true;
533 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000534
535 // Anything else is hard and scary.
536 return false;
537}
538
539/// emitStoresForInitAfterMemset - For inits that
540/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
541/// stores that would be required.
542static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
543 CGBuilderTy &Builder) {
544 // Zero doesn't require any stores.
Chris Lattner70b02942010-12-02 01:58:41 +0000545 if (isa<llvm::ConstantAggregateZero>(Init) ||
546 isa<llvm::ConstantPointerNull>(Init) ||
547 isa<llvm::UndefValue>(Init))
548 return;
Chris Lattner94cd0112010-12-01 02:05:19 +0000549
Chris Lattner70b02942010-12-02 01:58:41 +0000550 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
551 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
552 isa<llvm::ConstantExpr>(Init)) {
553 if (!Init->isNullValue())
554 Builder.CreateStore(Init, Loc);
555 return;
556 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000557
Chris Lattner70b02942010-12-02 01:58:41 +0000558 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
559 "Unknown value type!");
560
561 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
562 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
563 if (Elt->isNullValue()) continue;
564
565 // Otherwise, get a pointer to the element and emit it.
566 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
567 Builder);
568 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000569}
570
571
572/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
573/// plus some stores to initialize a local variable instead of using a memcpy
574/// from a constant global. It is beneficial to use memset if the global is all
575/// zeros, or mostly zeros and large.
576static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
577 uint64_t GlobalSize) {
578 // If a global is all zeros, always use a memset.
579 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
580
581
582 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
583 // do it if it will require 6 or fewer scalar stores.
584 // TODO: Should budget depends on the size? Avoiding a large global warrants
585 // plopping in more stores.
586 unsigned StoreBudget = 6;
587 uint64_t SizeLimit = 32;
588
589 return GlobalSize > SizeLimit &&
590 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
591}
592
593
John McCallb6bbcc92010-10-15 04:57:14 +0000594/// EmitLocalVarDecl - Emit code and set up an entry in LocalDeclMap for a
Reid Spencer5f016e22007-07-11 17:01:13 +0000595/// variable declaration with auto, register, or no storage class specifier.
Chris Lattner2621fd12008-05-08 05:58:21 +0000596/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallb6bbcc92010-10-15 04:57:14 +0000597void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D,
598 SpecialInitFn *SpecialInit) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000599 QualType Ty = D.getType();
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000600 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000601 bool isByRef = D.hasAttr<BlocksAttr>();
Mike Stump797b6322009-03-05 01:23:13 +0000602 bool needsDispose = false;
Ken Dyck8b752f12010-01-27 17:10:57 +0000603 CharUnits Align = CharUnits::Zero();
Chris Lattner761acc12009-12-05 08:22:11 +0000604 bool IsSimpleConstantInitializer = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000605
Douglas Gregord86c4772010-05-15 06:46:45 +0000606 bool NRVO = false;
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000607 llvm::Value *NRVOFlag = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000608 llvm::Value *DeclPtr;
Eli Friedman3c2b3172008-02-15 12:20:59 +0000609 if (Ty->isConstantSizeType()) {
Chris Lattner2621fd12008-05-08 05:58:21 +0000610 if (!Target.useGlobalsForAutomaticVariables()) {
Douglas Gregord86c4772010-05-15 06:46:45 +0000611 NRVO = getContext().getLangOptions().ElideConstructors &&
612 D.isNRVOVariable();
Chris Lattnerff933b72009-12-05 06:49:57 +0000613 // If this value is an array or struct, is POD, and if the initializer is
Douglas Gregord86c4772010-05-15 06:46:45 +0000614 // a staticly determinable constant, try to optimize it (unless the NRVO
615 // is already optimizing this).
John McCall4204f072010-08-02 21:13:48 +0000616 if (!NRVO && D.getInit() && !isByRef &&
Chris Lattnerff933b72009-12-05 06:49:57 +0000617 (Ty->isArrayType() || Ty->isRecordType()) &&
618 Ty->isPODType() &&
John McCall4204f072010-08-02 21:13:48 +0000619 D.getInit()->isConstantInitializer(getContext(), false)) {
Chris Lattnerff933b72009-12-05 06:49:57 +0000620 // If this variable is marked 'const', emit the value as a global.
621 if (CGM.getCodeGenOpts().MergeAllConstants &&
622 Ty.isConstant(getContext())) {
John McCallb6bbcc92010-10-15 04:57:14 +0000623 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
Tanya Lattner59876c22009-11-04 01:18:09 +0000624 return;
625 }
Chris Lattner761acc12009-12-05 08:22:11 +0000626
627 IsSimpleConstantInitializer = true;
Tanya Lattner59876c22009-11-04 01:18:09 +0000628 }
629
Douglas Gregord86c4772010-05-15 06:46:45 +0000630 // A normal fixed sized variable becomes an alloca in the entry block,
631 // unless it's an NRVO variable.
Eli Friedmana3460ac2009-03-04 04:25:14 +0000632 const llvm::Type *LTy = ConvertTypeForMem(Ty);
Douglas Gregord86c4772010-05-15 06:46:45 +0000633
634 if (NRVO) {
635 // The named return value optimization: allocate this variable in the
636 // return slot, so that we can elide the copy when returning this
637 // variable (C++0x [class.copy]p34).
638 DeclPtr = ReturnValue;
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000639
640 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
641 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
642 // Create a flag that is used to indicate when the NRVO was applied
643 // to this variable. Set it to zero to indicate that NRVO was not
644 // applied.
Chris Lattner4c53dc12010-12-01 01:47:15 +0000645 llvm::Value *Zero = Builder.getFalse();
646 NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000647 Builder.CreateStore(Zero, NRVOFlag);
648
649 // Record the NRVO flag for this variable.
650 NRVOFlags[&D] = NRVOFlag;
651 }
652 }
Douglas Gregord86c4772010-05-15 06:46:45 +0000653 } else {
654 if (isByRef)
655 LTy = BuildByRefType(&D);
656
657 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
658 Alloc->setName(D.getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +0000659
Douglas Gregord86c4772010-05-15 06:46:45 +0000660 Align = getContext().getDeclAlign(&D);
661 if (isByRef)
662 Align = std::max(Align,
663 CharUnits::fromQuantity(Target.getPointerAlign(0) / 8));
664 Alloc->setAlignment(Align.getQuantity());
665 DeclPtr = Alloc;
666 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000667 } else {
668 // Targets that don't support recursion emit locals as globals.
669 const char *Class =
John McCalld931b082010-08-26 03:08:43 +0000670 D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
John McCallb6bbcc92010-10-15 04:57:14 +0000671 DeclPtr = CreateStaticVarDecl(D, Class,
672 llvm::GlobalValue::InternalLinkage);
Chris Lattner2621fd12008-05-08 05:58:21 +0000673 }
Mike Stump1eb44332009-09-09 15:08:12 +0000674
Daniel Dunbard286f052009-07-19 06:58:07 +0000675 // FIXME: Can this happen?
Anders Carlsson60d35412008-12-20 20:46:34 +0000676 if (Ty->isVariablyModifiedType())
677 EmitVLASize(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000678 } else {
Daniel Dunbard286f052009-07-19 06:58:07 +0000679 EnsureInsertPoint();
680
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000681 if (!DidCallStackSave) {
Anders Carlsson5d463152008-12-12 07:38:43 +0000682 // Save the stack.
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000683 const llvm::Type *LTy = llvm::Type::getInt8PtrTy(VMContext);
Anders Carlsson5d463152008-12-12 07:38:43 +0000684 llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Anders Carlsson5d463152008-12-12 07:38:43 +0000686 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
687 llvm::Value *V = Builder.CreateCall(F);
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Anders Carlsson5d463152008-12-12 07:38:43 +0000689 Builder.CreateStore(V, Stack);
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000690
691 DidCallStackSave = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000692
John McCalld8715092010-07-21 06:13:08 +0000693 // Push a cleanup block and restore the stack there.
John McCall1f0fca52010-07-21 07:22:38 +0000694 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
Anders Carlsson5d463152008-12-12 07:38:43 +0000695 }
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Anders Carlsson5d463152008-12-12 07:38:43 +0000697 // Get the element type.
Mike Stump1eb44332009-09-09 15:08:12 +0000698 const llvm::Type *LElemTy = ConvertTypeForMem(Ty);
Chris Lattner1b726772010-12-02 07:07:26 +0000699 const llvm::Type *LElemPtrTy = LElemTy->getPointerTo(Ty.getAddressSpace());
Anders Carlsson5d463152008-12-12 07:38:43 +0000700
Anders Carlsson60d35412008-12-20 20:46:34 +0000701 llvm::Value *VLASize = EmitVLASize(Ty);
Anders Carlsson5d463152008-12-12 07:38:43 +0000702
703 // Allocate memory for the array.
Anders Carlsson41f8a132009-09-26 18:16:06 +0000704 llvm::AllocaInst *VLA =
705 Builder.CreateAlloca(llvm::Type::getInt8Ty(VMContext), VLASize, "vla");
Ken Dyck8b752f12010-01-27 17:10:57 +0000706 VLA->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000707
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000708 DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
Reid Spencer5f016e22007-07-11 17:01:13 +0000709 }
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000710
Reid Spencer5f016e22007-07-11 17:01:13 +0000711 llvm::Value *&DMEntry = LocalDeclMap[&D];
712 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
713 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000714
715 // Emit debug info for local var declaration.
Anders Carlssone896d982009-02-13 08:11:52 +0000716 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar25b6ebf2009-07-19 07:03:11 +0000717 assert(HaveInsertPoint() && "Unexpected unreachable point!");
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Daniel Dunbar66031a52008-10-17 16:15:48 +0000719 DI->setLocation(D.getLocation());
Sanjiv Gupta4381d4b2009-05-22 13:54:25 +0000720 if (Target.useGlobalsForAutomaticVariables()) {
721 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
Mike Stumpdab514f2009-03-04 03:23:46 +0000722 } else
723 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000724 }
725
Chris Lattner19785962007-07-12 00:39:48 +0000726 // If this local has an initializer, emit it now.
Daniel Dunbard286f052009-07-19 06:58:07 +0000727 const Expr *Init = D.getInit();
728
729 // If we are at an unreachable point, we don't need to emit the initializer
730 // unless it contains a label.
731 if (!HaveInsertPoint()) {
732 if (!ContainsLabel(Init))
733 Init = 0;
734 else
735 EnsureInsertPoint();
736 }
737
Mike Stumpdab514f2009-03-04 03:23:46 +0000738 if (isByRef) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000739 const llvm::PointerType *PtrToInt8Ty = llvm::Type::getInt8PtrTy(VMContext);
Mike Stumpdab514f2009-03-04 03:23:46 +0000740
Daniel Dunbard286f052009-07-19 06:58:07 +0000741 EnsureInsertPoint();
Mike Stumpdab514f2009-03-04 03:23:46 +0000742 llvm::Value *isa_field = Builder.CreateStructGEP(DeclPtr, 0);
743 llvm::Value *forwarding_field = Builder.CreateStructGEP(DeclPtr, 1);
744 llvm::Value *flags_field = Builder.CreateStructGEP(DeclPtr, 2);
745 llvm::Value *size_field = Builder.CreateStructGEP(DeclPtr, 3);
746 llvm::Value *V;
747 int flag = 0;
748 int flags = 0;
749
Mike Stumpf4bc3122009-03-07 06:04:31 +0000750 needsDispose = true;
Mike Stump00470a12009-03-05 08:32:30 +0000751
Mike Stumpdab514f2009-03-04 03:23:46 +0000752 if (Ty->isBlockPointerType()) {
753 flag |= BLOCK_FIELD_IS_BLOCK;
754 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahaniane38be612010-11-17 00:21:28 +0000755 } else if (getContext().isObjCNSObjectType(Ty) ||
756 Ty->isObjCObjectPointerType()) {
Mike Stumpdab514f2009-03-04 03:23:46 +0000757 flag |= BLOCK_FIELD_IS_OBJECT;
Mike Stump1851b682009-03-06 04:53:30 +0000758 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000759 } else if (getContext().getBlockVarCopyInits(&D)) {
760 flag |= BLOCK_HAS_CXX_OBJ;
761 flags |= BLOCK_HAS_COPY_DISPOSE;
Mike Stumpdab514f2009-03-04 03:23:46 +0000762 }
Mike Stumpf4bc3122009-03-07 06:04:31 +0000763
764 // FIXME: Someone double check this.
765 if (Ty.isObjCGCWeak())
766 flag |= BLOCK_FIELD_IS_WEAK;
Mike Stumpdab514f2009-03-04 03:23:46 +0000767
768 int isa = 0;
Chris Lattner94cd0112010-12-01 02:05:19 +0000769 if (flag & BLOCK_FIELD_IS_WEAK)
Mike Stumpdab514f2009-03-04 03:23:46 +0000770 isa = 1;
Chris Lattner4c53dc12010-12-01 01:47:15 +0000771 V = Builder.CreateIntToPtr(Builder.getInt32(isa), PtrToInt8Ty, "isa");
Mike Stumpdab514f2009-03-04 03:23:46 +0000772 Builder.CreateStore(V, isa_field);
773
Anders Carlsson36043862009-09-10 01:32:12 +0000774 Builder.CreateStore(DeclPtr, forwarding_field);
Mike Stumpdab514f2009-03-04 03:23:46 +0000775
Chris Lattner4c53dc12010-12-01 01:47:15 +0000776 Builder.CreateStore(Builder.getInt32(flags), flags_field);
Mike Stumpdab514f2009-03-04 03:23:46 +0000777
Mike Stump00470a12009-03-05 08:32:30 +0000778 const llvm::Type *V1;
779 V1 = cast<llvm::PointerType>(DeclPtr->getType())->getElementType();
Chris Lattner4c53dc12010-12-01 01:47:15 +0000780 V = Builder.getInt32(CGM.GetTargetTypeStoreSize(V1).getQuantity());
Mike Stumpdab514f2009-03-04 03:23:46 +0000781 Builder.CreateStore(V, size_field);
782
783 if (flags & BLOCK_HAS_COPY_DISPOSE) {
Fariborz Jahanian2715b202010-11-15 19:19:38 +0000784 SynthesizeCopyDisposeHelpers = true;
Mike Stumpdab514f2009-03-04 03:23:46 +0000785 llvm::Value *copy_helper = Builder.CreateStructGEP(DeclPtr, 4);
Ken Dyck8b752f12010-01-27 17:10:57 +0000786 Builder.CreateStore(BuildbyrefCopyHelper(DeclPtr->getType(), flag,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000787 Align.getQuantity(), &D),
Mike Stumpee094222009-03-06 06:12:24 +0000788 copy_helper);
Mike Stumpdab514f2009-03-04 03:23:46 +0000789
Mike Stump1851b682009-03-06 04:53:30 +0000790 llvm::Value *destroy_helper = Builder.CreateStructGEP(DeclPtr, 5);
Mike Stump3899a7f2009-06-05 23:26:36 +0000791 Builder.CreateStore(BuildbyrefDestroyHelper(DeclPtr->getType(), flag,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000792 Align.getQuantity(), &D),
Mike Stump1851b682009-03-06 04:53:30 +0000793 destroy_helper);
Chris Lattner9a19edf2007-08-26 05:13:54 +0000794 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000795 }
Anders Carlsson69c68b72009-02-07 23:51:38 +0000796
John McCallf1549f62010-07-06 01:34:17 +0000797 if (SpecialInit) {
798 SpecialInit(*this, D, DeclPtr);
799 } else if (Init) {
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000800 llvm::Value *Loc = DeclPtr;
801 if (isByRef)
802 Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D),
803 D.getNameAsString());
804
Daniel Dunbar4cac2a12010-08-21 02:17:08 +0000805 bool isVolatile = getContext().getCanonicalType(Ty).isVolatileQualified();
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000806
807 // If the initializer was a simple constant initializer, we can optimize it
808 // in various ways.
809 if (IsSimpleConstantInitializer) {
Daniel Dunbar4cac2a12010-08-21 02:17:08 +0000810 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), Ty,this);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000811 assert(Init != 0 && "Wasn't a simple constant init?");
812
Chris Lattner4c53dc12010-12-01 01:47:15 +0000813 llvm::Value *AlignVal = Builder.getInt32(Align.getQuantity());
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000814 llvm::Value *SizeVal =
Chris Lattner4c53dc12010-12-01 01:47:15 +0000815 llvm::ConstantInt::get(CGF.IntPtrTy,
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000816 getContext().getTypeSizeInChars(Ty).getQuantity());
817
818 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattnerc0f31fd2010-12-02 04:27:29 +0000819 if (Loc->getType() != BP)
820 Loc = Builder.CreateBitCast(Loc, BP, "tmp");
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000821
Chris Lattner4c53dc12010-12-01 01:47:15 +0000822 llvm::Value *NotVolatile = Builder.getFalse();
Mon P Wang3ecd7852010-04-04 03:10:52 +0000823
Chris Lattner94cd0112010-12-01 02:05:19 +0000824 // If the initializer is all or mostly zeros, codegen with memset then do
825 // a few stores afterward.
826 if (shouldUseMemSetPlusStoresToInitialize(Init,
827 CGM.getTargetData().getTypeAllocSize(Init->getType()))) {
828 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
Chris Lattner94cd0112010-12-01 02:05:19 +0000829
830 Builder.CreateCall5(CGM.getMemSetFn(BP, SizeVal->getType()),
Chris Lattnerc0f31fd2010-12-02 04:27:29 +0000831 Loc, Builder.getInt8(0), SizeVal, AlignVal,
Chris Lattner94cd0112010-12-01 02:05:19 +0000832 NotVolatile);
Chris Lattnerc0f31fd2010-12-02 04:27:29 +0000833 if (!Init->isNullValue()) {
834 Loc = Builder.CreateBitCast(Loc, Init->getType()->getPointerTo());
835 emitStoresForInitAfterMemset(Init, Loc, Builder);
836 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000837
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000838 } else {
839 // Otherwise, create a temporary global with the initializer then
840 // memcpy from the global to the alloca.
841 std::string Name = GetStaticDeclName(*this, D, ".");
842 llvm::GlobalVariable *GV =
843 new llvm::GlobalVariable(CGM.getModule(), Init->getType(), true,
844 llvm::GlobalValue::InternalLinkage,
845 Init, Name, 0, false, 0);
846 GV->setAlignment(Align.getQuantity());
847
848 llvm::Value *SrcPtr = GV;
849 if (SrcPtr->getType() != BP)
850 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
Mon P Wang3ecd7852010-04-04 03:10:52 +0000851
852 Builder.CreateCall5(CGM.getMemCpyFn(Loc->getType(), SrcPtr->getType(),
853 SizeVal->getType()),
854 Loc, SrcPtr, SizeVal, AlignVal, NotVolatile);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000855 }
856 } else if (Ty->isReferenceType()) {
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000857 RValue RV = EmitReferenceBindingToExpr(Init, &D);
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000858 EmitStoreOfScalar(RV.getScalarVal(), Loc, false, Alignment, Ty);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000859 } else if (!hasAggregateLLVMType(Init->getType())) {
860 llvm::Value *V = EmitScalarExpr(Init);
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000861 EmitStoreOfScalar(V, Loc, isVolatile, Alignment, Ty);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000862 } else if (Init->getType()->isAnyComplexType()) {
863 EmitComplexExprIntoAddr(Init, Loc, isVolatile);
864 } else {
Chris Lattner1b726772010-12-02 07:07:26 +0000865 EmitAggExpr(Init, AggValueSlot::forAddr(Loc, isVolatile, true, false));
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000866 }
867 }
John McCallf1549f62010-07-06 01:34:17 +0000868
Fariborz Jahanian6ca0b322009-08-03 20:20:07 +0000869 // Handle CXX destruction of variables.
Fariborz Jahanian667f36a2009-08-03 20:51:29 +0000870 QualType DtorTy(Ty);
Douglas Gregor89c49f02009-11-09 22:08:55 +0000871 while (const ArrayType *Array = getContext().getAsArrayType(DtorTy))
Fariborz Jahanian6fba7462009-10-29 16:22:54 +0000872 DtorTy = getContext().getBaseElementType(Array);
Fariborz Jahanian667f36a2009-08-03 20:51:29 +0000873 if (const RecordType *RT = DtorTy->getAs<RecordType>())
Douglas Gregord86c4772010-05-15 06:46:45 +0000874 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Douglas Gregorb5b30b92010-05-15 16:39:56 +0000875 if (!ClassDecl->hasTrivialDestructor()) {
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000876 // Note: We suppress the destructor call when the corresponding NRVO
877 // flag has been set.
Douglas Gregord86c4772010-05-15 06:46:45 +0000878 llvm::Value *Loc = DeclPtr;
879 if (isByRef)
880 Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D),
881 D.getNameAsString());
882
Douglas Gregor1d110e02010-07-01 14:13:13 +0000883 const CXXDestructorDecl *D = ClassDecl->getDestructor();
Fariborz Jahanian6ca0b322009-08-03 20:20:07 +0000884 assert(D && "EmitLocalBlockVarDecl - destructor is nul");
Fariborz Jahanian6fba7462009-10-29 16:22:54 +0000885
Fariborz Jahanian6fba7462009-10-29 16:22:54 +0000886 if (const ConstantArrayType *Array =
887 getContext().getAsConstantArrayType(Ty)) {
John McCall1f0fca52010-07-21 07:22:38 +0000888 EHStack.pushCleanup<CallArrayDtor>(NormalAndEHCleanup,
889 D, Array, Loc);
Fariborz Jahanian77996212009-11-04 17:57:40 +0000890 } else {
John McCall1f0fca52010-07-21 07:22:38 +0000891 EHStack.pushCleanup<CallVarDtor>(NormalAndEHCleanup,
892 D, NRVOFlag, Loc);
Fariborz Jahanian77996212009-11-04 17:57:40 +0000893 }
Fariborz Jahanian6ca0b322009-08-03 20:20:07 +0000894 }
895 }
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Anders Carlsson69c68b72009-02-07 23:51:38 +0000897 // Handle the cleanup attribute
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000898 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlsson69c68b72009-02-07 23:51:38 +0000899 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Anders Carlsson555b4bb2009-09-10 23:43:36 +0000901 llvm::Constant* F = CGM.GetAddrOfFunction(FD);
Anders Carlsson69c68b72009-02-07 23:51:38 +0000902 assert(F && "Could not find function!");
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Anders Carlssoncabec032009-04-26 00:34:20 +0000904 const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
John McCall1f0fca52010-07-21 07:22:38 +0000905 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup,
906 F, &Info, DeclPtr, &D);
Anders Carlsson69c68b72009-02-07 23:51:38 +0000907 }
Mike Stump797b6322009-03-05 01:23:13 +0000908
John McCalldb2cfec2010-07-22 21:25:44 +0000909 // If this is a block variable, clean it up.
John McCalld8715092010-07-21 06:13:08 +0000910 if (needsDispose && CGM.getLangOptions().getGCMode() != LangOptions::GCOnly)
John McCall34fdee32010-10-06 18:56:43 +0000911 EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, DeclPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000912}
913
Mike Stump1eb44332009-09-09 15:08:12 +0000914/// Emit an alloca (or GlobalValue depending on target)
Chris Lattner2621fd12008-05-08 05:58:21 +0000915/// for the specified parameter and set up LocalDeclMap.
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000916void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) {
917 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +0000918 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000919 "Invalid argument to EmitParmDecl");
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000920 QualType Ty = D.getType();
Mike Stumpdf317bf2009-11-03 23:25:48 +0000921 CanQualType CTy = getContext().getCanonicalType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Reid Spencer5f016e22007-07-11 17:01:13 +0000923 llvm::Value *DeclPtr;
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000924 // If this is an aggregate or variable sized value, reuse the input pointer.
925 if (!Ty->isConstantSizeType() ||
926 CodeGenFunction::hasAggregateLLVMType(Ty)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000927 DeclPtr = Arg;
Reid Spencer5f016e22007-07-11 17:01:13 +0000928 } else {
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000929 // Otherwise, create a temporary to hold the value.
Daniel Dunbar195337d2010-02-09 02:48:28 +0000930 DeclPtr = CreateMemTemp(Ty, D.getName() + ".addr");
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000932 // Store the initial value into the alloca.
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000933 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
934 EmitStoreOfScalar(Arg, DeclPtr, CTy.isVolatileQualified(), Alignment, Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000935 }
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000936 Arg->setName(D.getName());
Reid Spencer5f016e22007-07-11 17:01:13 +0000937
938 llvm::Value *&DMEntry = LocalDeclMap[&D];
939 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
940 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000941
942 // Emit debug info for param declaration.
Devang Patelfee53aa2009-10-09 22:06:15 +0000943 if (CGDebugInfo *DI = getDebugInfo()) {
944 DI->setLocation(D.getLocation());
Chris Lattner9c85ba32008-11-10 06:08:34 +0000945 DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder);
Devang Patelfee53aa2009-10-09 22:06:15 +0000946 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000947}