blob: 9b400cbe2aa1fb693356a8f5810a34b0033f50ea [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:
Devang Patel12e6d832011-04-05 20:28:21 +000072 assert(0 && "Declaration should not be in declstmts!");
Reid Spencer5f016e22007-07-11 17:01:13 +000073 case Decl::Function: // void X();
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000074 case Decl::Record: // struct/union/class X;
Reid Spencer5f016e22007-07-11 17:01:13 +000075 case Decl::Enum: // enum X;
Mike Stump1eb44332009-09-09 15:08:12 +000076 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000077 case Decl::CXXRecord: // struct/union/class X; [C++]
Daniel Dunbarfa133a12009-11-23 00:07:06 +000078 case Decl::Using: // using X; [C++]
79 case Decl::UsingShadow:
80 case Decl::UsingDirective: // using namespace X; [C++]
Douglas Gregor08688ac2010-04-23 02:02:43 +000081 case Decl::NamespaceAlias:
Anders Carlsson7b0ca3f2009-12-03 17:26:31 +000082 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner4ae493c2011-02-18 02:08:43 +000083 case Decl::Label: // __label__ x;
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) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 switch (D.getStorageClass()) {
John McCalld931b082010-08-26 03:08:43 +0000108 case SC_None:
109 case SC_Auto:
110 case SC_Register:
John McCallb6bbcc92010-10-15 04:57:14 +0000111 return EmitAutoVarDecl(D);
John McCalld931b082010-08-26 03:08:43 +0000112 case SC_Static: {
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000113 llvm::GlobalValue::LinkageTypes Linkage =
114 llvm::GlobalValue::InternalLinkage;
115
John McCall8b242332010-05-25 04:30:21 +0000116 // If the function definition has some sort of weak linkage, its
117 // static variables should also be weak so that they get properly
118 // uniqued. We can't do this in C, though, because there's no
119 // standard way to agree on which variables are the same (i.e.
120 // there's no mangling).
121 if (getContext().getLangOptions().CPlusPlus)
122 if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
123 Linkage = CurFn->getLinkage();
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000124
John McCallb6bbcc92010-10-15 04:57:14 +0000125 return EmitStaticVarDecl(D, Linkage);
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000126 }
John McCalld931b082010-08-26 03:08:43 +0000127 case SC_Extern:
128 case SC_PrivateExtern:
Lauro Ramos Venanciofea90b82008-02-16 22:30:38 +0000129 // Don't emit it now, allow it to be emitted lazily on its first use.
130 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000131 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000132
133 assert(0 && "Unknown storage class");
Reid Spencer5f016e22007-07-11 17:01:13 +0000134}
135
Chris Lattner761acc12009-12-05 08:22:11 +0000136static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
137 const char *Separator) {
138 CodeGenModule &CGM = CGF.CGM;
John McCallf746aa62010-03-19 23:29:14 +0000139 if (CGF.getContext().getLangOptions().CPlusPlus) {
Anders Carlsson9a20d552010-06-22 16:16:50 +0000140 llvm::StringRef Name = CGM.getMangledName(&D);
141 return Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000142 }
Chris Lattner761acc12009-12-05 08:22:11 +0000143
144 std::string ContextName;
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000145 if (!CGF.CurFuncDecl) {
146 // Better be in a block declared in global scope.
147 const NamedDecl *ND = cast<NamedDecl>(&D);
148 const DeclContext *DC = ND->getDeclContext();
149 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
150 MangleBuffer Name;
Peter Collingbourne14110472011-01-13 18:57:25 +0000151 CGM.getBlockMangledName(GlobalDecl(), Name, BD);
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000152 ContextName = Name.getString();
153 }
154 else
155 assert(0 && "Unknown context for block static var decl");
156 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
Anders Carlsson9a20d552010-06-22 16:16:50 +0000157 llvm::StringRef Name = CGM.getMangledName(FD);
158 ContextName = Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000159 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattner761acc12009-12-05 08:22:11 +0000160 ContextName = CGF.CurFn->getName();
161 else
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000162 assert(0 && "Unknown context for static var decl");
Chris Lattner761acc12009-12-05 08:22:11 +0000163
164 return ContextName + Separator + D.getNameAsString();
165}
166
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000167llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000168CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
169 const char *Separator,
170 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000171 QualType Ty = D.getType();
Eli Friedman3c2b3172008-02-15 12:20:59 +0000172 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000173
Chris Lattner761acc12009-12-05 08:22:11 +0000174 std::string Name = GetStaticDeclName(*this, D, Separator);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000175
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000176 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Anders Carlsson41f8a132009-09-26 18:16:06 +0000177 llvm::GlobalVariable *GV =
178 new llvm::GlobalVariable(CGM.getModule(), LTy,
179 Ty.isConstant(getContext()), Linkage,
180 CGM.EmitNullConstant(D.getType()), Name, 0,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000181 D.isThreadSpecified(),
182 CGM.getContext().getTargetAddressSpace(Ty));
Ken Dyck8b752f12010-01-27 17:10:57 +0000183 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
John McCall112c9672010-11-02 21:04:24 +0000184 if (Linkage != llvm::GlobalValue::InternalLinkage)
185 GV->setVisibility(CurFn->getVisibility());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000186 return GV;
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000187}
188
John McCallb6bbcc92010-10-15 04:57:14 +0000189/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
Chris Lattner761acc12009-12-05 08:22:11 +0000190/// global variable that has already been created for it. If the initializer
191/// has a different type than GV does, this may free GV and return a different
192/// one. Otherwise it just returns GV.
193llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000194CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
195 llvm::GlobalVariable *GV) {
Chris Lattner761acc12009-12-05 08:22:11 +0000196 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this);
John McCallbf40cb52010-07-15 23:40:35 +0000197
Chris Lattner761acc12009-12-05 08:22:11 +0000198 // If constant emission failed, then this should be a C++ static
199 // initializer.
200 if (!Init) {
201 if (!getContext().getLangOptions().CPlusPlus)
202 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall5cd91b52010-09-08 01:44:27 +0000203 else if (Builder.GetInsertBlock()) {
Anders Carlsson071c8102010-01-26 04:02:23 +0000204 // Since we have a static initializer, this global variable can't
205 // be constant.
206 GV->setConstant(false);
John McCall5cd91b52010-09-08 01:44:27 +0000207
John McCall3030eb82010-11-06 09:44:32 +0000208 EmitCXXGuardedInit(D, GV);
Anders Carlsson071c8102010-01-26 04:02:23 +0000209 }
Chris Lattner761acc12009-12-05 08:22:11 +0000210 return GV;
211 }
John McCallbf40cb52010-07-15 23:40:35 +0000212
Chris Lattner761acc12009-12-05 08:22:11 +0000213 // The initializer may differ in type from the global. Rewrite
214 // the global to match the initializer. (We have to do this
215 // because some types, like unions, can't be completely represented
216 // in the LLVM type system.)
John McCall9c20fa92010-09-03 18:58:50 +0000217 if (GV->getType()->getElementType() != Init->getType()) {
Chris Lattner761acc12009-12-05 08:22:11 +0000218 llvm::GlobalVariable *OldGV = GV;
219
220 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
221 OldGV->isConstant(),
222 OldGV->getLinkage(), Init, "",
John McCall112c9672010-11-02 21:04:24 +0000223 /*InsertBefore*/ OldGV,
224 D.isThreadSpecified(),
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000225 CGM.getContext().getTargetAddressSpace(D.getType()));
John McCall112c9672010-11-02 21:04:24 +0000226 GV->setVisibility(OldGV->getVisibility());
Chris Lattner761acc12009-12-05 08:22:11 +0000227
228 // Steal the name of the old global
229 GV->takeName(OldGV);
230
231 // Replace all uses of the old global with the new global
232 llvm::Constant *NewPtrForOldDecl =
233 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
234 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
235
236 // Erase the old global, since it is no longer used.
237 OldGV->eraseFromParent();
238 }
239
240 GV->setInitializer(Init);
241 return GV;
242}
243
John McCallb6bbcc92010-10-15 04:57:14 +0000244void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000245 llvm::GlobalValue::LinkageTypes Linkage) {
Daniel Dunbara985b312009-02-25 19:45:19 +0000246 llvm::Value *&DMEntry = LocalDeclMap[&D];
247 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
Mike Stump1eb44332009-09-09 15:08:12 +0000248
John McCallb6bbcc92010-10-15 04:57:14 +0000249 llvm::GlobalVariable *GV = CreateStaticVarDecl(D, ".", Linkage);
Daniel Dunbara985b312009-02-25 19:45:19 +0000250
Daniel Dunbare5731f82009-02-25 20:08:33 +0000251 // Store into LocalDeclMap before generating initializer to handle
252 // circular references.
253 DMEntry = GV;
254
John McCallfe67f3b2010-05-04 20:45:42 +0000255 // We can't have a VLA here, but we can have a pointer to a VLA,
256 // even though that doesn't really make any sense.
Eli Friedmanc62aad82009-04-20 03:54:15 +0000257 // Make sure to evaluate VLA bounds now so that we have them for later.
258 if (D.getType()->isVariablyModifiedType())
259 EmitVLASize(D.getType());
Fariborz Jahanian09349142010-09-07 23:26:17 +0000260
261 // Local static block variables must be treated as globals as they may be
262 // referenced in their RHS initializer block-literal expresion.
263 CGM.setStaticLocalDeclAddress(&D, GV);
Eli Friedmanc62aad82009-04-20 03:54:15 +0000264
Chris Lattner761acc12009-12-05 08:22:11 +0000265 // If this value has an initializer, emit it.
266 if (D.getInit())
John McCallb6bbcc92010-10-15 04:57:14 +0000267 GV = AddInitializerToStaticVarDecl(D, GV);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000268
Chris Lattner0af95232010-03-10 23:59:59 +0000269 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
270
Daniel Dunbar30510ab2009-02-12 23:32:54 +0000271 // FIXME: Merge attribute handling.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000272 if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000273 SourceManager &SM = CGM.getContext().getSourceManager();
274 llvm::Constant *Ann =
Mike Stump1eb44332009-09-09 15:08:12 +0000275 CGM.EmitAnnotateAttr(GV, AA,
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000276 SM.getInstantiationLineNumber(D.getLocation()));
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000277 CGM.AddAnnotation(Ann);
278 }
279
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000280 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
Daniel Dunbar30510ab2009-02-12 23:32:54 +0000281 GV->setSection(SA->getName());
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000283 if (D.hasAttr<UsedAttr>())
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000284 CGM.AddUsedGlobal(GV);
285
Daniel Dunbare5731f82009-02-25 20:08:33 +0000286 // We may have to cast the constant because of the initializer
287 // mismatch above.
288 //
289 // FIXME: It is really dangerous to store this in the map; if anyone
290 // RAUW's the GV uses of this constant will be invalid.
Eli Friedman26590522008-06-08 01:23:18 +0000291 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000292 const llvm::Type *LPtrTy =
293 LTy->getPointerTo(CGM.getContext().getTargetAddressSpace(D.getType()));
Owen Anderson3c4972d2009-07-29 18:54:39 +0000294 DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000295
296 // Emit global variable debug descriptor for static vars.
Anders Carlssone896d982009-02-13 08:11:52 +0000297 CGDebugInfo *DI = getDebugInfo();
Mike Stump4451bd92009-02-20 00:19:45 +0000298 if (DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000299 DI->setLocation(D.getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000300 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
301 }
Anders Carlsson1a86b332007-10-17 00:52:43 +0000302}
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCallda65ea82010-07-13 20:32:21 +0000304namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000305 struct CallArrayDtor : EHScopeStack::Cleanup {
John McCallda65ea82010-07-13 20:32:21 +0000306 CallArrayDtor(const CXXDestructorDecl *Dtor,
307 const ConstantArrayType *Type,
308 llvm::Value *Loc)
309 : Dtor(Dtor), Type(Type), Loc(Loc) {}
310
311 const CXXDestructorDecl *Dtor;
312 const ConstantArrayType *Type;
313 llvm::Value *Loc;
314
315 void Emit(CodeGenFunction &CGF, bool IsForEH) {
316 QualType BaseElementTy = CGF.getContext().getBaseElementType(Type);
317 const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
318 BasePtr = llvm::PointerType::getUnqual(BasePtr);
319 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(Loc, BasePtr);
320 CGF.EmitCXXAggrDestructorCall(Dtor, Type, BaseAddrPtr);
321 }
322 };
323
John McCall1f0fca52010-07-21 07:22:38 +0000324 struct CallVarDtor : EHScopeStack::Cleanup {
John McCallda65ea82010-07-13 20:32:21 +0000325 CallVarDtor(const CXXDestructorDecl *Dtor,
326 llvm::Value *NRVOFlag,
327 llvm::Value *Loc)
328 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(Loc) {}
329
330 const CXXDestructorDecl *Dtor;
331 llvm::Value *NRVOFlag;
332 llvm::Value *Loc;
333
334 void Emit(CodeGenFunction &CGF, bool IsForEH) {
335 // Along the exceptions path we always execute the dtor.
336 bool NRVO = !IsForEH && NRVOFlag;
337
338 llvm::BasicBlock *SkipDtorBB = 0;
339 if (NRVO) {
340 // If we exited via NRVO, we skip the destructor call.
341 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
342 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
343 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
344 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
345 CGF.EmitBlock(RunDtorBB);
346 }
347
348 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
349 /*ForVirtualBase=*/false, Loc);
350
351 if (NRVO) CGF.EmitBlock(SkipDtorBB);
352 }
353 };
354}
355
John McCalld8715092010-07-21 06:13:08 +0000356namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000357 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000358 llvm::Value *Stack;
359 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
360 void Emit(CodeGenFunction &CGF, bool IsForEH) {
361 llvm::Value *V = CGF.Builder.CreateLoad(Stack, "tmp");
362 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
363 CGF.Builder.CreateCall(F, V);
364 }
365 };
366
John McCall1f0fca52010-07-21 07:22:38 +0000367 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000368 llvm::Constant *CleanupFn;
369 const CGFunctionInfo &FnInfo;
John McCalld8715092010-07-21 06:13:08 +0000370 const VarDecl &Var;
371
372 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCall34695852011-02-22 06:44:22 +0000373 const VarDecl *Var)
374 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalld8715092010-07-21 06:13:08 +0000375
376 void Emit(CodeGenFunction &CGF, bool IsForEH) {
John McCall34695852011-02-22 06:44:22 +0000377 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue,
378 SourceLocation());
379 // Compute the address of the local variable, in case it's a byref
380 // or something.
381 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
382
John McCalld8715092010-07-21 06:13:08 +0000383 // In some cases, the type of the function argument will be different from
384 // the type of the pointer. An example of this is
385 // void f(void* arg);
386 // __attribute__((cleanup(f))) void *g;
387 //
388 // To fix this we insert a bitcast here.
389 QualType ArgTy = FnInfo.arg_begin()->type;
390 llvm::Value *Arg =
391 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
392
393 CallArgList Args;
394 Args.push_back(std::make_pair(RValue::get(Arg),
395 CGF.getContext().getPointerType(Var.getType())));
396 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
397 }
398 };
John McCalld8715092010-07-21 06:13:08 +0000399}
400
Chris Lattner94cd0112010-12-01 02:05:19 +0000401
402/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
403/// non-zero parts of the specified initializer with equal or fewer than
404/// NumStores scalar stores.
405static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
406 unsigned &NumStores) {
Chris Lattner70b02942010-12-02 01:58:41 +0000407 // Zero and Undef never requires any extra stores.
408 if (isa<llvm::ConstantAggregateZero>(Init) ||
409 isa<llvm::ConstantPointerNull>(Init) ||
410 isa<llvm::UndefValue>(Init))
411 return true;
412 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
413 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
414 isa<llvm::ConstantExpr>(Init))
415 return Init->isNullValue() || NumStores--;
416
417 // See if we can emit each element.
418 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
419 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
420 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
421 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
422 return false;
423 }
424 return true;
425 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000426
427 // Anything else is hard and scary.
428 return false;
429}
430
431/// emitStoresForInitAfterMemset - For inits that
432/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
433/// stores that would be required.
434static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCall34695852011-02-22 06:44:22 +0000435 bool isVolatile, CGBuilderTy &Builder) {
Chris Lattner94cd0112010-12-01 02:05:19 +0000436 // Zero doesn't require any stores.
Chris Lattner70b02942010-12-02 01:58:41 +0000437 if (isa<llvm::ConstantAggregateZero>(Init) ||
438 isa<llvm::ConstantPointerNull>(Init) ||
439 isa<llvm::UndefValue>(Init))
440 return;
Chris Lattner94cd0112010-12-01 02:05:19 +0000441
Chris Lattner70b02942010-12-02 01:58:41 +0000442 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
443 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
444 isa<llvm::ConstantExpr>(Init)) {
445 if (!Init->isNullValue())
John McCall34695852011-02-22 06:44:22 +0000446 Builder.CreateStore(Init, Loc, isVolatile);
Chris Lattner70b02942010-12-02 01:58:41 +0000447 return;
448 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000449
Chris Lattner70b02942010-12-02 01:58:41 +0000450 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
451 "Unknown value type!");
452
453 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
454 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
455 if (Elt->isNullValue()) continue;
456
457 // Otherwise, get a pointer to the element and emit it.
458 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
John McCall34695852011-02-22 06:44:22 +0000459 isVolatile, Builder);
Chris Lattner70b02942010-12-02 01:58:41 +0000460 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000461}
462
463
464/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
465/// plus some stores to initialize a local variable instead of using a memcpy
466/// from a constant global. It is beneficial to use memset if the global is all
467/// zeros, or mostly zeros and large.
468static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
469 uint64_t GlobalSize) {
470 // If a global is all zeros, always use a memset.
471 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
472
473
474 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
475 // do it if it will require 6 or fewer scalar stores.
476 // TODO: Should budget depends on the size? Avoiding a large global warrants
477 // plopping in more stores.
478 unsigned StoreBudget = 6;
479 uint64_t SizeLimit = 32;
480
481 return GlobalSize > SizeLimit &&
482 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
483}
484
485
Nick Lewyckya9de3fa2010-12-30 20:21:55 +0000486/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Reid Spencer5f016e22007-07-11 17:01:13 +0000487/// variable declaration with auto, register, or no storage class specifier.
Chris Lattner2621fd12008-05-08 05:58:21 +0000488/// These turn into simple stack objects, or GlobalValues depending on target.
John McCall34695852011-02-22 06:44:22 +0000489void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
490 AutoVarEmission emission = EmitAutoVarAlloca(D);
491 EmitAutoVarInit(emission);
492 EmitAutoVarCleanups(emission);
493}
Reid Spencer5f016e22007-07-11 17:01:13 +0000494
John McCall34695852011-02-22 06:44:22 +0000495/// EmitAutoVarAlloca - Emit the alloca and debug information for a
496/// local variable. Does not emit initalization or destruction.
497CodeGenFunction::AutoVarEmission
498CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
499 QualType Ty = D.getType();
500
501 AutoVarEmission emission(D);
502
503 bool isByRef = D.hasAttr<BlocksAttr>();
504 emission.IsByRef = isByRef;
505
506 CharUnits alignment = getContext().getDeclAlign(&D);
507 emission.Alignment = alignment;
508
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 llvm::Value *DeclPtr;
Eli Friedman3c2b3172008-02-15 12:20:59 +0000510 if (Ty->isConstantSizeType()) {
Chris Lattner2621fd12008-05-08 05:58:21 +0000511 if (!Target.useGlobalsForAutomaticVariables()) {
John McCall34695852011-02-22 06:44:22 +0000512 bool NRVO = getContext().getLangOptions().ElideConstructors &&
513 D.isNRVOVariable();
514
515 // If this value is a POD array or struct with a statically
516 // determinable constant initializer, there are optimizations we
517 // can do.
518 // TODO: we can potentially constant-evaluate non-POD structs and
519 // arrays as long as the initialization is trivial (e.g. if they
520 // have a non-trivial destructor, but not a non-trivial constructor).
521 if (D.getInit() &&
522 (Ty->isArrayType() || Ty->isRecordType()) && Ty->isPODType() &&
John McCall4204f072010-08-02 21:13:48 +0000523 D.getInit()->isConstantInitializer(getContext(), false)) {
John McCall34695852011-02-22 06:44:22 +0000524
525 // If the variable's a const type, and it's neither an NRVO
526 // candidate nor a __block variable, emit it as a global instead.
527 if (CGM.getCodeGenOpts().MergeAllConstants && Ty.isConstQualified() &&
528 !NRVO && !isByRef) {
Douglas Gregor4707b9a2011-03-06 23:28:21 +0000529 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCall34695852011-02-22 06:44:22 +0000530
531 emission.Address = 0; // signal this condition to later callbacks
532 assert(emission.wasEmittedAsGlobal());
533 return emission;
Tanya Lattner59876c22009-11-04 01:18:09 +0000534 }
John McCall34695852011-02-22 06:44:22 +0000535
536 // Otherwise, tell the initialization code that we're in this case.
537 emission.IsConstantAggregate = true;
Tanya Lattner59876c22009-11-04 01:18:09 +0000538 }
539
Douglas Gregord86c4772010-05-15 06:46:45 +0000540 // A normal fixed sized variable becomes an alloca in the entry block,
541 // unless it's an NRVO variable.
Eli Friedmana3460ac2009-03-04 04:25:14 +0000542 const llvm::Type *LTy = ConvertTypeForMem(Ty);
Douglas Gregord86c4772010-05-15 06:46:45 +0000543
544 if (NRVO) {
545 // The named return value optimization: allocate this variable in the
546 // return slot, so that we can elide the copy when returning this
547 // variable (C++0x [class.copy]p34).
548 DeclPtr = ReturnValue;
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000549
550 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
551 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
552 // Create a flag that is used to indicate when the NRVO was applied
553 // to this variable. Set it to zero to indicate that NRVO was not
554 // applied.
Chris Lattner4c53dc12010-12-01 01:47:15 +0000555 llvm::Value *Zero = Builder.getFalse();
John McCall34695852011-02-22 06:44:22 +0000556 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
Nick Lewyckya03733b2011-02-16 23:59:08 +0000557 EnsureInsertPoint();
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000558 Builder.CreateStore(Zero, NRVOFlag);
559
560 // Record the NRVO flag for this variable.
561 NRVOFlags[&D] = NRVOFlag;
John McCall34695852011-02-22 06:44:22 +0000562 emission.NRVOFlag = NRVOFlag;
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000563 }
564 }
Douglas Gregord86c4772010-05-15 06:46:45 +0000565 } else {
566 if (isByRef)
567 LTy = BuildByRefType(&D);
568
569 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
570 Alloc->setName(D.getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +0000571
John McCall34695852011-02-22 06:44:22 +0000572 CharUnits allocaAlignment = alignment;
Douglas Gregord86c4772010-05-15 06:46:45 +0000573 if (isByRef)
John McCall34695852011-02-22 06:44:22 +0000574 allocaAlignment = std::max(allocaAlignment,
Ken Dyck06f486e2011-01-18 02:01:14 +0000575 getContext().toCharUnitsFromBits(Target.getPointerAlign(0)));
John McCall34695852011-02-22 06:44:22 +0000576 Alloc->setAlignment(allocaAlignment.getQuantity());
Douglas Gregord86c4772010-05-15 06:46:45 +0000577 DeclPtr = Alloc;
578 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000579 } else {
580 // Targets that don't support recursion emit locals as globals.
581 const char *Class =
John McCalld931b082010-08-26 03:08:43 +0000582 D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
John McCallb6bbcc92010-10-15 04:57:14 +0000583 DeclPtr = CreateStaticVarDecl(D, Class,
584 llvm::GlobalValue::InternalLinkage);
Chris Lattner2621fd12008-05-08 05:58:21 +0000585 }
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Daniel Dunbard286f052009-07-19 06:58:07 +0000587 // FIXME: Can this happen?
Anders Carlsson60d35412008-12-20 20:46:34 +0000588 if (Ty->isVariablyModifiedType())
589 EmitVLASize(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000590 } else {
Daniel Dunbard286f052009-07-19 06:58:07 +0000591 EnsureInsertPoint();
592
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000593 if (!DidCallStackSave) {
Anders Carlsson5d463152008-12-12 07:38:43 +0000594 // Save the stack.
John McCalld16c2cf2011-02-08 08:22:06 +0000595 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Anders Carlsson5d463152008-12-12 07:38:43 +0000597 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
598 llvm::Value *V = Builder.CreateCall(F);
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Anders Carlsson5d463152008-12-12 07:38:43 +0000600 Builder.CreateStore(V, Stack);
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000601
602 DidCallStackSave = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000603
John McCalld8715092010-07-21 06:13:08 +0000604 // Push a cleanup block and restore the stack there.
John McCall3ad32c82011-01-28 08:37:24 +0000605 // FIXME: in general circumstances, this should be an EH cleanup.
John McCall1f0fca52010-07-21 07:22:38 +0000606 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
Anders Carlsson5d463152008-12-12 07:38:43 +0000607 }
Mike Stump1eb44332009-09-09 15:08:12 +0000608
Anders Carlsson5d463152008-12-12 07:38:43 +0000609 // Get the element type.
Mike Stump1eb44332009-09-09 15:08:12 +0000610 const llvm::Type *LElemTy = ConvertTypeForMem(Ty);
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000611 const llvm::Type *LElemPtrTy =
612 LElemTy->getPointerTo(CGM.getContext().getTargetAddressSpace(Ty));
Anders Carlsson5d463152008-12-12 07:38:43 +0000613
Anders Carlsson60d35412008-12-20 20:46:34 +0000614 llvm::Value *VLASize = EmitVLASize(Ty);
Anders Carlsson5d463152008-12-12 07:38:43 +0000615
616 // Allocate memory for the array.
Anders Carlsson41f8a132009-09-26 18:16:06 +0000617 llvm::AllocaInst *VLA =
John McCalld16c2cf2011-02-08 08:22:06 +0000618 Builder.CreateAlloca(llvm::Type::getInt8Ty(getLLVMContext()), VLASize, "vla");
John McCall34695852011-02-22 06:44:22 +0000619 VLA->setAlignment(alignment.getQuantity());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000620
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000621 DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
Reid Spencer5f016e22007-07-11 17:01:13 +0000622 }
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000623
Reid Spencer5f016e22007-07-11 17:01:13 +0000624 llvm::Value *&DMEntry = LocalDeclMap[&D];
625 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
626 DMEntry = DeclPtr;
John McCall34695852011-02-22 06:44:22 +0000627 emission.Address = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000628
629 // Emit debug info for local var declaration.
Anders Carlssone896d982009-02-13 08:11:52 +0000630 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar25b6ebf2009-07-19 07:03:11 +0000631 assert(HaveInsertPoint() && "Unexpected unreachable point!");
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Daniel Dunbar66031a52008-10-17 16:15:48 +0000633 DI->setLocation(D.getLocation());
Sanjiv Gupta4381d4b2009-05-22 13:54:25 +0000634 if (Target.useGlobalsForAutomaticVariables()) {
635 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
Mike Stumpdab514f2009-03-04 03:23:46 +0000636 } else
637 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000638 }
639
John McCall34695852011-02-22 06:44:22 +0000640 return emission;
641}
642
643/// Determines whether the given __block variable is potentially
644/// captured by the given expression.
645static bool isCapturedBy(const VarDecl &var, const Expr *e) {
646 // Skip the most common kinds of expressions that make
647 // hierarchy-walking expensive.
648 e = e->IgnoreParenCasts();
649
650 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
651 const BlockDecl *block = be->getBlockDecl();
652 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
653 e = block->capture_end(); i != e; ++i) {
654 if (i->getVariable() == &var)
655 return true;
656 }
657
658 // No need to walk into the subexpressions.
659 return false;
660 }
661
662 for (Stmt::const_child_range children = e->children(); children; ++children)
663 if (isCapturedBy(var, cast<Expr>(*children)))
664 return true;
665
666 return false;
667}
668
669void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +0000670 assert(emission.Variable && "emission was not valid!");
671
John McCall34695852011-02-22 06:44:22 +0000672 // If this was emitted as a global constant, we're done.
673 if (emission.wasEmittedAsGlobal()) return;
674
John McCall57b3b6a2011-02-22 07:16:58 +0000675 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +0000676 QualType type = D.getType();
677
Chris Lattner19785962007-07-12 00:39:48 +0000678 // If this local has an initializer, emit it now.
Daniel Dunbard286f052009-07-19 06:58:07 +0000679 const Expr *Init = D.getInit();
680
681 // If we are at an unreachable point, we don't need to emit the initializer
682 // unless it contains a label.
683 if (!HaveInsertPoint()) {
John McCall34695852011-02-22 06:44:22 +0000684 if (!Init || !ContainsLabel(Init)) return;
685 EnsureInsertPoint();
Daniel Dunbard286f052009-07-19 06:58:07 +0000686 }
687
John McCall5af02db2011-03-31 01:59:53 +0000688 // Initialize the structure of a __block variable.
689 if (emission.IsByRef)
690 emitByrefStructureInit(emission);
Anders Carlsson69c68b72009-02-07 23:51:38 +0000691
John McCall34695852011-02-22 06:44:22 +0000692 if (!Init) return;
Mon P Wang3ecd7852010-04-04 03:10:52 +0000693
John McCall5af02db2011-03-31 01:59:53 +0000694 CharUnits alignment = emission.Alignment;
695
John McCall34695852011-02-22 06:44:22 +0000696 // Check whether this is a byref variable that's potentially
697 // captured and moved by its own initializer. If so, we'll need to
698 // emit the initializer first, then copy into the variable.
699 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
700
701 llvm::Value *Loc =
702 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
703
John McCall60d33652011-03-08 09:11:50 +0000704 if (!emission.IsConstantAggregate)
705 return EmitExprAsInit(Init, &D, Loc, alignment, capturedByInit);
706
John McCall34695852011-02-22 06:44:22 +0000707 // If this is a simple aggregate initialization, we can optimize it
708 // in various ways.
John McCall60d33652011-03-08 09:11:50 +0000709 assert(!capturedByInit && "constant init contains a capturing block?");
John McCall34695852011-02-22 06:44:22 +0000710
John McCall60d33652011-03-08 09:11:50 +0000711 bool isVolatile = type.isVolatileQualified();
John McCall34695852011-02-22 06:44:22 +0000712
John McCall60d33652011-03-08 09:11:50 +0000713 llvm::Constant *constant = CGM.EmitConstantExpr(D.getInit(), type, this);
714 assert(constant != 0 && "Wasn't a simple constant init?");
John McCall34695852011-02-22 06:44:22 +0000715
John McCall60d33652011-03-08 09:11:50 +0000716 llvm::Value *SizeVal =
717 llvm::ConstantInt::get(IntPtrTy,
718 getContext().getTypeSizeInChars(type).getQuantity());
John McCall34695852011-02-22 06:44:22 +0000719
John McCall60d33652011-03-08 09:11:50 +0000720 const llvm::Type *BP = Int8PtrTy;
721 if (Loc->getType() != BP)
722 Loc = Builder.CreateBitCast(Loc, BP, "tmp");
Mon P Wang3ecd7852010-04-04 03:10:52 +0000723
John McCall60d33652011-03-08 09:11:50 +0000724 // If the initializer is all or mostly zeros, codegen with memset then do
725 // a few stores afterward.
726 if (shouldUseMemSetPlusStoresToInitialize(constant,
727 CGM.getTargetData().getTypeAllocSize(constant->getType()))) {
728 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
729 alignment.getQuantity(), isVolatile);
730 if (!constant->isNullValue()) {
731 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
732 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000733 }
John McCall60d33652011-03-08 09:11:50 +0000734 } else {
735 // Otherwise, create a temporary global with the initializer then
736 // memcpy from the global to the alloca.
737 std::string Name = GetStaticDeclName(*this, D, ".");
738 llvm::GlobalVariable *GV =
739 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
740 llvm::GlobalValue::InternalLinkage,
741 constant, Name, 0, false, 0);
742 GV->setAlignment(alignment.getQuantity());
743
744 llvm::Value *SrcPtr = GV;
745 if (SrcPtr->getType() != BP)
746 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
747
748 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
749 isVolatile);
750 }
751}
752
753/// Emit an expression as an initializer for a variable at the given
754/// location. The expression is not necessarily the normal
755/// initializer for the variable, and the address is not necessarily
756/// its normal location.
757///
758/// \param init the initializing expression
759/// \param var the variable to act as if we're initializing
760/// \param loc the address to initialize; its type is a pointer
761/// to the LLVM mapping of the variable's type
762/// \param alignment the alignment of the address
763/// \param capturedByInit true if the variable is a __block variable
764/// whose address is potentially changed by the initializer
765void CodeGenFunction::EmitExprAsInit(const Expr *init,
766 const VarDecl *var,
767 llvm::Value *loc,
768 CharUnits alignment,
769 bool capturedByInit) {
770 QualType type = var->getType();
771 bool isVolatile = type.isVolatileQualified();
772
773 if (type->isReferenceType()) {
774 RValue RV = EmitReferenceBindingToExpr(init, var);
775 if (capturedByInit) loc = BuildBlockByrefAddress(loc, var);
776 EmitStoreOfScalar(RV.getScalarVal(), loc, false,
777 alignment.getQuantity(), type);
John McCall34695852011-02-22 06:44:22 +0000778 } else if (!hasAggregateLLVMType(type)) {
John McCall60d33652011-03-08 09:11:50 +0000779 llvm::Value *V = EmitScalarExpr(init);
780 if (capturedByInit) loc = BuildBlockByrefAddress(loc, var);
781 EmitStoreOfScalar(V, loc, isVolatile, alignment.getQuantity(), type);
John McCall34695852011-02-22 06:44:22 +0000782 } else if (type->isAnyComplexType()) {
John McCall60d33652011-03-08 09:11:50 +0000783 ComplexPairTy complex = EmitComplexExpr(init);
784 if (capturedByInit) loc = BuildBlockByrefAddress(loc, var);
785 StoreComplexToAddr(complex, loc, isVolatile);
John McCall34695852011-02-22 06:44:22 +0000786 } else {
787 // TODO: how can we delay here if D is captured by its initializer?
John McCall60d33652011-03-08 09:11:50 +0000788 EmitAggExpr(init, AggValueSlot::forAddr(loc, isVolatile, true, false));
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +0000789 }
John McCall34695852011-02-22 06:44:22 +0000790}
John McCallf1549f62010-07-06 01:34:17 +0000791
John McCall34695852011-02-22 06:44:22 +0000792void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +0000793 assert(emission.Variable && "emission was not valid!");
794
John McCall34695852011-02-22 06:44:22 +0000795 // If this was emitted as a global constant, we're done.
796 if (emission.wasEmittedAsGlobal()) return;
797
John McCall57b3b6a2011-02-22 07:16:58 +0000798 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +0000799
800 // Handle C++ destruction of variables.
801 if (getLangOptions().CPlusPlus) {
802 QualType type = D.getType();
803 QualType baseType = getContext().getBaseElementType(type);
804 if (const RecordType *RT = baseType->getAs<RecordType>()) {
805 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Douglas Gregorb5b30b92010-05-15 16:39:56 +0000806 if (!ClassDecl->hasTrivialDestructor()) {
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000807 // Note: We suppress the destructor call when the corresponding NRVO
808 // flag has been set.
John McCall34695852011-02-22 06:44:22 +0000809
810 // Note that for __block variables, we want to destroy the
811 // original stack object, not the possible forwarded object.
812 llvm::Value *Loc = emission.getObjectAddress(*this);
Douglas Gregord86c4772010-05-15 06:46:45 +0000813
Douglas Gregor1d110e02010-07-01 14:13:13 +0000814 const CXXDestructorDecl *D = ClassDecl->getDestructor();
Fariborz Jahanian6ca0b322009-08-03 20:20:07 +0000815 assert(D && "EmitLocalBlockVarDecl - destructor is nul");
Fariborz Jahanian6fba7462009-10-29 16:22:54 +0000816
John McCall34695852011-02-22 06:44:22 +0000817 if (type != baseType) {
818 const ConstantArrayType *Array =
819 getContext().getAsConstantArrayType(type);
820 assert(Array && "types changed without array?");
John McCall1f0fca52010-07-21 07:22:38 +0000821 EHStack.pushCleanup<CallArrayDtor>(NormalAndEHCleanup,
822 D, Array, Loc);
Fariborz Jahanian77996212009-11-04 17:57:40 +0000823 } else {
John McCall1f0fca52010-07-21 07:22:38 +0000824 EHStack.pushCleanup<CallVarDtor>(NormalAndEHCleanup,
John McCall34695852011-02-22 06:44:22 +0000825 D, emission.NRVOFlag, Loc);
Fariborz Jahanian77996212009-11-04 17:57:40 +0000826 }
Fariborz Jahanian6ca0b322009-08-03 20:20:07 +0000827 }
John McCall34695852011-02-22 06:44:22 +0000828 }
Fariborz Jahanian6ca0b322009-08-03 20:20:07 +0000829 }
Mike Stump1eb44332009-09-09 15:08:12 +0000830
John McCall34695852011-02-22 06:44:22 +0000831 // Handle the cleanup attribute.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000832 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlsson69c68b72009-02-07 23:51:38 +0000833 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000834
John McCall34695852011-02-22 06:44:22 +0000835 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlsson69c68b72009-02-07 23:51:38 +0000836 assert(F && "Could not find function!");
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Anders Carlssoncabec032009-04-26 00:34:20 +0000838 const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
John McCall34695852011-02-22 06:44:22 +0000839 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlsson69c68b72009-02-07 23:51:38 +0000840 }
Mike Stump797b6322009-03-05 01:23:13 +0000841
John McCall34695852011-02-22 06:44:22 +0000842 // If this is a block variable, call _Block_object_destroy
843 // (on the unforwarded address).
John McCall5af02db2011-03-31 01:59:53 +0000844 if (emission.IsByRef)
845 enterByrefCleanup(emission);
Reid Spencer5f016e22007-07-11 17:01:13 +0000846}
847
Mike Stump1eb44332009-09-09 15:08:12 +0000848/// Emit an alloca (or GlobalValue depending on target)
Chris Lattner2621fd12008-05-08 05:58:21 +0000849/// for the specified parameter and set up LocalDeclMap.
Devang Patel093ac462011-03-03 20:13:15 +0000850void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
851 unsigned ArgNo) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000852 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +0000853 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000854 "Invalid argument to EmitParmDecl");
John McCall8178df32011-02-22 22:38:33 +0000855
856 Arg->setName(D.getName());
857
858 // Use better IR generation for certain implicit parameters.
859 if (isa<ImplicitParamDecl>(D)) {
860 // The only implicit argument a block has is its literal.
861 if (BlockInfo) {
862 LocalDeclMap[&D] = Arg;
863
864 if (CGDebugInfo *DI = getDebugInfo()) {
865 DI->setLocation(D.getLocation());
866 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, Builder);
867 }
868
869 return;
870 }
871 }
872
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000873 QualType Ty = D.getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Reid Spencer5f016e22007-07-11 17:01:13 +0000875 llvm::Value *DeclPtr;
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000876 // If this is an aggregate or variable sized value, reuse the input pointer.
877 if (!Ty->isConstantSizeType() ||
878 CodeGenFunction::hasAggregateLLVMType(Ty)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000879 DeclPtr = Arg;
Reid Spencer5f016e22007-07-11 17:01:13 +0000880 } else {
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000881 // Otherwise, create a temporary to hold the value.
Daniel Dunbar195337d2010-02-09 02:48:28 +0000882 DeclPtr = CreateMemTemp(Ty, D.getName() + ".addr");
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Daniel Dunbare86bcf02010-02-08 22:53:07 +0000884 // Store the initial value into the alloca.
John McCall5936e332011-02-15 09:22:45 +0000885 EmitStoreOfScalar(Arg, DeclPtr, Ty.isVolatileQualified(),
886 getContext().getDeclAlign(&D).getQuantity(), Ty,
887 CGM.getTBAAInfo(Ty));
Reid Spencer5f016e22007-07-11 17:01:13 +0000888 }
889
890 llvm::Value *&DMEntry = LocalDeclMap[&D];
891 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
892 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000893
894 // Emit debug info for param declaration.
Devang Patelfee53aa2009-10-09 22:06:15 +0000895 if (CGDebugInfo *DI = getDebugInfo()) {
896 DI->setLocation(D.getLocation());
Devang Patel093ac462011-03-03 20:13:15 +0000897 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
Devang Patelfee53aa2009-10-09 22:06:15 +0000898 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000899}