blob: ff85fc56886eb43b014713c3c93b2c8a05f4d37f [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"
Peter Collingbourne8c25fc52011-09-19 21:14:35 +000017#include "CGOpenCLRuntime.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000019#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Anders Carlsson19567ee2008-08-25 01:38:19 +000021#include "clang/AST/DeclObjC.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner2621fd12008-05-08 05:58:21 +000023#include "clang/Basic/TargetInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000024#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson1a86b332007-10-17 00:52:43 +000025#include "llvm/GlobalVariable.h"
Anders Carlsson5d463152008-12-12 07:38:43 +000026#include "llvm/Intrinsics.h"
Mike Stumpdab514f2009-03-04 03:23:46 +000027#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "llvm/Type.h"
29using namespace clang;
30using namespace CodeGen;
31
32
33void CodeGenFunction::EmitDecl(const Decl &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +000034 switch (D.getKind()) {
Douglas Gregor08688ac2010-04-23 02:02:43 +000035 case Decl::TranslationUnit:
36 case Decl::Namespace:
37 case Decl::UnresolvedUsingTypename:
38 case Decl::ClassTemplateSpecialization:
39 case Decl::ClassTemplatePartialSpecialization:
40 case Decl::TemplateTypeParm:
41 case Decl::UnresolvedUsingValue:
Sean Hunt9a555912010-05-30 07:21:58 +000042 case Decl::NonTypeTemplateParm:
Douglas Gregor08688ac2010-04-23 02:02:43 +000043 case Decl::CXXMethod:
44 case Decl::CXXConstructor:
45 case Decl::CXXDestructor:
46 case Decl::CXXConversion:
47 case Decl::Field:
Francois Pichet41f5e662010-11-21 06:49:41 +000048 case Decl::IndirectField:
Douglas Gregor08688ac2010-04-23 02:02:43 +000049 case Decl::ObjCIvar:
Eric Christophere1f54902011-08-23 22:38:00 +000050 case Decl::ObjCAtDefsField:
Chris Lattneraa9fc462007-10-08 21:37:32 +000051 case Decl::ParmVar:
Douglas Gregor08688ac2010-04-23 02:02:43 +000052 case Decl::ImplicitParam:
53 case Decl::ClassTemplate:
54 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +000055 case Decl::TypeAliasTemplate:
Douglas Gregor08688ac2010-04-23 02:02:43 +000056 case Decl::TemplateTemplateParm:
57 case Decl::ObjCMethod:
58 case Decl::ObjCCategory:
59 case Decl::ObjCProtocol:
60 case Decl::ObjCInterface:
61 case Decl::ObjCCategoryImpl:
62 case Decl::ObjCImplementation:
63 case Decl::ObjCProperty:
64 case Decl::ObjCCompatibleAlias:
Abramo Bagnara6206d532010-06-05 05:09:32 +000065 case Decl::AccessSpec:
Douglas Gregor08688ac2010-04-23 02:02:43 +000066 case Decl::LinkageSpec:
67 case Decl::ObjCPropertyImpl:
68 case Decl::ObjCClass:
69 case Decl::ObjCForwardProtocol:
70 case Decl::FileScopeAsm:
71 case Decl::Friend:
72 case Decl::FriendTemplate:
73 case Decl::Block:
Francois Pichetaf0f4d02011-08-14 03:52:19 +000074 case Decl::ClassScopeFunctionSpecialization:
David Blaikieb219cfc2011-09-23 05:06:16 +000075 llvm_unreachable("Declaration should not be in declstmts!");
Reid Spencer5f016e22007-07-11 17:01:13 +000076 case Decl::Function: // void X();
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000077 case Decl::Record: // struct/union/class X;
Reid Spencer5f016e22007-07-11 17:01:13 +000078 case Decl::Enum: // enum X;
Mike Stump1eb44332009-09-09 15:08:12 +000079 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000080 case Decl::CXXRecord: // struct/union/class X; [C++]
Daniel Dunbarfa133a12009-11-23 00:07:06 +000081 case Decl::Using: // using X; [C++]
82 case Decl::UsingShadow:
83 case Decl::UsingDirective: // using namespace X; [C++]
Douglas Gregor08688ac2010-04-23 02:02:43 +000084 case Decl::NamespaceAlias:
Anders Carlsson7b0ca3f2009-12-03 17:26:31 +000085 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner4ae493c2011-02-18 02:08:43 +000086 case Decl::Label: // __label__ x;
Douglas Gregor15de72c2011-12-02 23:23:56 +000087 case Decl::Import:
Reid Spencer5f016e22007-07-11 17:01:13 +000088 // None of these decls require codegen support.
89 return;
Mike Stump1eb44332009-09-09 15:08:12 +000090
Daniel Dunbar662174c82008-08-29 17:28:43 +000091 case Decl::Var: {
92 const VarDecl &VD = cast<VarDecl>(D);
John McCallb6bbcc92010-10-15 04:57:14 +000093 assert(VD.isLocalVarDecl() &&
Daniel Dunbar662174c82008-08-29 17:28:43 +000094 "Should not see file-scope variables inside a function!");
John McCallb6bbcc92010-10-15 04:57:14 +000095 return EmitVarDecl(VD);
Reid Spencer5f016e22007-07-11 17:01:13 +000096 }
Mike Stump1eb44332009-09-09 15:08:12 +000097
Richard Smith162e1c12011-04-15 14:24:37 +000098 case Decl::Typedef: // typedef int X;
99 case Decl::TypeAlias: { // using X = int; [C++0x]
100 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000101 QualType Ty = TD.getUnderlyingType();
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000103 if (Ty->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000104 EmitVariablyModifiedType(Ty);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000105 }
Daniel Dunbar662174c82008-08-29 17:28:43 +0000106 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000107}
108
John McCallb6bbcc92010-10-15 04:57:14 +0000109/// EmitVarDecl - This method handles emission of any variable declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000110/// inside a function, including static vars etc.
John McCallb6bbcc92010-10-15 04:57:14 +0000111void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000112 switch (D.getStorageClass()) {
John McCalld931b082010-08-26 03:08:43 +0000113 case SC_None:
114 case SC_Auto:
115 case SC_Register:
John McCallb6bbcc92010-10-15 04:57:14 +0000116 return EmitAutoVarDecl(D);
John McCalld931b082010-08-26 03:08:43 +0000117 case SC_Static: {
Eric Christophere1f54902011-08-23 22:38:00 +0000118 llvm::GlobalValue::LinkageTypes Linkage =
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000119 llvm::GlobalValue::InternalLinkage;
120
John McCall8b242332010-05-25 04:30:21 +0000121 // If the function definition has some sort of weak linkage, its
122 // static variables should also be weak so that they get properly
123 // uniqued. We can't do this in C, though, because there's no
124 // standard way to agree on which variables are the same (i.e.
125 // there's no mangling).
126 if (getContext().getLangOptions().CPlusPlus)
127 if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
128 Linkage = CurFn->getLinkage();
Eric Christophere1f54902011-08-23 22:38:00 +0000129
John McCallb6bbcc92010-10-15 04:57:14 +0000130 return EmitStaticVarDecl(D, Linkage);
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000131 }
John McCalld931b082010-08-26 03:08:43 +0000132 case SC_Extern:
133 case SC_PrivateExtern:
Lauro Ramos Venanciofea90b82008-02-16 22:30:38 +0000134 // Don't emit it now, allow it to be emitted lazily on its first use.
135 return;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000136 case SC_OpenCLWorkGroupLocal:
137 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000138 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000139
David Blaikieb219cfc2011-09-23 05:06:16 +0000140 llvm_unreachable("Unknown storage class");
Reid Spencer5f016e22007-07-11 17:01:13 +0000141}
142
Chris Lattner761acc12009-12-05 08:22:11 +0000143static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
144 const char *Separator) {
145 CodeGenModule &CGM = CGF.CGM;
John McCallf746aa62010-03-19 23:29:14 +0000146 if (CGF.getContext().getLangOptions().CPlusPlus) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000147 StringRef Name = CGM.getMangledName(&D);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000148 return Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000149 }
Eric Christophere1f54902011-08-23 22:38:00 +0000150
Chris Lattner761acc12009-12-05 08:22:11 +0000151 std::string ContextName;
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000152 if (!CGF.CurFuncDecl) {
153 // Better be in a block declared in global scope.
154 const NamedDecl *ND = cast<NamedDecl>(&D);
155 const DeclContext *DC = ND->getDeclContext();
156 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
157 MangleBuffer Name;
Peter Collingbourne14110472011-01-13 18:57:25 +0000158 CGM.getBlockMangledName(GlobalDecl(), Name, BD);
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000159 ContextName = Name.getString();
160 }
161 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000162 llvm_unreachable("Unknown context for block static var decl");
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000163 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000164 StringRef Name = CGM.getMangledName(FD);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000165 ContextName = Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000166 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattner761acc12009-12-05 08:22:11 +0000167 ContextName = CGF.CurFn->getName();
168 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000169 llvm_unreachable("Unknown context for static var decl");
Eric Christophere1f54902011-08-23 22:38:00 +0000170
Chris Lattner761acc12009-12-05 08:22:11 +0000171 return ContextName + Separator + D.getNameAsString();
172}
173
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000174llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000175CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
176 const char *Separator,
177 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000178 QualType Ty = D.getType();
Eli Friedman3c2b3172008-02-15 12:20:59 +0000179 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000180
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000181 // Use the label if the variable is renamed with the asm-label extension.
182 std::string Name;
Benjamin Kramerc3c8f222011-11-21 15:47:23 +0000183 if (D.hasAttr<AsmLabelAttr>())
184 Name = CGM.getMangledName(&D);
185 else
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000186 Name = GetStaticDeclName(*this, D, Separator);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000187
Chris Lattner2acc6e32011-07-18 04:24:23 +0000188 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Anders Carlsson41f8a132009-09-26 18:16:06 +0000189 llvm::GlobalVariable *GV =
190 new llvm::GlobalVariable(CGM.getModule(), LTy,
191 Ty.isConstant(getContext()), Linkage,
192 CGM.EmitNullConstant(D.getType()), Name, 0,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000193 D.isThreadSpecified(),
194 CGM.getContext().getTargetAddressSpace(Ty));
Ken Dyck8b752f12010-01-27 17:10:57 +0000195 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
John McCall112c9672010-11-02 21:04:24 +0000196 if (Linkage != llvm::GlobalValue::InternalLinkage)
197 GV->setVisibility(CurFn->getVisibility());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000198 return GV;
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000199}
200
John McCallb6bbcc92010-10-15 04:57:14 +0000201/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
Chris Lattner761acc12009-12-05 08:22:11 +0000202/// global variable that has already been created for it. If the initializer
203/// has a different type than GV does, this may free GV and return a different
204/// one. Otherwise it just returns GV.
205llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000206CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
207 llvm::GlobalVariable *GV) {
Chris Lattner761acc12009-12-05 08:22:11 +0000208 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this);
John McCallbf40cb52010-07-15 23:40:35 +0000209
Chris Lattner761acc12009-12-05 08:22:11 +0000210 // If constant emission failed, then this should be a C++ static
211 // initializer.
212 if (!Init) {
213 if (!getContext().getLangOptions().CPlusPlus)
214 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall5cd91b52010-09-08 01:44:27 +0000215 else if (Builder.GetInsertBlock()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000216 // Since we have a static initializer, this global variable can't
Anders Carlsson071c8102010-01-26 04:02:23 +0000217 // be constant.
218 GV->setConstant(false);
John McCall5cd91b52010-09-08 01:44:27 +0000219
John McCall3030eb82010-11-06 09:44:32 +0000220 EmitCXXGuardedInit(D, GV);
Anders Carlsson071c8102010-01-26 04:02:23 +0000221 }
Chris Lattner761acc12009-12-05 08:22:11 +0000222 return GV;
223 }
John McCallbf40cb52010-07-15 23:40:35 +0000224
Chris Lattner761acc12009-12-05 08:22:11 +0000225 // The initializer may differ in type from the global. Rewrite
226 // the global to match the initializer. (We have to do this
227 // because some types, like unions, can't be completely represented
228 // in the LLVM type system.)
John McCall9c20fa92010-09-03 18:58:50 +0000229 if (GV->getType()->getElementType() != Init->getType()) {
Chris Lattner761acc12009-12-05 08:22:11 +0000230 llvm::GlobalVariable *OldGV = GV;
Eric Christophere1f54902011-08-23 22:38:00 +0000231
Chris Lattner761acc12009-12-05 08:22:11 +0000232 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
233 OldGV->isConstant(),
234 OldGV->getLinkage(), Init, "",
John McCall112c9672010-11-02 21:04:24 +0000235 /*InsertBefore*/ OldGV,
236 D.isThreadSpecified(),
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000237 CGM.getContext().getTargetAddressSpace(D.getType()));
John McCall112c9672010-11-02 21:04:24 +0000238 GV->setVisibility(OldGV->getVisibility());
Eric Christophere1f54902011-08-23 22:38:00 +0000239
Chris Lattner761acc12009-12-05 08:22:11 +0000240 // Steal the name of the old global
241 GV->takeName(OldGV);
Eric Christophere1f54902011-08-23 22:38:00 +0000242
Chris Lattner761acc12009-12-05 08:22:11 +0000243 // Replace all uses of the old global with the new global
244 llvm::Constant *NewPtrForOldDecl =
245 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
246 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christophere1f54902011-08-23 22:38:00 +0000247
Chris Lattner761acc12009-12-05 08:22:11 +0000248 // Erase the old global, since it is no longer used.
249 OldGV->eraseFromParent();
250 }
Eric Christophere1f54902011-08-23 22:38:00 +0000251
Chris Lattner761acc12009-12-05 08:22:11 +0000252 GV->setInitializer(Init);
253 return GV;
254}
255
John McCallb6bbcc92010-10-15 04:57:14 +0000256void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000257 llvm::GlobalValue::LinkageTypes Linkage) {
Daniel Dunbara985b312009-02-25 19:45:19 +0000258 llvm::Value *&DMEntry = LocalDeclMap[&D];
259 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
Mike Stump1eb44332009-09-09 15:08:12 +0000260
John McCallb6bbcc92010-10-15 04:57:14 +0000261 llvm::GlobalVariable *GV = CreateStaticVarDecl(D, ".", Linkage);
Daniel Dunbara985b312009-02-25 19:45:19 +0000262
Daniel Dunbare5731f82009-02-25 20:08:33 +0000263 // Store into LocalDeclMap before generating initializer to handle
264 // circular references.
265 DMEntry = GV;
266
John McCallfe67f3b2010-05-04 20:45:42 +0000267 // We can't have a VLA here, but we can have a pointer to a VLA,
268 // even though that doesn't really make any sense.
Eli Friedmanc62aad82009-04-20 03:54:15 +0000269 // Make sure to evaluate VLA bounds now so that we have them for later.
270 if (D.getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000271 EmitVariablyModifiedType(D.getType());
Eric Christophere1f54902011-08-23 22:38:00 +0000272
Fariborz Jahanian09349142010-09-07 23:26:17 +0000273 // Local static block variables must be treated as globals as they may be
274 // referenced in their RHS initializer block-literal expresion.
275 CGM.setStaticLocalDeclAddress(&D, GV);
Eli Friedmanc62aad82009-04-20 03:54:15 +0000276
Chris Lattner761acc12009-12-05 08:22:11 +0000277 // If this value has an initializer, emit it.
278 if (D.getInit())
John McCallb6bbcc92010-10-15 04:57:14 +0000279 GV = AddInitializerToStaticVarDecl(D, GV);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000280
Chris Lattner0af95232010-03-10 23:59:59 +0000281 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
282
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000283 if (D.hasAttr<AnnotateAttr>())
284 CGM.AddGlobalAnnotations(&D, GV);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000285
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000286 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
Daniel Dunbar30510ab2009-02-12 23:32:54 +0000287 GV->setSection(SA->getName());
Mike Stump1eb44332009-09-09 15:08:12 +0000288
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000289 if (D.hasAttr<UsedAttr>())
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000290 CGM.AddUsedGlobal(GV);
291
Daniel Dunbare5731f82009-02-25 20:08:33 +0000292 // We may have to cast the constant because of the initializer
293 // mismatch above.
294 //
295 // FIXME: It is really dangerous to store this in the map; if anyone
296 // RAUW's the GV uses of this constant will be invalid.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000297 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
298 llvm::Type *LPtrTy =
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000299 LTy->getPointerTo(CGM.getContext().getTargetAddressSpace(D.getType()));
Owen Anderson3c4972d2009-07-29 18:54:39 +0000300 DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000301
302 // Emit global variable debug descriptor for static vars.
Anders Carlssone896d982009-02-13 08:11:52 +0000303 CGDebugInfo *DI = getDebugInfo();
Mike Stump4451bd92009-02-20 00:19:45 +0000304 if (DI) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000305 DI->setLocation(D.getLocation());
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000306 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
307 }
Anders Carlsson1a86b332007-10-17 00:52:43 +0000308}
Mike Stump1eb44332009-09-09 15:08:12 +0000309
John McCallda65ea82010-07-13 20:32:21 +0000310namespace {
John McCallbdc4d802011-07-09 01:37:26 +0000311 struct DestroyObject : EHScopeStack::Cleanup {
312 DestroyObject(llvm::Value *addr, QualType type,
John McCall2673c682011-07-11 08:38:19 +0000313 CodeGenFunction::Destroyer *destroyer,
314 bool useEHCleanupForArray)
315 : addr(addr), type(type), destroyer(*destroyer),
316 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallda65ea82010-07-13 20:32:21 +0000317
John McCallbdc4d802011-07-09 01:37:26 +0000318 llvm::Value *addr;
319 QualType type;
320 CodeGenFunction::Destroyer &destroyer;
John McCall2673c682011-07-11 08:38:19 +0000321 bool useEHCleanupForArray;
John McCallda65ea82010-07-13 20:32:21 +0000322
John McCallad346f42011-07-12 20:27:29 +0000323 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +0000324 // Don't use an EH cleanup recursively from an EH cleanup.
John McCallad346f42011-07-12 20:27:29 +0000325 bool useEHCleanupForArray =
326 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall2673c682011-07-11 08:38:19 +0000327
328 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCallda65ea82010-07-13 20:32:21 +0000329 }
330 };
331
John McCallbdc4d802011-07-09 01:37:26 +0000332 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
333 DestroyNRVOVariable(llvm::Value *addr,
334 const CXXDestructorDecl *Dtor,
335 llvm::Value *NRVOFlag)
336 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCallda65ea82010-07-13 20:32:21 +0000337
338 const CXXDestructorDecl *Dtor;
339 llvm::Value *NRVOFlag;
340 llvm::Value *Loc;
341
John McCallad346f42011-07-12 20:27:29 +0000342 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallda65ea82010-07-13 20:32:21 +0000343 // Along the exceptions path we always execute the dtor.
John McCallad346f42011-07-12 20:27:29 +0000344 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCallda65ea82010-07-13 20:32:21 +0000345
346 llvm::BasicBlock *SkipDtorBB = 0;
347 if (NRVO) {
348 // If we exited via NRVO, we skip the destructor call.
349 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
350 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
351 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
352 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
353 CGF.EmitBlock(RunDtorBB);
354 }
Eric Christophere1f54902011-08-23 22:38:00 +0000355
John McCallda65ea82010-07-13 20:32:21 +0000356 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
357 /*ForVirtualBase=*/false, Loc);
358
359 if (NRVO) CGF.EmitBlock(SkipDtorBB);
360 }
361 };
John McCallda65ea82010-07-13 20:32:21 +0000362
John McCall1f0fca52010-07-21 07:22:38 +0000363 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000364 llvm::Value *Stack;
365 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
John McCallad346f42011-07-12 20:27:29 +0000366 void Emit(CodeGenFunction &CGF, Flags flags) {
Benjamin Kramer578faa82011-09-27 21:06:10 +0000367 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalld8715092010-07-21 06:13:08 +0000368 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
369 CGF.Builder.CreateCall(F, V);
370 }
371 };
372
John McCall0c24c802011-06-24 23:21:27 +0000373 struct ExtendGCLifetime : EHScopeStack::Cleanup {
374 const VarDecl &Var;
375 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
376
John McCallad346f42011-07-12 20:27:29 +0000377 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall0c24c802011-06-24 23:21:27 +0000378 // Compute the address of the local variable, in case it's a
379 // byref or something.
380 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue,
381 SourceLocation());
382 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
383 CGF.EmitExtendGCLifetime(value);
384 }
385 };
386
John McCall1f0fca52010-07-21 07:22:38 +0000387 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000388 llvm::Constant *CleanupFn;
389 const CGFunctionInfo &FnInfo;
John McCalld8715092010-07-21 06:13:08 +0000390 const VarDecl &Var;
Eric Christophere1f54902011-08-23 22:38:00 +0000391
John McCalld8715092010-07-21 06:13:08 +0000392 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCall34695852011-02-22 06:44:22 +0000393 const VarDecl *Var)
394 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalld8715092010-07-21 06:13:08 +0000395
John McCallad346f42011-07-12 20:27:29 +0000396 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall34695852011-02-22 06:44:22 +0000397 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue,
398 SourceLocation());
399 // Compute the address of the local variable, in case it's a byref
400 // or something.
401 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
402
John McCalld8715092010-07-21 06:13:08 +0000403 // In some cases, the type of the function argument will be different from
404 // the type of the pointer. An example of this is
405 // void f(void* arg);
406 // __attribute__((cleanup(f))) void *g;
407 //
408 // To fix this we insert a bitcast here.
409 QualType ArgTy = FnInfo.arg_begin()->type;
410 llvm::Value *Arg =
411 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
412
413 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000414 Args.add(RValue::get(Arg),
415 CGF.getContext().getPointerType(Var.getType()));
John McCalld8715092010-07-21 06:13:08 +0000416 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
417 }
418 };
John McCalld8715092010-07-21 06:13:08 +0000419}
420
John McCallf85e1932011-06-15 23:02:42 +0000421/// EmitAutoVarWithLifetime - Does the setup required for an automatic
422/// variable with lifetime.
423static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
424 llvm::Value *addr,
425 Qualifiers::ObjCLifetime lifetime) {
426 switch (lifetime) {
427 case Qualifiers::OCL_None:
428 llvm_unreachable("present but none");
429
430 case Qualifiers::OCL_ExplicitNone:
431 // nothing to do
432 break;
433
434 case Qualifiers::OCL_Strong: {
John McCall9928c482011-07-12 16:41:08 +0000435 CodeGenFunction::Destroyer &destroyer =
436 (var.hasAttr<ObjCPreciseLifetimeAttr>()
437 ? CodeGenFunction::destroyARCStrongPrecise
438 : CodeGenFunction::destroyARCStrongImprecise);
439
440 CleanupKind cleanupKind = CGF.getARCCleanupKind();
441 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
442 cleanupKind & EHCleanup);
John McCallf85e1932011-06-15 23:02:42 +0000443 break;
444 }
445 case Qualifiers::OCL_Autoreleasing:
446 // nothing to do
447 break;
Eric Christophere1f54902011-08-23 22:38:00 +0000448
John McCallf85e1932011-06-15 23:02:42 +0000449 case Qualifiers::OCL_Weak:
450 // __weak objects always get EH cleanups; otherwise, exceptions
451 // could cause really nasty crashes instead of mere leaks.
John McCall9928c482011-07-12 16:41:08 +0000452 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
453 CodeGenFunction::destroyARCWeak,
454 /*useEHCleanup*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000455 break;
456 }
457}
458
459static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
460 if (const Expr *e = dyn_cast<Expr>(s)) {
461 // Skip the most common kinds of expressions that make
462 // hierarchy-walking expensive.
463 s = e = e->IgnoreParenCasts();
464
465 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
466 return (ref->getDecl() == &var);
467 }
468
469 for (Stmt::const_child_range children = s->children(); children; ++children)
Fariborz Jahanian8fefc8e2011-06-29 20:00:16 +0000470 // children might be null; as in missing decl or conditional of an if-stmt.
471 if ((*children) && isAccessedBy(var, *children))
John McCallf85e1932011-06-15 23:02:42 +0000472 return true;
473
474 return false;
475}
476
477static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
478 if (!decl) return false;
479 if (!isa<VarDecl>(decl)) return false;
480 const VarDecl *var = cast<VarDecl>(decl);
481 return isAccessedBy(*var, e);
482}
483
John McCalla07398e2011-06-16 04:16:24 +0000484static void drillIntoBlockVariable(CodeGenFunction &CGF,
485 LValue &lvalue,
486 const VarDecl *var) {
487 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
488}
489
John McCallf85e1932011-06-15 23:02:42 +0000490void CodeGenFunction::EmitScalarInit(const Expr *init,
491 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +0000492 LValue lvalue,
493 bool capturedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000494 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCallf85e1932011-06-15 23:02:42 +0000495 if (!lifetime) {
496 llvm::Value *value = EmitScalarExpr(init);
John McCalla07398e2011-06-16 04:16:24 +0000497 if (capturedByInit)
498 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall545d9962011-06-25 02:11:03 +0000499 EmitStoreThroughLValue(RValue::get(value), lvalue);
John McCallf85e1932011-06-15 23:02:42 +0000500 return;
501 }
502
503 // If we're emitting a value with lifetime, we have to do the
504 // initialization *before* we leave the cleanup scopes.
John McCall1a343eb2011-11-10 08:15:53 +0000505 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
506 enterFullExpression(ewc);
John McCallf85e1932011-06-15 23:02:42 +0000507 init = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +0000508 }
509 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCallf85e1932011-06-15 23:02:42 +0000510
511 // We have to maintain the illusion that the variable is
512 // zero-initialized. If the variable might be accessed in its
513 // initializer, zero-initialize before running the initializer, then
514 // actually perform the initialization with an assign.
515 bool accessedByInit = false;
516 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallfb720812011-07-28 07:23:35 +0000517 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCallf85e1932011-06-15 23:02:42 +0000518 if (accessedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000519 LValue tempLV = lvalue;
John McCallf85e1932011-06-15 23:02:42 +0000520 // Drill down to the __block object if necessary.
John McCallf85e1932011-06-15 23:02:42 +0000521 if (capturedByInit) {
522 // We can use a simple GEP for this because it can't have been
523 // moved yet.
John McCalla07398e2011-06-16 04:16:24 +0000524 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
525 getByRefValueLLVMField(cast<VarDecl>(D))));
John McCallf85e1932011-06-15 23:02:42 +0000526 }
527
Chris Lattner2acc6e32011-07-18 04:24:23 +0000528 llvm::PointerType *ty
John McCalla07398e2011-06-16 04:16:24 +0000529 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
John McCallf85e1932011-06-15 23:02:42 +0000530 ty = cast<llvm::PointerType>(ty->getElementType());
531
532 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000533
John McCallf85e1932011-06-15 23:02:42 +0000534 // If __weak, we want to use a barrier under certain conditions.
535 if (lifetime == Qualifiers::OCL_Weak)
John McCalla07398e2011-06-16 04:16:24 +0000536 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCallf85e1932011-06-15 23:02:42 +0000537
538 // Otherwise just do a simple store.
539 else
John McCalla07398e2011-06-16 04:16:24 +0000540 EmitStoreOfScalar(zero, tempLV);
John McCallf85e1932011-06-15 23:02:42 +0000541 }
542
543 // Emit the initializer.
544 llvm::Value *value = 0;
545
546 switch (lifetime) {
547 case Qualifiers::OCL_None:
548 llvm_unreachable("present but none");
549
550 case Qualifiers::OCL_ExplicitNone:
551 // nothing to do
552 value = EmitScalarExpr(init);
553 break;
554
555 case Qualifiers::OCL_Strong: {
556 value = EmitARCRetainScalarExpr(init);
557 break;
558 }
559
560 case Qualifiers::OCL_Weak: {
561 // No way to optimize a producing initializer into this. It's not
562 // worth optimizing for, because the value will immediately
563 // disappear in the common case.
564 value = EmitScalarExpr(init);
565
John McCalla07398e2011-06-16 04:16:24 +0000566 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000567 if (accessedByInit)
John McCalla07398e2011-06-16 04:16:24 +0000568 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000569 else
John McCalla07398e2011-06-16 04:16:24 +0000570 EmitARCInitWeak(lvalue.getAddress(), value);
John McCallf85e1932011-06-15 23:02:42 +0000571 return;
572 }
573
574 case Qualifiers::OCL_Autoreleasing:
575 value = EmitARCRetainAutoreleaseScalarExpr(init);
576 break;
577 }
578
John McCalla07398e2011-06-16 04:16:24 +0000579 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000580
581 // If the variable might have been accessed by its initializer, we
582 // might have to initialize with a barrier. We have to do this for
583 // both __weak and __strong, but __weak got filtered out above.
584 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
John McCalla07398e2011-06-16 04:16:24 +0000585 llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
586 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +0000587 EmitARCRelease(oldValue, /*precise*/ false);
588 return;
589 }
590
John McCalla07398e2011-06-16 04:16:24 +0000591 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +0000592}
Chris Lattner94cd0112010-12-01 02:05:19 +0000593
John McCall7acddac2011-06-17 06:42:21 +0000594/// EmitScalarInit - Initialize the given lvalue with the given object.
595void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
596 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
597 if (!lifetime)
John McCall545d9962011-06-25 02:11:03 +0000598 return EmitStoreThroughLValue(RValue::get(init), lvalue);
John McCall7acddac2011-06-17 06:42:21 +0000599
600 switch (lifetime) {
601 case Qualifiers::OCL_None:
602 llvm_unreachable("present but none");
603
604 case Qualifiers::OCL_ExplicitNone:
605 // nothing to do
606 break;
607
608 case Qualifiers::OCL_Strong:
609 init = EmitARCRetain(lvalue.getType(), init);
610 break;
611
612 case Qualifiers::OCL_Weak:
613 // Initialize and then skip the primitive store.
614 EmitARCInitWeak(lvalue.getAddress(), init);
615 return;
616
617 case Qualifiers::OCL_Autoreleasing:
618 init = EmitARCRetainAutorelease(lvalue.getType(), init);
619 break;
620 }
621
Eric Christophere1f54902011-08-23 22:38:00 +0000622 EmitStoreOfScalar(init, lvalue);
John McCall7acddac2011-06-17 06:42:21 +0000623}
624
Chris Lattner94cd0112010-12-01 02:05:19 +0000625/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
626/// non-zero parts of the specified initializer with equal or fewer than
627/// NumStores scalar stores.
628static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
629 unsigned &NumStores) {
Chris Lattner70b02942010-12-02 01:58:41 +0000630 // Zero and Undef never requires any extra stores.
631 if (isa<llvm::ConstantAggregateZero>(Init) ||
632 isa<llvm::ConstantPointerNull>(Init) ||
633 isa<llvm::UndefValue>(Init))
634 return true;
635 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
636 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
637 isa<llvm::ConstantExpr>(Init))
638 return Init->isNullValue() || NumStores--;
639
640 // See if we can emit each element.
641 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
642 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
643 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
644 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
645 return false;
646 }
647 return true;
648 }
Eric Christophere1f54902011-08-23 22:38:00 +0000649
Chris Lattner94cd0112010-12-01 02:05:19 +0000650 // Anything else is hard and scary.
651 return false;
652}
653
654/// emitStoresForInitAfterMemset - For inits that
655/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
656/// stores that would be required.
657static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCall34695852011-02-22 06:44:22 +0000658 bool isVolatile, CGBuilderTy &Builder) {
Chris Lattner94cd0112010-12-01 02:05:19 +0000659 // Zero doesn't require any stores.
Chris Lattner70b02942010-12-02 01:58:41 +0000660 if (isa<llvm::ConstantAggregateZero>(Init) ||
661 isa<llvm::ConstantPointerNull>(Init) ||
662 isa<llvm::UndefValue>(Init))
663 return;
Eric Christophere1f54902011-08-23 22:38:00 +0000664
Chris Lattner70b02942010-12-02 01:58:41 +0000665 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
666 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
667 isa<llvm::ConstantExpr>(Init)) {
668 if (!Init->isNullValue())
John McCall34695852011-02-22 06:44:22 +0000669 Builder.CreateStore(Init, Loc, isVolatile);
Chris Lattner70b02942010-12-02 01:58:41 +0000670 return;
671 }
Eric Christophere1f54902011-08-23 22:38:00 +0000672
Chris Lattner70b02942010-12-02 01:58:41 +0000673 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
674 "Unknown value type!");
Eric Christophere1f54902011-08-23 22:38:00 +0000675
Chris Lattner70b02942010-12-02 01:58:41 +0000676 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
677 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
678 if (Elt->isNullValue()) continue;
Eric Christophere1f54902011-08-23 22:38:00 +0000679
Chris Lattner70b02942010-12-02 01:58:41 +0000680 // Otherwise, get a pointer to the element and emit it.
681 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
John McCall34695852011-02-22 06:44:22 +0000682 isVolatile, Builder);
Chris Lattner70b02942010-12-02 01:58:41 +0000683 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000684}
685
686
687/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
688/// plus some stores to initialize a local variable instead of using a memcpy
689/// from a constant global. It is beneficial to use memset if the global is all
690/// zeros, or mostly zeros and large.
691static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
692 uint64_t GlobalSize) {
693 // If a global is all zeros, always use a memset.
694 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
695
696
697 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
698 // do it if it will require 6 or fewer scalar stores.
699 // TODO: Should budget depends on the size? Avoiding a large global warrants
700 // plopping in more stores.
701 unsigned StoreBudget = 6;
702 uint64_t SizeLimit = 32;
Eric Christophere1f54902011-08-23 22:38:00 +0000703
704 return GlobalSize > SizeLimit &&
Chris Lattner94cd0112010-12-01 02:05:19 +0000705 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
706}
707
708
Nick Lewyckya9de3fa2010-12-30 20:21:55 +0000709/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Reid Spencer5f016e22007-07-11 17:01:13 +0000710/// variable declaration with auto, register, or no storage class specifier.
Chris Lattner2621fd12008-05-08 05:58:21 +0000711/// These turn into simple stack objects, or GlobalValues depending on target.
John McCall34695852011-02-22 06:44:22 +0000712void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
713 AutoVarEmission emission = EmitAutoVarAlloca(D);
714 EmitAutoVarInit(emission);
715 EmitAutoVarCleanups(emission);
716}
Reid Spencer5f016e22007-07-11 17:01:13 +0000717
John McCall34695852011-02-22 06:44:22 +0000718/// EmitAutoVarAlloca - Emit the alloca and debug information for a
719/// local variable. Does not emit initalization or destruction.
720CodeGenFunction::AutoVarEmission
721CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
722 QualType Ty = D.getType();
723
724 AutoVarEmission emission(D);
725
726 bool isByRef = D.hasAttr<BlocksAttr>();
727 emission.IsByRef = isByRef;
728
729 CharUnits alignment = getContext().getDeclAlign(&D);
730 emission.Alignment = alignment;
731
John McCallbc8d40d2011-06-24 21:55:10 +0000732 // If the type is variably-modified, emit all the VLA sizes for it.
733 if (Ty->isVariablyModifiedType())
734 EmitVariablyModifiedType(Ty);
735
Reid Spencer5f016e22007-07-11 17:01:13 +0000736 llvm::Value *DeclPtr;
Eli Friedman3c2b3172008-02-15 12:20:59 +0000737 if (Ty->isConstantSizeType()) {
Chris Lattner2621fd12008-05-08 05:58:21 +0000738 if (!Target.useGlobalsForAutomaticVariables()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000739 bool NRVO = getContext().getLangOptions().ElideConstructors &&
John McCall34695852011-02-22 06:44:22 +0000740 D.isNRVOVariable();
741
742 // If this value is a POD array or struct with a statically
Richard Smith4bb66862011-12-02 00:30:33 +0000743 // determinable constant initializer, there are optimizations we can do.
744 //
745 // TODO: we should constant-evaluate any variable of literal type
746 // as long as it is initialized by a constant expression. Currently,
747 // isConstantInitializer produces wrong answers for structs with
748 // reference or bitfield members, and a few other cases, and checking
749 // for POD-ness protects us from some of these.
John McCall34695852011-02-22 06:44:22 +0000750 if (D.getInit() &&
Eric Christophere1f54902011-08-23 22:38:00 +0000751 (Ty->isArrayType() || Ty->isRecordType()) &&
John McCallf85e1932011-06-15 23:02:42 +0000752 (Ty.isPODType(getContext()) ||
753 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
John McCall4204f072010-08-02 21:13:48 +0000754 D.getInit()->isConstantInitializer(getContext(), false)) {
John McCall34695852011-02-22 06:44:22 +0000755
756 // If the variable's a const type, and it's neither an NRVO
Richard Smith4bb66862011-12-02 00:30:33 +0000757 // candidate nor a __block variable and has no mutable members,
758 // emit it as a global instead.
John McCall34695852011-02-22 06:44:22 +0000759 if (CGM.getCodeGenOpts().MergeAllConstants && Ty.isConstQualified() &&
Richard Smith4bb66862011-12-02 00:30:33 +0000760 !NRVO && !isByRef && Ty->isLiteralType()) {
Douglas Gregor4707b9a2011-03-06 23:28:21 +0000761 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCall34695852011-02-22 06:44:22 +0000762
763 emission.Address = 0; // signal this condition to later callbacks
764 assert(emission.wasEmittedAsGlobal());
765 return emission;
Tanya Lattner59876c22009-11-04 01:18:09 +0000766 }
John McCall34695852011-02-22 06:44:22 +0000767
768 // Otherwise, tell the initialization code that we're in this case.
769 emission.IsConstantAggregate = true;
Tanya Lattner59876c22009-11-04 01:18:09 +0000770 }
Eric Christophere1f54902011-08-23 22:38:00 +0000771
Douglas Gregord86c4772010-05-15 06:46:45 +0000772 // A normal fixed sized variable becomes an alloca in the entry block,
773 // unless it's an NRVO variable.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000774 llvm::Type *LTy = ConvertTypeForMem(Ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000775
Douglas Gregord86c4772010-05-15 06:46:45 +0000776 if (NRVO) {
777 // The named return value optimization: allocate this variable in the
778 // return slot, so that we can elide the copy when returning this
779 // variable (C++0x [class.copy]p34).
780 DeclPtr = ReturnValue;
Eric Christophere1f54902011-08-23 22:38:00 +0000781
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000782 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
783 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
784 // Create a flag that is used to indicate when the NRVO was applied
Eric Christophere1f54902011-08-23 22:38:00 +0000785 // to this variable. Set it to zero to indicate that NRVO was not
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000786 // applied.
Chris Lattner4c53dc12010-12-01 01:47:15 +0000787 llvm::Value *Zero = Builder.getFalse();
John McCall34695852011-02-22 06:44:22 +0000788 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
Nick Lewyckya03733b2011-02-16 23:59:08 +0000789 EnsureInsertPoint();
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000790 Builder.CreateStore(Zero, NRVOFlag);
Eric Christophere1f54902011-08-23 22:38:00 +0000791
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000792 // Record the NRVO flag for this variable.
793 NRVOFlags[&D] = NRVOFlag;
John McCall34695852011-02-22 06:44:22 +0000794 emission.NRVOFlag = NRVOFlag;
Douglas Gregor3d91bbc2010-05-17 15:52:46 +0000795 }
796 }
Douglas Gregord86c4772010-05-15 06:46:45 +0000797 } else {
798 if (isByRef)
799 LTy = BuildByRefType(&D);
Eric Christophere1f54902011-08-23 22:38:00 +0000800
Douglas Gregord86c4772010-05-15 06:46:45 +0000801 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
Benjamin Kramer7a715242011-11-29 14:46:55 +0000802 Alloc->setName(D.getName());
Mike Stump1eb44332009-09-09 15:08:12 +0000803
John McCall34695852011-02-22 06:44:22 +0000804 CharUnits allocaAlignment = alignment;
Douglas Gregord86c4772010-05-15 06:46:45 +0000805 if (isByRef)
Eric Christophere1f54902011-08-23 22:38:00 +0000806 allocaAlignment = std::max(allocaAlignment,
Ken Dyck06f486e2011-01-18 02:01:14 +0000807 getContext().toCharUnitsFromBits(Target.getPointerAlign(0)));
John McCall34695852011-02-22 06:44:22 +0000808 Alloc->setAlignment(allocaAlignment.getQuantity());
Douglas Gregord86c4772010-05-15 06:46:45 +0000809 DeclPtr = Alloc;
810 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000811 } else {
812 // Targets that don't support recursion emit locals as globals.
813 const char *Class =
John McCalld931b082010-08-26 03:08:43 +0000814 D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
John McCallb6bbcc92010-10-15 04:57:14 +0000815 DeclPtr = CreateStaticVarDecl(D, Class,
816 llvm::GlobalValue::InternalLinkage);
Chris Lattner2621fd12008-05-08 05:58:21 +0000817 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000818 } else {
Daniel Dunbard286f052009-07-19 06:58:07 +0000819 EnsureInsertPoint();
820
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000821 if (!DidCallStackSave) {
Anders Carlsson5d463152008-12-12 07:38:43 +0000822 // Save the stack.
John McCalld16c2cf2011-02-08 08:22:06 +0000823 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Anders Carlsson5d463152008-12-12 07:38:43 +0000825 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
826 llvm::Value *V = Builder.CreateCall(F);
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Anders Carlsson5d463152008-12-12 07:38:43 +0000828 Builder.CreateStore(V, Stack);
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000829
830 DidCallStackSave = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000831
John McCalld8715092010-07-21 06:13:08 +0000832 // Push a cleanup block and restore the stack there.
John McCall3ad32c82011-01-28 08:37:24 +0000833 // FIXME: in general circumstances, this should be an EH cleanup.
John McCall1f0fca52010-07-21 07:22:38 +0000834 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
Anders Carlsson5d463152008-12-12 07:38:43 +0000835 }
Mike Stump1eb44332009-09-09 15:08:12 +0000836
John McCallbc8d40d2011-06-24 21:55:10 +0000837 llvm::Value *elementCount;
838 QualType elementType;
839 llvm::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson5d463152008-12-12 07:38:43 +0000840
Chris Lattner2acc6e32011-07-18 04:24:23 +0000841 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson5d463152008-12-12 07:38:43 +0000842
843 // Allocate memory for the array.
John McCallbc8d40d2011-06-24 21:55:10 +0000844 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
845 vla->setAlignment(alignment.getQuantity());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000846
John McCallbc8d40d2011-06-24 21:55:10 +0000847 DeclPtr = vla;
Reid Spencer5f016e22007-07-11 17:01:13 +0000848 }
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000849
Reid Spencer5f016e22007-07-11 17:01:13 +0000850 llvm::Value *&DMEntry = LocalDeclMap[&D];
851 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
852 DMEntry = DeclPtr;
John McCall34695852011-02-22 06:44:22 +0000853 emission.Address = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000854
855 // Emit debug info for local var declaration.
Devang Patelc594abd2011-06-03 19:21:47 +0000856 if (HaveInsertPoint())
857 if (CGDebugInfo *DI = getDebugInfo()) {
858 DI->setLocation(D.getLocation());
Devang Patelc594abd2011-06-03 19:21:47 +0000859 if (Target.useGlobalsForAutomaticVariables()) {
860 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
861 } else
862 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
863 }
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000864
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000865 if (D.hasAttr<AnnotateAttr>())
866 EmitVarAnnotations(&D, emission.Address);
867
John McCall34695852011-02-22 06:44:22 +0000868 return emission;
869}
870
871/// Determines whether the given __block variable is potentially
872/// captured by the given expression.
873static bool isCapturedBy(const VarDecl &var, const Expr *e) {
874 // Skip the most common kinds of expressions that make
875 // hierarchy-walking expensive.
876 e = e->IgnoreParenCasts();
877
878 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
879 const BlockDecl *block = be->getBlockDecl();
880 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
881 e = block->capture_end(); i != e; ++i) {
882 if (i->getVariable() == &var)
883 return true;
884 }
885
886 // No need to walk into the subexpressions.
887 return false;
888 }
889
Fariborz Jahanian5033be12011-08-23 16:47:15 +0000890 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
891 const CompoundStmt *CS = SE->getSubStmt();
Eric Christopherc6fad602011-08-23 23:44:09 +0000892 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
893 BE = CS->body_end(); BI != BE; ++BI)
Fariborz Jahanian045c8422011-08-25 00:06:26 +0000894 if (Expr *E = dyn_cast<Expr>((*BI))) {
Fariborz Jahanian5033be12011-08-23 16:47:15 +0000895 if (isCapturedBy(var, E))
896 return true;
Fariborz Jahanian045c8422011-08-25 00:06:26 +0000897 }
898 else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
899 // special case declarations
900 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
901 I != E; ++I) {
902 if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
903 Expr *Init = VD->getInit();
904 if (Init && isCapturedBy(var, Init))
905 return true;
906 }
907 }
908 }
909 else
910 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
911 // Later, provide code to poke into statements for capture analysis.
912 return true;
Fariborz Jahanian5033be12011-08-23 16:47:15 +0000913 return false;
914 }
Eric Christophere1f54902011-08-23 22:38:00 +0000915
John McCall34695852011-02-22 06:44:22 +0000916 for (Stmt::const_child_range children = e->children(); children; ++children)
917 if (isCapturedBy(var, cast<Expr>(*children)))
918 return true;
919
920 return false;
921}
922
Douglas Gregorbcc3e662011-07-01 21:08:19 +0000923/// \brief Determine whether the given initializer is trivial in the sense
924/// that it requires no code to be generated.
925static bool isTrivialInitializer(const Expr *Init) {
926 if (!Init)
927 return true;
Eric Christophere1f54902011-08-23 22:38:00 +0000928
Douglas Gregorbcc3e662011-07-01 21:08:19 +0000929 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
930 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
931 if (Constructor->isTrivial() &&
932 Constructor->isDefaultConstructor() &&
933 !Construct->requiresZeroInitialization())
934 return true;
Eric Christophere1f54902011-08-23 22:38:00 +0000935
Douglas Gregorbcc3e662011-07-01 21:08:19 +0000936 return false;
937}
John McCall34695852011-02-22 06:44:22 +0000938void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +0000939 assert(emission.Variable && "emission was not valid!");
940
John McCall34695852011-02-22 06:44:22 +0000941 // If this was emitted as a global constant, we're done.
942 if (emission.wasEmittedAsGlobal()) return;
943
John McCall57b3b6a2011-02-22 07:16:58 +0000944 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +0000945 QualType type = D.getType();
946
Chris Lattner19785962007-07-12 00:39:48 +0000947 // If this local has an initializer, emit it now.
Daniel Dunbard286f052009-07-19 06:58:07 +0000948 const Expr *Init = D.getInit();
949
950 // If we are at an unreachable point, we don't need to emit the initializer
951 // unless it contains a label.
952 if (!HaveInsertPoint()) {
John McCall34695852011-02-22 06:44:22 +0000953 if (!Init || !ContainsLabel(Init)) return;
954 EnsureInsertPoint();
Daniel Dunbard286f052009-07-19 06:58:07 +0000955 }
956
John McCall5af02db2011-03-31 01:59:53 +0000957 // Initialize the structure of a __block variable.
958 if (emission.IsByRef)
959 emitByrefStructureInit(emission);
Anders Carlsson69c68b72009-02-07 23:51:38 +0000960
Douglas Gregorbcc3e662011-07-01 21:08:19 +0000961 if (isTrivialInitializer(Init))
962 return;
Eric Christophere1f54902011-08-23 22:38:00 +0000963
John McCall5af02db2011-03-31 01:59:53 +0000964 CharUnits alignment = emission.Alignment;
965
John McCall34695852011-02-22 06:44:22 +0000966 // Check whether this is a byref variable that's potentially
967 // captured and moved by its own initializer. If so, we'll need to
968 // emit the initializer first, then copy into the variable.
969 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
970
971 llvm::Value *Loc =
972 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
973
John McCalla07398e2011-06-16 04:16:24 +0000974 if (!emission.IsConstantAggregate) {
Eli Friedman6da2c712011-12-03 04:14:32 +0000975 LValue lv = MakeAddrLValue(Loc, type, alignment);
John McCalla07398e2011-06-16 04:16:24 +0000976 lv.setNonGC(true);
977 return EmitExprAsInit(Init, &D, lv, capturedByInit);
978 }
John McCall60d33652011-03-08 09:11:50 +0000979
John McCall34695852011-02-22 06:44:22 +0000980 // If this is a simple aggregate initialization, we can optimize it
981 // in various ways.
John McCall60d33652011-03-08 09:11:50 +0000982 assert(!capturedByInit && "constant init contains a capturing block?");
John McCall34695852011-02-22 06:44:22 +0000983
John McCall60d33652011-03-08 09:11:50 +0000984 bool isVolatile = type.isVolatileQualified();
John McCall34695852011-02-22 06:44:22 +0000985
John McCall60d33652011-03-08 09:11:50 +0000986 llvm::Constant *constant = CGM.EmitConstantExpr(D.getInit(), type, this);
987 assert(constant != 0 && "Wasn't a simple constant init?");
John McCall34695852011-02-22 06:44:22 +0000988
John McCall60d33652011-03-08 09:11:50 +0000989 llvm::Value *SizeVal =
Eric Christophere1f54902011-08-23 22:38:00 +0000990 llvm::ConstantInt::get(IntPtrTy,
John McCall60d33652011-03-08 09:11:50 +0000991 getContext().getTypeSizeInChars(type).getQuantity());
John McCall34695852011-02-22 06:44:22 +0000992
Chris Lattner2acc6e32011-07-18 04:24:23 +0000993 llvm::Type *BP = Int8PtrTy;
John McCall60d33652011-03-08 09:11:50 +0000994 if (Loc->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +0000995 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wang3ecd7852010-04-04 03:10:52 +0000996
John McCall60d33652011-03-08 09:11:50 +0000997 // If the initializer is all or mostly zeros, codegen with memset then do
998 // a few stores afterward.
Eric Christophere1f54902011-08-23 22:38:00 +0000999 if (shouldUseMemSetPlusStoresToInitialize(constant,
John McCall60d33652011-03-08 09:11:50 +00001000 CGM.getTargetData().getTypeAllocSize(constant->getType()))) {
1001 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1002 alignment.getQuantity(), isVolatile);
1003 if (!constant->isNullValue()) {
1004 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1005 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001006 }
John McCall60d33652011-03-08 09:11:50 +00001007 } else {
Eric Christophere1f54902011-08-23 22:38:00 +00001008 // Otherwise, create a temporary global with the initializer then
John McCall60d33652011-03-08 09:11:50 +00001009 // memcpy from the global to the alloca.
1010 std::string Name = GetStaticDeclName(*this, D, ".");
1011 llvm::GlobalVariable *GV =
1012 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopher736a9c22011-08-24 00:33:55 +00001013 llvm::GlobalValue::PrivateLinkage,
John McCall60d33652011-03-08 09:11:50 +00001014 constant, Name, 0, false, 0);
1015 GV->setAlignment(alignment.getQuantity());
Eli Friedman460980d2011-05-27 22:32:55 +00001016 GV->setUnnamedAddr(true);
Eric Christophere1f54902011-08-23 22:38:00 +00001017
John McCall60d33652011-03-08 09:11:50 +00001018 llvm::Value *SrcPtr = GV;
1019 if (SrcPtr->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001020 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall60d33652011-03-08 09:11:50 +00001021
1022 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1023 isVolatile);
1024 }
1025}
1026
1027/// Emit an expression as an initializer for a variable at the given
1028/// location. The expression is not necessarily the normal
1029/// initializer for the variable, and the address is not necessarily
1030/// its normal location.
1031///
1032/// \param init the initializing expression
1033/// \param var the variable to act as if we're initializing
1034/// \param loc the address to initialize; its type is a pointer
1035/// to the LLVM mapping of the variable's type
1036/// \param alignment the alignment of the address
1037/// \param capturedByInit true if the variable is a __block variable
1038/// whose address is potentially changed by the initializer
1039void CodeGenFunction::EmitExprAsInit(const Expr *init,
John McCallf85e1932011-06-15 23:02:42 +00001040 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +00001041 LValue lvalue,
John McCall60d33652011-03-08 09:11:50 +00001042 bool capturedByInit) {
John McCallf85e1932011-06-15 23:02:42 +00001043 QualType type = D->getType();
John McCall60d33652011-03-08 09:11:50 +00001044
1045 if (type->isReferenceType()) {
John McCalla07398e2011-06-16 04:16:24 +00001046 RValue rvalue = EmitReferenceBindingToExpr(init, D);
Eric Christophere1f54902011-08-23 22:38:00 +00001047 if (capturedByInit)
John McCalla07398e2011-06-16 04:16:24 +00001048 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall545d9962011-06-25 02:11:03 +00001049 EmitStoreThroughLValue(rvalue, lvalue);
John McCall34695852011-02-22 06:44:22 +00001050 } else if (!hasAggregateLLVMType(type)) {
John McCalla07398e2011-06-16 04:16:24 +00001051 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall34695852011-02-22 06:44:22 +00001052 } else if (type->isAnyComplexType()) {
John McCall60d33652011-03-08 09:11:50 +00001053 ComplexPairTy complex = EmitComplexExpr(init);
John McCalla07398e2011-06-16 04:16:24 +00001054 if (capturedByInit)
1055 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1056 StoreComplexToAddr(complex, lvalue.getAddress(), lvalue.isVolatile());
John McCall34695852011-02-22 06:44:22 +00001057 } else {
1058 // TODO: how can we delay here if D is captured by its initializer?
John McCall7c2349b2011-08-25 20:40:09 +00001059 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1060 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001061 AggValueSlot::DoesNotNeedGCBarriers,
1062 AggValueSlot::IsNotAliased));
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001063 }
John McCall34695852011-02-22 06:44:22 +00001064}
John McCallf1549f62010-07-06 01:34:17 +00001065
John McCallbdc4d802011-07-09 01:37:26 +00001066/// Enter a destroy cleanup for the given local variable.
1067void CodeGenFunction::emitAutoVarTypeCleanup(
1068 const CodeGenFunction::AutoVarEmission &emission,
1069 QualType::DestructionKind dtorKind) {
1070 assert(dtorKind != QualType::DK_none);
1071
1072 // Note that for __block variables, we want to destroy the
1073 // original stack object, not the possibly forwarded object.
1074 llvm::Value *addr = emission.getObjectAddress(*this);
1075
1076 const VarDecl *var = emission.Variable;
1077 QualType type = var->getType();
1078
1079 CleanupKind cleanupKind = NormalAndEHCleanup;
1080 CodeGenFunction::Destroyer *destroyer = 0;
1081
1082 switch (dtorKind) {
1083 case QualType::DK_none:
1084 llvm_unreachable("no cleanup for trivially-destructible variable");
1085
1086 case QualType::DK_cxx_destructor:
1087 // If there's an NRVO flag on the emission, we need a different
1088 // cleanup.
1089 if (emission.NRVOFlag) {
1090 assert(!type->isArrayType());
1091 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1092 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1093 emission.NRVOFlag);
1094 return;
1095 }
1096 break;
1097
1098 case QualType::DK_objc_strong_lifetime:
1099 // Suppress cleanups for pseudo-strong variables.
1100 if (var->isARCPseudoStrong()) return;
Eric Christophere1f54902011-08-23 22:38:00 +00001101
John McCallbdc4d802011-07-09 01:37:26 +00001102 // Otherwise, consider whether to use an EH cleanup or not.
1103 cleanupKind = getARCCleanupKind();
1104
1105 // Use the imprecise destroyer by default.
1106 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1107 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1108 break;
1109
1110 case QualType::DK_objc_weak_lifetime:
1111 break;
1112 }
1113
1114 // If we haven't chosen a more specific destroyer, use the default.
1115 if (!destroyer) destroyer = &getDestroyer(dtorKind);
John McCall2673c682011-07-11 08:38:19 +00001116
1117 // Use an EH cleanup in array destructors iff the destructor itself
1118 // is being pushed as an EH cleanup.
1119 bool useEHCleanup = (cleanupKind & EHCleanup);
1120 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1121 useEHCleanup);
John McCallbdc4d802011-07-09 01:37:26 +00001122}
1123
John McCall34695852011-02-22 06:44:22 +00001124void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001125 assert(emission.Variable && "emission was not valid!");
1126
John McCall34695852011-02-22 06:44:22 +00001127 // If this was emitted as a global constant, we're done.
1128 if (emission.wasEmittedAsGlobal()) return;
1129
John McCall57b3b6a2011-02-22 07:16:58 +00001130 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001131
John McCallbdc4d802011-07-09 01:37:26 +00001132 // Check the type for a cleanup.
1133 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1134 emitAutoVarTypeCleanup(emission, dtorKind);
John McCallf85e1932011-06-15 23:02:42 +00001135
John McCall0c24c802011-06-24 23:21:27 +00001136 // In GC mode, honor objc_precise_lifetime.
Douglas Gregore289d812011-09-13 17:21:33 +00001137 if (getLangOptions().getGC() != LangOptions::NonGC &&
John McCall0c24c802011-06-24 23:21:27 +00001138 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1139 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1140 }
1141
John McCall34695852011-02-22 06:44:22 +00001142 // Handle the cleanup attribute.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001143 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlsson69c68b72009-02-07 23:51:38 +00001144 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001145
John McCall34695852011-02-22 06:44:22 +00001146 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001147 assert(F && "Could not find function!");
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Anders Carlssoncabec032009-04-26 00:34:20 +00001149 const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
John McCall34695852011-02-22 06:44:22 +00001150 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001151 }
Mike Stump797b6322009-03-05 01:23:13 +00001152
John McCall34695852011-02-22 06:44:22 +00001153 // If this is a block variable, call _Block_object_destroy
1154 // (on the unforwarded address).
John McCall5af02db2011-03-31 01:59:53 +00001155 if (emission.IsByRef)
1156 enterByrefCleanup(emission);
Reid Spencer5f016e22007-07-11 17:01:13 +00001157}
1158
John McCallbdc4d802011-07-09 01:37:26 +00001159CodeGenFunction::Destroyer &
1160CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
John McCall0850e8d2011-07-09 09:09:00 +00001161 // This is surprisingly compiler-dependent. GCC 4.2 can't bind
1162 // references to functions directly in returns, and using '*&foo'
1163 // confuses MSVC. Luckily, the following code pattern works in both.
1164 Destroyer *destroyer = 0;
John McCallbdc4d802011-07-09 01:37:26 +00001165 switch (kind) {
1166 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCall0850e8d2011-07-09 09:09:00 +00001167 case QualType::DK_cxx_destructor:
1168 destroyer = &destroyCXXObject;
1169 break;
1170 case QualType::DK_objc_strong_lifetime:
1171 destroyer = &destroyARCStrongPrecise;
1172 break;
1173 case QualType::DK_objc_weak_lifetime:
1174 destroyer = &destroyARCWeak;
1175 break;
John McCallbdc4d802011-07-09 01:37:26 +00001176 }
John McCall0850e8d2011-07-09 09:09:00 +00001177 return *destroyer;
John McCallbdc4d802011-07-09 01:37:26 +00001178}
1179
John McCall9928c482011-07-12 16:41:08 +00001180/// pushDestroy - Push the standard destructor for the given type.
1181void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1182 llvm::Value *addr, QualType type) {
1183 assert(dtorKind && "cannot push destructor for trivial type");
1184
1185 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1186 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1187 cleanupKind & EHCleanup);
1188}
1189
John McCallbdc4d802011-07-09 01:37:26 +00001190void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
John McCall2673c682011-07-11 08:38:19 +00001191 QualType type, Destroyer &destroyer,
1192 bool useEHCleanupForArray) {
John McCall9928c482011-07-12 16:41:08 +00001193 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1194 destroyer, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001195}
1196
John McCall2673c682011-07-11 08:38:19 +00001197/// emitDestroy - Immediately perform the destruction of the given
1198/// object.
1199///
1200/// \param addr - the address of the object; a type*
1201/// \param type - the type of the object; if an array type, all
1202/// objects are destroyed in reverse order
1203/// \param destroyer - the function to call to destroy individual
1204/// elements
1205/// \param useEHCleanupForArray - whether an EH cleanup should be
1206/// used when destroying array elements, in case one of the
1207/// destructions throws an exception
John McCallbdc4d802011-07-09 01:37:26 +00001208void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
John McCall2673c682011-07-11 08:38:19 +00001209 Destroyer &destroyer,
1210 bool useEHCleanupForArray) {
John McCallbdc4d802011-07-09 01:37:26 +00001211 const ArrayType *arrayType = getContext().getAsArrayType(type);
1212 if (!arrayType)
1213 return destroyer(*this, addr, type);
1214
1215 llvm::Value *begin = addr;
1216 llvm::Value *length = emitArrayLength(arrayType, type, begin);
John McCallfbf780a2011-07-13 08:09:46 +00001217
1218 // Normally we have to check whether the array is zero-length.
1219 bool checkZeroLength = true;
1220
1221 // But if the array length is constant, we can suppress that.
1222 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1223 // ...and if it's constant zero, we can just skip the entire thing.
1224 if (constLength->isZero()) return;
1225 checkZeroLength = false;
1226 }
1227
John McCallbdc4d802011-07-09 01:37:26 +00001228 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCallfbf780a2011-07-13 08:09:46 +00001229 emitArrayDestroy(begin, end, type, destroyer,
1230 checkZeroLength, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001231}
1232
John McCall2673c682011-07-11 08:38:19 +00001233/// emitArrayDestroy - Destroys all the elements of the given array,
1234/// beginning from last to first. The array cannot be zero-length.
1235///
1236/// \param begin - a type* denoting the first element of the array
1237/// \param end - a type* denoting one past the end of the array
1238/// \param type - the element type of the array
1239/// \param destroyer - the function to call to destroy elements
1240/// \param useEHCleanup - whether to push an EH cleanup to destroy
1241/// the remaining elements in case the destruction of a single
1242/// element throws
John McCallbdc4d802011-07-09 01:37:26 +00001243void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1244 llvm::Value *end,
1245 QualType type,
John McCall2673c682011-07-11 08:38:19 +00001246 Destroyer &destroyer,
John McCallfbf780a2011-07-13 08:09:46 +00001247 bool checkZeroLength,
John McCall2673c682011-07-11 08:38:19 +00001248 bool useEHCleanup) {
John McCallbdc4d802011-07-09 01:37:26 +00001249 assert(!type->isArrayType());
1250
1251 // The basic structure here is a do-while loop, because we don't
1252 // need to check for the zero-element case.
1253 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1254 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1255
John McCallfbf780a2011-07-13 08:09:46 +00001256 if (checkZeroLength) {
1257 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1258 "arraydestroy.isempty");
1259 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1260 }
1261
John McCallbdc4d802011-07-09 01:37:26 +00001262 // Enter the loop body, making that address the current address.
1263 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1264 EmitBlock(bodyBB);
1265 llvm::PHINode *elementPast =
1266 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1267 elementPast->addIncoming(end, entryBB);
1268
1269 // Shift the address back by one element.
1270 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1271 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1272 "arraydestroy.element");
1273
John McCall2673c682011-07-11 08:38:19 +00001274 if (useEHCleanup)
1275 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1276
John McCallbdc4d802011-07-09 01:37:26 +00001277 // Perform the actual destruction there.
1278 destroyer(*this, element, type);
1279
John McCall2673c682011-07-11 08:38:19 +00001280 if (useEHCleanup)
1281 PopCleanupBlock();
1282
John McCallbdc4d802011-07-09 01:37:26 +00001283 // Check whether we've reached the end.
1284 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1285 Builder.CreateCondBr(done, doneBB, bodyBB);
1286 elementPast->addIncoming(element, Builder.GetInsertBlock());
1287
1288 // Done.
1289 EmitBlock(doneBB);
1290}
1291
John McCall2673c682011-07-11 08:38:19 +00001292/// Perform partial array destruction as if in an EH cleanup. Unlike
1293/// emitArrayDestroy, the element type here may still be an array type.
John McCall2673c682011-07-11 08:38:19 +00001294static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1295 llvm::Value *begin, llvm::Value *end,
1296 QualType type,
1297 CodeGenFunction::Destroyer &destroyer) {
John McCall2673c682011-07-11 08:38:19 +00001298 // If the element type is itself an array, drill down.
John McCallfbf780a2011-07-13 08:09:46 +00001299 unsigned arrayDepth = 0;
John McCall2673c682011-07-11 08:38:19 +00001300 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1301 // VLAs don't require a GEP index to walk into.
1302 if (!isa<VariableArrayType>(arrayType))
John McCallfbf780a2011-07-13 08:09:46 +00001303 arrayDepth++;
John McCall2673c682011-07-11 08:38:19 +00001304 type = arrayType->getElementType();
1305 }
John McCallfbf780a2011-07-13 08:09:46 +00001306
1307 if (arrayDepth) {
1308 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1309
Chris Lattner5f9e2722011-07-23 10:55:15 +00001310 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001311 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1312 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall2673c682011-07-11 08:38:19 +00001313 }
1314
John McCallfbf780a2011-07-13 08:09:46 +00001315 // Destroy the array. We don't ever need an EH cleanup because we
1316 // assume that we're in an EH cleanup ourselves, so a throwing
1317 // destructor causes an immediate terminate.
1318 CGF.emitArrayDestroy(begin, end, type, destroyer,
1319 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall2673c682011-07-11 08:38:19 +00001320}
1321
John McCallbdc4d802011-07-09 01:37:26 +00001322namespace {
John McCall2673c682011-07-11 08:38:19 +00001323 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1324 /// array destroy where the end pointer is regularly determined and
1325 /// does not need to be loaded from a local.
1326 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1327 llvm::Value *ArrayBegin;
1328 llvm::Value *ArrayEnd;
1329 QualType ElementType;
1330 CodeGenFunction::Destroyer &Destroyer;
1331 public:
1332 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1333 QualType elementType,
1334 CodeGenFunction::Destroyer *destroyer)
1335 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1336 ElementType(elementType), Destroyer(*destroyer) {}
1337
John McCallad346f42011-07-12 20:27:29 +00001338 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +00001339 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1340 ElementType, Destroyer);
1341 }
1342 };
1343
1344 /// IrregularPartialArrayDestroy - a cleanup which performs a
1345 /// partial array destroy where the end pointer is irregularly
1346 /// determined and must be loaded from a local.
1347 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
John McCallbdc4d802011-07-09 01:37:26 +00001348 llvm::Value *ArrayBegin;
1349 llvm::Value *ArrayEndPointer;
1350 QualType ElementType;
1351 CodeGenFunction::Destroyer &Destroyer;
1352 public:
John McCall2673c682011-07-11 08:38:19 +00001353 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1354 llvm::Value *arrayEndPointer,
1355 QualType elementType,
1356 CodeGenFunction::Destroyer *destroyer)
John McCallbdc4d802011-07-09 01:37:26 +00001357 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1358 ElementType(elementType), Destroyer(*destroyer) {}
1359
John McCallad346f42011-07-12 20:27:29 +00001360 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallbdc4d802011-07-09 01:37:26 +00001361 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall2673c682011-07-11 08:38:19 +00001362 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1363 ElementType, Destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001364 }
1365 };
1366}
1367
John McCall2673c682011-07-11 08:38:19 +00001368/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCallbdc4d802011-07-09 01:37:26 +00001369/// already-constructed elements of the given array. The cleanup
John McCall2673c682011-07-11 08:38:19 +00001370/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001371///
John McCallbdc4d802011-07-09 01:37:26 +00001372/// \param elementType - the immediate element type of the array;
1373/// possibly still an array type
1374/// \param array - a value of type elementType*
1375/// \param destructionKind - the kind of destruction required
1376/// \param initializedElementCount - a value of type size_t* holding
1377/// the number of successfully-constructed elements
John McCall9928c482011-07-12 16:41:08 +00001378void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall2673c682011-07-11 08:38:19 +00001379 llvm::Value *arrayEndPointer,
1380 QualType elementType,
1381 Destroyer &destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001382 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1383 arrayBegin, arrayEndPointer,
John McCall2673c682011-07-11 08:38:19 +00001384 elementType, &destroyer);
1385}
1386
1387/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1388/// already-constructed elements of the given array. The cleanup
1389/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001390///
John McCall2673c682011-07-11 08:38:19 +00001391/// \param elementType - the immediate element type of the array;
1392/// possibly still an array type
1393/// \param array - a value of type elementType*
1394/// \param destructionKind - the kind of destruction required
1395/// \param initializedElementCount - a value of type size_t* holding
1396/// the number of successfully-constructed elements
1397void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1398 llvm::Value *arrayEnd,
1399 QualType elementType,
1400 Destroyer &destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001401 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall2673c682011-07-11 08:38:19 +00001402 arrayBegin, arrayEnd,
1403 elementType, &destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001404}
1405
John McCallf85e1932011-06-15 23:02:42 +00001406namespace {
1407 /// A cleanup to perform a release of an object at the end of a
1408 /// function. This is used to balance out the incoming +1 of a
1409 /// ns_consumed argument when we can't reasonably do that just by
1410 /// not doing the initial retain for a __block argument.
1411 struct ConsumeARCParameter : EHScopeStack::Cleanup {
1412 ConsumeARCParameter(llvm::Value *param) : Param(param) {}
1413
1414 llvm::Value *Param;
1415
John McCallad346f42011-07-12 20:27:29 +00001416 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001417 CGF.EmitARCRelease(Param, /*precise*/ false);
1418 }
1419 };
1420}
1421
Mike Stump1eb44332009-09-09 15:08:12 +00001422/// Emit an alloca (or GlobalValue depending on target)
Chris Lattner2621fd12008-05-08 05:58:21 +00001423/// for the specified parameter and set up LocalDeclMap.
Devang Patel093ac462011-03-03 20:13:15 +00001424void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1425 unsigned ArgNo) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001426 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00001427 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001428 "Invalid argument to EmitParmDecl");
John McCall8178df32011-02-22 22:38:33 +00001429
1430 Arg->setName(D.getName());
1431
1432 // Use better IR generation for certain implicit parameters.
1433 if (isa<ImplicitParamDecl>(D)) {
1434 // The only implicit argument a block has is its literal.
1435 if (BlockInfo) {
1436 LocalDeclMap[&D] = Arg;
1437
1438 if (CGDebugInfo *DI = getDebugInfo()) {
1439 DI->setLocation(D.getLocation());
1440 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, Builder);
1441 }
1442
1443 return;
1444 }
1445 }
1446
Chris Lattner8bcfc5b2008-04-06 23:10:54 +00001447 QualType Ty = D.getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 llvm::Value *DeclPtr;
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001450 // If this is an aggregate or variable sized value, reuse the input pointer.
1451 if (!Ty->isConstantSizeType() ||
1452 CodeGenFunction::hasAggregateLLVMType(Ty)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001453 DeclPtr = Arg;
Reid Spencer5f016e22007-07-11 17:01:13 +00001454 } else {
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001455 // Otherwise, create a temporary to hold the value.
Eli Friedmanddfb8d12011-11-03 20:31:28 +00001456 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1457 D.getName() + ".addr");
1458 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1459 DeclPtr = Alloc;
Mike Stump1eb44332009-09-09 15:08:12 +00001460
John McCallf85e1932011-06-15 23:02:42 +00001461 bool doStore = true;
1462
1463 Qualifiers qs = Ty.getQualifiers();
1464
1465 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1466 // We honor __attribute__((ns_consumed)) for types with lifetime.
1467 // For __strong, it's handled by just skipping the initial retain;
1468 // otherwise we have to balance out the initial +1 with an extra
1469 // cleanup to do the release at the end of the function.
1470 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1471
1472 // 'self' is always formally __strong, but if this is not an
1473 // init method then we don't want to retain it.
John McCall7acddac2011-06-17 06:42:21 +00001474 if (D.isARCPseudoStrong()) {
John McCallf85e1932011-06-15 23:02:42 +00001475 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1476 assert(&D == method->getSelfDecl());
John McCall7acddac2011-06-17 06:42:21 +00001477 assert(lt == Qualifiers::OCL_Strong);
1478 assert(qs.hasConst());
John McCallf85e1932011-06-15 23:02:42 +00001479 assert(method->getMethodFamily() != OMF_init);
John McCall175d6592011-06-15 23:40:09 +00001480 (void) method;
John McCallf85e1932011-06-15 23:02:42 +00001481 lt = Qualifiers::OCL_ExplicitNone;
1482 }
1483
1484 if (lt == Qualifiers::OCL_Strong) {
1485 if (!isConsumed)
1486 // Don't use objc_retainBlock for block pointers, because we
1487 // don't want to Block_copy something just because we got it
1488 // as a parameter.
1489 Arg = EmitARCRetainNonBlock(Arg);
1490 } else {
1491 // Push the cleanup for a consumed parameter.
1492 if (isConsumed)
1493 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg);
1494
1495 if (lt == Qualifiers::OCL_Weak) {
1496 EmitARCInitWeak(DeclPtr, Arg);
1497 doStore = false; // The weak init is a store, no need to do two
1498 }
1499 }
1500
1501 // Enter the cleanup scope.
1502 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1503 }
1504
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001505 // Store the initial value into the alloca.
John McCall545d9962011-06-25 02:11:03 +00001506 if (doStore) {
1507 LValue lv = MakeAddrLValue(DeclPtr, Ty,
Eli Friedman6da2c712011-12-03 04:14:32 +00001508 getContext().getDeclAlign(&D));
John McCall545d9962011-06-25 02:11:03 +00001509 EmitStoreOfScalar(Arg, lv);
1510 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001511 }
1512
1513 llvm::Value *&DMEntry = LocalDeclMap[&D];
1514 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1515 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +00001516
1517 // Emit debug info for param declaration.
Devang Patel98703d32011-06-15 17:57:08 +00001518 if (CGDebugInfo *DI = getDebugInfo())
Devang Patel093ac462011-03-03 20:13:15 +00001519 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001520
1521 if (D.hasAttr<AnnotateAttr>())
1522 EmitVarAnnotations(&D, DeclPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001523}