blob: 970f9781b7896bcef8f5e2afa436d9f15beb39a0 [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:
Larisse Voufoef4579c2013-08-06 01:03:05 +000040 case Decl::VarTemplateSpecialization:
41 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor08688ac2010-04-23 02:02:43 +000042 case Decl::TemplateTypeParm:
43 case Decl::UnresolvedUsingValue:
Sean Hunt9a555912010-05-30 07:21:58 +000044 case Decl::NonTypeTemplateParm:
Douglas Gregor08688ac2010-04-23 02:02:43 +000045 case Decl::CXXMethod:
46 case Decl::CXXConstructor:
47 case Decl::CXXDestructor:
48 case Decl::CXXConversion:
49 case Decl::Field:
John McCall76da55d2013-04-16 07:28:30 +000050 case Decl::MSProperty:
Francois Pichet41f5e662010-11-21 06:49:41 +000051 case Decl::IndirectField:
Douglas Gregor08688ac2010-04-23 02:02:43 +000052 case Decl::ObjCIvar:
Eric Christophere1f54902011-08-23 22:38:00 +000053 case Decl::ObjCAtDefsField:
Chris Lattneraa9fc462007-10-08 21:37:32 +000054 case Decl::ParmVar:
Douglas Gregor08688ac2010-04-23 02:02:43 +000055 case Decl::ImplicitParam:
56 case Decl::ClassTemplate:
Larisse Voufoef4579c2013-08-06 01:03:05 +000057 case Decl::VarTemplate:
Douglas Gregor08688ac2010-04-23 02:02:43 +000058 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +000059 case Decl::TypeAliasTemplate:
Douglas Gregor08688ac2010-04-23 02:02:43 +000060 case Decl::TemplateTemplateParm:
61 case Decl::ObjCMethod:
62 case Decl::ObjCCategory:
63 case Decl::ObjCProtocol:
64 case Decl::ObjCInterface:
65 case Decl::ObjCCategoryImpl:
66 case Decl::ObjCImplementation:
67 case Decl::ObjCProperty:
68 case Decl::ObjCCompatibleAlias:
Abramo Bagnara6206d532010-06-05 05:09:32 +000069 case Decl::AccessSpec:
Douglas Gregor08688ac2010-04-23 02:02:43 +000070 case Decl::LinkageSpec:
71 case Decl::ObjCPropertyImpl:
Douglas Gregor08688ac2010-04-23 02:02:43 +000072 case Decl::FileScopeAsm:
73 case Decl::Friend:
74 case Decl::FriendTemplate:
75 case Decl::Block:
Tareq A. Siraj6afcf882013-04-16 19:37:38 +000076 case Decl::Captured:
Francois Pichetaf0f4d02011-08-14 03:52:19 +000077 case Decl::ClassScopeFunctionSpecialization:
David Blaikie9faebd22013-05-20 04:58:53 +000078 case Decl::UsingShadow:
David Blaikieb219cfc2011-09-23 05:06:16 +000079 llvm_unreachable("Declaration should not be in declstmts!");
Reid Spencer5f016e22007-07-11 17:01:13 +000080 case Decl::Function: // void X();
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000081 case Decl::Record: // struct/union/class X;
Reid Spencer5f016e22007-07-11 17:01:13 +000082 case Decl::Enum: // enum X;
Mike Stump1eb44332009-09-09 15:08:12 +000083 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000084 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlsson7b0ca3f2009-12-03 17:26:31 +000085 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner4ae493c2011-02-18 02:08:43 +000086 case Decl::Label: // __label__ x;
Douglas Gregor15de72c2011-12-02 23:23:56 +000087 case Decl::Import:
Alexey Bataevc6400582013-03-22 06:34:35 +000088 case Decl::OMPThreadPrivate:
Michael Han684aa732013-02-22 17:15:32 +000089 case Decl::Empty:
Reid Spencer5f016e22007-07-11 17:01:13 +000090 // None of these decls require codegen support.
91 return;
David Blaikiec8c24272013-02-02 00:39:32 +000092
David Blaikiefc46ebc2013-05-20 22:50:41 +000093 case Decl::NamespaceAlias:
94 if (CGDebugInfo *DI = getDebugInfo())
95 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
96 return;
David Blaikie9faebd22013-05-20 04:58:53 +000097 case Decl::Using: // using X; [C++]
98 if (CGDebugInfo *DI = getDebugInfo())
99 DI->EmitUsingDecl(cast<UsingDecl>(D));
100 return;
David Blaikie957dac52013-04-22 06:13:21 +0000101 case Decl::UsingDirective: // using namespace X; [C++]
102 if (CGDebugInfo *DI = getDebugInfo())
103 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
104 return;
Daniel Dunbar662174c82008-08-29 17:28:43 +0000105 case Decl::Var: {
106 const VarDecl &VD = cast<VarDecl>(D);
John McCallb6bbcc92010-10-15 04:57:14 +0000107 assert(VD.isLocalVarDecl() &&
Daniel Dunbar662174c82008-08-29 17:28:43 +0000108 "Should not see file-scope variables inside a function!");
John McCallb6bbcc92010-10-15 04:57:14 +0000109 return EmitVarDecl(VD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000110 }
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Richard Smith162e1c12011-04-15 14:24:37 +0000112 case Decl::Typedef: // typedef int X;
113 case Decl::TypeAlias: { // using X = int; [C++0x]
114 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000115 QualType Ty = TD.getUnderlyingType();
Mike Stump1eb44332009-09-09 15:08:12 +0000116
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000117 if (Ty->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000118 EmitVariablyModifiedType(Ty);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000119 }
Daniel Dunbar662174c82008-08-29 17:28:43 +0000120 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000121}
122
John McCallb6bbcc92010-10-15 04:57:14 +0000123/// EmitVarDecl - This method handles emission of any variable declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000124/// inside a function, including static vars etc.
John McCallb6bbcc92010-10-15 04:57:14 +0000125void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000126 if (D.isStaticLocal()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000127 llvm::GlobalValue::LinkageTypes Linkage =
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000128 llvm::GlobalValue::InternalLinkage;
129
Eli Friedman7a36a592013-07-01 20:53:07 +0000130 // If the variable is externally visible, it must have weak linkage so it
131 // can be uniqued.
Rafael Espindola9610d772013-06-17 20:04:51 +0000132 if (D.isExternallyVisible()) {
Eli Friedman7a36a592013-07-01 20:53:07 +0000133 Linkage = llvm::GlobalValue::LinkOnceODRLinkage;
Eli Friedman07369dd2013-07-01 20:22:57 +0000134
135 // FIXME: We need to force the emission/use of a guard variable for
136 // some variables even if we can constant-evaluate them because
137 // we can't guarantee every translation unit will constant-evaluate them.
Eli Friedman678eca42013-06-13 21:50:44 +0000138 }
Eric Christophere1f54902011-08-23 22:38:00 +0000139
John McCallb6bbcc92010-10-15 04:57:14 +0000140 return EmitStaticVarDecl(D, Linkage);
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000141 }
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000142
143 if (D.hasExternalStorage())
Lauro Ramos Venanciofea90b82008-02-16 22:30:38 +0000144 // Don't emit it now, allow it to be emitted lazily on its first use.
145 return;
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000146
Enea Zaffanella713e3f22013-05-16 11:27:56 +0000147 if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
148 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
149
150 assert(D.hasLocalStorage());
151 return EmitAutoVarDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000152}
153
Chris Lattner761acc12009-12-05 08:22:11 +0000154static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
155 const char *Separator) {
156 CodeGenModule &CGM = CGF.CGM;
Richard Smith7edf9e32012-11-01 22:30:59 +0000157 if (CGF.getLangOpts().CPlusPlus) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000158 StringRef Name = CGM.getMangledName(&D);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000159 return Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000160 }
Eric Christophere1f54902011-08-23 22:38:00 +0000161
Chris Lattner761acc12009-12-05 08:22:11 +0000162 std::string ContextName;
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000163 if (!CGF.CurFuncDecl) {
164 // Better be in a block declared in global scope.
165 const NamedDecl *ND = cast<NamedDecl>(&D);
166 const DeclContext *DC = ND->getDeclContext();
167 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
168 MangleBuffer Name;
Peter Collingbourne14110472011-01-13 18:57:25 +0000169 CGM.getBlockMangledName(GlobalDecl(), Name, BD);
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000170 ContextName = Name.getString();
171 }
172 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000173 llvm_unreachable("Unknown context for block static var decl");
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000174 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000175 StringRef Name = CGM.getMangledName(FD);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000176 ContextName = Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000177 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattner761acc12009-12-05 08:22:11 +0000178 ContextName = CGF.CurFn->getName();
179 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000180 llvm_unreachable("Unknown context for static var decl");
Eric Christophere1f54902011-08-23 22:38:00 +0000181
Chris Lattner761acc12009-12-05 08:22:11 +0000182 return ContextName + Separator + D.getNameAsString();
183}
184
Chandler Carruth0f30a122012-03-30 19:44:53 +0000185llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000186CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
187 const char *Separator,
188 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000189 QualType Ty = D.getType();
Eli Friedman3c2b3172008-02-15 12:20:59 +0000190 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000191
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000192 // Use the label if the variable is renamed with the asm-label extension.
193 std::string Name;
Benjamin Kramerc3c8f222011-11-21 15:47:23 +0000194 if (D.hasAttr<AsmLabelAttr>())
195 Name = CGM.getMangledName(&D);
196 else
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000197 Name = GetStaticDeclName(*this, D, Separator);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000198
Chris Lattner2acc6e32011-07-18 04:24:23 +0000199 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Peter Collingbourne1aba7782012-08-28 20:37:10 +0000200 unsigned AddrSpace =
201 CGM.GetGlobalVarAddressSpace(&D, CGM.getContext().getTargetAddressSpace(Ty));
Anders Carlsson41f8a132009-09-26 18:16:06 +0000202 llvm::GlobalVariable *GV =
203 new llvm::GlobalVariable(CGM.getModule(), LTy,
204 Ty.isConstant(getContext()), Linkage,
Hans Wennborgde981f32012-06-28 08:01:44 +0000205 CGM.EmitNullConstant(D.getType()), Name, 0,
206 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourne1aba7782012-08-28 20:37:10 +0000207 AddrSpace);
Ken Dyck8b752f12010-01-27 17:10:57 +0000208 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Eli Friedman93cc5152013-06-17 21:51:45 +0000209 CGM.setGlobalVisibility(GV, &D);
Hans Wennborgde981f32012-06-28 08:01:44 +0000210
Richard Smith38afbc72013-04-13 02:43:54 +0000211 if (D.getTLSKind())
Hans Wennborgde981f32012-06-28 08:01:44 +0000212 CGM.setTLSMode(GV, D);
213
Anders Carlsson41f8a132009-09-26 18:16:06 +0000214 return GV;
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000215}
216
Richard Smith7ca48502012-02-13 22:16:19 +0000217/// hasNontrivialDestruction - Determine whether a type's destruction is
218/// non-trivial. If so, and the variable uses static initialization, we must
219/// register its destructor to run on exit.
220static bool hasNontrivialDestruction(QualType T) {
221 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
222 return RD && !RD->hasTrivialDestructor();
223}
224
Chandler Carruth0f30a122012-03-30 19:44:53 +0000225/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
226/// global variable that has already been created for it. If the initializer
227/// has a different type than GV does, this may free GV and return a different
228/// one. Otherwise it just returns GV.
229llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000230CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000231 llvm::GlobalVariable *GV) {
232 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCallbf40cb52010-07-15 23:40:35 +0000233
Chris Lattner761acc12009-12-05 08:22:11 +0000234 // If constant emission failed, then this should be a C++ static
235 // initializer.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000236 if (!Init) {
Richard Smith7edf9e32012-11-01 22:30:59 +0000237 if (!getLangOpts().CPlusPlus)
Chris Lattner761acc12009-12-05 08:22:11 +0000238 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall5cd91b52010-09-08 01:44:27 +0000239 else if (Builder.GetInsertBlock()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000240 // Since we have a static initializer, this global variable can't
Anders Carlsson071c8102010-01-26 04:02:23 +0000241 // be constant.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000242 GV->setConstant(false);
John McCall5cd91b52010-09-08 01:44:27 +0000243
Chandler Carruth0f30a122012-03-30 19:44:53 +0000244 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson071c8102010-01-26 04:02:23 +0000245 }
Chandler Carruth0f30a122012-03-30 19:44:53 +0000246 return GV;
Chris Lattner761acc12009-12-05 08:22:11 +0000247 }
John McCallbf40cb52010-07-15 23:40:35 +0000248
Chris Lattner761acc12009-12-05 08:22:11 +0000249 // The initializer may differ in type from the global. Rewrite
250 // the global to match the initializer. (We have to do this
251 // because some types, like unions, can't be completely represented
252 // in the LLVM type system.)
Chandler Carruth0f30a122012-03-30 19:44:53 +0000253 if (GV->getType()->getElementType() != Init->getType()) {
254 llvm::GlobalVariable *OldGV = GV;
255
256 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
257 OldGV->isConstant(),
258 OldGV->getLinkage(), Init, "",
259 /*InsertBefore*/ OldGV,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +0000260 OldGV->getThreadLocalMode(),
Chandler Carruth0f30a122012-03-30 19:44:53 +0000261 CGM.getContext().getTargetAddressSpace(D.getType()));
262 GV->setVisibility(OldGV->getVisibility());
Eric Christophere1f54902011-08-23 22:38:00 +0000263
Chris Lattner761acc12009-12-05 08:22:11 +0000264 // Steal the name of the old global
Chandler Carruth0f30a122012-03-30 19:44:53 +0000265 GV->takeName(OldGV);
Eric Christophere1f54902011-08-23 22:38:00 +0000266
Chris Lattner761acc12009-12-05 08:22:11 +0000267 // Replace all uses of the old global with the new global
Chandler Carruth0f30a122012-03-30 19:44:53 +0000268 llvm::Constant *NewPtrForOldDecl =
269 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
270 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christophere1f54902011-08-23 22:38:00 +0000271
Chris Lattner761acc12009-12-05 08:22:11 +0000272 // Erase the old global, since it is no longer used.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000273 OldGV->eraseFromParent();
Chris Lattner761acc12009-12-05 08:22:11 +0000274 }
Eric Christophere1f54902011-08-23 22:38:00 +0000275
Chandler Carruth0f30a122012-03-30 19:44:53 +0000276 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
277 GV->setInitializer(Init);
Richard Smith7ca48502012-02-13 22:16:19 +0000278
279 if (hasNontrivialDestruction(D.getType())) {
280 // We have a constant initializer, but a nontrivial destructor. We still
281 // need to perform a guarded "initialization" in order to register the
Richard Smitha9b21d22012-02-17 06:48:11 +0000282 // destructor.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000283 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith7ca48502012-02-13 22:16:19 +0000284 }
285
Chandler Carruth0f30a122012-03-30 19:44:53 +0000286 return GV;
Chris Lattner761acc12009-12-05 08:22:11 +0000287}
288
John McCallb6bbcc92010-10-15 04:57:14 +0000289void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000290 llvm::GlobalValue::LinkageTypes Linkage) {
Chandler Carruth0f30a122012-03-30 19:44:53 +0000291 llvm::Value *&DMEntry = LocalDeclMap[&D];
292 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
Mike Stump1eb44332009-09-09 15:08:12 +0000293
John McCall355bba72012-03-30 21:00:39 +0000294 // Check to see if we already have a global variable for this
295 // declaration. This can happen when double-emitting function
296 // bodies, e.g. with complete and base constructors.
297 llvm::Constant *addr =
298 CGM.getStaticLocalDeclAddress(&D);
299
300 llvm::GlobalVariable *var;
301 if (addr) {
302 var = cast<llvm::GlobalVariable>(addr->stripPointerCasts());
303 } else {
304 addr = var = CreateStaticVarDecl(D, ".", Linkage);
305 }
Daniel Dunbara985b312009-02-25 19:45:19 +0000306
Daniel Dunbare5731f82009-02-25 20:08:33 +0000307 // Store into LocalDeclMap before generating initializer to handle
308 // circular references.
John McCall355bba72012-03-30 21:00:39 +0000309 DMEntry = addr;
310 CGM.setStaticLocalDeclAddress(&D, addr);
Daniel Dunbare5731f82009-02-25 20:08:33 +0000311
John McCallfe67f3b2010-05-04 20:45:42 +0000312 // We can't have a VLA here, but we can have a pointer to a VLA,
313 // even though that doesn't really make any sense.
Eli Friedmanc62aad82009-04-20 03:54:15 +0000314 // Make sure to evaluate VLA bounds now so that we have them for later.
315 if (D.getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000316 EmitVariablyModifiedType(D.getType());
Eric Christophere1f54902011-08-23 22:38:00 +0000317
John McCall355bba72012-03-30 21:00:39 +0000318 // Save the type in case adding the initializer forces a type change.
319 llvm::Type *expectedType = addr->getType();
Eli Friedmanc62aad82009-04-20 03:54:15 +0000320
Chris Lattner761acc12009-12-05 08:22:11 +0000321 // If this value has an initializer, emit it.
322 if (D.getInit())
John McCall355bba72012-03-30 21:00:39 +0000323 var = AddInitializerToStaticVarDecl(D, var);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000324
John McCall355bba72012-03-30 21:00:39 +0000325 var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Chris Lattner0af95232010-03-10 23:59:59 +0000326
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000327 if (D.hasAttr<AnnotateAttr>())
John McCall355bba72012-03-30 21:00:39 +0000328 CGM.AddGlobalAnnotations(&D, var);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000329
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000330 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCall355bba72012-03-30 21:00:39 +0000331 var->setSection(SA->getName());
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000333 if (D.hasAttr<UsedAttr>())
John McCall355bba72012-03-30 21:00:39 +0000334 CGM.AddUsedGlobal(var);
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000335
Chandler Carruth0f30a122012-03-30 19:44:53 +0000336 // We may have to cast the constant because of the initializer
337 // mismatch above.
338 //
339 // FIXME: It is really dangerous to store this in the map; if anyone
340 // RAUW's the GV uses of this constant will be invalid.
John McCall355bba72012-03-30 21:00:39 +0000341 llvm::Constant *castedAddr = llvm::ConstantExpr::getBitCast(var, expectedType);
342 DMEntry = castedAddr;
343 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000344
345 // Emit global variable debug descriptor for static vars.
Anders Carlssone896d982009-02-13 08:11:52 +0000346 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000347 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +0000348 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000349 DI->setLocation(D.getLocation());
John McCall355bba72012-03-30 21:00:39 +0000350 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000351 }
Anders Carlsson1a86b332007-10-17 00:52:43 +0000352}
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCallda65ea82010-07-13 20:32:21 +0000354namespace {
John McCallbdc4d802011-07-09 01:37:26 +0000355 struct DestroyObject : EHScopeStack::Cleanup {
356 DestroyObject(llvm::Value *addr, QualType type,
John McCall2673c682011-07-11 08:38:19 +0000357 CodeGenFunction::Destroyer *destroyer,
358 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000359 : addr(addr), type(type), destroyer(destroyer),
John McCall2673c682011-07-11 08:38:19 +0000360 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallda65ea82010-07-13 20:32:21 +0000361
John McCallbdc4d802011-07-09 01:37:26 +0000362 llvm::Value *addr;
363 QualType type;
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000364 CodeGenFunction::Destroyer *destroyer;
John McCall2673c682011-07-11 08:38:19 +0000365 bool useEHCleanupForArray;
John McCallda65ea82010-07-13 20:32:21 +0000366
John McCallad346f42011-07-12 20:27:29 +0000367 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +0000368 // Don't use an EH cleanup recursively from an EH cleanup.
John McCallad346f42011-07-12 20:27:29 +0000369 bool useEHCleanupForArray =
370 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall2673c682011-07-11 08:38:19 +0000371
372 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCallda65ea82010-07-13 20:32:21 +0000373 }
374 };
375
John McCallbdc4d802011-07-09 01:37:26 +0000376 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
377 DestroyNRVOVariable(llvm::Value *addr,
378 const CXXDestructorDecl *Dtor,
379 llvm::Value *NRVOFlag)
380 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCallda65ea82010-07-13 20:32:21 +0000381
382 const CXXDestructorDecl *Dtor;
383 llvm::Value *NRVOFlag;
384 llvm::Value *Loc;
385
John McCallad346f42011-07-12 20:27:29 +0000386 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallda65ea82010-07-13 20:32:21 +0000387 // Along the exceptions path we always execute the dtor.
John McCallad346f42011-07-12 20:27:29 +0000388 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCallda65ea82010-07-13 20:32:21 +0000389
390 llvm::BasicBlock *SkipDtorBB = 0;
391 if (NRVO) {
392 // If we exited via NRVO, we skip the destructor call.
393 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
394 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
395 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
396 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
397 CGF.EmitBlock(RunDtorBB);
398 }
Eric Christophere1f54902011-08-23 22:38:00 +0000399
John McCallda65ea82010-07-13 20:32:21 +0000400 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +0000401 /*ForVirtualBase=*/false,
402 /*Delegating=*/false,
403 Loc);
John McCallda65ea82010-07-13 20:32:21 +0000404
405 if (NRVO) CGF.EmitBlock(SkipDtorBB);
406 }
407 };
John McCallda65ea82010-07-13 20:32:21 +0000408
John McCall1f0fca52010-07-21 07:22:38 +0000409 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000410 llvm::Value *Stack;
411 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
John McCallad346f42011-07-12 20:27:29 +0000412 void Emit(CodeGenFunction &CGF, Flags flags) {
Benjamin Kramer578faa82011-09-27 21:06:10 +0000413 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalld8715092010-07-21 06:13:08 +0000414 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
415 CGF.Builder.CreateCall(F, V);
416 }
417 };
418
John McCall0c24c802011-06-24 23:21:27 +0000419 struct ExtendGCLifetime : EHScopeStack::Cleanup {
420 const VarDecl &Var;
421 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
422
John McCallad346f42011-07-12 20:27:29 +0000423 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall0c24c802011-06-24 23:21:27 +0000424 // Compute the address of the local variable, in case it's a
425 // byref or something.
John McCallf4b88a42012-03-10 09:33:50 +0000426 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
427 Var.getType(), VK_LValue, SourceLocation());
John McCall0c24c802011-06-24 23:21:27 +0000428 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
429 CGF.EmitExtendGCLifetime(value);
430 }
431 };
432
John McCall1f0fca52010-07-21 07:22:38 +0000433 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000434 llvm::Constant *CleanupFn;
435 const CGFunctionInfo &FnInfo;
John McCalld8715092010-07-21 06:13:08 +0000436 const VarDecl &Var;
Eric Christophere1f54902011-08-23 22:38:00 +0000437
John McCalld8715092010-07-21 06:13:08 +0000438 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCall34695852011-02-22 06:44:22 +0000439 const VarDecl *Var)
440 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalld8715092010-07-21 06:13:08 +0000441
John McCallad346f42011-07-12 20:27:29 +0000442 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf4b88a42012-03-10 09:33:50 +0000443 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
444 Var.getType(), VK_LValue, SourceLocation());
John McCall34695852011-02-22 06:44:22 +0000445 // Compute the address of the local variable, in case it's a byref
446 // or something.
447 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
448
John McCalld8715092010-07-21 06:13:08 +0000449 // In some cases, the type of the function argument will be different from
450 // the type of the pointer. An example of this is
451 // void f(void* arg);
452 // __attribute__((cleanup(f))) void *g;
453 //
454 // To fix this we insert a bitcast here.
455 QualType ArgTy = FnInfo.arg_begin()->type;
456 llvm::Value *Arg =
457 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
458
459 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000460 Args.add(RValue::get(Arg),
461 CGF.getContext().getPointerType(Var.getType()));
John McCalld8715092010-07-21 06:13:08 +0000462 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
463 }
464 };
Nadav Rotem495cfa42013-03-23 06:43:35 +0000465
466 /// A cleanup to call @llvm.lifetime.end.
467 class CallLifetimeEnd : public EHScopeStack::Cleanup {
468 llvm::Value *Addr;
469 llvm::Value *Size;
470 public:
471 CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
472 : Addr(addr), Size(size) {}
473
474 void Emit(CodeGenFunction &CGF, Flags flags) {
475 llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
476 CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
477 Size, castAddr)
478 ->setDoesNotThrow();
479 }
480 };
John McCalld8715092010-07-21 06:13:08 +0000481}
482
John McCallf85e1932011-06-15 23:02:42 +0000483/// EmitAutoVarWithLifetime - Does the setup required for an automatic
484/// variable with lifetime.
485static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
486 llvm::Value *addr,
487 Qualifiers::ObjCLifetime lifetime) {
488 switch (lifetime) {
489 case Qualifiers::OCL_None:
490 llvm_unreachable("present but none");
491
492 case Qualifiers::OCL_ExplicitNone:
493 // nothing to do
494 break;
495
496 case Qualifiers::OCL_Strong: {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000497 CodeGenFunction::Destroyer *destroyer =
John McCall9928c482011-07-12 16:41:08 +0000498 (var.hasAttr<ObjCPreciseLifetimeAttr>()
499 ? CodeGenFunction::destroyARCStrongPrecise
500 : CodeGenFunction::destroyARCStrongImprecise);
501
502 CleanupKind cleanupKind = CGF.getARCCleanupKind();
503 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
504 cleanupKind & EHCleanup);
John McCallf85e1932011-06-15 23:02:42 +0000505 break;
506 }
507 case Qualifiers::OCL_Autoreleasing:
508 // nothing to do
509 break;
Eric Christophere1f54902011-08-23 22:38:00 +0000510
John McCallf85e1932011-06-15 23:02:42 +0000511 case Qualifiers::OCL_Weak:
512 // __weak objects always get EH cleanups; otherwise, exceptions
513 // could cause really nasty crashes instead of mere leaks.
John McCall9928c482011-07-12 16:41:08 +0000514 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
515 CodeGenFunction::destroyARCWeak,
516 /*useEHCleanup*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000517 break;
518 }
519}
520
521static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
522 if (const Expr *e = dyn_cast<Expr>(s)) {
523 // Skip the most common kinds of expressions that make
524 // hierarchy-walking expensive.
525 s = e = e->IgnoreParenCasts();
526
527 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
528 return (ref->getDecl() == &var);
Fariborz Jahanianddfc8a12012-06-19 20:53:26 +0000529 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
530 const BlockDecl *block = be->getBlockDecl();
531 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
532 e = block->capture_end(); i != e; ++i) {
533 if (i->getVariable() == &var)
534 return true;
535 }
536 }
John McCallf85e1932011-06-15 23:02:42 +0000537 }
538
539 for (Stmt::const_child_range children = s->children(); children; ++children)
Fariborz Jahanian8fefc8e2011-06-29 20:00:16 +0000540 // children might be null; as in missing decl or conditional of an if-stmt.
541 if ((*children) && isAccessedBy(var, *children))
John McCallf85e1932011-06-15 23:02:42 +0000542 return true;
543
544 return false;
545}
546
547static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
548 if (!decl) return false;
549 if (!isa<VarDecl>(decl)) return false;
550 const VarDecl *var = cast<VarDecl>(decl);
551 return isAccessedBy(*var, e);
552}
553
John McCalla07398e2011-06-16 04:16:24 +0000554static void drillIntoBlockVariable(CodeGenFunction &CGF,
555 LValue &lvalue,
556 const VarDecl *var) {
557 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
558}
559
John McCallf85e1932011-06-15 23:02:42 +0000560void CodeGenFunction::EmitScalarInit(const Expr *init,
561 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +0000562 LValue lvalue,
563 bool capturedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000564 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCallf85e1932011-06-15 23:02:42 +0000565 if (!lifetime) {
566 llvm::Value *value = EmitScalarExpr(init);
John McCalla07398e2011-06-16 04:16:24 +0000567 if (capturedByInit)
568 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +0000569 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCallf85e1932011-06-15 23:02:42 +0000570 return;
571 }
572
573 // If we're emitting a value with lifetime, we have to do the
574 // initialization *before* we leave the cleanup scopes.
John McCall1a343eb2011-11-10 08:15:53 +0000575 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
576 enterFullExpression(ewc);
John McCallf85e1932011-06-15 23:02:42 +0000577 init = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +0000578 }
579 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCallf85e1932011-06-15 23:02:42 +0000580
581 // We have to maintain the illusion that the variable is
582 // zero-initialized. If the variable might be accessed in its
583 // initializer, zero-initialize before running the initializer, then
584 // actually perform the initialization with an assign.
585 bool accessedByInit = false;
586 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallfb720812011-07-28 07:23:35 +0000587 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCallf85e1932011-06-15 23:02:42 +0000588 if (accessedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000589 LValue tempLV = lvalue;
John McCallf85e1932011-06-15 23:02:42 +0000590 // Drill down to the __block object if necessary.
John McCallf85e1932011-06-15 23:02:42 +0000591 if (capturedByInit) {
592 // We can use a simple GEP for this because it can't have been
593 // moved yet.
John McCalla07398e2011-06-16 04:16:24 +0000594 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
595 getByRefValueLLVMField(cast<VarDecl>(D))));
John McCallf85e1932011-06-15 23:02:42 +0000596 }
597
Chris Lattner2acc6e32011-07-18 04:24:23 +0000598 llvm::PointerType *ty
John McCalla07398e2011-06-16 04:16:24 +0000599 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
John McCallf85e1932011-06-15 23:02:42 +0000600 ty = cast<llvm::PointerType>(ty->getElementType());
601
602 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000603
John McCallf85e1932011-06-15 23:02:42 +0000604 // If __weak, we want to use a barrier under certain conditions.
605 if (lifetime == Qualifiers::OCL_Weak)
John McCalla07398e2011-06-16 04:16:24 +0000606 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCallf85e1932011-06-15 23:02:42 +0000607
608 // Otherwise just do a simple store.
609 else
David Chisnall7a7ee302012-01-16 17:27:18 +0000610 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000611 }
612
613 // Emit the initializer.
614 llvm::Value *value = 0;
615
616 switch (lifetime) {
617 case Qualifiers::OCL_None:
618 llvm_unreachable("present but none");
619
620 case Qualifiers::OCL_ExplicitNone:
621 // nothing to do
622 value = EmitScalarExpr(init);
623 break;
624
625 case Qualifiers::OCL_Strong: {
626 value = EmitARCRetainScalarExpr(init);
627 break;
628 }
629
630 case Qualifiers::OCL_Weak: {
631 // No way to optimize a producing initializer into this. It's not
632 // worth optimizing for, because the value will immediately
633 // disappear in the common case.
634 value = EmitScalarExpr(init);
635
John McCalla07398e2011-06-16 04:16:24 +0000636 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000637 if (accessedByInit)
John McCalla07398e2011-06-16 04:16:24 +0000638 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000639 else
John McCalla07398e2011-06-16 04:16:24 +0000640 EmitARCInitWeak(lvalue.getAddress(), value);
John McCallf85e1932011-06-15 23:02:42 +0000641 return;
642 }
643
644 case Qualifiers::OCL_Autoreleasing:
645 value = EmitARCRetainAutoreleaseScalarExpr(init);
646 break;
647 }
648
John McCalla07398e2011-06-16 04:16:24 +0000649 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000650
651 // If the variable might have been accessed by its initializer, we
652 // might have to initialize with a barrier. We have to do this for
653 // both __weak and __strong, but __weak got filtered out above.
654 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
John McCalla07398e2011-06-16 04:16:24 +0000655 llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
David Chisnall7a7ee302012-01-16 17:27:18 +0000656 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall5b07e802013-03-13 03:10:54 +0000657 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +0000658 return;
659 }
660
David Chisnall7a7ee302012-01-16 17:27:18 +0000661 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000662}
Chris Lattner94cd0112010-12-01 02:05:19 +0000663
John McCall7acddac2011-06-17 06:42:21 +0000664/// EmitScalarInit - Initialize the given lvalue with the given object.
665void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
666 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
667 if (!lifetime)
David Chisnall7a7ee302012-01-16 17:27:18 +0000668 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCall7acddac2011-06-17 06:42:21 +0000669
670 switch (lifetime) {
671 case Qualifiers::OCL_None:
672 llvm_unreachable("present but none");
673
674 case Qualifiers::OCL_ExplicitNone:
675 // nothing to do
676 break;
677
678 case Qualifiers::OCL_Strong:
679 init = EmitARCRetain(lvalue.getType(), init);
680 break;
681
682 case Qualifiers::OCL_Weak:
683 // Initialize and then skip the primitive store.
684 EmitARCInitWeak(lvalue.getAddress(), init);
685 return;
686
687 case Qualifiers::OCL_Autoreleasing:
688 init = EmitARCRetainAutorelease(lvalue.getType(), init);
689 break;
690 }
691
David Chisnall7a7ee302012-01-16 17:27:18 +0000692 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCall7acddac2011-06-17 06:42:21 +0000693}
694
Chris Lattner94cd0112010-12-01 02:05:19 +0000695/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
696/// non-zero parts of the specified initializer with equal or fewer than
697/// NumStores scalar stores.
698static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
699 unsigned &NumStores) {
Chris Lattner70b02942010-12-02 01:58:41 +0000700 // Zero and Undef never requires any extra stores.
701 if (isa<llvm::ConstantAggregateZero>(Init) ||
702 isa<llvm::ConstantPointerNull>(Init) ||
703 isa<llvm::UndefValue>(Init))
704 return true;
705 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
706 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
707 isa<llvm::ConstantExpr>(Init))
708 return Init->isNullValue() || NumStores--;
709
710 // See if we can emit each element.
711 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
712 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
713 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
714 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
715 return false;
716 }
717 return true;
718 }
Chris Lattnerf492cb12012-01-31 04:36:19 +0000719
720 if (llvm::ConstantDataSequential *CDS =
721 dyn_cast<llvm::ConstantDataSequential>(Init)) {
722 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
723 llvm::Constant *Elt = CDS->getElementAsConstant(i);
724 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
725 return false;
726 }
727 return true;
728 }
Eric Christophere1f54902011-08-23 22:38:00 +0000729
Chris Lattner94cd0112010-12-01 02:05:19 +0000730 // Anything else is hard and scary.
731 return false;
732}
733
734/// emitStoresForInitAfterMemset - For inits that
735/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
736/// stores that would be required.
737static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCall34695852011-02-22 06:44:22 +0000738 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer06d43682012-08-27 22:07:02 +0000739 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
740 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christophere1f54902011-08-23 22:38:00 +0000741
Chris Lattner70b02942010-12-02 01:58:41 +0000742 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
743 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
744 isa<llvm::ConstantExpr>(Init)) {
Chris Lattnerf492cb12012-01-31 04:36:19 +0000745 Builder.CreateStore(Init, Loc, isVolatile);
746 return;
747 }
748
749 if (llvm::ConstantDataSequential *CDS =
750 dyn_cast<llvm::ConstantDataSequential>(Init)) {
751 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
752 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramercfa07e32012-08-27 21:35:58 +0000753
754 // If necessary, get a pointer to the element and emit it.
755 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
756 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
757 isVolatile, Builder);
Chris Lattnerf492cb12012-01-31 04:36:19 +0000758 }
Chris Lattner70b02942010-12-02 01:58:41 +0000759 return;
760 }
Eric Christophere1f54902011-08-23 22:38:00 +0000761
Chris Lattner70b02942010-12-02 01:58:41 +0000762 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
763 "Unknown value type!");
Eric Christophere1f54902011-08-23 22:38:00 +0000764
Chris Lattner70b02942010-12-02 01:58:41 +0000765 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
766 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramercfa07e32012-08-27 21:35:58 +0000767
768 // If necessary, get a pointer to the element and emit it.
769 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
770 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
771 isVolatile, Builder);
Chris Lattner70b02942010-12-02 01:58:41 +0000772 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000773}
774
775
776/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
777/// plus some stores to initialize a local variable instead of using a memcpy
778/// from a constant global. It is beneficial to use memset if the global is all
779/// zeros, or mostly zeros and large.
780static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
781 uint64_t GlobalSize) {
782 // If a global is all zeros, always use a memset.
783 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
784
Chris Lattner94cd0112010-12-01 02:05:19 +0000785 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
786 // do it if it will require 6 or fewer scalar stores.
787 // TODO: Should budget depends on the size? Avoiding a large global warrants
788 // plopping in more stores.
789 unsigned StoreBudget = 6;
790 uint64_t SizeLimit = 32;
Eric Christophere1f54902011-08-23 22:38:00 +0000791
792 return GlobalSize > SizeLimit &&
Chris Lattner94cd0112010-12-01 02:05:19 +0000793 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
794}
795
Nadav Rotem495cfa42013-03-23 06:43:35 +0000796/// Should we use the LLVM lifetime intrinsics for the given local variable?
797static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
798 unsigned Size) {
Alexey Samsonov4f01ed42013-04-02 13:19:46 +0000799 // Always emit lifetime markers in -fsanitize=use-after-scope mode.
800 if (CGF.getLangOpts().Sanitize.UseAfterScope)
801 return true;
Nadav Rotem495cfa42013-03-23 06:43:35 +0000802 // For now, only in optimized builds.
803 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
804 return false;
805
806 // Limit the size of marked objects to 32 bytes. We don't want to increase
807 // compile time by marking tiny objects.
808 unsigned SizeThreshold = 32;
809
810 return Size > SizeThreshold;
811}
812
Chris Lattner94cd0112010-12-01 02:05:19 +0000813
Nick Lewyckya9de3fa2010-12-30 20:21:55 +0000814/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Reid Spencer5f016e22007-07-11 17:01:13 +0000815/// variable declaration with auto, register, or no storage class specifier.
Chris Lattner2621fd12008-05-08 05:58:21 +0000816/// These turn into simple stack objects, or GlobalValues depending on target.
John McCall34695852011-02-22 06:44:22 +0000817void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
818 AutoVarEmission emission = EmitAutoVarAlloca(D);
819 EmitAutoVarInit(emission);
820 EmitAutoVarCleanups(emission);
821}
Reid Spencer5f016e22007-07-11 17:01:13 +0000822
John McCall34695852011-02-22 06:44:22 +0000823/// EmitAutoVarAlloca - Emit the alloca and debug information for a
824/// local variable. Does not emit initalization or destruction.
825CodeGenFunction::AutoVarEmission
826CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
827 QualType Ty = D.getType();
828
829 AutoVarEmission emission(D);
830
831 bool isByRef = D.hasAttr<BlocksAttr>();
832 emission.IsByRef = isByRef;
833
834 CharUnits alignment = getContext().getDeclAlign(&D);
835 emission.Alignment = alignment;
836
John McCallbc8d40d2011-06-24 21:55:10 +0000837 // If the type is variably-modified, emit all the VLA sizes for it.
838 if (Ty->isVariablyModifiedType())
839 EmitVariablyModifiedType(Ty);
840
Reid Spencer5f016e22007-07-11 17:01:13 +0000841 llvm::Value *DeclPtr;
Eli Friedman3c2b3172008-02-15 12:20:59 +0000842 if (Ty->isConstantSizeType()) {
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000843 bool NRVO = getLangOpts().ElideConstructors &&
844 D.isNRVOVariable();
John McCall34695852011-02-22 06:44:22 +0000845
Richard Smithe67ca582013-06-02 00:09:52 +0000846 // If this value is an array or struct with a statically determinable
847 // constant initializer, there are optimizations we can do.
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000848 //
849 // TODO: We should constant-evaluate the initializer of any variable,
850 // as long as it is initialized by a constant expression. Currently,
851 // isConstantInitializer produces wrong answers for structs with
852 // reference or bitfield members, and a few other cases, and checking
853 // for POD-ness protects us from some of these.
Richard Smithe67ca582013-06-02 00:09:52 +0000854 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
855 (D.isConstexpr() ||
856 ((Ty.isPODType(getContext()) ||
857 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
858 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCall34695852011-02-22 06:44:22 +0000859
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000860 // If the variable's a const type, and it's neither an NRVO
861 // candidate nor a __block variable and has no mutable members,
862 // emit it as a global instead.
863 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
864 CGM.isTypeConstant(Ty, true)) {
865 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCall34695852011-02-22 06:44:22 +0000866
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000867 emission.Address = 0; // signal this condition to later callbacks
868 assert(emission.wasEmittedAsGlobal());
869 return emission;
Tanya Lattner59876c22009-11-04 01:18:09 +0000870 }
Eric Christophere1f54902011-08-23 22:38:00 +0000871
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000872 // Otherwise, tell the initialization code that we're in this case.
873 emission.IsConstantAggregate = true;
874 }
Eric Christophere1f54902011-08-23 22:38:00 +0000875
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000876 // A normal fixed sized variable becomes an alloca in the entry block,
877 // unless it's an NRVO variable.
878 llvm::Type *LTy = ConvertTypeForMem(Ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000879
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000880 if (NRVO) {
881 // The named return value optimization: allocate this variable in the
882 // return slot, so that we can elide the copy when returning this
883 // variable (C++0x [class.copy]p34).
884 DeclPtr = ReturnValue;
Eric Christophere1f54902011-08-23 22:38:00 +0000885
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000886 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
887 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
888 // Create a flag that is used to indicate when the NRVO was applied
889 // to this variable. Set it to zero to indicate that NRVO was not
890 // applied.
891 llvm::Value *Zero = Builder.getFalse();
892 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
893 EnsureInsertPoint();
894 Builder.CreateStore(Zero, NRVOFlag);
Eric Christophere1f54902011-08-23 22:38:00 +0000895
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000896 // Record the NRVO flag for this variable.
897 NRVOFlags[&D] = NRVOFlag;
898 emission.NRVOFlag = NRVOFlag;
Nadav Rotem495cfa42013-03-23 06:43:35 +0000899 }
Douglas Gregord86c4772010-05-15 06:46:45 +0000900 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000901 } else {
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000902 if (isByRef)
903 LTy = BuildByRefType(&D);
904
905 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
906 Alloc->setName(D.getName());
907
908 CharUnits allocaAlignment = alignment;
909 if (isByRef)
910 allocaAlignment = std::max(allocaAlignment,
John McCall64aa4b32013-04-16 22:48:15 +0000911 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000912 Alloc->setAlignment(allocaAlignment.getQuantity());
913 DeclPtr = Alloc;
914
915 // Emit a lifetime intrinsic if meaningful. There's no point
916 // in doing this if we don't have a valid insertion point (?).
917 uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
918 if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
919 llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
920
921 emission.SizeForLifetimeMarkers = sizeV;
922 llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
923 Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
924 ->setDoesNotThrow();
925 } else {
926 assert(!emission.useLifetimeMarkers());
927 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000928 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000929 } else {
Daniel Dunbard286f052009-07-19 06:58:07 +0000930 EnsureInsertPoint();
931
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000932 if (!DidCallStackSave) {
Anders Carlsson5d463152008-12-12 07:38:43 +0000933 // Save the stack.
John McCalld16c2cf2011-02-08 08:22:06 +0000934 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Anders Carlsson5d463152008-12-12 07:38:43 +0000936 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
937 llvm::Value *V = Builder.CreateCall(F);
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Anders Carlsson5d463152008-12-12 07:38:43 +0000939 Builder.CreateStore(V, Stack);
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000940
941 DidCallStackSave = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000942
John McCalld8715092010-07-21 06:13:08 +0000943 // Push a cleanup block and restore the stack there.
John McCall3ad32c82011-01-28 08:37:24 +0000944 // FIXME: in general circumstances, this should be an EH cleanup.
John McCall1f0fca52010-07-21 07:22:38 +0000945 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
Anders Carlsson5d463152008-12-12 07:38:43 +0000946 }
Mike Stump1eb44332009-09-09 15:08:12 +0000947
John McCallbc8d40d2011-06-24 21:55:10 +0000948 llvm::Value *elementCount;
949 QualType elementType;
950 llvm::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson5d463152008-12-12 07:38:43 +0000951
Chris Lattner2acc6e32011-07-18 04:24:23 +0000952 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson5d463152008-12-12 07:38:43 +0000953
954 // Allocate memory for the array.
John McCallbc8d40d2011-06-24 21:55:10 +0000955 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
956 vla->setAlignment(alignment.getQuantity());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000957
John McCallbc8d40d2011-06-24 21:55:10 +0000958 DeclPtr = vla;
Reid Spencer5f016e22007-07-11 17:01:13 +0000959 }
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000960
Reid Spencer5f016e22007-07-11 17:01:13 +0000961 llvm::Value *&DMEntry = LocalDeclMap[&D];
962 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
963 DMEntry = DeclPtr;
John McCall34695852011-02-22 06:44:22 +0000964 emission.Address = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000965
966 // Emit debug info for local var declaration.
Devang Patelc594abd2011-06-03 19:21:47 +0000967 if (HaveInsertPoint())
968 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +0000969 if (CGM.getCodeGenOpts().getDebugInfo()
970 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000971 DI->setLocation(D.getLocation());
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000972 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000973 }
Devang Patelc594abd2011-06-03 19:21:47 +0000974 }
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000975
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000976 if (D.hasAttr<AnnotateAttr>())
977 EmitVarAnnotations(&D, emission.Address);
978
John McCall34695852011-02-22 06:44:22 +0000979 return emission;
980}
981
982/// Determines whether the given __block variable is potentially
983/// captured by the given expression.
984static bool isCapturedBy(const VarDecl &var, const Expr *e) {
985 // Skip the most common kinds of expressions that make
986 // hierarchy-walking expensive.
987 e = e->IgnoreParenCasts();
988
989 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
990 const BlockDecl *block = be->getBlockDecl();
991 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
992 e = block->capture_end(); i != e; ++i) {
993 if (i->getVariable() == &var)
994 return true;
995 }
996
997 // No need to walk into the subexpressions.
998 return false;
999 }
1000
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001001 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1002 const CompoundStmt *CS = SE->getSubStmt();
Eric Christopherc6fad602011-08-23 23:44:09 +00001003 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1004 BE = CS->body_end(); BI != BE; ++BI)
Fariborz Jahanian045c8422011-08-25 00:06:26 +00001005 if (Expr *E = dyn_cast<Expr>((*BI))) {
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001006 if (isCapturedBy(var, E))
1007 return true;
Fariborz Jahanian045c8422011-08-25 00:06:26 +00001008 }
1009 else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
1010 // special case declarations
1011 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1012 I != E; ++I) {
1013 if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
1014 Expr *Init = VD->getInit();
1015 if (Init && isCapturedBy(var, Init))
1016 return true;
1017 }
1018 }
1019 }
1020 else
1021 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1022 // Later, provide code to poke into statements for capture analysis.
1023 return true;
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001024 return false;
1025 }
Eric Christophere1f54902011-08-23 22:38:00 +00001026
John McCall34695852011-02-22 06:44:22 +00001027 for (Stmt::const_child_range children = e->children(); children; ++children)
1028 if (isCapturedBy(var, cast<Expr>(*children)))
1029 return true;
1030
1031 return false;
1032}
1033
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001034/// \brief Determine whether the given initializer is trivial in the sense
1035/// that it requires no code to be generated.
1036static bool isTrivialInitializer(const Expr *Init) {
1037 if (!Init)
1038 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001039
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001040 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1041 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1042 if (Constructor->isTrivial() &&
1043 Constructor->isDefaultConstructor() &&
1044 !Construct->requiresZeroInitialization())
1045 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001046
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001047 return false;
1048}
John McCall34695852011-02-22 06:44:22 +00001049void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001050 assert(emission.Variable && "emission was not valid!");
1051
John McCall34695852011-02-22 06:44:22 +00001052 // If this was emitted as a global constant, we're done.
1053 if (emission.wasEmittedAsGlobal()) return;
1054
John McCall57b3b6a2011-02-22 07:16:58 +00001055 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001056 QualType type = D.getType();
1057
Chris Lattner19785962007-07-12 00:39:48 +00001058 // If this local has an initializer, emit it now.
Daniel Dunbard286f052009-07-19 06:58:07 +00001059 const Expr *Init = D.getInit();
1060
1061 // If we are at an unreachable point, we don't need to emit the initializer
1062 // unless it contains a label.
1063 if (!HaveInsertPoint()) {
John McCall34695852011-02-22 06:44:22 +00001064 if (!Init || !ContainsLabel(Init)) return;
1065 EnsureInsertPoint();
Daniel Dunbard286f052009-07-19 06:58:07 +00001066 }
1067
John McCall5af02db2011-03-31 01:59:53 +00001068 // Initialize the structure of a __block variable.
1069 if (emission.IsByRef)
1070 emitByrefStructureInit(emission);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001071
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001072 if (isTrivialInitializer(Init))
1073 return;
Eric Christophere1f54902011-08-23 22:38:00 +00001074
John McCall5af02db2011-03-31 01:59:53 +00001075 CharUnits alignment = emission.Alignment;
1076
John McCall34695852011-02-22 06:44:22 +00001077 // Check whether this is a byref variable that's potentially
1078 // captured and moved by its own initializer. If so, we'll need to
1079 // emit the initializer first, then copy into the variable.
1080 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1081
1082 llvm::Value *Loc =
1083 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1084
Richard Smith51201882011-12-30 21:15:51 +00001085 llvm::Constant *constant = 0;
Richard Smithe67ca582013-06-02 00:09:52 +00001086 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smith51201882011-12-30 21:15:51 +00001087 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smith2d6a5672012-01-14 04:30:29 +00001088 constant = CGM.EmitConstantInit(D, this);
Richard Smith51201882011-12-30 21:15:51 +00001089 }
1090
1091 if (!constant) {
Eli Friedman6da2c712011-12-03 04:14:32 +00001092 LValue lv = MakeAddrLValue(Loc, type, alignment);
John McCalla07398e2011-06-16 04:16:24 +00001093 lv.setNonGC(true);
1094 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1095 }
John McCall60d33652011-03-08 09:11:50 +00001096
Richard Smithe67ca582013-06-02 00:09:52 +00001097 if (!emission.IsConstantAggregate) {
1098 // For simple scalar/complex initialization, store the value directly.
1099 LValue lv = MakeAddrLValue(Loc, type, alignment);
1100 lv.setNonGC(true);
1101 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1102 }
1103
John McCall34695852011-02-22 06:44:22 +00001104 // If this is a simple aggregate initialization, we can optimize it
1105 // in various ways.
John McCall60d33652011-03-08 09:11:50 +00001106 bool isVolatile = type.isVolatileQualified();
John McCall34695852011-02-22 06:44:22 +00001107
John McCall60d33652011-03-08 09:11:50 +00001108 llvm::Value *SizeVal =
Eric Christophere1f54902011-08-23 22:38:00 +00001109 llvm::ConstantInt::get(IntPtrTy,
John McCall60d33652011-03-08 09:11:50 +00001110 getContext().getTypeSizeInChars(type).getQuantity());
John McCall34695852011-02-22 06:44:22 +00001111
Chris Lattner2acc6e32011-07-18 04:24:23 +00001112 llvm::Type *BP = Int8PtrTy;
John McCall60d33652011-03-08 09:11:50 +00001113 if (Loc->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001114 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wang3ecd7852010-04-04 03:10:52 +00001115
John McCall60d33652011-03-08 09:11:50 +00001116 // If the initializer is all or mostly zeros, codegen with memset then do
1117 // a few stores afterward.
Eric Christophere1f54902011-08-23 22:38:00 +00001118 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmow25a6a842012-10-08 16:25:52 +00001119 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall60d33652011-03-08 09:11:50 +00001120 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1121 alignment.getQuantity(), isVolatile);
Benjamin Kramer06d43682012-08-27 22:07:02 +00001122 // Zero and undef don't require a stores.
1123 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall60d33652011-03-08 09:11:50 +00001124 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1125 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001126 }
John McCall60d33652011-03-08 09:11:50 +00001127 } else {
Eric Christophere1f54902011-08-23 22:38:00 +00001128 // Otherwise, create a temporary global with the initializer then
John McCall60d33652011-03-08 09:11:50 +00001129 // memcpy from the global to the alloca.
1130 std::string Name = GetStaticDeclName(*this, D, ".");
1131 llvm::GlobalVariable *GV =
1132 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopher736a9c22011-08-24 00:33:55 +00001133 llvm::GlobalValue::PrivateLinkage,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +00001134 constant, Name);
John McCall60d33652011-03-08 09:11:50 +00001135 GV->setAlignment(alignment.getQuantity());
Eli Friedman460980d2011-05-27 22:32:55 +00001136 GV->setUnnamedAddr(true);
Eric Christophere1f54902011-08-23 22:38:00 +00001137
John McCall60d33652011-03-08 09:11:50 +00001138 llvm::Value *SrcPtr = GV;
1139 if (SrcPtr->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001140 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall60d33652011-03-08 09:11:50 +00001141
1142 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1143 isVolatile);
1144 }
1145}
1146
1147/// Emit an expression as an initializer for a variable at the given
1148/// location. The expression is not necessarily the normal
1149/// initializer for the variable, and the address is not necessarily
1150/// its normal location.
1151///
1152/// \param init the initializing expression
1153/// \param var the variable to act as if we're initializing
1154/// \param loc the address to initialize; its type is a pointer
1155/// to the LLVM mapping of the variable's type
1156/// \param alignment the alignment of the address
1157/// \param capturedByInit true if the variable is a __block variable
1158/// whose address is potentially changed by the initializer
1159void CodeGenFunction::EmitExprAsInit(const Expr *init,
John McCallf85e1932011-06-15 23:02:42 +00001160 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +00001161 LValue lvalue,
John McCall60d33652011-03-08 09:11:50 +00001162 bool capturedByInit) {
John McCallf85e1932011-06-15 23:02:42 +00001163 QualType type = D->getType();
John McCall60d33652011-03-08 09:11:50 +00001164
1165 if (type->isReferenceType()) {
Richard Smithd4ec5622013-06-12 23:38:09 +00001166 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christophere1f54902011-08-23 22:38:00 +00001167 if (capturedByInit)
John McCalla07398e2011-06-16 04:16:24 +00001168 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +00001169 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall9d232c82013-03-07 21:37:08 +00001170 return;
1171 }
1172 switch (getEvaluationKind(type)) {
1173 case TEK_Scalar:
John McCalla07398e2011-06-16 04:16:24 +00001174 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall9d232c82013-03-07 21:37:08 +00001175 return;
1176 case TEK_Complex: {
John McCall60d33652011-03-08 09:11:50 +00001177 ComplexPairTy complex = EmitComplexExpr(init);
John McCalla07398e2011-06-16 04:16:24 +00001178 if (capturedByInit)
1179 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall9d232c82013-03-07 21:37:08 +00001180 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1181 return;
1182 }
1183 case TEK_Aggregate:
John McCall9eda3ab2013-03-07 21:37:17 +00001184 if (type->isAtomicType()) {
1185 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1186 } else {
1187 // TODO: how can we delay here if D is captured by its initializer?
1188 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier649b4a12012-03-29 17:37:10 +00001189 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001190 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001191 AggValueSlot::IsNotAliased));
John McCall9eda3ab2013-03-07 21:37:17 +00001192 }
John McCall9d232c82013-03-07 21:37:08 +00001193 return;
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001194 }
John McCall9d232c82013-03-07 21:37:08 +00001195 llvm_unreachable("bad evaluation kind");
John McCall34695852011-02-22 06:44:22 +00001196}
John McCallf1549f62010-07-06 01:34:17 +00001197
John McCallbdc4d802011-07-09 01:37:26 +00001198/// Enter a destroy cleanup for the given local variable.
1199void CodeGenFunction::emitAutoVarTypeCleanup(
1200 const CodeGenFunction::AutoVarEmission &emission,
1201 QualType::DestructionKind dtorKind) {
1202 assert(dtorKind != QualType::DK_none);
1203
1204 // Note that for __block variables, we want to destroy the
1205 // original stack object, not the possibly forwarded object.
1206 llvm::Value *addr = emission.getObjectAddress(*this);
1207
1208 const VarDecl *var = emission.Variable;
1209 QualType type = var->getType();
1210
1211 CleanupKind cleanupKind = NormalAndEHCleanup;
1212 CodeGenFunction::Destroyer *destroyer = 0;
1213
1214 switch (dtorKind) {
1215 case QualType::DK_none:
1216 llvm_unreachable("no cleanup for trivially-destructible variable");
1217
1218 case QualType::DK_cxx_destructor:
1219 // If there's an NRVO flag on the emission, we need a different
1220 // cleanup.
1221 if (emission.NRVOFlag) {
1222 assert(!type->isArrayType());
1223 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1224 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1225 emission.NRVOFlag);
1226 return;
1227 }
1228 break;
1229
1230 case QualType::DK_objc_strong_lifetime:
1231 // Suppress cleanups for pseudo-strong variables.
1232 if (var->isARCPseudoStrong()) return;
Eric Christophere1f54902011-08-23 22:38:00 +00001233
John McCallbdc4d802011-07-09 01:37:26 +00001234 // Otherwise, consider whether to use an EH cleanup or not.
1235 cleanupKind = getARCCleanupKind();
1236
1237 // Use the imprecise destroyer by default.
1238 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1239 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1240 break;
1241
1242 case QualType::DK_objc_weak_lifetime:
1243 break;
1244 }
1245
1246 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001247 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall2673c682011-07-11 08:38:19 +00001248
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00001249 // Use an EH cleanup in array destructors iff the destructor itself
John McCall2673c682011-07-11 08:38:19 +00001250 // is being pushed as an EH cleanup.
1251 bool useEHCleanup = (cleanupKind & EHCleanup);
1252 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1253 useEHCleanup);
John McCallbdc4d802011-07-09 01:37:26 +00001254}
1255
John McCall34695852011-02-22 06:44:22 +00001256void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001257 assert(emission.Variable && "emission was not valid!");
1258
John McCall34695852011-02-22 06:44:22 +00001259 // If this was emitted as a global constant, we're done.
1260 if (emission.wasEmittedAsGlobal()) return;
1261
John McCall38baeab2012-04-13 18:44:05 +00001262 // If we don't have an insertion point, we're done. Sema prevents
1263 // us from jumping into any of these scopes anyway.
1264 if (!HaveInsertPoint()) return;
1265
John McCall57b3b6a2011-02-22 07:16:58 +00001266 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001267
Nadav Rotem495cfa42013-03-23 06:43:35 +00001268 // Make sure we call @llvm.lifetime.end. This needs to happen
1269 // *last*, so the cleanup needs to be pushed *first*.
1270 if (emission.useLifetimeMarkers()) {
1271 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1272 emission.getAllocatedAddress(),
1273 emission.getSizeForLifetimeMarkers());
1274 }
1275
John McCallbdc4d802011-07-09 01:37:26 +00001276 // Check the type for a cleanup.
1277 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1278 emitAutoVarTypeCleanup(emission, dtorKind);
John McCallf85e1932011-06-15 23:02:42 +00001279
John McCall0c24c802011-06-24 23:21:27 +00001280 // In GC mode, honor objc_precise_lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00001281 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall0c24c802011-06-24 23:21:27 +00001282 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1283 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1284 }
1285
John McCall34695852011-02-22 06:44:22 +00001286 // Handle the cleanup attribute.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001287 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlsson69c68b72009-02-07 23:51:38 +00001288 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001289
John McCall34695852011-02-22 06:44:22 +00001290 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001291 assert(F && "Could not find function!");
Mike Stump1eb44332009-09-09 15:08:12 +00001292
John McCallde5d3c72012-02-17 03:33:10 +00001293 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCall34695852011-02-22 06:44:22 +00001294 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001295 }
Mike Stump797b6322009-03-05 01:23:13 +00001296
John McCall34695852011-02-22 06:44:22 +00001297 // If this is a block variable, call _Block_object_destroy
1298 // (on the unforwarded address).
John McCall5af02db2011-03-31 01:59:53 +00001299 if (emission.IsByRef)
1300 enterByrefCleanup(emission);
Reid Spencer5f016e22007-07-11 17:01:13 +00001301}
1302
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001303CodeGenFunction::Destroyer *
John McCallbdc4d802011-07-09 01:37:26 +00001304CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1305 switch (kind) {
1306 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCall0850e8d2011-07-09 09:09:00 +00001307 case QualType::DK_cxx_destructor:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001308 return destroyCXXObject;
John McCall0850e8d2011-07-09 09:09:00 +00001309 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001310 return destroyARCStrongPrecise;
John McCall0850e8d2011-07-09 09:09:00 +00001311 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001312 return destroyARCWeak;
John McCallbdc4d802011-07-09 01:37:26 +00001313 }
Matt Beaumont-Gayba4be252012-01-27 00:46:27 +00001314 llvm_unreachable("Unknown DestructionKind");
John McCallbdc4d802011-07-09 01:37:26 +00001315}
1316
John McCall074cae02013-02-01 05:11:40 +00001317/// pushEHDestroy - Push the standard destructor for the given type as
1318/// an EH-only cleanup.
1319void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1320 llvm::Value *addr, QualType type) {
1321 assert(dtorKind && "cannot push destructor for trivial type");
1322 assert(needsEHCleanup(dtorKind));
1323
1324 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1325}
1326
1327/// pushDestroy - Push the standard destructor for the given type as
1328/// at least a normal cleanup.
John McCall9928c482011-07-12 16:41:08 +00001329void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1330 llvm::Value *addr, QualType type) {
1331 assert(dtorKind && "cannot push destructor for trivial type");
1332
1333 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1334 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1335 cleanupKind & EHCleanup);
1336}
1337
John McCallbdc4d802011-07-09 01:37:26 +00001338void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001339 QualType type, Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001340 bool useEHCleanupForArray) {
John McCall9928c482011-07-12 16:41:08 +00001341 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1342 destroyer, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001343}
1344
Richard Smith8a07cd32013-06-12 20:42:33 +00001345void CodeGenFunction::pushLifetimeExtendedDestroy(
1346 CleanupKind cleanupKind, llvm::Value *addr, QualType type,
1347 Destroyer *destroyer, bool useEHCleanupForArray) {
1348 assert(!isInConditionalBranch() &&
1349 "performing lifetime extension from within conditional");
1350
1351 // Push an EH-only cleanup for the object now.
1352 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1353 // around in case a temporary's destructor throws an exception.
1354 if (cleanupKind & EHCleanup)
1355 EHStack.pushCleanup<DestroyObject>(
1356 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1357 destroyer, useEHCleanupForArray);
1358
1359 // Remember that we need to push a full cleanup for the object at the
1360 // end of the full-expression.
1361 pushCleanupAfterFullExpr<DestroyObject>(
1362 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1363}
1364
John McCall2673c682011-07-11 08:38:19 +00001365/// emitDestroy - Immediately perform the destruction of the given
1366/// object.
1367///
1368/// \param addr - the address of the object; a type*
1369/// \param type - the type of the object; if an array type, all
1370/// objects are destroyed in reverse order
1371/// \param destroyer - the function to call to destroy individual
1372/// elements
1373/// \param useEHCleanupForArray - whether an EH cleanup should be
1374/// used when destroying array elements, in case one of the
1375/// destructions throws an exception
John McCallbdc4d802011-07-09 01:37:26 +00001376void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001377 Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001378 bool useEHCleanupForArray) {
John McCallbdc4d802011-07-09 01:37:26 +00001379 const ArrayType *arrayType = getContext().getAsArrayType(type);
1380 if (!arrayType)
1381 return destroyer(*this, addr, type);
1382
1383 llvm::Value *begin = addr;
1384 llvm::Value *length = emitArrayLength(arrayType, type, begin);
John McCallfbf780a2011-07-13 08:09:46 +00001385
1386 // Normally we have to check whether the array is zero-length.
1387 bool checkZeroLength = true;
1388
1389 // But if the array length is constant, we can suppress that.
1390 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1391 // ...and if it's constant zero, we can just skip the entire thing.
1392 if (constLength->isZero()) return;
1393 checkZeroLength = false;
1394 }
1395
John McCallbdc4d802011-07-09 01:37:26 +00001396 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCallfbf780a2011-07-13 08:09:46 +00001397 emitArrayDestroy(begin, end, type, destroyer,
1398 checkZeroLength, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001399}
1400
John McCall2673c682011-07-11 08:38:19 +00001401/// emitArrayDestroy - Destroys all the elements of the given array,
1402/// beginning from last to first. The array cannot be zero-length.
1403///
1404/// \param begin - a type* denoting the first element of the array
1405/// \param end - a type* denoting one past the end of the array
1406/// \param type - the element type of the array
1407/// \param destroyer - the function to call to destroy elements
1408/// \param useEHCleanup - whether to push an EH cleanup to destroy
1409/// the remaining elements in case the destruction of a single
1410/// element throws
John McCallbdc4d802011-07-09 01:37:26 +00001411void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1412 llvm::Value *end,
1413 QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001414 Destroyer *destroyer,
John McCallfbf780a2011-07-13 08:09:46 +00001415 bool checkZeroLength,
John McCall2673c682011-07-11 08:38:19 +00001416 bool useEHCleanup) {
John McCallbdc4d802011-07-09 01:37:26 +00001417 assert(!type->isArrayType());
1418
1419 // The basic structure here is a do-while loop, because we don't
1420 // need to check for the zero-element case.
1421 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1422 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1423
John McCallfbf780a2011-07-13 08:09:46 +00001424 if (checkZeroLength) {
1425 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1426 "arraydestroy.isempty");
1427 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1428 }
1429
John McCallbdc4d802011-07-09 01:37:26 +00001430 // Enter the loop body, making that address the current address.
1431 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1432 EmitBlock(bodyBB);
1433 llvm::PHINode *elementPast =
1434 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1435 elementPast->addIncoming(end, entryBB);
1436
1437 // Shift the address back by one element.
1438 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1439 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1440 "arraydestroy.element");
1441
John McCall2673c682011-07-11 08:38:19 +00001442 if (useEHCleanup)
1443 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1444
John McCallbdc4d802011-07-09 01:37:26 +00001445 // Perform the actual destruction there.
1446 destroyer(*this, element, type);
1447
John McCall2673c682011-07-11 08:38:19 +00001448 if (useEHCleanup)
1449 PopCleanupBlock();
1450
John McCallbdc4d802011-07-09 01:37:26 +00001451 // Check whether we've reached the end.
1452 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1453 Builder.CreateCondBr(done, doneBB, bodyBB);
1454 elementPast->addIncoming(element, Builder.GetInsertBlock());
1455
1456 // Done.
1457 EmitBlock(doneBB);
1458}
1459
John McCall2673c682011-07-11 08:38:19 +00001460/// Perform partial array destruction as if in an EH cleanup. Unlike
1461/// emitArrayDestroy, the element type here may still be an array type.
John McCall2673c682011-07-11 08:38:19 +00001462static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1463 llvm::Value *begin, llvm::Value *end,
1464 QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001465 CodeGenFunction::Destroyer *destroyer) {
John McCall2673c682011-07-11 08:38:19 +00001466 // If the element type is itself an array, drill down.
John McCallfbf780a2011-07-13 08:09:46 +00001467 unsigned arrayDepth = 0;
John McCall2673c682011-07-11 08:38:19 +00001468 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1469 // VLAs don't require a GEP index to walk into.
1470 if (!isa<VariableArrayType>(arrayType))
John McCallfbf780a2011-07-13 08:09:46 +00001471 arrayDepth++;
John McCall2673c682011-07-11 08:38:19 +00001472 type = arrayType->getElementType();
1473 }
John McCallfbf780a2011-07-13 08:09:46 +00001474
1475 if (arrayDepth) {
1476 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1477
Chris Lattner5f9e2722011-07-23 10:55:15 +00001478 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001479 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1480 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall2673c682011-07-11 08:38:19 +00001481 }
1482
John McCallfbf780a2011-07-13 08:09:46 +00001483 // Destroy the array. We don't ever need an EH cleanup because we
1484 // assume that we're in an EH cleanup ourselves, so a throwing
1485 // destructor causes an immediate terminate.
1486 CGF.emitArrayDestroy(begin, end, type, destroyer,
1487 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall2673c682011-07-11 08:38:19 +00001488}
1489
John McCallbdc4d802011-07-09 01:37:26 +00001490namespace {
John McCall2673c682011-07-11 08:38:19 +00001491 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1492 /// array destroy where the end pointer is regularly determined and
1493 /// does not need to be loaded from a local.
1494 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1495 llvm::Value *ArrayBegin;
1496 llvm::Value *ArrayEnd;
1497 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001498 CodeGenFunction::Destroyer *Destroyer;
John McCall2673c682011-07-11 08:38:19 +00001499 public:
1500 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1501 QualType elementType,
1502 CodeGenFunction::Destroyer *destroyer)
1503 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001504 ElementType(elementType), Destroyer(destroyer) {}
John McCall2673c682011-07-11 08:38:19 +00001505
John McCallad346f42011-07-12 20:27:29 +00001506 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +00001507 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1508 ElementType, Destroyer);
1509 }
1510 };
1511
1512 /// IrregularPartialArrayDestroy - a cleanup which performs a
1513 /// partial array destroy where the end pointer is irregularly
1514 /// determined and must be loaded from a local.
1515 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
John McCallbdc4d802011-07-09 01:37:26 +00001516 llvm::Value *ArrayBegin;
1517 llvm::Value *ArrayEndPointer;
1518 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001519 CodeGenFunction::Destroyer *Destroyer;
John McCallbdc4d802011-07-09 01:37:26 +00001520 public:
John McCall2673c682011-07-11 08:38:19 +00001521 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1522 llvm::Value *arrayEndPointer,
1523 QualType elementType,
1524 CodeGenFunction::Destroyer *destroyer)
John McCallbdc4d802011-07-09 01:37:26 +00001525 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001526 ElementType(elementType), Destroyer(destroyer) {}
John McCallbdc4d802011-07-09 01:37:26 +00001527
John McCallad346f42011-07-12 20:27:29 +00001528 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallbdc4d802011-07-09 01:37:26 +00001529 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall2673c682011-07-11 08:38:19 +00001530 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1531 ElementType, Destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001532 }
1533 };
1534}
1535
John McCall2673c682011-07-11 08:38:19 +00001536/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCallbdc4d802011-07-09 01:37:26 +00001537/// already-constructed elements of the given array. The cleanup
John McCall2673c682011-07-11 08:38:19 +00001538/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001539///
John McCallbdc4d802011-07-09 01:37:26 +00001540/// \param elementType - the immediate element type of the array;
1541/// possibly still an array type
John McCall9928c482011-07-12 16:41:08 +00001542void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall2673c682011-07-11 08:38:19 +00001543 llvm::Value *arrayEndPointer,
1544 QualType elementType,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001545 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001546 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1547 arrayBegin, arrayEndPointer,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001548 elementType, destroyer);
John McCall2673c682011-07-11 08:38:19 +00001549}
1550
1551/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1552/// already-constructed elements of the given array. The cleanup
1553/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001554///
John McCall2673c682011-07-11 08:38:19 +00001555/// \param elementType - the immediate element type of the array;
1556/// possibly still an array type
John McCall2673c682011-07-11 08:38:19 +00001557void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1558 llvm::Value *arrayEnd,
1559 QualType elementType,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001560 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001561 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall2673c682011-07-11 08:38:19 +00001562 arrayBegin, arrayEnd,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001563 elementType, destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001564}
1565
Nadav Rotem495cfa42013-03-23 06:43:35 +00001566/// Lazily declare the @llvm.lifetime.start intrinsic.
1567llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1568 if (LifetimeStartFn) return LifetimeStartFn;
1569 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1570 llvm::Intrinsic::lifetime_start);
1571 return LifetimeStartFn;
1572}
1573
1574/// Lazily declare the @llvm.lifetime.end intrinsic.
1575llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1576 if (LifetimeEndFn) return LifetimeEndFn;
1577 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1578 llvm::Intrinsic::lifetime_end);
1579 return LifetimeEndFn;
1580}
1581
John McCallf85e1932011-06-15 23:02:42 +00001582namespace {
1583 /// A cleanup to perform a release of an object at the end of a
1584 /// function. This is used to balance out the incoming +1 of a
1585 /// ns_consumed argument when we can't reasonably do that just by
1586 /// not doing the initial retain for a __block argument.
1587 struct ConsumeARCParameter : EHScopeStack::Cleanup {
John McCall5b07e802013-03-13 03:10:54 +00001588 ConsumeARCParameter(llvm::Value *param,
1589 ARCPreciseLifetime_t precise)
1590 : Param(param), Precise(precise) {}
John McCallf85e1932011-06-15 23:02:42 +00001591
1592 llvm::Value *Param;
John McCall5b07e802013-03-13 03:10:54 +00001593 ARCPreciseLifetime_t Precise;
John McCallf85e1932011-06-15 23:02:42 +00001594
John McCallad346f42011-07-12 20:27:29 +00001595 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall5b07e802013-03-13 03:10:54 +00001596 CGF.EmitARCRelease(Param, Precise);
John McCallf85e1932011-06-15 23:02:42 +00001597 }
1598 };
1599}
1600
Mike Stump1eb44332009-09-09 15:08:12 +00001601/// Emit an alloca (or GlobalValue depending on target)
Chris Lattner2621fd12008-05-08 05:58:21 +00001602/// for the specified parameter and set up LocalDeclMap.
Devang Patel093ac462011-03-03 20:13:15 +00001603void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1604 unsigned ArgNo) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001605 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00001606 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001607 "Invalid argument to EmitParmDecl");
John McCall8178df32011-02-22 22:38:33 +00001608
1609 Arg->setName(D.getName());
1610
Adrian Prantl836e7c92013-03-14 17:53:33 +00001611 QualType Ty = D.getType();
1612
John McCall8178df32011-02-22 22:38:33 +00001613 // Use better IR generation for certain implicit parameters.
1614 if (isa<ImplicitParamDecl>(D)) {
1615 // The only implicit argument a block has is its literal.
1616 if (BlockInfo) {
1617 LocalDeclMap[&D] = Arg;
Adrian Prantl836e7c92013-03-14 17:53:33 +00001618 llvm::Value *LocalAddr = 0;
1619 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001620 // Allocate a stack slot to let the debug info survive the RA.
Adrian Prantl836e7c92013-03-14 17:53:33 +00001621 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1622 D.getName() + ".addr");
1623 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1624 LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1625 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1626 LocalAddr = Builder.CreateLoad(Alloc);
1627 }
John McCall8178df32011-02-22 22:38:33 +00001628
1629 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +00001630 if (CGM.getCodeGenOpts().getDebugInfo()
1631 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001632 DI->setLocation(D.getLocation());
Adrian Prantl836e7c92013-03-14 17:53:33 +00001633 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, LocalAddr, Builder);
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001634 }
John McCall8178df32011-02-22 22:38:33 +00001635 }
1636
1637 return;
1638 }
1639 }
1640
Reid Spencer5f016e22007-07-11 17:01:13 +00001641 llvm::Value *DeclPtr;
Reid Kleckner9b601952013-06-21 12:45:15 +00001642 bool HasNonScalarEvalKind = !CodeGenFunction::hasScalarEvaluationKind(Ty);
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001643 // If this is an aggregate or variable sized value, reuse the input pointer.
Reid Kleckner9b601952013-06-21 12:45:15 +00001644 if (HasNonScalarEvalKind || !Ty->isConstantSizeType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001645 DeclPtr = Arg;
Reid Kleckner9b601952013-06-21 12:45:15 +00001646 // Push a destructor cleanup for this parameter if the ABI requires it.
1647 if (HasNonScalarEvalKind &&
1648 getTarget().getCXXABI().isArgumentDestroyedByCallee()) {
1649 if (const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl()) {
1650 if (RD->hasNonTrivialDestructor())
1651 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
1652 }
1653 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001654 } else {
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001655 // Otherwise, create a temporary to hold the value.
Eli Friedmanddfb8d12011-11-03 20:31:28 +00001656 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1657 D.getName() + ".addr");
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001658 CharUnits Align = getContext().getDeclAlign(&D);
1659 Alloc->setAlignment(Align.getQuantity());
Eli Friedmanddfb8d12011-11-03 20:31:28 +00001660 DeclPtr = Alloc;
Mike Stump1eb44332009-09-09 15:08:12 +00001661
John McCallf85e1932011-06-15 23:02:42 +00001662 bool doStore = true;
1663
1664 Qualifiers qs = Ty.getQualifiers();
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001665 LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
John McCallf85e1932011-06-15 23:02:42 +00001666 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1667 // We honor __attribute__((ns_consumed)) for types with lifetime.
1668 // For __strong, it's handled by just skipping the initial retain;
1669 // otherwise we have to balance out the initial +1 with an extra
1670 // cleanup to do the release at the end of the function.
1671 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1672
1673 // 'self' is always formally __strong, but if this is not an
1674 // init method then we don't want to retain it.
John McCall7acddac2011-06-17 06:42:21 +00001675 if (D.isARCPseudoStrong()) {
John McCallf85e1932011-06-15 23:02:42 +00001676 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1677 assert(&D == method->getSelfDecl());
John McCall7acddac2011-06-17 06:42:21 +00001678 assert(lt == Qualifiers::OCL_Strong);
1679 assert(qs.hasConst());
John McCallf85e1932011-06-15 23:02:42 +00001680 assert(method->getMethodFamily() != OMF_init);
John McCall175d6592011-06-15 23:40:09 +00001681 (void) method;
John McCallf85e1932011-06-15 23:02:42 +00001682 lt = Qualifiers::OCL_ExplicitNone;
1683 }
1684
1685 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001686 if (!isConsumed) {
1687 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1688 // use objc_storeStrong(&dest, value) for retaining the
1689 // object. But first, store a null into 'dest' because
1690 // objc_storeStrong attempts to release its old value.
1691 llvm::Value * Null = CGM.EmitNullConstant(D.getType());
1692 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1693 EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
1694 doStore = false;
1695 }
1696 else
John McCallf85e1932011-06-15 23:02:42 +00001697 // Don't use objc_retainBlock for block pointers, because we
1698 // don't want to Block_copy something just because we got it
1699 // as a parameter.
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001700 Arg = EmitARCRetainNonBlock(Arg);
1701 }
John McCallf85e1932011-06-15 23:02:42 +00001702 } else {
1703 // Push the cleanup for a consumed parameter.
John McCall5b07e802013-03-13 03:10:54 +00001704 if (isConsumed) {
1705 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1706 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1707 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1708 precise);
1709 }
John McCallf85e1932011-06-15 23:02:42 +00001710
1711 if (lt == Qualifiers::OCL_Weak) {
1712 EmitARCInitWeak(DeclPtr, Arg);
Chad Rosier7acebfb2012-02-18 01:20:35 +00001713 doStore = false; // The weak init is a store, no need to do two.
John McCallf85e1932011-06-15 23:02:42 +00001714 }
1715 }
1716
1717 // Enter the cleanup scope.
1718 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1719 }
1720
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001721 // Store the initial value into the alloca.
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001722 if (doStore)
David Chisnall7a7ee302012-01-16 17:27:18 +00001723 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001724 }
1725
1726 llvm::Value *&DMEntry = LocalDeclMap[&D];
1727 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1728 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +00001729
1730 // Emit debug info for param declaration.
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001731 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +00001732 if (CGM.getCodeGenOpts().getDebugInfo()
1733 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001734 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1735 }
1736 }
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001737
1738 if (D.hasAttr<AnnotateAttr>())
1739 EmitVarAnnotations(&D, DeclPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001740}