blob: 62cd7442ec3c7418ee0354f13b489b1cd896917c [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
14#include "CodeGenFunction.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
Peter Collingbourne8c25fc52011-09-19 21:14:35 +000016#include "CGOpenCLRuntime.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "CodeGenModule.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"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/GlobalVariable.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/Type.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using 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:
John McCall76da55d2013-04-16 07:28:30 +000048 case Decl::MSProperty:
Francois Pichet41f5e662010-11-21 06:49:41 +000049 case Decl::IndirectField:
Douglas Gregor08688ac2010-04-23 02:02:43 +000050 case Decl::ObjCIvar:
Eric Christophere1f54902011-08-23 22:38:00 +000051 case Decl::ObjCAtDefsField:
Chris Lattneraa9fc462007-10-08 21:37:32 +000052 case Decl::ParmVar:
Douglas Gregor08688ac2010-04-23 02:02:43 +000053 case Decl::ImplicitParam:
54 case Decl::ClassTemplate:
55 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +000056 case Decl::TypeAliasTemplate:
Douglas Gregor08688ac2010-04-23 02:02:43 +000057 case Decl::TemplateTemplateParm:
58 case Decl::ObjCMethod:
59 case Decl::ObjCCategory:
60 case Decl::ObjCProtocol:
61 case Decl::ObjCInterface:
62 case Decl::ObjCCategoryImpl:
63 case Decl::ObjCImplementation:
64 case Decl::ObjCProperty:
65 case Decl::ObjCCompatibleAlias:
Abramo Bagnara6206d532010-06-05 05:09:32 +000066 case Decl::AccessSpec:
Douglas Gregor08688ac2010-04-23 02:02:43 +000067 case Decl::LinkageSpec:
68 case Decl::ObjCPropertyImpl:
Douglas Gregor08688ac2010-04-23 02:02:43 +000069 case Decl::FileScopeAsm:
70 case Decl::Friend:
71 case Decl::FriendTemplate:
72 case Decl::Block:
Tareq A. Siraj6afcf882013-04-16 19:37:38 +000073 case Decl::Captured:
Francois Pichetaf0f4d02011-08-14 03:52:19 +000074 case Decl::ClassScopeFunctionSpecialization:
David Blaikie9faebd22013-05-20 04:58:53 +000075 case Decl::UsingShadow:
David Blaikieb219cfc2011-09-23 05:06:16 +000076 llvm_unreachable("Declaration should not be in declstmts!");
Reid Spencer5f016e22007-07-11 17:01:13 +000077 case Decl::Function: // void X();
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000078 case Decl::Record: // struct/union/class X;
Reid Spencer5f016e22007-07-11 17:01:13 +000079 case Decl::Enum: // enum X;
Mike Stump1eb44332009-09-09 15:08:12 +000080 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000081 case Decl::CXXRecord: // struct/union/class X; [C++]
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;
Douglas Gregor15de72c2011-12-02 23:23:56 +000084 case Decl::Import:
Alexey Bataevc6400582013-03-22 06:34:35 +000085 case Decl::OMPThreadPrivate:
Michael Han684aa732013-02-22 17:15:32 +000086 case Decl::Empty:
Reid Spencer5f016e22007-07-11 17:01:13 +000087 // None of these decls require codegen support.
88 return;
David Blaikiec8c24272013-02-02 00:39:32 +000089
David Blaikiefc46ebc2013-05-20 22:50:41 +000090 case Decl::NamespaceAlias:
91 if (CGDebugInfo *DI = getDebugInfo())
92 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
93 return;
David Blaikie9faebd22013-05-20 04:58:53 +000094 case Decl::Using: // using X; [C++]
95 if (CGDebugInfo *DI = getDebugInfo())
96 DI->EmitUsingDecl(cast<UsingDecl>(D));
97 return;
David Blaikie957dac52013-04-22 06:13:21 +000098 case Decl::UsingDirective: // using namespace X; [C++]
99 if (CGDebugInfo *DI = getDebugInfo())
100 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
101 return;
Daniel Dunbar662174c82008-08-29 17:28:43 +0000102 case Decl::Var: {
103 const VarDecl &VD = cast<VarDecl>(D);
John McCallb6bbcc92010-10-15 04:57:14 +0000104 assert(VD.isLocalVarDecl() &&
Daniel Dunbar662174c82008-08-29 17:28:43 +0000105 "Should not see file-scope variables inside a function!");
John McCallb6bbcc92010-10-15 04:57:14 +0000106 return EmitVarDecl(VD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000107 }
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Richard Smith162e1c12011-04-15 14:24:37 +0000109 case Decl::Typedef: // typedef int X;
110 case Decl::TypeAlias: { // using X = int; [C++0x]
111 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000112 QualType Ty = TD.getUnderlyingType();
Mike Stump1eb44332009-09-09 15:08:12 +0000113
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000114 if (Ty->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000115 EmitVariablyModifiedType(Ty);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000116 }
Daniel Dunbar662174c82008-08-29 17:28:43 +0000117 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000118}
119
John McCallb6bbcc92010-10-15 04:57:14 +0000120/// EmitVarDecl - This method handles emission of any variable declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000121/// inside a function, including static vars etc.
John McCallb6bbcc92010-10-15 04:57:14 +0000122void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000123 if (D.isStaticLocal()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000124 llvm::GlobalValue::LinkageTypes Linkage =
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000125 llvm::GlobalValue::InternalLinkage;
126
John McCall8b242332010-05-25 04:30:21 +0000127 // If the function definition has some sort of weak linkage, its
128 // static variables should also be weak so that they get properly
Rafael Espindola9610d772013-06-17 20:04:51 +0000129 // uniqued.
130 if (D.isExternallyVisible()) {
Eli Friedman678eca42013-06-13 21:50:44 +0000131 const Decl *D = CurCodeDecl;
132 while (true) {
Eli Friedman07369dd2013-07-01 20:22:57 +0000133 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
134 if (!BD->getBlockManglingNumber())
135 break;
136
137 // This block has the linkage/visibility of its contained variables
138 // determined by its owner.
139 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
140 if (Decl *ContextDecl = BD->getBlockManglingContextDecl()) {
141 if (isa<ParmVarDecl>(ContextDecl)) {
142 DC = ContextDecl->getDeclContext()->getRedeclContext();
143 } else {
144 D = ContextDecl;
145 continue;
146 }
147 }
148
149 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC)) {
150 D = ND;
151 continue;
152 }
153
Eli Friedman678eca42013-06-13 21:50:44 +0000154 break;
155 } else if (isa<CapturedDecl>(D)) {
156 D = cast<Decl>(cast<CapturedDecl>(D)->getParent());
157 } else {
158 break;
159 }
160 }
Eli Friedman07369dd2013-07-01 20:22:57 +0000161 llvm::GlobalValue::LinkageTypes ParentLinkage;
Rafael Espindola9610d772013-06-17 20:04:51 +0000162 if (isa<FunctionDecl>(D)) {
Eli Friedman07369dd2013-07-01 20:22:57 +0000163 ParentLinkage = CGM.getFunctionLinkage(cast<FunctionDecl>(D));
164 } else if (isa<VarDecl>(D)) {
165 // FIXME: I'm pretty sure this is wrong...
166 ParentLinkage = CGM.GetLLVMLinkageVarDefinition(cast<VarDecl>(D),
167 /*constant*/false);
168 } else {
169 assert(isa<FieldDecl>(D) && "Expect function, variable, or field");
170 // FIXME: Is this right?
171 ParentLinkage = llvm::GlobalValue::LinkOnceODRLinkage;
Eli Friedman678eca42013-06-13 21:50:44 +0000172 }
Eli Friedman07369dd2013-07-01 20:22:57 +0000173
174 if (llvm::GlobalValue::isWeakForLinker(ParentLinkage))
175 Linkage = ParentLinkage;
176
177 // FIXME: We need to force the emission/use of a guard variable for
178 // some variables even if we can constant-evaluate them because
179 // we can't guarantee every translation unit will constant-evaluate them.
180 // Also, we might need to fix up the linkage.
Eli Friedman678eca42013-06-13 21:50:44 +0000181 }
Eric Christophere1f54902011-08-23 22:38:00 +0000182
John McCallb6bbcc92010-10-15 04:57:14 +0000183 return EmitStaticVarDecl(D, Linkage);
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000184 }
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000185
186 if (D.hasExternalStorage())
Lauro Ramos Venanciofea90b82008-02-16 22:30:38 +0000187 // Don't emit it now, allow it to be emitted lazily on its first use.
188 return;
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000189
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000190 if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
191 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
192
193 assert(D.hasLocalStorage());
194 return EmitAutoVarDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000195}
196
Chris Lattner761acc12009-12-05 08:22:11 +0000197static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
198 const char *Separator) {
199 CodeGenModule &CGM = CGF.CGM;
Richard Smith7edf9e32012-11-01 22:30:59 +0000200 if (CGF.getLangOpts().CPlusPlus) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000201 StringRef Name = CGM.getMangledName(&D);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000202 return Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000203 }
Eric Christophere1f54902011-08-23 22:38:00 +0000204
Chris Lattner761acc12009-12-05 08:22:11 +0000205 std::string ContextName;
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000206 if (!CGF.CurFuncDecl) {
207 // Better be in a block declared in global scope.
208 const NamedDecl *ND = cast<NamedDecl>(&D);
209 const DeclContext *DC = ND->getDeclContext();
210 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
211 MangleBuffer Name;
Peter Collingbourne14110472011-01-13 18:57:25 +0000212 CGM.getBlockMangledName(GlobalDecl(), Name, BD);
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000213 ContextName = Name.getString();
214 }
215 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000216 llvm_unreachable("Unknown context for block static var decl");
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000217 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000218 StringRef Name = CGM.getMangledName(FD);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000219 ContextName = Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000220 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattner761acc12009-12-05 08:22:11 +0000221 ContextName = CGF.CurFn->getName();
222 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000223 llvm_unreachable("Unknown context for static var decl");
Eric Christophere1f54902011-08-23 22:38:00 +0000224
Chris Lattner761acc12009-12-05 08:22:11 +0000225 return ContextName + Separator + D.getNameAsString();
226}
227
Chandler Carruth0f30a122012-03-30 19:44:53 +0000228llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000229CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
230 const char *Separator,
231 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000232 QualType Ty = D.getType();
Eli Friedman3c2b3172008-02-15 12:20:59 +0000233 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000234
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000235 // Use the label if the variable is renamed with the asm-label extension.
236 std::string Name;
Benjamin Kramerc3c8f222011-11-21 15:47:23 +0000237 if (D.hasAttr<AsmLabelAttr>())
238 Name = CGM.getMangledName(&D);
239 else
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000240 Name = GetStaticDeclName(*this, D, Separator);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000241
Chris Lattner2acc6e32011-07-18 04:24:23 +0000242 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Peter Collingbourne1aba7782012-08-28 20:37:10 +0000243 unsigned AddrSpace =
244 CGM.GetGlobalVarAddressSpace(&D, CGM.getContext().getTargetAddressSpace(Ty));
Anders Carlsson41f8a132009-09-26 18:16:06 +0000245 llvm::GlobalVariable *GV =
246 new llvm::GlobalVariable(CGM.getModule(), LTy,
247 Ty.isConstant(getContext()), Linkage,
Hans Wennborgde981f32012-06-28 08:01:44 +0000248 CGM.EmitNullConstant(D.getType()), Name, 0,
249 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourne1aba7782012-08-28 20:37:10 +0000250 AddrSpace);
Ken Dyck8b752f12010-01-27 17:10:57 +0000251 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Eli Friedman93cc5152013-06-17 21:51:45 +0000252 CGM.setGlobalVisibility(GV, &D);
Hans Wennborgde981f32012-06-28 08:01:44 +0000253
Richard Smith38afbc72013-04-13 02:43:54 +0000254 if (D.getTLSKind())
Hans Wennborgde981f32012-06-28 08:01:44 +0000255 CGM.setTLSMode(GV, D);
256
Anders Carlsson41f8a132009-09-26 18:16:06 +0000257 return GV;
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000258}
259
Richard Smith7ca48502012-02-13 22:16:19 +0000260/// hasNontrivialDestruction - Determine whether a type's destruction is
261/// non-trivial. If so, and the variable uses static initialization, we must
262/// register its destructor to run on exit.
263static bool hasNontrivialDestruction(QualType T) {
264 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
265 return RD && !RD->hasTrivialDestructor();
266}
267
Chandler Carruth0f30a122012-03-30 19:44:53 +0000268/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
269/// global variable that has already been created for it. If the initializer
270/// has a different type than GV does, this may free GV and return a different
271/// one. Otherwise it just returns GV.
272llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000273CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000274 llvm::GlobalVariable *GV) {
275 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCallbf40cb52010-07-15 23:40:35 +0000276
Chris Lattner761acc12009-12-05 08:22:11 +0000277 // If constant emission failed, then this should be a C++ static
278 // initializer.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000279 if (!Init) {
Richard Smith7edf9e32012-11-01 22:30:59 +0000280 if (!getLangOpts().CPlusPlus)
Chris Lattner761acc12009-12-05 08:22:11 +0000281 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall5cd91b52010-09-08 01:44:27 +0000282 else if (Builder.GetInsertBlock()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000283 // Since we have a static initializer, this global variable can't
Anders Carlsson071c8102010-01-26 04:02:23 +0000284 // be constant.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000285 GV->setConstant(false);
John McCall5cd91b52010-09-08 01:44:27 +0000286
Chandler Carruth0f30a122012-03-30 19:44:53 +0000287 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson071c8102010-01-26 04:02:23 +0000288 }
Chandler Carruth0f30a122012-03-30 19:44:53 +0000289 return GV;
Chris Lattner761acc12009-12-05 08:22:11 +0000290 }
John McCallbf40cb52010-07-15 23:40:35 +0000291
Chris Lattner761acc12009-12-05 08:22:11 +0000292 // The initializer may differ in type from the global. Rewrite
293 // the global to match the initializer. (We have to do this
294 // because some types, like unions, can't be completely represented
295 // in the LLVM type system.)
Chandler Carruth0f30a122012-03-30 19:44:53 +0000296 if (GV->getType()->getElementType() != Init->getType()) {
297 llvm::GlobalVariable *OldGV = GV;
298
299 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
300 OldGV->isConstant(),
301 OldGV->getLinkage(), Init, "",
302 /*InsertBefore*/ OldGV,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +0000303 OldGV->getThreadLocalMode(),
Chandler Carruth0f30a122012-03-30 19:44:53 +0000304 CGM.getContext().getTargetAddressSpace(D.getType()));
305 GV->setVisibility(OldGV->getVisibility());
Eric Christophere1f54902011-08-23 22:38:00 +0000306
Chris Lattner761acc12009-12-05 08:22:11 +0000307 // Steal the name of the old global
Chandler Carruth0f30a122012-03-30 19:44:53 +0000308 GV->takeName(OldGV);
Eric Christophere1f54902011-08-23 22:38:00 +0000309
Chris Lattner761acc12009-12-05 08:22:11 +0000310 // Replace all uses of the old global with the new global
Chandler Carruth0f30a122012-03-30 19:44:53 +0000311 llvm::Constant *NewPtrForOldDecl =
312 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
313 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christophere1f54902011-08-23 22:38:00 +0000314
Chris Lattner761acc12009-12-05 08:22:11 +0000315 // Erase the old global, since it is no longer used.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000316 OldGV->eraseFromParent();
Chris Lattner761acc12009-12-05 08:22:11 +0000317 }
Eric Christophere1f54902011-08-23 22:38:00 +0000318
Chandler Carruth0f30a122012-03-30 19:44:53 +0000319 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
320 GV->setInitializer(Init);
Richard Smith7ca48502012-02-13 22:16:19 +0000321
322 if (hasNontrivialDestruction(D.getType())) {
323 // We have a constant initializer, but a nontrivial destructor. We still
324 // need to perform a guarded "initialization" in order to register the
Richard Smitha9b21d22012-02-17 06:48:11 +0000325 // destructor.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000326 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith7ca48502012-02-13 22:16:19 +0000327 }
328
Chandler Carruth0f30a122012-03-30 19:44:53 +0000329 return GV;
Chris Lattner761acc12009-12-05 08:22:11 +0000330}
331
John McCallb6bbcc92010-10-15 04:57:14 +0000332void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000333 llvm::GlobalValue::LinkageTypes Linkage) {
Chandler Carruth0f30a122012-03-30 19:44:53 +0000334 llvm::Value *&DMEntry = LocalDeclMap[&D];
335 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
Mike Stump1eb44332009-09-09 15:08:12 +0000336
John McCall355bba72012-03-30 21:00:39 +0000337 // Check to see if we already have a global variable for this
338 // declaration. This can happen when double-emitting function
339 // bodies, e.g. with complete and base constructors.
340 llvm::Constant *addr =
341 CGM.getStaticLocalDeclAddress(&D);
342
343 llvm::GlobalVariable *var;
344 if (addr) {
345 var = cast<llvm::GlobalVariable>(addr->stripPointerCasts());
346 } else {
347 addr = var = CreateStaticVarDecl(D, ".", Linkage);
348 }
Daniel Dunbara985b312009-02-25 19:45:19 +0000349
Daniel Dunbare5731f82009-02-25 20:08:33 +0000350 // Store into LocalDeclMap before generating initializer to handle
351 // circular references.
John McCall355bba72012-03-30 21:00:39 +0000352 DMEntry = addr;
353 CGM.setStaticLocalDeclAddress(&D, addr);
Daniel Dunbare5731f82009-02-25 20:08:33 +0000354
John McCallfe67f3b2010-05-04 20:45:42 +0000355 // We can't have a VLA here, but we can have a pointer to a VLA,
356 // even though that doesn't really make any sense.
Eli Friedmanc62aad82009-04-20 03:54:15 +0000357 // Make sure to evaluate VLA bounds now so that we have them for later.
358 if (D.getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000359 EmitVariablyModifiedType(D.getType());
Eric Christophere1f54902011-08-23 22:38:00 +0000360
John McCall355bba72012-03-30 21:00:39 +0000361 // Save the type in case adding the initializer forces a type change.
362 llvm::Type *expectedType = addr->getType();
Eli Friedmanc62aad82009-04-20 03:54:15 +0000363
Chris Lattner761acc12009-12-05 08:22:11 +0000364 // If this value has an initializer, emit it.
365 if (D.getInit())
John McCall355bba72012-03-30 21:00:39 +0000366 var = AddInitializerToStaticVarDecl(D, var);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000367
John McCall355bba72012-03-30 21:00:39 +0000368 var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Chris Lattner0af95232010-03-10 23:59:59 +0000369
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000370 if (D.hasAttr<AnnotateAttr>())
John McCall355bba72012-03-30 21:00:39 +0000371 CGM.AddGlobalAnnotations(&D, var);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000372
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000373 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCall355bba72012-03-30 21:00:39 +0000374 var->setSection(SA->getName());
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000376 if (D.hasAttr<UsedAttr>())
John McCall355bba72012-03-30 21:00:39 +0000377 CGM.AddUsedGlobal(var);
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000378
Chandler Carruth0f30a122012-03-30 19:44:53 +0000379 // We may have to cast the constant because of the initializer
380 // mismatch above.
381 //
382 // FIXME: It is really dangerous to store this in the map; if anyone
383 // RAUW's the GV uses of this constant will be invalid.
John McCall355bba72012-03-30 21:00:39 +0000384 llvm::Constant *castedAddr = llvm::ConstantExpr::getBitCast(var, expectedType);
385 DMEntry = castedAddr;
386 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000387
388 // Emit global variable debug descriptor for static vars.
Anders Carlssone896d982009-02-13 08:11:52 +0000389 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000390 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +0000391 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000392 DI->setLocation(D.getLocation());
John McCall355bba72012-03-30 21:00:39 +0000393 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000394 }
Anders Carlsson1a86b332007-10-17 00:52:43 +0000395}
Mike Stump1eb44332009-09-09 15:08:12 +0000396
John McCallda65ea82010-07-13 20:32:21 +0000397namespace {
John McCallbdc4d802011-07-09 01:37:26 +0000398 struct DestroyObject : EHScopeStack::Cleanup {
399 DestroyObject(llvm::Value *addr, QualType type,
John McCall2673c682011-07-11 08:38:19 +0000400 CodeGenFunction::Destroyer *destroyer,
401 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000402 : addr(addr), type(type), destroyer(destroyer),
John McCall2673c682011-07-11 08:38:19 +0000403 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallda65ea82010-07-13 20:32:21 +0000404
John McCallbdc4d802011-07-09 01:37:26 +0000405 llvm::Value *addr;
406 QualType type;
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000407 CodeGenFunction::Destroyer *destroyer;
John McCall2673c682011-07-11 08:38:19 +0000408 bool useEHCleanupForArray;
John McCallda65ea82010-07-13 20:32:21 +0000409
John McCallad346f42011-07-12 20:27:29 +0000410 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +0000411 // Don't use an EH cleanup recursively from an EH cleanup.
John McCallad346f42011-07-12 20:27:29 +0000412 bool useEHCleanupForArray =
413 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall2673c682011-07-11 08:38:19 +0000414
415 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCallda65ea82010-07-13 20:32:21 +0000416 }
417 };
418
John McCallbdc4d802011-07-09 01:37:26 +0000419 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
420 DestroyNRVOVariable(llvm::Value *addr,
421 const CXXDestructorDecl *Dtor,
422 llvm::Value *NRVOFlag)
423 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCallda65ea82010-07-13 20:32:21 +0000424
425 const CXXDestructorDecl *Dtor;
426 llvm::Value *NRVOFlag;
427 llvm::Value *Loc;
428
John McCallad346f42011-07-12 20:27:29 +0000429 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallda65ea82010-07-13 20:32:21 +0000430 // Along the exceptions path we always execute the dtor.
John McCallad346f42011-07-12 20:27:29 +0000431 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCallda65ea82010-07-13 20:32:21 +0000432
433 llvm::BasicBlock *SkipDtorBB = 0;
434 if (NRVO) {
435 // If we exited via NRVO, we skip the destructor call.
436 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
437 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
438 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
439 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
440 CGF.EmitBlock(RunDtorBB);
441 }
Eric Christophere1f54902011-08-23 22:38:00 +0000442
John McCallda65ea82010-07-13 20:32:21 +0000443 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +0000444 /*ForVirtualBase=*/false,
445 /*Delegating=*/false,
446 Loc);
John McCallda65ea82010-07-13 20:32:21 +0000447
448 if (NRVO) CGF.EmitBlock(SkipDtorBB);
449 }
450 };
John McCallda65ea82010-07-13 20:32:21 +0000451
John McCall1f0fca52010-07-21 07:22:38 +0000452 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000453 llvm::Value *Stack;
454 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
John McCallad346f42011-07-12 20:27:29 +0000455 void Emit(CodeGenFunction &CGF, Flags flags) {
Benjamin Kramer578faa82011-09-27 21:06:10 +0000456 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalld8715092010-07-21 06:13:08 +0000457 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
458 CGF.Builder.CreateCall(F, V);
459 }
460 };
461
John McCall0c24c802011-06-24 23:21:27 +0000462 struct ExtendGCLifetime : EHScopeStack::Cleanup {
463 const VarDecl &Var;
464 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
465
John McCallad346f42011-07-12 20:27:29 +0000466 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall0c24c802011-06-24 23:21:27 +0000467 // Compute the address of the local variable, in case it's a
468 // byref or something.
John McCallf4b88a42012-03-10 09:33:50 +0000469 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
470 Var.getType(), VK_LValue, SourceLocation());
John McCall0c24c802011-06-24 23:21:27 +0000471 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
472 CGF.EmitExtendGCLifetime(value);
473 }
474 };
475
John McCall1f0fca52010-07-21 07:22:38 +0000476 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000477 llvm::Constant *CleanupFn;
478 const CGFunctionInfo &FnInfo;
John McCalld8715092010-07-21 06:13:08 +0000479 const VarDecl &Var;
Eric Christophere1f54902011-08-23 22:38:00 +0000480
John McCalld8715092010-07-21 06:13:08 +0000481 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCall34695852011-02-22 06:44:22 +0000482 const VarDecl *Var)
483 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalld8715092010-07-21 06:13:08 +0000484
John McCallad346f42011-07-12 20:27:29 +0000485 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf4b88a42012-03-10 09:33:50 +0000486 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
487 Var.getType(), VK_LValue, SourceLocation());
John McCall34695852011-02-22 06:44:22 +0000488 // Compute the address of the local variable, in case it's a byref
489 // or something.
490 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
491
John McCalld8715092010-07-21 06:13:08 +0000492 // In some cases, the type of the function argument will be different from
493 // the type of the pointer. An example of this is
494 // void f(void* arg);
495 // __attribute__((cleanup(f))) void *g;
496 //
497 // To fix this we insert a bitcast here.
498 QualType ArgTy = FnInfo.arg_begin()->type;
499 llvm::Value *Arg =
500 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
501
502 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000503 Args.add(RValue::get(Arg),
504 CGF.getContext().getPointerType(Var.getType()));
John McCalld8715092010-07-21 06:13:08 +0000505 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
506 }
507 };
Nadav Rotem495cfa42013-03-23 06:43:35 +0000508
509 /// A cleanup to call @llvm.lifetime.end.
510 class CallLifetimeEnd : public EHScopeStack::Cleanup {
511 llvm::Value *Addr;
512 llvm::Value *Size;
513 public:
514 CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
515 : Addr(addr), Size(size) {}
516
517 void Emit(CodeGenFunction &CGF, Flags flags) {
518 llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
519 CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
520 Size, castAddr)
521 ->setDoesNotThrow();
522 }
523 };
John McCalld8715092010-07-21 06:13:08 +0000524}
525
John McCallf85e1932011-06-15 23:02:42 +0000526/// EmitAutoVarWithLifetime - Does the setup required for an automatic
527/// variable with lifetime.
528static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
529 llvm::Value *addr,
530 Qualifiers::ObjCLifetime lifetime) {
531 switch (lifetime) {
532 case Qualifiers::OCL_None:
533 llvm_unreachable("present but none");
534
535 case Qualifiers::OCL_ExplicitNone:
536 // nothing to do
537 break;
538
539 case Qualifiers::OCL_Strong: {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000540 CodeGenFunction::Destroyer *destroyer =
John McCall9928c482011-07-12 16:41:08 +0000541 (var.hasAttr<ObjCPreciseLifetimeAttr>()
542 ? CodeGenFunction::destroyARCStrongPrecise
543 : CodeGenFunction::destroyARCStrongImprecise);
544
545 CleanupKind cleanupKind = CGF.getARCCleanupKind();
546 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
547 cleanupKind & EHCleanup);
John McCallf85e1932011-06-15 23:02:42 +0000548 break;
549 }
550 case Qualifiers::OCL_Autoreleasing:
551 // nothing to do
552 break;
Eric Christophere1f54902011-08-23 22:38:00 +0000553
John McCallf85e1932011-06-15 23:02:42 +0000554 case Qualifiers::OCL_Weak:
555 // __weak objects always get EH cleanups; otherwise, exceptions
556 // could cause really nasty crashes instead of mere leaks.
John McCall9928c482011-07-12 16:41:08 +0000557 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
558 CodeGenFunction::destroyARCWeak,
559 /*useEHCleanup*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000560 break;
561 }
562}
563
564static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
565 if (const Expr *e = dyn_cast<Expr>(s)) {
566 // Skip the most common kinds of expressions that make
567 // hierarchy-walking expensive.
568 s = e = e->IgnoreParenCasts();
569
570 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
571 return (ref->getDecl() == &var);
Fariborz Jahanianddfc8a12012-06-19 20:53:26 +0000572 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
573 const BlockDecl *block = be->getBlockDecl();
574 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
575 e = block->capture_end(); i != e; ++i) {
576 if (i->getVariable() == &var)
577 return true;
578 }
579 }
John McCallf85e1932011-06-15 23:02:42 +0000580 }
581
582 for (Stmt::const_child_range children = s->children(); children; ++children)
Fariborz Jahanian8fefc8e2011-06-29 20:00:16 +0000583 // children might be null; as in missing decl or conditional of an if-stmt.
584 if ((*children) && isAccessedBy(var, *children))
John McCallf85e1932011-06-15 23:02:42 +0000585 return true;
586
587 return false;
588}
589
590static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
591 if (!decl) return false;
592 if (!isa<VarDecl>(decl)) return false;
593 const VarDecl *var = cast<VarDecl>(decl);
594 return isAccessedBy(*var, e);
595}
596
John McCalla07398e2011-06-16 04:16:24 +0000597static void drillIntoBlockVariable(CodeGenFunction &CGF,
598 LValue &lvalue,
599 const VarDecl *var) {
600 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
601}
602
John McCallf85e1932011-06-15 23:02:42 +0000603void CodeGenFunction::EmitScalarInit(const Expr *init,
604 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +0000605 LValue lvalue,
606 bool capturedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000607 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCallf85e1932011-06-15 23:02:42 +0000608 if (!lifetime) {
609 llvm::Value *value = EmitScalarExpr(init);
John McCalla07398e2011-06-16 04:16:24 +0000610 if (capturedByInit)
611 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +0000612 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCallf85e1932011-06-15 23:02:42 +0000613 return;
614 }
615
616 // If we're emitting a value with lifetime, we have to do the
617 // initialization *before* we leave the cleanup scopes.
John McCall1a343eb2011-11-10 08:15:53 +0000618 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
619 enterFullExpression(ewc);
John McCallf85e1932011-06-15 23:02:42 +0000620 init = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +0000621 }
622 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCallf85e1932011-06-15 23:02:42 +0000623
624 // We have to maintain the illusion that the variable is
625 // zero-initialized. If the variable might be accessed in its
626 // initializer, zero-initialize before running the initializer, then
627 // actually perform the initialization with an assign.
628 bool accessedByInit = false;
629 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallfb720812011-07-28 07:23:35 +0000630 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCallf85e1932011-06-15 23:02:42 +0000631 if (accessedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000632 LValue tempLV = lvalue;
John McCallf85e1932011-06-15 23:02:42 +0000633 // Drill down to the __block object if necessary.
John McCallf85e1932011-06-15 23:02:42 +0000634 if (capturedByInit) {
635 // We can use a simple GEP for this because it can't have been
636 // moved yet.
John McCalla07398e2011-06-16 04:16:24 +0000637 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
638 getByRefValueLLVMField(cast<VarDecl>(D))));
John McCallf85e1932011-06-15 23:02:42 +0000639 }
640
Chris Lattner2acc6e32011-07-18 04:24:23 +0000641 llvm::PointerType *ty
John McCalla07398e2011-06-16 04:16:24 +0000642 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
John McCallf85e1932011-06-15 23:02:42 +0000643 ty = cast<llvm::PointerType>(ty->getElementType());
644
645 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000646
John McCallf85e1932011-06-15 23:02:42 +0000647 // If __weak, we want to use a barrier under certain conditions.
648 if (lifetime == Qualifiers::OCL_Weak)
John McCalla07398e2011-06-16 04:16:24 +0000649 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCallf85e1932011-06-15 23:02:42 +0000650
651 // Otherwise just do a simple store.
652 else
David Chisnall7a7ee302012-01-16 17:27:18 +0000653 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000654 }
655
656 // Emit the initializer.
657 llvm::Value *value = 0;
658
659 switch (lifetime) {
660 case Qualifiers::OCL_None:
661 llvm_unreachable("present but none");
662
663 case Qualifiers::OCL_ExplicitNone:
664 // nothing to do
665 value = EmitScalarExpr(init);
666 break;
667
668 case Qualifiers::OCL_Strong: {
669 value = EmitARCRetainScalarExpr(init);
670 break;
671 }
672
673 case Qualifiers::OCL_Weak: {
674 // No way to optimize a producing initializer into this. It's not
675 // worth optimizing for, because the value will immediately
676 // disappear in the common case.
677 value = EmitScalarExpr(init);
678
John McCalla07398e2011-06-16 04:16:24 +0000679 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000680 if (accessedByInit)
John McCalla07398e2011-06-16 04:16:24 +0000681 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000682 else
John McCalla07398e2011-06-16 04:16:24 +0000683 EmitARCInitWeak(lvalue.getAddress(), value);
John McCallf85e1932011-06-15 23:02:42 +0000684 return;
685 }
686
687 case Qualifiers::OCL_Autoreleasing:
688 value = EmitARCRetainAutoreleaseScalarExpr(init);
689 break;
690 }
691
John McCalla07398e2011-06-16 04:16:24 +0000692 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000693
694 // If the variable might have been accessed by its initializer, we
695 // might have to initialize with a barrier. We have to do this for
696 // both __weak and __strong, but __weak got filtered out above.
697 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
John McCalla07398e2011-06-16 04:16:24 +0000698 llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
David Chisnall7a7ee302012-01-16 17:27:18 +0000699 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall5b07e802013-03-13 03:10:54 +0000700 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +0000701 return;
702 }
703
David Chisnall7a7ee302012-01-16 17:27:18 +0000704 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000705}
Chris Lattner94cd0112010-12-01 02:05:19 +0000706
John McCall7acddac2011-06-17 06:42:21 +0000707/// EmitScalarInit - Initialize the given lvalue with the given object.
708void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
709 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
710 if (!lifetime)
David Chisnall7a7ee302012-01-16 17:27:18 +0000711 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCall7acddac2011-06-17 06:42:21 +0000712
713 switch (lifetime) {
714 case Qualifiers::OCL_None:
715 llvm_unreachable("present but none");
716
717 case Qualifiers::OCL_ExplicitNone:
718 // nothing to do
719 break;
720
721 case Qualifiers::OCL_Strong:
722 init = EmitARCRetain(lvalue.getType(), init);
723 break;
724
725 case Qualifiers::OCL_Weak:
726 // Initialize and then skip the primitive store.
727 EmitARCInitWeak(lvalue.getAddress(), init);
728 return;
729
730 case Qualifiers::OCL_Autoreleasing:
731 init = EmitARCRetainAutorelease(lvalue.getType(), init);
732 break;
733 }
734
David Chisnall7a7ee302012-01-16 17:27:18 +0000735 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCall7acddac2011-06-17 06:42:21 +0000736}
737
Chris Lattner94cd0112010-12-01 02:05:19 +0000738/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
739/// non-zero parts of the specified initializer with equal or fewer than
740/// NumStores scalar stores.
741static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
742 unsigned &NumStores) {
Chris Lattner70b02942010-12-02 01:58:41 +0000743 // Zero and Undef never requires any extra stores.
744 if (isa<llvm::ConstantAggregateZero>(Init) ||
745 isa<llvm::ConstantPointerNull>(Init) ||
746 isa<llvm::UndefValue>(Init))
747 return true;
748 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
749 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
750 isa<llvm::ConstantExpr>(Init))
751 return Init->isNullValue() || NumStores--;
752
753 // See if we can emit each element.
754 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
755 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
756 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
757 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
758 return false;
759 }
760 return true;
761 }
Chris Lattnerf492cb12012-01-31 04:36:19 +0000762
763 if (llvm::ConstantDataSequential *CDS =
764 dyn_cast<llvm::ConstantDataSequential>(Init)) {
765 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
766 llvm::Constant *Elt = CDS->getElementAsConstant(i);
767 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
768 return false;
769 }
770 return true;
771 }
Eric Christophere1f54902011-08-23 22:38:00 +0000772
Chris Lattner94cd0112010-12-01 02:05:19 +0000773 // Anything else is hard and scary.
774 return false;
775}
776
777/// emitStoresForInitAfterMemset - For inits that
778/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
779/// stores that would be required.
780static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCall34695852011-02-22 06:44:22 +0000781 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer06d43682012-08-27 22:07:02 +0000782 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
783 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christophere1f54902011-08-23 22:38:00 +0000784
Chris Lattner70b02942010-12-02 01:58:41 +0000785 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
786 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
787 isa<llvm::ConstantExpr>(Init)) {
Chris Lattnerf492cb12012-01-31 04:36:19 +0000788 Builder.CreateStore(Init, Loc, isVolatile);
789 return;
790 }
791
792 if (llvm::ConstantDataSequential *CDS =
793 dyn_cast<llvm::ConstantDataSequential>(Init)) {
794 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
795 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramercfa07e32012-08-27 21:35:58 +0000796
797 // If necessary, get a pointer to the element and emit it.
798 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
799 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
800 isVolatile, Builder);
Chris Lattnerf492cb12012-01-31 04:36:19 +0000801 }
Chris Lattner70b02942010-12-02 01:58:41 +0000802 return;
803 }
Eric Christophere1f54902011-08-23 22:38:00 +0000804
Chris Lattner70b02942010-12-02 01:58:41 +0000805 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
806 "Unknown value type!");
Eric Christophere1f54902011-08-23 22:38:00 +0000807
Chris Lattner70b02942010-12-02 01:58:41 +0000808 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
809 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramercfa07e32012-08-27 21:35:58 +0000810
811 // If necessary, get a pointer to the element and emit it.
812 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
813 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
814 isVolatile, Builder);
Chris Lattner70b02942010-12-02 01:58:41 +0000815 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000816}
817
818
819/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
820/// plus some stores to initialize a local variable instead of using a memcpy
821/// from a constant global. It is beneficial to use memset if the global is all
822/// zeros, or mostly zeros and large.
823static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
824 uint64_t GlobalSize) {
825 // If a global is all zeros, always use a memset.
826 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
827
Chris Lattner94cd0112010-12-01 02:05:19 +0000828 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
829 // do it if it will require 6 or fewer scalar stores.
830 // TODO: Should budget depends on the size? Avoiding a large global warrants
831 // plopping in more stores.
832 unsigned StoreBudget = 6;
833 uint64_t SizeLimit = 32;
Eric Christophere1f54902011-08-23 22:38:00 +0000834
835 return GlobalSize > SizeLimit &&
Chris Lattner94cd0112010-12-01 02:05:19 +0000836 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
837}
838
Nadav Rotem495cfa42013-03-23 06:43:35 +0000839/// Should we use the LLVM lifetime intrinsics for the given local variable?
840static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
841 unsigned Size) {
Alexey Samsonov4f01ed42013-04-02 13:19:46 +0000842 // Always emit lifetime markers in -fsanitize=use-after-scope mode.
843 if (CGF.getLangOpts().Sanitize.UseAfterScope)
844 return true;
Nadav Rotem495cfa42013-03-23 06:43:35 +0000845 // For now, only in optimized builds.
846 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
847 return false;
848
849 // Limit the size of marked objects to 32 bytes. We don't want to increase
850 // compile time by marking tiny objects.
851 unsigned SizeThreshold = 32;
852
853 return Size > SizeThreshold;
854}
855
Chris Lattner94cd0112010-12-01 02:05:19 +0000856
Nick Lewyckya9de3fa2010-12-30 20:21:55 +0000857/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Reid Spencer5f016e22007-07-11 17:01:13 +0000858/// variable declaration with auto, register, or no storage class specifier.
Chris Lattner2621fd12008-05-08 05:58:21 +0000859/// These turn into simple stack objects, or GlobalValues depending on target.
John McCall34695852011-02-22 06:44:22 +0000860void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
861 AutoVarEmission emission = EmitAutoVarAlloca(D);
862 EmitAutoVarInit(emission);
863 EmitAutoVarCleanups(emission);
864}
Reid Spencer5f016e22007-07-11 17:01:13 +0000865
John McCall34695852011-02-22 06:44:22 +0000866/// EmitAutoVarAlloca - Emit the alloca and debug information for a
867/// local variable. Does not emit initalization or destruction.
868CodeGenFunction::AutoVarEmission
869CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
870 QualType Ty = D.getType();
871
872 AutoVarEmission emission(D);
873
874 bool isByRef = D.hasAttr<BlocksAttr>();
875 emission.IsByRef = isByRef;
876
877 CharUnits alignment = getContext().getDeclAlign(&D);
878 emission.Alignment = alignment;
879
John McCallbc8d40d2011-06-24 21:55:10 +0000880 // If the type is variably-modified, emit all the VLA sizes for it.
881 if (Ty->isVariablyModifiedType())
882 EmitVariablyModifiedType(Ty);
883
Reid Spencer5f016e22007-07-11 17:01:13 +0000884 llvm::Value *DeclPtr;
Eli Friedman3c2b3172008-02-15 12:20:59 +0000885 if (Ty->isConstantSizeType()) {
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000886 bool NRVO = getLangOpts().ElideConstructors &&
887 D.isNRVOVariable();
John McCall34695852011-02-22 06:44:22 +0000888
Richard Smithe67ca582013-06-02 00:09:52 +0000889 // If this value is an array or struct with a statically determinable
890 // constant initializer, there are optimizations we can do.
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000891 //
892 // TODO: We should constant-evaluate the initializer of any variable,
893 // as long as it is initialized by a constant expression. Currently,
894 // isConstantInitializer produces wrong answers for structs with
895 // reference or bitfield members, and a few other cases, and checking
896 // for POD-ness protects us from some of these.
Richard Smithe67ca582013-06-02 00:09:52 +0000897 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
898 (D.isConstexpr() ||
899 ((Ty.isPODType(getContext()) ||
900 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
901 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCall34695852011-02-22 06:44:22 +0000902
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000903 // If the variable's a const type, and it's neither an NRVO
904 // candidate nor a __block variable and has no mutable members,
905 // emit it as a global instead.
906 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
907 CGM.isTypeConstant(Ty, true)) {
908 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCall34695852011-02-22 06:44:22 +0000909
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000910 emission.Address = 0; // signal this condition to later callbacks
911 assert(emission.wasEmittedAsGlobal());
912 return emission;
Tanya Lattner59876c22009-11-04 01:18:09 +0000913 }
Eric Christophere1f54902011-08-23 22:38:00 +0000914
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000915 // Otherwise, tell the initialization code that we're in this case.
916 emission.IsConstantAggregate = true;
917 }
Eric Christophere1f54902011-08-23 22:38:00 +0000918
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000919 // A normal fixed sized variable becomes an alloca in the entry block,
920 // unless it's an NRVO variable.
921 llvm::Type *LTy = ConvertTypeForMem(Ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000922
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000923 if (NRVO) {
924 // The named return value optimization: allocate this variable in the
925 // return slot, so that we can elide the copy when returning this
926 // variable (C++0x [class.copy]p34).
927 DeclPtr = ReturnValue;
Eric Christophere1f54902011-08-23 22:38:00 +0000928
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000929 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
930 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
931 // Create a flag that is used to indicate when the NRVO was applied
932 // to this variable. Set it to zero to indicate that NRVO was not
933 // applied.
934 llvm::Value *Zero = Builder.getFalse();
935 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
936 EnsureInsertPoint();
937 Builder.CreateStore(Zero, NRVOFlag);
Eric Christophere1f54902011-08-23 22:38:00 +0000938
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000939 // Record the NRVO flag for this variable.
940 NRVOFlags[&D] = NRVOFlag;
941 emission.NRVOFlag = NRVOFlag;
Nadav Rotem495cfa42013-03-23 06:43:35 +0000942 }
Douglas Gregord86c4772010-05-15 06:46:45 +0000943 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000944 } else {
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000945 if (isByRef)
946 LTy = BuildByRefType(&D);
947
948 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
949 Alloc->setName(D.getName());
950
951 CharUnits allocaAlignment = alignment;
952 if (isByRef)
953 allocaAlignment = std::max(allocaAlignment,
John McCall64aa4b32013-04-16 22:48:15 +0000954 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000955 Alloc->setAlignment(allocaAlignment.getQuantity());
956 DeclPtr = Alloc;
957
958 // Emit a lifetime intrinsic if meaningful. There's no point
959 // in doing this if we don't have a valid insertion point (?).
960 uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
961 if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
962 llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
963
964 emission.SizeForLifetimeMarkers = sizeV;
965 llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
966 Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
967 ->setDoesNotThrow();
968 } else {
969 assert(!emission.useLifetimeMarkers());
970 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000971 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 } else {
Daniel Dunbard286f052009-07-19 06:58:07 +0000973 EnsureInsertPoint();
974
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000975 if (!DidCallStackSave) {
Anders Carlsson5d463152008-12-12 07:38:43 +0000976 // Save the stack.
John McCalld16c2cf2011-02-08 08:22:06 +0000977 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Anders Carlsson5d463152008-12-12 07:38:43 +0000979 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
980 llvm::Value *V = Builder.CreateCall(F);
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Anders Carlsson5d463152008-12-12 07:38:43 +0000982 Builder.CreateStore(V, Stack);
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000983
984 DidCallStackSave = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000985
John McCalld8715092010-07-21 06:13:08 +0000986 // Push a cleanup block and restore the stack there.
John McCall3ad32c82011-01-28 08:37:24 +0000987 // FIXME: in general circumstances, this should be an EH cleanup.
John McCall1f0fca52010-07-21 07:22:38 +0000988 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
Anders Carlsson5d463152008-12-12 07:38:43 +0000989 }
Mike Stump1eb44332009-09-09 15:08:12 +0000990
John McCallbc8d40d2011-06-24 21:55:10 +0000991 llvm::Value *elementCount;
992 QualType elementType;
993 llvm::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson5d463152008-12-12 07:38:43 +0000994
Chris Lattner2acc6e32011-07-18 04:24:23 +0000995 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson5d463152008-12-12 07:38:43 +0000996
997 // Allocate memory for the array.
John McCallbc8d40d2011-06-24 21:55:10 +0000998 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
999 vla->setAlignment(alignment.getQuantity());
Anders Carlsson41f8a132009-09-26 18:16:06 +00001000
John McCallbc8d40d2011-06-24 21:55:10 +00001001 DeclPtr = vla;
Reid Spencer5f016e22007-07-11 17:01:13 +00001002 }
Eli Friedman8f39f5e2008-12-20 23:11:59 +00001003
Reid Spencer5f016e22007-07-11 17:01:13 +00001004 llvm::Value *&DMEntry = LocalDeclMap[&D];
1005 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1006 DMEntry = DeclPtr;
John McCall34695852011-02-22 06:44:22 +00001007 emission.Address = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +00001008
1009 // Emit debug info for local var declaration.
Devang Patelc594abd2011-06-03 19:21:47 +00001010 if (HaveInsertPoint())
1011 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +00001012 if (CGM.getCodeGenOpts().getDebugInfo()
1013 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001014 DI->setLocation(D.getLocation());
Rafael Espindola6c82fc62013-03-26 18:41:47 +00001015 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001016 }
Devang Patelc594abd2011-06-03 19:21:47 +00001017 }
Sanjiv Guptacc9b1632008-05-30 10:30:31 +00001018
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001019 if (D.hasAttr<AnnotateAttr>())
1020 EmitVarAnnotations(&D, emission.Address);
1021
John McCall34695852011-02-22 06:44:22 +00001022 return emission;
1023}
1024
1025/// Determines whether the given __block variable is potentially
1026/// captured by the given expression.
1027static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1028 // Skip the most common kinds of expressions that make
1029 // hierarchy-walking expensive.
1030 e = e->IgnoreParenCasts();
1031
1032 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1033 const BlockDecl *block = be->getBlockDecl();
1034 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
1035 e = block->capture_end(); i != e; ++i) {
1036 if (i->getVariable() == &var)
1037 return true;
1038 }
1039
1040 // No need to walk into the subexpressions.
1041 return false;
1042 }
1043
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001044 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1045 const CompoundStmt *CS = SE->getSubStmt();
Eric Christopherc6fad602011-08-23 23:44:09 +00001046 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1047 BE = CS->body_end(); BI != BE; ++BI)
Fariborz Jahanian045c8422011-08-25 00:06:26 +00001048 if (Expr *E = dyn_cast<Expr>((*BI))) {
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001049 if (isCapturedBy(var, E))
1050 return true;
Fariborz Jahanian045c8422011-08-25 00:06:26 +00001051 }
1052 else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
1053 // special case declarations
1054 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1055 I != E; ++I) {
1056 if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
1057 Expr *Init = VD->getInit();
1058 if (Init && isCapturedBy(var, Init))
1059 return true;
1060 }
1061 }
1062 }
1063 else
1064 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1065 // Later, provide code to poke into statements for capture analysis.
1066 return true;
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001067 return false;
1068 }
Eric Christophere1f54902011-08-23 22:38:00 +00001069
John McCall34695852011-02-22 06:44:22 +00001070 for (Stmt::const_child_range children = e->children(); children; ++children)
1071 if (isCapturedBy(var, cast<Expr>(*children)))
1072 return true;
1073
1074 return false;
1075}
1076
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001077/// \brief Determine whether the given initializer is trivial in the sense
1078/// that it requires no code to be generated.
1079static bool isTrivialInitializer(const Expr *Init) {
1080 if (!Init)
1081 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001082
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001083 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1084 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1085 if (Constructor->isTrivial() &&
1086 Constructor->isDefaultConstructor() &&
1087 !Construct->requiresZeroInitialization())
1088 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001089
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001090 return false;
1091}
John McCall34695852011-02-22 06:44:22 +00001092void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001093 assert(emission.Variable && "emission was not valid!");
1094
John McCall34695852011-02-22 06:44:22 +00001095 // If this was emitted as a global constant, we're done.
1096 if (emission.wasEmittedAsGlobal()) return;
1097
John McCall57b3b6a2011-02-22 07:16:58 +00001098 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001099 QualType type = D.getType();
1100
Chris Lattner19785962007-07-12 00:39:48 +00001101 // If this local has an initializer, emit it now.
Daniel Dunbard286f052009-07-19 06:58:07 +00001102 const Expr *Init = D.getInit();
1103
1104 // If we are at an unreachable point, we don't need to emit the initializer
1105 // unless it contains a label.
1106 if (!HaveInsertPoint()) {
John McCall34695852011-02-22 06:44:22 +00001107 if (!Init || !ContainsLabel(Init)) return;
1108 EnsureInsertPoint();
Daniel Dunbard286f052009-07-19 06:58:07 +00001109 }
1110
John McCall5af02db2011-03-31 01:59:53 +00001111 // Initialize the structure of a __block variable.
1112 if (emission.IsByRef)
1113 emitByrefStructureInit(emission);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001114
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001115 if (isTrivialInitializer(Init))
1116 return;
Eric Christophere1f54902011-08-23 22:38:00 +00001117
John McCall5af02db2011-03-31 01:59:53 +00001118 CharUnits alignment = emission.Alignment;
1119
John McCall34695852011-02-22 06:44:22 +00001120 // Check whether this is a byref variable that's potentially
1121 // captured and moved by its own initializer. If so, we'll need to
1122 // emit the initializer first, then copy into the variable.
1123 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1124
1125 llvm::Value *Loc =
1126 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1127
Richard Smith51201882011-12-30 21:15:51 +00001128 llvm::Constant *constant = 0;
Richard Smithe67ca582013-06-02 00:09:52 +00001129 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smith51201882011-12-30 21:15:51 +00001130 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smith2d6a5672012-01-14 04:30:29 +00001131 constant = CGM.EmitConstantInit(D, this);
Richard Smith51201882011-12-30 21:15:51 +00001132 }
1133
1134 if (!constant) {
Eli Friedman6da2c712011-12-03 04:14:32 +00001135 LValue lv = MakeAddrLValue(Loc, type, alignment);
John McCalla07398e2011-06-16 04:16:24 +00001136 lv.setNonGC(true);
1137 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1138 }
John McCall60d33652011-03-08 09:11:50 +00001139
Richard Smithe67ca582013-06-02 00:09:52 +00001140 if (!emission.IsConstantAggregate) {
1141 // For simple scalar/complex initialization, store the value directly.
1142 LValue lv = MakeAddrLValue(Loc, type, alignment);
1143 lv.setNonGC(true);
1144 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1145 }
1146
John McCall34695852011-02-22 06:44:22 +00001147 // If this is a simple aggregate initialization, we can optimize it
1148 // in various ways.
John McCall60d33652011-03-08 09:11:50 +00001149 bool isVolatile = type.isVolatileQualified();
John McCall34695852011-02-22 06:44:22 +00001150
John McCall60d33652011-03-08 09:11:50 +00001151 llvm::Value *SizeVal =
Eric Christophere1f54902011-08-23 22:38:00 +00001152 llvm::ConstantInt::get(IntPtrTy,
John McCall60d33652011-03-08 09:11:50 +00001153 getContext().getTypeSizeInChars(type).getQuantity());
John McCall34695852011-02-22 06:44:22 +00001154
Chris Lattner2acc6e32011-07-18 04:24:23 +00001155 llvm::Type *BP = Int8PtrTy;
John McCall60d33652011-03-08 09:11:50 +00001156 if (Loc->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001157 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wang3ecd7852010-04-04 03:10:52 +00001158
John McCall60d33652011-03-08 09:11:50 +00001159 // If the initializer is all or mostly zeros, codegen with memset then do
1160 // a few stores afterward.
Eric Christophere1f54902011-08-23 22:38:00 +00001161 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmow25a6a842012-10-08 16:25:52 +00001162 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall60d33652011-03-08 09:11:50 +00001163 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1164 alignment.getQuantity(), isVolatile);
Benjamin Kramer06d43682012-08-27 22:07:02 +00001165 // Zero and undef don't require a stores.
1166 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall60d33652011-03-08 09:11:50 +00001167 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1168 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001169 }
John McCall60d33652011-03-08 09:11:50 +00001170 } else {
Eric Christophere1f54902011-08-23 22:38:00 +00001171 // Otherwise, create a temporary global with the initializer then
John McCall60d33652011-03-08 09:11:50 +00001172 // memcpy from the global to the alloca.
1173 std::string Name = GetStaticDeclName(*this, D, ".");
1174 llvm::GlobalVariable *GV =
1175 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopher736a9c22011-08-24 00:33:55 +00001176 llvm::GlobalValue::PrivateLinkage,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +00001177 constant, Name);
John McCall60d33652011-03-08 09:11:50 +00001178 GV->setAlignment(alignment.getQuantity());
Eli Friedman460980d2011-05-27 22:32:55 +00001179 GV->setUnnamedAddr(true);
Eric Christophere1f54902011-08-23 22:38:00 +00001180
John McCall60d33652011-03-08 09:11:50 +00001181 llvm::Value *SrcPtr = GV;
1182 if (SrcPtr->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001183 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall60d33652011-03-08 09:11:50 +00001184
1185 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1186 isVolatile);
1187 }
1188}
1189
1190/// Emit an expression as an initializer for a variable at the given
1191/// location. The expression is not necessarily the normal
1192/// initializer for the variable, and the address is not necessarily
1193/// its normal location.
1194///
1195/// \param init the initializing expression
1196/// \param var the variable to act as if we're initializing
1197/// \param loc the address to initialize; its type is a pointer
1198/// to the LLVM mapping of the variable's type
1199/// \param alignment the alignment of the address
1200/// \param capturedByInit true if the variable is a __block variable
1201/// whose address is potentially changed by the initializer
1202void CodeGenFunction::EmitExprAsInit(const Expr *init,
John McCallf85e1932011-06-15 23:02:42 +00001203 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +00001204 LValue lvalue,
John McCall60d33652011-03-08 09:11:50 +00001205 bool capturedByInit) {
John McCallf85e1932011-06-15 23:02:42 +00001206 QualType type = D->getType();
John McCall60d33652011-03-08 09:11:50 +00001207
1208 if (type->isReferenceType()) {
Richard Smithd4ec5622013-06-12 23:38:09 +00001209 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christophere1f54902011-08-23 22:38:00 +00001210 if (capturedByInit)
John McCalla07398e2011-06-16 04:16:24 +00001211 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +00001212 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall9d232c82013-03-07 21:37:08 +00001213 return;
1214 }
1215 switch (getEvaluationKind(type)) {
1216 case TEK_Scalar:
John McCalla07398e2011-06-16 04:16:24 +00001217 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall9d232c82013-03-07 21:37:08 +00001218 return;
1219 case TEK_Complex: {
John McCall60d33652011-03-08 09:11:50 +00001220 ComplexPairTy complex = EmitComplexExpr(init);
John McCalla07398e2011-06-16 04:16:24 +00001221 if (capturedByInit)
1222 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall9d232c82013-03-07 21:37:08 +00001223 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1224 return;
1225 }
1226 case TEK_Aggregate:
John McCall9eda3ab2013-03-07 21:37:17 +00001227 if (type->isAtomicType()) {
1228 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1229 } else {
1230 // TODO: how can we delay here if D is captured by its initializer?
1231 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier649b4a12012-03-29 17:37:10 +00001232 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001233 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001234 AggValueSlot::IsNotAliased));
John McCall9eda3ab2013-03-07 21:37:17 +00001235 }
John McCall9d232c82013-03-07 21:37:08 +00001236 return;
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001237 }
John McCall9d232c82013-03-07 21:37:08 +00001238 llvm_unreachable("bad evaluation kind");
John McCall34695852011-02-22 06:44:22 +00001239}
John McCallf1549f62010-07-06 01:34:17 +00001240
John McCallbdc4d802011-07-09 01:37:26 +00001241/// Enter a destroy cleanup for the given local variable.
1242void CodeGenFunction::emitAutoVarTypeCleanup(
1243 const CodeGenFunction::AutoVarEmission &emission,
1244 QualType::DestructionKind dtorKind) {
1245 assert(dtorKind != QualType::DK_none);
1246
1247 // Note that for __block variables, we want to destroy the
1248 // original stack object, not the possibly forwarded object.
1249 llvm::Value *addr = emission.getObjectAddress(*this);
1250
1251 const VarDecl *var = emission.Variable;
1252 QualType type = var->getType();
1253
1254 CleanupKind cleanupKind = NormalAndEHCleanup;
1255 CodeGenFunction::Destroyer *destroyer = 0;
1256
1257 switch (dtorKind) {
1258 case QualType::DK_none:
1259 llvm_unreachable("no cleanup for trivially-destructible variable");
1260
1261 case QualType::DK_cxx_destructor:
1262 // If there's an NRVO flag on the emission, we need a different
1263 // cleanup.
1264 if (emission.NRVOFlag) {
1265 assert(!type->isArrayType());
1266 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1267 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1268 emission.NRVOFlag);
1269 return;
1270 }
1271 break;
1272
1273 case QualType::DK_objc_strong_lifetime:
1274 // Suppress cleanups for pseudo-strong variables.
1275 if (var->isARCPseudoStrong()) return;
Eric Christophere1f54902011-08-23 22:38:00 +00001276
John McCallbdc4d802011-07-09 01:37:26 +00001277 // Otherwise, consider whether to use an EH cleanup or not.
1278 cleanupKind = getARCCleanupKind();
1279
1280 // Use the imprecise destroyer by default.
1281 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1282 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1283 break;
1284
1285 case QualType::DK_objc_weak_lifetime:
1286 break;
1287 }
1288
1289 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001290 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall2673c682011-07-11 08:38:19 +00001291
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00001292 // Use an EH cleanup in array destructors iff the destructor itself
John McCall2673c682011-07-11 08:38:19 +00001293 // is being pushed as an EH cleanup.
1294 bool useEHCleanup = (cleanupKind & EHCleanup);
1295 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1296 useEHCleanup);
John McCallbdc4d802011-07-09 01:37:26 +00001297}
1298
John McCall34695852011-02-22 06:44:22 +00001299void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001300 assert(emission.Variable && "emission was not valid!");
1301
John McCall34695852011-02-22 06:44:22 +00001302 // If this was emitted as a global constant, we're done.
1303 if (emission.wasEmittedAsGlobal()) return;
1304
John McCall38baeab2012-04-13 18:44:05 +00001305 // If we don't have an insertion point, we're done. Sema prevents
1306 // us from jumping into any of these scopes anyway.
1307 if (!HaveInsertPoint()) return;
1308
John McCall57b3b6a2011-02-22 07:16:58 +00001309 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001310
Nadav Rotem495cfa42013-03-23 06:43:35 +00001311 // Make sure we call @llvm.lifetime.end. This needs to happen
1312 // *last*, so the cleanup needs to be pushed *first*.
1313 if (emission.useLifetimeMarkers()) {
1314 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1315 emission.getAllocatedAddress(),
1316 emission.getSizeForLifetimeMarkers());
1317 }
1318
John McCallbdc4d802011-07-09 01:37:26 +00001319 // Check the type for a cleanup.
1320 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1321 emitAutoVarTypeCleanup(emission, dtorKind);
John McCallf85e1932011-06-15 23:02:42 +00001322
John McCall0c24c802011-06-24 23:21:27 +00001323 // In GC mode, honor objc_precise_lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00001324 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall0c24c802011-06-24 23:21:27 +00001325 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1326 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1327 }
1328
John McCall34695852011-02-22 06:44:22 +00001329 // Handle the cleanup attribute.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001330 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlsson69c68b72009-02-07 23:51:38 +00001331 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001332
John McCall34695852011-02-22 06:44:22 +00001333 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001334 assert(F && "Could not find function!");
Mike Stump1eb44332009-09-09 15:08:12 +00001335
John McCallde5d3c72012-02-17 03:33:10 +00001336 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCall34695852011-02-22 06:44:22 +00001337 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001338 }
Mike Stump797b6322009-03-05 01:23:13 +00001339
John McCall34695852011-02-22 06:44:22 +00001340 // If this is a block variable, call _Block_object_destroy
1341 // (on the unforwarded address).
John McCall5af02db2011-03-31 01:59:53 +00001342 if (emission.IsByRef)
1343 enterByrefCleanup(emission);
Reid Spencer5f016e22007-07-11 17:01:13 +00001344}
1345
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001346CodeGenFunction::Destroyer *
John McCallbdc4d802011-07-09 01:37:26 +00001347CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1348 switch (kind) {
1349 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCall0850e8d2011-07-09 09:09:00 +00001350 case QualType::DK_cxx_destructor:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001351 return destroyCXXObject;
John McCall0850e8d2011-07-09 09:09:00 +00001352 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001353 return destroyARCStrongPrecise;
John McCall0850e8d2011-07-09 09:09:00 +00001354 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001355 return destroyARCWeak;
John McCallbdc4d802011-07-09 01:37:26 +00001356 }
Matt Beaumont-Gayba4be252012-01-27 00:46:27 +00001357 llvm_unreachable("Unknown DestructionKind");
John McCallbdc4d802011-07-09 01:37:26 +00001358}
1359
John McCall074cae02013-02-01 05:11:40 +00001360/// pushEHDestroy - Push the standard destructor for the given type as
1361/// an EH-only cleanup.
1362void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1363 llvm::Value *addr, QualType type) {
1364 assert(dtorKind && "cannot push destructor for trivial type");
1365 assert(needsEHCleanup(dtorKind));
1366
1367 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1368}
1369
1370/// pushDestroy - Push the standard destructor for the given type as
1371/// at least a normal cleanup.
John McCall9928c482011-07-12 16:41:08 +00001372void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1373 llvm::Value *addr, QualType type) {
1374 assert(dtorKind && "cannot push destructor for trivial type");
1375
1376 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1377 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1378 cleanupKind & EHCleanup);
1379}
1380
John McCallbdc4d802011-07-09 01:37:26 +00001381void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001382 QualType type, Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001383 bool useEHCleanupForArray) {
John McCall9928c482011-07-12 16:41:08 +00001384 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1385 destroyer, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001386}
1387
Richard Smith8a07cd32013-06-12 20:42:33 +00001388void CodeGenFunction::pushLifetimeExtendedDestroy(
1389 CleanupKind cleanupKind, llvm::Value *addr, QualType type,
1390 Destroyer *destroyer, bool useEHCleanupForArray) {
1391 assert(!isInConditionalBranch() &&
1392 "performing lifetime extension from within conditional");
1393
1394 // Push an EH-only cleanup for the object now.
1395 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1396 // around in case a temporary's destructor throws an exception.
1397 if (cleanupKind & EHCleanup)
1398 EHStack.pushCleanup<DestroyObject>(
1399 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1400 destroyer, useEHCleanupForArray);
1401
1402 // Remember that we need to push a full cleanup for the object at the
1403 // end of the full-expression.
1404 pushCleanupAfterFullExpr<DestroyObject>(
1405 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1406}
1407
John McCall2673c682011-07-11 08:38:19 +00001408/// emitDestroy - Immediately perform the destruction of the given
1409/// object.
1410///
1411/// \param addr - the address of the object; a type*
1412/// \param type - the type of the object; if an array type, all
1413/// objects are destroyed in reverse order
1414/// \param destroyer - the function to call to destroy individual
1415/// elements
1416/// \param useEHCleanupForArray - whether an EH cleanup should be
1417/// used when destroying array elements, in case one of the
1418/// destructions throws an exception
John McCallbdc4d802011-07-09 01:37:26 +00001419void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001420 Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001421 bool useEHCleanupForArray) {
John McCallbdc4d802011-07-09 01:37:26 +00001422 const ArrayType *arrayType = getContext().getAsArrayType(type);
1423 if (!arrayType)
1424 return destroyer(*this, addr, type);
1425
1426 llvm::Value *begin = addr;
1427 llvm::Value *length = emitArrayLength(arrayType, type, begin);
John McCallfbf780a2011-07-13 08:09:46 +00001428
1429 // Normally we have to check whether the array is zero-length.
1430 bool checkZeroLength = true;
1431
1432 // But if the array length is constant, we can suppress that.
1433 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1434 // ...and if it's constant zero, we can just skip the entire thing.
1435 if (constLength->isZero()) return;
1436 checkZeroLength = false;
1437 }
1438
John McCallbdc4d802011-07-09 01:37:26 +00001439 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCallfbf780a2011-07-13 08:09:46 +00001440 emitArrayDestroy(begin, end, type, destroyer,
1441 checkZeroLength, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001442}
1443
John McCall2673c682011-07-11 08:38:19 +00001444/// emitArrayDestroy - Destroys all the elements of the given array,
1445/// beginning from last to first. The array cannot be zero-length.
1446///
1447/// \param begin - a type* denoting the first element of the array
1448/// \param end - a type* denoting one past the end of the array
1449/// \param type - the element type of the array
1450/// \param destroyer - the function to call to destroy elements
1451/// \param useEHCleanup - whether to push an EH cleanup to destroy
1452/// the remaining elements in case the destruction of a single
1453/// element throws
John McCallbdc4d802011-07-09 01:37:26 +00001454void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1455 llvm::Value *end,
1456 QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001457 Destroyer *destroyer,
John McCallfbf780a2011-07-13 08:09:46 +00001458 bool checkZeroLength,
John McCall2673c682011-07-11 08:38:19 +00001459 bool useEHCleanup) {
John McCallbdc4d802011-07-09 01:37:26 +00001460 assert(!type->isArrayType());
1461
1462 // The basic structure here is a do-while loop, because we don't
1463 // need to check for the zero-element case.
1464 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1465 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1466
John McCallfbf780a2011-07-13 08:09:46 +00001467 if (checkZeroLength) {
1468 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1469 "arraydestroy.isempty");
1470 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1471 }
1472
John McCallbdc4d802011-07-09 01:37:26 +00001473 // Enter the loop body, making that address the current address.
1474 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1475 EmitBlock(bodyBB);
1476 llvm::PHINode *elementPast =
1477 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1478 elementPast->addIncoming(end, entryBB);
1479
1480 // Shift the address back by one element.
1481 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1482 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1483 "arraydestroy.element");
1484
John McCall2673c682011-07-11 08:38:19 +00001485 if (useEHCleanup)
1486 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1487
John McCallbdc4d802011-07-09 01:37:26 +00001488 // Perform the actual destruction there.
1489 destroyer(*this, element, type);
1490
John McCall2673c682011-07-11 08:38:19 +00001491 if (useEHCleanup)
1492 PopCleanupBlock();
1493
John McCallbdc4d802011-07-09 01:37:26 +00001494 // Check whether we've reached the end.
1495 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1496 Builder.CreateCondBr(done, doneBB, bodyBB);
1497 elementPast->addIncoming(element, Builder.GetInsertBlock());
1498
1499 // Done.
1500 EmitBlock(doneBB);
1501}
1502
John McCall2673c682011-07-11 08:38:19 +00001503/// Perform partial array destruction as if in an EH cleanup. Unlike
1504/// emitArrayDestroy, the element type here may still be an array type.
John McCall2673c682011-07-11 08:38:19 +00001505static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1506 llvm::Value *begin, llvm::Value *end,
1507 QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001508 CodeGenFunction::Destroyer *destroyer) {
John McCall2673c682011-07-11 08:38:19 +00001509 // If the element type is itself an array, drill down.
John McCallfbf780a2011-07-13 08:09:46 +00001510 unsigned arrayDepth = 0;
John McCall2673c682011-07-11 08:38:19 +00001511 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1512 // VLAs don't require a GEP index to walk into.
1513 if (!isa<VariableArrayType>(arrayType))
John McCallfbf780a2011-07-13 08:09:46 +00001514 arrayDepth++;
John McCall2673c682011-07-11 08:38:19 +00001515 type = arrayType->getElementType();
1516 }
John McCallfbf780a2011-07-13 08:09:46 +00001517
1518 if (arrayDepth) {
1519 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1520
Chris Lattner5f9e2722011-07-23 10:55:15 +00001521 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001522 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1523 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall2673c682011-07-11 08:38:19 +00001524 }
1525
John McCallfbf780a2011-07-13 08:09:46 +00001526 // Destroy the array. We don't ever need an EH cleanup because we
1527 // assume that we're in an EH cleanup ourselves, so a throwing
1528 // destructor causes an immediate terminate.
1529 CGF.emitArrayDestroy(begin, end, type, destroyer,
1530 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall2673c682011-07-11 08:38:19 +00001531}
1532
John McCallbdc4d802011-07-09 01:37:26 +00001533namespace {
John McCall2673c682011-07-11 08:38:19 +00001534 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1535 /// array destroy where the end pointer is regularly determined and
1536 /// does not need to be loaded from a local.
1537 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1538 llvm::Value *ArrayBegin;
1539 llvm::Value *ArrayEnd;
1540 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001541 CodeGenFunction::Destroyer *Destroyer;
John McCall2673c682011-07-11 08:38:19 +00001542 public:
1543 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1544 QualType elementType,
1545 CodeGenFunction::Destroyer *destroyer)
1546 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001547 ElementType(elementType), Destroyer(destroyer) {}
John McCall2673c682011-07-11 08:38:19 +00001548
John McCallad346f42011-07-12 20:27:29 +00001549 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +00001550 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1551 ElementType, Destroyer);
1552 }
1553 };
1554
1555 /// IrregularPartialArrayDestroy - a cleanup which performs a
1556 /// partial array destroy where the end pointer is irregularly
1557 /// determined and must be loaded from a local.
1558 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
John McCallbdc4d802011-07-09 01:37:26 +00001559 llvm::Value *ArrayBegin;
1560 llvm::Value *ArrayEndPointer;
1561 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001562 CodeGenFunction::Destroyer *Destroyer;
John McCallbdc4d802011-07-09 01:37:26 +00001563 public:
John McCall2673c682011-07-11 08:38:19 +00001564 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1565 llvm::Value *arrayEndPointer,
1566 QualType elementType,
1567 CodeGenFunction::Destroyer *destroyer)
John McCallbdc4d802011-07-09 01:37:26 +00001568 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001569 ElementType(elementType), Destroyer(destroyer) {}
John McCallbdc4d802011-07-09 01:37:26 +00001570
John McCallad346f42011-07-12 20:27:29 +00001571 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallbdc4d802011-07-09 01:37:26 +00001572 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall2673c682011-07-11 08:38:19 +00001573 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1574 ElementType, Destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001575 }
1576 };
1577}
1578
John McCall2673c682011-07-11 08:38:19 +00001579/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCallbdc4d802011-07-09 01:37:26 +00001580/// already-constructed elements of the given array. The cleanup
John McCall2673c682011-07-11 08:38:19 +00001581/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001582///
John McCallbdc4d802011-07-09 01:37:26 +00001583/// \param elementType - the immediate element type of the array;
1584/// possibly still an array type
John McCall9928c482011-07-12 16:41:08 +00001585void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall2673c682011-07-11 08:38:19 +00001586 llvm::Value *arrayEndPointer,
1587 QualType elementType,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001588 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001589 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1590 arrayBegin, arrayEndPointer,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001591 elementType, destroyer);
John McCall2673c682011-07-11 08:38:19 +00001592}
1593
1594/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1595/// already-constructed elements of the given array. The cleanup
1596/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001597///
John McCall2673c682011-07-11 08:38:19 +00001598/// \param elementType - the immediate element type of the array;
1599/// possibly still an array type
John McCall2673c682011-07-11 08:38:19 +00001600void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1601 llvm::Value *arrayEnd,
1602 QualType elementType,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001603 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001604 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall2673c682011-07-11 08:38:19 +00001605 arrayBegin, arrayEnd,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001606 elementType, destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001607}
1608
Nadav Rotem495cfa42013-03-23 06:43:35 +00001609/// Lazily declare the @llvm.lifetime.start intrinsic.
1610llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1611 if (LifetimeStartFn) return LifetimeStartFn;
1612 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1613 llvm::Intrinsic::lifetime_start);
1614 return LifetimeStartFn;
1615}
1616
1617/// Lazily declare the @llvm.lifetime.end intrinsic.
1618llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1619 if (LifetimeEndFn) return LifetimeEndFn;
1620 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1621 llvm::Intrinsic::lifetime_end);
1622 return LifetimeEndFn;
1623}
1624
John McCallf85e1932011-06-15 23:02:42 +00001625namespace {
1626 /// A cleanup to perform a release of an object at the end of a
1627 /// function. This is used to balance out the incoming +1 of a
1628 /// ns_consumed argument when we can't reasonably do that just by
1629 /// not doing the initial retain for a __block argument.
1630 struct ConsumeARCParameter : EHScopeStack::Cleanup {
John McCall5b07e802013-03-13 03:10:54 +00001631 ConsumeARCParameter(llvm::Value *param,
1632 ARCPreciseLifetime_t precise)
1633 : Param(param), Precise(precise) {}
John McCallf85e1932011-06-15 23:02:42 +00001634
1635 llvm::Value *Param;
John McCall5b07e802013-03-13 03:10:54 +00001636 ARCPreciseLifetime_t Precise;
John McCallf85e1932011-06-15 23:02:42 +00001637
John McCallad346f42011-07-12 20:27:29 +00001638 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall5b07e802013-03-13 03:10:54 +00001639 CGF.EmitARCRelease(Param, Precise);
John McCallf85e1932011-06-15 23:02:42 +00001640 }
1641 };
1642}
1643
Mike Stump1eb44332009-09-09 15:08:12 +00001644/// Emit an alloca (or GlobalValue depending on target)
Chris Lattner2621fd12008-05-08 05:58:21 +00001645/// for the specified parameter and set up LocalDeclMap.
Devang Patel093ac462011-03-03 20:13:15 +00001646void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1647 unsigned ArgNo) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001648 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00001649 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001650 "Invalid argument to EmitParmDecl");
John McCall8178df32011-02-22 22:38:33 +00001651
1652 Arg->setName(D.getName());
1653
Adrian Prantl836e7c92013-03-14 17:53:33 +00001654 QualType Ty = D.getType();
1655
John McCall8178df32011-02-22 22:38:33 +00001656 // Use better IR generation for certain implicit parameters.
1657 if (isa<ImplicitParamDecl>(D)) {
1658 // The only implicit argument a block has is its literal.
1659 if (BlockInfo) {
1660 LocalDeclMap[&D] = Arg;
Adrian Prantl836e7c92013-03-14 17:53:33 +00001661 llvm::Value *LocalAddr = 0;
1662 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001663 // Allocate a stack slot to let the debug info survive the RA.
Adrian Prantl836e7c92013-03-14 17:53:33 +00001664 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1665 D.getName() + ".addr");
1666 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1667 LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1668 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1669 LocalAddr = Builder.CreateLoad(Alloc);
1670 }
John McCall8178df32011-02-22 22:38:33 +00001671
1672 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +00001673 if (CGM.getCodeGenOpts().getDebugInfo()
1674 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001675 DI->setLocation(D.getLocation());
Adrian Prantl836e7c92013-03-14 17:53:33 +00001676 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, LocalAddr, Builder);
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001677 }
John McCall8178df32011-02-22 22:38:33 +00001678 }
1679
1680 return;
1681 }
1682 }
1683
Reid Spencer5f016e22007-07-11 17:01:13 +00001684 llvm::Value *DeclPtr;
Reid Kleckner9b601952013-06-21 12:45:15 +00001685 bool HasNonScalarEvalKind = !CodeGenFunction::hasScalarEvaluationKind(Ty);
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001686 // If this is an aggregate or variable sized value, reuse the input pointer.
Reid Kleckner9b601952013-06-21 12:45:15 +00001687 if (HasNonScalarEvalKind || !Ty->isConstantSizeType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001688 DeclPtr = Arg;
Reid Kleckner9b601952013-06-21 12:45:15 +00001689 // Push a destructor cleanup for this parameter if the ABI requires it.
1690 if (HasNonScalarEvalKind &&
1691 getTarget().getCXXABI().isArgumentDestroyedByCallee()) {
1692 if (const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl()) {
1693 if (RD->hasNonTrivialDestructor())
1694 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
1695 }
1696 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 } else {
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001698 // Otherwise, create a temporary to hold the value.
Eli Friedmanddfb8d12011-11-03 20:31:28 +00001699 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1700 D.getName() + ".addr");
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001701 CharUnits Align = getContext().getDeclAlign(&D);
1702 Alloc->setAlignment(Align.getQuantity());
Eli Friedmanddfb8d12011-11-03 20:31:28 +00001703 DeclPtr = Alloc;
Mike Stump1eb44332009-09-09 15:08:12 +00001704
John McCallf85e1932011-06-15 23:02:42 +00001705 bool doStore = true;
1706
1707 Qualifiers qs = Ty.getQualifiers();
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001708 LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
John McCallf85e1932011-06-15 23:02:42 +00001709 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1710 // We honor __attribute__((ns_consumed)) for types with lifetime.
1711 // For __strong, it's handled by just skipping the initial retain;
1712 // otherwise we have to balance out the initial +1 with an extra
1713 // cleanup to do the release at the end of the function.
1714 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1715
1716 // 'self' is always formally __strong, but if this is not an
1717 // init method then we don't want to retain it.
John McCall7acddac2011-06-17 06:42:21 +00001718 if (D.isARCPseudoStrong()) {
John McCallf85e1932011-06-15 23:02:42 +00001719 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1720 assert(&D == method->getSelfDecl());
John McCall7acddac2011-06-17 06:42:21 +00001721 assert(lt == Qualifiers::OCL_Strong);
1722 assert(qs.hasConst());
John McCallf85e1932011-06-15 23:02:42 +00001723 assert(method->getMethodFamily() != OMF_init);
John McCall175d6592011-06-15 23:40:09 +00001724 (void) method;
John McCallf85e1932011-06-15 23:02:42 +00001725 lt = Qualifiers::OCL_ExplicitNone;
1726 }
1727
1728 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001729 if (!isConsumed) {
1730 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1731 // use objc_storeStrong(&dest, value) for retaining the
1732 // object. But first, store a null into 'dest' because
1733 // objc_storeStrong attempts to release its old value.
1734 llvm::Value * Null = CGM.EmitNullConstant(D.getType());
1735 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1736 EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
1737 doStore = false;
1738 }
1739 else
John McCallf85e1932011-06-15 23:02:42 +00001740 // Don't use objc_retainBlock for block pointers, because we
1741 // don't want to Block_copy something just because we got it
1742 // as a parameter.
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001743 Arg = EmitARCRetainNonBlock(Arg);
1744 }
John McCallf85e1932011-06-15 23:02:42 +00001745 } else {
1746 // Push the cleanup for a consumed parameter.
John McCall5b07e802013-03-13 03:10:54 +00001747 if (isConsumed) {
1748 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1749 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1750 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1751 precise);
1752 }
John McCallf85e1932011-06-15 23:02:42 +00001753
1754 if (lt == Qualifiers::OCL_Weak) {
1755 EmitARCInitWeak(DeclPtr, Arg);
Chad Rosier7acebfb2012-02-18 01:20:35 +00001756 doStore = false; // The weak init is a store, no need to do two.
John McCallf85e1932011-06-15 23:02:42 +00001757 }
1758 }
1759
1760 // Enter the cleanup scope.
1761 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1762 }
1763
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001764 // Store the initial value into the alloca.
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001765 if (doStore)
David Chisnall7a7ee302012-01-16 17:27:18 +00001766 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001767 }
1768
1769 llvm::Value *&DMEntry = LocalDeclMap[&D];
1770 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1771 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +00001772
1773 // Emit debug info for param declaration.
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001774 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +00001775 if (CGM.getCodeGenOpts().getDebugInfo()
1776 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001777 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1778 }
1779 }
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001780
1781 if (D.hasAttr<AnnotateAttr>())
1782 EmitVarAnnotations(&D, DeclPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001783}