blob: 9ad9cf022cb268aff205d2269e3f55b63d61309c [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Decl nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
Peter Collingbourne8c25fc52011-09-19 21:14:35 +000016#include "CGOpenCLRuntime.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "CodeGenModule.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000019#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Anders Carlsson19567ee2008-08-25 01:38:19 +000021#include "clang/AST/DeclObjC.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner2621fd12008-05-08 05:58:21 +000023#include "clang/Basic/TargetInfo.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000024#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/GlobalVariable.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/Type.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30using namespace CodeGen;
31
32
33void CodeGenFunction::EmitDecl(const Decl &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +000034 switch (D.getKind()) {
Douglas Gregor08688ac2010-04-23 02:02:43 +000035 case Decl::TranslationUnit:
36 case Decl::Namespace:
37 case Decl::UnresolvedUsingTypename:
38 case Decl::ClassTemplateSpecialization:
39 case Decl::ClassTemplatePartialSpecialization:
40 case Decl::TemplateTypeParm:
41 case Decl::UnresolvedUsingValue:
Sean Hunt9a555912010-05-30 07:21:58 +000042 case Decl::NonTypeTemplateParm:
Douglas Gregor08688ac2010-04-23 02:02:43 +000043 case Decl::CXXMethod:
44 case Decl::CXXConstructor:
45 case Decl::CXXDestructor:
46 case Decl::CXXConversion:
47 case Decl::Field:
John McCall76da55d2013-04-16 07:28:30 +000048 case Decl::MSProperty:
Francois Pichet41f5e662010-11-21 06:49:41 +000049 case Decl::IndirectField:
Douglas Gregor08688ac2010-04-23 02:02:43 +000050 case Decl::ObjCIvar:
Eric Christophere1f54902011-08-23 22:38:00 +000051 case Decl::ObjCAtDefsField:
Chris Lattneraa9fc462007-10-08 21:37:32 +000052 case Decl::ParmVar:
Douglas Gregor08688ac2010-04-23 02:02:43 +000053 case Decl::ImplicitParam:
54 case Decl::ClassTemplate:
55 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +000056 case Decl::TypeAliasTemplate:
Douglas Gregor08688ac2010-04-23 02:02:43 +000057 case Decl::TemplateTemplateParm:
58 case Decl::ObjCMethod:
59 case Decl::ObjCCategory:
60 case Decl::ObjCProtocol:
61 case Decl::ObjCInterface:
62 case Decl::ObjCCategoryImpl:
63 case Decl::ObjCImplementation:
64 case Decl::ObjCProperty:
65 case Decl::ObjCCompatibleAlias:
Abramo Bagnara6206d532010-06-05 05:09:32 +000066 case Decl::AccessSpec:
Douglas Gregor08688ac2010-04-23 02:02:43 +000067 case Decl::LinkageSpec:
68 case Decl::ObjCPropertyImpl:
Douglas Gregor08688ac2010-04-23 02:02:43 +000069 case Decl::FileScopeAsm:
70 case Decl::Friend:
71 case Decl::FriendTemplate:
72 case Decl::Block:
Tareq A. Siraj6afcf882013-04-16 19:37:38 +000073 case Decl::Captured:
Francois Pichetaf0f4d02011-08-14 03:52:19 +000074 case Decl::ClassScopeFunctionSpecialization:
David Blaikieb219cfc2011-09-23 05:06:16 +000075 llvm_unreachable("Declaration should not be in declstmts!");
Reid Spencer5f016e22007-07-11 17:01:13 +000076 case Decl::Function: // void X();
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000077 case Decl::Record: // struct/union/class X;
Reid Spencer5f016e22007-07-11 17:01:13 +000078 case Decl::Enum: // enum X;
Mike Stump1eb44332009-09-09 15:08:12 +000079 case Decl::EnumConstant: // enum ? { X = ? }
Argyrios Kyrtzidis35bc0822008-10-15 00:42:39 +000080 case Decl::CXXRecord: // struct/union/class X; [C++]
Daniel Dunbarfa133a12009-11-23 00:07:06 +000081 case Decl::Using: // using X; [C++]
82 case Decl::UsingShadow:
Eric Christopherc3e81e72013-04-19 07:46:36 +000083 case Decl::UsingDirective: // using namespace X; [C++]
Douglas Gregor08688ac2010-04-23 02:02:43 +000084 case Decl::NamespaceAlias:
Anders Carlsson7b0ca3f2009-12-03 17:26:31 +000085 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner4ae493c2011-02-18 02:08:43 +000086 case Decl::Label: // __label__ x;
Douglas Gregor15de72c2011-12-02 23:23:56 +000087 case Decl::Import:
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
Daniel Dunbar662174c82008-08-29 17:28:43 +000093 case Decl::Var: {
94 const VarDecl &VD = cast<VarDecl>(D);
John McCallb6bbcc92010-10-15 04:57:14 +000095 assert(VD.isLocalVarDecl() &&
Daniel Dunbar662174c82008-08-29 17:28:43 +000096 "Should not see file-scope variables inside a function!");
John McCallb6bbcc92010-10-15 04:57:14 +000097 return EmitVarDecl(VD);
Reid Spencer5f016e22007-07-11 17:01:13 +000098 }
Mike Stump1eb44332009-09-09 15:08:12 +000099
Richard Smith162e1c12011-04-15 14:24:37 +0000100 case Decl::Typedef: // typedef int X;
101 case Decl::TypeAlias: { // using X = int; [C++0x]
102 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000103 QualType Ty = TD.getUnderlyingType();
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000105 if (Ty->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000106 EmitVariablyModifiedType(Ty);
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000107 }
Daniel Dunbar662174c82008-08-29 17:28:43 +0000108 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000109}
110
John McCallb6bbcc92010-10-15 04:57:14 +0000111/// EmitVarDecl - This method handles emission of any variable declaration
Reid Spencer5f016e22007-07-11 17:01:13 +0000112/// inside a function, including static vars etc.
John McCallb6bbcc92010-10-15 04:57:14 +0000113void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000114 switch (D.getStorageClass()) {
John McCalld931b082010-08-26 03:08:43 +0000115 case SC_None:
116 case SC_Auto:
117 case SC_Register:
John McCallb6bbcc92010-10-15 04:57:14 +0000118 return EmitAutoVarDecl(D);
John McCalld931b082010-08-26 03:08:43 +0000119 case SC_Static: {
Eric Christophere1f54902011-08-23 22:38:00 +0000120 llvm::GlobalValue::LinkageTypes Linkage =
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000121 llvm::GlobalValue::InternalLinkage;
122
John McCall8b242332010-05-25 04:30:21 +0000123 // If the function definition has some sort of weak linkage, its
124 // static variables should also be weak so that they get properly
125 // uniqued. We can't do this in C, though, because there's no
126 // standard way to agree on which variables are the same (i.e.
127 // there's no mangling).
Richard Smith7edf9e32012-11-01 22:30:59 +0000128 if (getLangOpts().CPlusPlus)
John McCall8b242332010-05-25 04:30:21 +0000129 if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
130 Linkage = CurFn->getLinkage();
Eric Christophere1f54902011-08-23 22:38:00 +0000131
John McCallb6bbcc92010-10-15 04:57:14 +0000132 return EmitStaticVarDecl(D, Linkage);
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000133 }
John McCalld931b082010-08-26 03:08:43 +0000134 case SC_Extern:
135 case SC_PrivateExtern:
Lauro Ramos Venanciofea90b82008-02-16 22:30:38 +0000136 // Don't emit it now, allow it to be emitted lazily on its first use.
137 return;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000138 case SC_OpenCLWorkGroupLocal:
139 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000140 }
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000141
David Blaikieb219cfc2011-09-23 05:06:16 +0000142 llvm_unreachable("Unknown storage class");
Reid Spencer5f016e22007-07-11 17:01:13 +0000143}
144
Chris Lattner761acc12009-12-05 08:22:11 +0000145static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
146 const char *Separator) {
147 CodeGenModule &CGM = CGF.CGM;
Richard Smith7edf9e32012-11-01 22:30:59 +0000148 if (CGF.getLangOpts().CPlusPlus) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000149 StringRef Name = CGM.getMangledName(&D);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000150 return Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000151 }
Eric Christophere1f54902011-08-23 22:38:00 +0000152
Chris Lattner761acc12009-12-05 08:22:11 +0000153 std::string ContextName;
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000154 if (!CGF.CurFuncDecl) {
155 // Better be in a block declared in global scope.
156 const NamedDecl *ND = cast<NamedDecl>(&D);
157 const DeclContext *DC = ND->getDeclContext();
158 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
159 MangleBuffer Name;
Peter Collingbourne14110472011-01-13 18:57:25 +0000160 CGM.getBlockMangledName(GlobalDecl(), Name, BD);
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000161 ContextName = Name.getString();
162 }
163 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000164 llvm_unreachable("Unknown context for block static var decl");
Fariborz Jahanianfaa5bfc2010-11-30 23:07:14 +0000165 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000166 StringRef Name = CGM.getMangledName(FD);
Anders Carlsson9a20d552010-06-22 16:16:50 +0000167 ContextName = Name.str();
John McCallf746aa62010-03-19 23:29:14 +0000168 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
Chris Lattner761acc12009-12-05 08:22:11 +0000169 ContextName = CGF.CurFn->getName();
170 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000171 llvm_unreachable("Unknown context for static var decl");
Eric Christophere1f54902011-08-23 22:38:00 +0000172
Chris Lattner761acc12009-12-05 08:22:11 +0000173 return ContextName + Separator + D.getNameAsString();
174}
175
Chandler Carruth0f30a122012-03-30 19:44:53 +0000176llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000177CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
178 const char *Separator,
179 llvm::GlobalValue::LinkageTypes Linkage) {
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000180 QualType Ty = D.getType();
Eli Friedman3c2b3172008-02-15 12:20:59 +0000181 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000182
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000183 // Use the label if the variable is renamed with the asm-label extension.
184 std::string Name;
Benjamin Kramerc3c8f222011-11-21 15:47:23 +0000185 if (D.hasAttr<AsmLabelAttr>())
186 Name = CGM.getMangledName(&D);
187 else
Benjamin Kramer5c247db2011-11-20 21:05:04 +0000188 Name = GetStaticDeclName(*this, D, Separator);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000189
Chris Lattner2acc6e32011-07-18 04:24:23 +0000190 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
Peter Collingbourne1aba7782012-08-28 20:37:10 +0000191 unsigned AddrSpace =
192 CGM.GetGlobalVarAddressSpace(&D, CGM.getContext().getTargetAddressSpace(Ty));
Anders Carlsson41f8a132009-09-26 18:16:06 +0000193 llvm::GlobalVariable *GV =
194 new llvm::GlobalVariable(CGM.getModule(), LTy,
195 Ty.isConstant(getContext()), Linkage,
Hans Wennborgde981f32012-06-28 08:01:44 +0000196 CGM.EmitNullConstant(D.getType()), Name, 0,
197 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourne1aba7782012-08-28 20:37:10 +0000198 AddrSpace);
Ken Dyck8b752f12010-01-27 17:10:57 +0000199 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
John McCall112c9672010-11-02 21:04:24 +0000200 if (Linkage != llvm::GlobalValue::InternalLinkage)
201 GV->setVisibility(CurFn->getVisibility());
Hans Wennborgde981f32012-06-28 08:01:44 +0000202
Richard Smith38afbc72013-04-13 02:43:54 +0000203 if (D.getTLSKind())
Hans Wennborgde981f32012-06-28 08:01:44 +0000204 CGM.setTLSMode(GV, D);
205
Anders Carlsson41f8a132009-09-26 18:16:06 +0000206 return GV;
Daniel Dunbar0096acf2009-02-25 19:24:29 +0000207}
208
Richard Smith7ca48502012-02-13 22:16:19 +0000209/// hasNontrivialDestruction - Determine whether a type's destruction is
210/// non-trivial. If so, and the variable uses static initialization, we must
211/// register its destructor to run on exit.
212static bool hasNontrivialDestruction(QualType T) {
213 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
214 return RD && !RD->hasTrivialDestructor();
215}
216
Chandler Carruth0f30a122012-03-30 19:44:53 +0000217/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
218/// global variable that has already been created for it. If the initializer
219/// has a different type than GV does, this may free GV and return a different
220/// one. Otherwise it just returns GV.
221llvm::GlobalVariable *
John McCallb6bbcc92010-10-15 04:57:14 +0000222CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth0f30a122012-03-30 19:44:53 +0000223 llvm::GlobalVariable *GV) {
224 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCallbf40cb52010-07-15 23:40:35 +0000225
Chris Lattner761acc12009-12-05 08:22:11 +0000226 // If constant emission failed, then this should be a C++ static
227 // initializer.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000228 if (!Init) {
Richard Smith7edf9e32012-11-01 22:30:59 +0000229 if (!getLangOpts().CPlusPlus)
Chris Lattner761acc12009-12-05 08:22:11 +0000230 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall5cd91b52010-09-08 01:44:27 +0000231 else if (Builder.GetInsertBlock()) {
Eric Christophere1f54902011-08-23 22:38:00 +0000232 // Since we have a static initializer, this global variable can't
Anders Carlsson071c8102010-01-26 04:02:23 +0000233 // be constant.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000234 GV->setConstant(false);
John McCall5cd91b52010-09-08 01:44:27 +0000235
Chandler Carruth0f30a122012-03-30 19:44:53 +0000236 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson071c8102010-01-26 04:02:23 +0000237 }
Chandler Carruth0f30a122012-03-30 19:44:53 +0000238 return GV;
Chris Lattner761acc12009-12-05 08:22:11 +0000239 }
John McCallbf40cb52010-07-15 23:40:35 +0000240
Chris Lattner761acc12009-12-05 08:22:11 +0000241 // The initializer may differ in type from the global. Rewrite
242 // the global to match the initializer. (We have to do this
243 // because some types, like unions, can't be completely represented
244 // in the LLVM type system.)
Chandler Carruth0f30a122012-03-30 19:44:53 +0000245 if (GV->getType()->getElementType() != Init->getType()) {
246 llvm::GlobalVariable *OldGV = GV;
247
248 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
249 OldGV->isConstant(),
250 OldGV->getLinkage(), Init, "",
251 /*InsertBefore*/ OldGV,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +0000252 OldGV->getThreadLocalMode(),
Chandler Carruth0f30a122012-03-30 19:44:53 +0000253 CGM.getContext().getTargetAddressSpace(D.getType()));
254 GV->setVisibility(OldGV->getVisibility());
Eric Christophere1f54902011-08-23 22:38:00 +0000255
Chris Lattner761acc12009-12-05 08:22:11 +0000256 // Steal the name of the old global
Chandler Carruth0f30a122012-03-30 19:44:53 +0000257 GV->takeName(OldGV);
Eric Christophere1f54902011-08-23 22:38:00 +0000258
Chris Lattner761acc12009-12-05 08:22:11 +0000259 // Replace all uses of the old global with the new global
Chandler Carruth0f30a122012-03-30 19:44:53 +0000260 llvm::Constant *NewPtrForOldDecl =
261 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
262 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christophere1f54902011-08-23 22:38:00 +0000263
Chris Lattner761acc12009-12-05 08:22:11 +0000264 // Erase the old global, since it is no longer used.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000265 OldGV->eraseFromParent();
Chris Lattner761acc12009-12-05 08:22:11 +0000266 }
Eric Christophere1f54902011-08-23 22:38:00 +0000267
Chandler Carruth0f30a122012-03-30 19:44:53 +0000268 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
269 GV->setInitializer(Init);
Richard Smith7ca48502012-02-13 22:16:19 +0000270
271 if (hasNontrivialDestruction(D.getType())) {
272 // We have a constant initializer, but a nontrivial destructor. We still
273 // need to perform a guarded "initialization" in order to register the
Richard Smitha9b21d22012-02-17 06:48:11 +0000274 // destructor.
Chandler Carruth0f30a122012-03-30 19:44:53 +0000275 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith7ca48502012-02-13 22:16:19 +0000276 }
277
Chandler Carruth0f30a122012-03-30 19:44:53 +0000278 return GV;
Chris Lattner761acc12009-12-05 08:22:11 +0000279}
280
John McCallb6bbcc92010-10-15 04:57:14 +0000281void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssonf6b89a12010-02-07 02:03:08 +0000282 llvm::GlobalValue::LinkageTypes Linkage) {
Chandler Carruth0f30a122012-03-30 19:44:53 +0000283 llvm::Value *&DMEntry = LocalDeclMap[&D];
284 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
Mike Stump1eb44332009-09-09 15:08:12 +0000285
John McCall355bba72012-03-30 21:00:39 +0000286 // Check to see if we already have a global variable for this
287 // declaration. This can happen when double-emitting function
288 // bodies, e.g. with complete and base constructors.
289 llvm::Constant *addr =
290 CGM.getStaticLocalDeclAddress(&D);
291
292 llvm::GlobalVariable *var;
293 if (addr) {
294 var = cast<llvm::GlobalVariable>(addr->stripPointerCasts());
295 } else {
296 addr = var = CreateStaticVarDecl(D, ".", Linkage);
297 }
Daniel Dunbara985b312009-02-25 19:45:19 +0000298
Daniel Dunbare5731f82009-02-25 20:08:33 +0000299 // Store into LocalDeclMap before generating initializer to handle
300 // circular references.
John McCall355bba72012-03-30 21:00:39 +0000301 DMEntry = addr;
302 CGM.setStaticLocalDeclAddress(&D, addr);
Daniel Dunbare5731f82009-02-25 20:08:33 +0000303
John McCallfe67f3b2010-05-04 20:45:42 +0000304 // We can't have a VLA here, but we can have a pointer to a VLA,
305 // even though that doesn't really make any sense.
Eli Friedmanc62aad82009-04-20 03:54:15 +0000306 // Make sure to evaluate VLA bounds now so that we have them for later.
307 if (D.getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000308 EmitVariablyModifiedType(D.getType());
Eric Christophere1f54902011-08-23 22:38:00 +0000309
John McCall355bba72012-03-30 21:00:39 +0000310 // Save the type in case adding the initializer forces a type change.
311 llvm::Type *expectedType = addr->getType();
Eli Friedmanc62aad82009-04-20 03:54:15 +0000312
Chris Lattner761acc12009-12-05 08:22:11 +0000313 // If this value has an initializer, emit it.
314 if (D.getInit())
John McCall355bba72012-03-30 21:00:39 +0000315 var = AddInitializerToStaticVarDecl(D, var);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000316
John McCall355bba72012-03-30 21:00:39 +0000317 var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Chris Lattner0af95232010-03-10 23:59:59 +0000318
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000319 if (D.hasAttr<AnnotateAttr>())
John McCall355bba72012-03-30 21:00:39 +0000320 CGM.AddGlobalAnnotations(&D, var);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000321
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000322 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCall355bba72012-03-30 21:00:39 +0000323 var->setSection(SA->getName());
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000325 if (D.hasAttr<UsedAttr>())
John McCall355bba72012-03-30 21:00:39 +0000326 CGM.AddUsedGlobal(var);
Daniel Dunbar5c61d972009-02-13 22:08:43 +0000327
Chandler Carruth0f30a122012-03-30 19:44:53 +0000328 // We may have to cast the constant because of the initializer
329 // mismatch above.
330 //
331 // FIXME: It is really dangerous to store this in the map; if anyone
332 // RAUW's the GV uses of this constant will be invalid.
John McCall355bba72012-03-30 21:00:39 +0000333 llvm::Constant *castedAddr = llvm::ConstantExpr::getBitCast(var, expectedType);
334 DMEntry = castedAddr;
335 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000336
337 // Emit global variable debug descriptor for static vars.
Anders Carlssone896d982009-02-13 08:11:52 +0000338 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000339 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +0000340 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
Daniel Dunbar66031a52008-10-17 16:15:48 +0000341 DI->setLocation(D.getLocation());
John McCall355bba72012-03-30 21:00:39 +0000342 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta686226b2008-06-05 08:59:10 +0000343 }
Anders Carlsson1a86b332007-10-17 00:52:43 +0000344}
Mike Stump1eb44332009-09-09 15:08:12 +0000345
John McCallda65ea82010-07-13 20:32:21 +0000346namespace {
John McCallbdc4d802011-07-09 01:37:26 +0000347 struct DestroyObject : EHScopeStack::Cleanup {
348 DestroyObject(llvm::Value *addr, QualType type,
John McCall2673c682011-07-11 08:38:19 +0000349 CodeGenFunction::Destroyer *destroyer,
350 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000351 : addr(addr), type(type), destroyer(destroyer),
John McCall2673c682011-07-11 08:38:19 +0000352 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallda65ea82010-07-13 20:32:21 +0000353
John McCallbdc4d802011-07-09 01:37:26 +0000354 llvm::Value *addr;
355 QualType type;
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000356 CodeGenFunction::Destroyer *destroyer;
John McCall2673c682011-07-11 08:38:19 +0000357 bool useEHCleanupForArray;
John McCallda65ea82010-07-13 20:32:21 +0000358
John McCallad346f42011-07-12 20:27:29 +0000359 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +0000360 // Don't use an EH cleanup recursively from an EH cleanup.
John McCallad346f42011-07-12 20:27:29 +0000361 bool useEHCleanupForArray =
362 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall2673c682011-07-11 08:38:19 +0000363
364 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCallda65ea82010-07-13 20:32:21 +0000365 }
366 };
367
John McCallbdc4d802011-07-09 01:37:26 +0000368 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
369 DestroyNRVOVariable(llvm::Value *addr,
370 const CXXDestructorDecl *Dtor,
371 llvm::Value *NRVOFlag)
372 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCallda65ea82010-07-13 20:32:21 +0000373
374 const CXXDestructorDecl *Dtor;
375 llvm::Value *NRVOFlag;
376 llvm::Value *Loc;
377
John McCallad346f42011-07-12 20:27:29 +0000378 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallda65ea82010-07-13 20:32:21 +0000379 // Along the exceptions path we always execute the dtor.
John McCallad346f42011-07-12 20:27:29 +0000380 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCallda65ea82010-07-13 20:32:21 +0000381
382 llvm::BasicBlock *SkipDtorBB = 0;
383 if (NRVO) {
384 // If we exited via NRVO, we skip the destructor call.
385 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
386 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
387 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
388 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
389 CGF.EmitBlock(RunDtorBB);
390 }
Eric Christophere1f54902011-08-23 22:38:00 +0000391
John McCallda65ea82010-07-13 20:32:21 +0000392 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +0000393 /*ForVirtualBase=*/false,
394 /*Delegating=*/false,
395 Loc);
John McCallda65ea82010-07-13 20:32:21 +0000396
397 if (NRVO) CGF.EmitBlock(SkipDtorBB);
398 }
399 };
John McCallda65ea82010-07-13 20:32:21 +0000400
John McCall1f0fca52010-07-21 07:22:38 +0000401 struct CallStackRestore : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000402 llvm::Value *Stack;
403 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
John McCallad346f42011-07-12 20:27:29 +0000404 void Emit(CodeGenFunction &CGF, Flags flags) {
Benjamin Kramer578faa82011-09-27 21:06:10 +0000405 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalld8715092010-07-21 06:13:08 +0000406 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
407 CGF.Builder.CreateCall(F, V);
408 }
409 };
410
John McCall0c24c802011-06-24 23:21:27 +0000411 struct ExtendGCLifetime : EHScopeStack::Cleanup {
412 const VarDecl &Var;
413 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
414
John McCallad346f42011-07-12 20:27:29 +0000415 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall0c24c802011-06-24 23:21:27 +0000416 // Compute the address of the local variable, in case it's a
417 // byref or something.
John McCallf4b88a42012-03-10 09:33:50 +0000418 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
419 Var.getType(), VK_LValue, SourceLocation());
John McCall0c24c802011-06-24 23:21:27 +0000420 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
421 CGF.EmitExtendGCLifetime(value);
422 }
423 };
424
John McCall1f0fca52010-07-21 07:22:38 +0000425 struct CallCleanupFunction : EHScopeStack::Cleanup {
John McCalld8715092010-07-21 06:13:08 +0000426 llvm::Constant *CleanupFn;
427 const CGFunctionInfo &FnInfo;
John McCalld8715092010-07-21 06:13:08 +0000428 const VarDecl &Var;
Eric Christophere1f54902011-08-23 22:38:00 +0000429
John McCalld8715092010-07-21 06:13:08 +0000430 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCall34695852011-02-22 06:44:22 +0000431 const VarDecl *Var)
432 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalld8715092010-07-21 06:13:08 +0000433
John McCallad346f42011-07-12 20:27:29 +0000434 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf4b88a42012-03-10 09:33:50 +0000435 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
436 Var.getType(), VK_LValue, SourceLocation());
John McCall34695852011-02-22 06:44:22 +0000437 // Compute the address of the local variable, in case it's a byref
438 // or something.
439 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
440
John McCalld8715092010-07-21 06:13:08 +0000441 // In some cases, the type of the function argument will be different from
442 // the type of the pointer. An example of this is
443 // void f(void* arg);
444 // __attribute__((cleanup(f))) void *g;
445 //
446 // To fix this we insert a bitcast here.
447 QualType ArgTy = FnInfo.arg_begin()->type;
448 llvm::Value *Arg =
449 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
450
451 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000452 Args.add(RValue::get(Arg),
453 CGF.getContext().getPointerType(Var.getType()));
John McCalld8715092010-07-21 06:13:08 +0000454 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
455 }
456 };
Nadav Rotem495cfa42013-03-23 06:43:35 +0000457
458 /// A cleanup to call @llvm.lifetime.end.
459 class CallLifetimeEnd : public EHScopeStack::Cleanup {
460 llvm::Value *Addr;
461 llvm::Value *Size;
462 public:
463 CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
464 : Addr(addr), Size(size) {}
465
466 void Emit(CodeGenFunction &CGF, Flags flags) {
467 llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
468 CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
469 Size, castAddr)
470 ->setDoesNotThrow();
471 }
472 };
John McCalld8715092010-07-21 06:13:08 +0000473}
474
John McCallf85e1932011-06-15 23:02:42 +0000475/// EmitAutoVarWithLifetime - Does the setup required for an automatic
476/// variable with lifetime.
477static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
478 llvm::Value *addr,
479 Qualifiers::ObjCLifetime lifetime) {
480 switch (lifetime) {
481 case Qualifiers::OCL_None:
482 llvm_unreachable("present but none");
483
484 case Qualifiers::OCL_ExplicitNone:
485 // nothing to do
486 break;
487
488 case Qualifiers::OCL_Strong: {
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000489 CodeGenFunction::Destroyer *destroyer =
John McCall9928c482011-07-12 16:41:08 +0000490 (var.hasAttr<ObjCPreciseLifetimeAttr>()
491 ? CodeGenFunction::destroyARCStrongPrecise
492 : CodeGenFunction::destroyARCStrongImprecise);
493
494 CleanupKind cleanupKind = CGF.getARCCleanupKind();
495 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
496 cleanupKind & EHCleanup);
John McCallf85e1932011-06-15 23:02:42 +0000497 break;
498 }
499 case Qualifiers::OCL_Autoreleasing:
500 // nothing to do
501 break;
Eric Christophere1f54902011-08-23 22:38:00 +0000502
John McCallf85e1932011-06-15 23:02:42 +0000503 case Qualifiers::OCL_Weak:
504 // __weak objects always get EH cleanups; otherwise, exceptions
505 // could cause really nasty crashes instead of mere leaks.
John McCall9928c482011-07-12 16:41:08 +0000506 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
507 CodeGenFunction::destroyARCWeak,
508 /*useEHCleanup*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000509 break;
510 }
511}
512
513static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
514 if (const Expr *e = dyn_cast<Expr>(s)) {
515 // Skip the most common kinds of expressions that make
516 // hierarchy-walking expensive.
517 s = e = e->IgnoreParenCasts();
518
519 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
520 return (ref->getDecl() == &var);
Fariborz Jahanianddfc8a12012-06-19 20:53:26 +0000521 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
522 const BlockDecl *block = be->getBlockDecl();
523 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
524 e = block->capture_end(); i != e; ++i) {
525 if (i->getVariable() == &var)
526 return true;
527 }
528 }
John McCallf85e1932011-06-15 23:02:42 +0000529 }
530
531 for (Stmt::const_child_range children = s->children(); children; ++children)
Fariborz Jahanian8fefc8e2011-06-29 20:00:16 +0000532 // children might be null; as in missing decl or conditional of an if-stmt.
533 if ((*children) && isAccessedBy(var, *children))
John McCallf85e1932011-06-15 23:02:42 +0000534 return true;
535
536 return false;
537}
538
539static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
540 if (!decl) return false;
541 if (!isa<VarDecl>(decl)) return false;
542 const VarDecl *var = cast<VarDecl>(decl);
543 return isAccessedBy(*var, e);
544}
545
John McCalla07398e2011-06-16 04:16:24 +0000546static void drillIntoBlockVariable(CodeGenFunction &CGF,
547 LValue &lvalue,
548 const VarDecl *var) {
549 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
550}
551
John McCallf85e1932011-06-15 23:02:42 +0000552void CodeGenFunction::EmitScalarInit(const Expr *init,
553 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +0000554 LValue lvalue,
555 bool capturedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000556 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCallf85e1932011-06-15 23:02:42 +0000557 if (!lifetime) {
558 llvm::Value *value = EmitScalarExpr(init);
John McCalla07398e2011-06-16 04:16:24 +0000559 if (capturedByInit)
560 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +0000561 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCallf85e1932011-06-15 23:02:42 +0000562 return;
563 }
564
565 // If we're emitting a value with lifetime, we have to do the
566 // initialization *before* we leave the cleanup scopes.
John McCall1a343eb2011-11-10 08:15:53 +0000567 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
568 enterFullExpression(ewc);
John McCallf85e1932011-06-15 23:02:42 +0000569 init = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +0000570 }
571 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCallf85e1932011-06-15 23:02:42 +0000572
573 // We have to maintain the illusion that the variable is
574 // zero-initialized. If the variable might be accessed in its
575 // initializer, zero-initialize before running the initializer, then
576 // actually perform the initialization with an assign.
577 bool accessedByInit = false;
578 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallfb720812011-07-28 07:23:35 +0000579 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCallf85e1932011-06-15 23:02:42 +0000580 if (accessedByInit) {
John McCalla07398e2011-06-16 04:16:24 +0000581 LValue tempLV = lvalue;
John McCallf85e1932011-06-15 23:02:42 +0000582 // Drill down to the __block object if necessary.
John McCallf85e1932011-06-15 23:02:42 +0000583 if (capturedByInit) {
584 // We can use a simple GEP for this because it can't have been
585 // moved yet.
John McCalla07398e2011-06-16 04:16:24 +0000586 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
587 getByRefValueLLVMField(cast<VarDecl>(D))));
John McCallf85e1932011-06-15 23:02:42 +0000588 }
589
Chris Lattner2acc6e32011-07-18 04:24:23 +0000590 llvm::PointerType *ty
John McCalla07398e2011-06-16 04:16:24 +0000591 = cast<llvm::PointerType>(tempLV.getAddress()->getType());
John McCallf85e1932011-06-15 23:02:42 +0000592 ty = cast<llvm::PointerType>(ty->getElementType());
593
594 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000595
John McCallf85e1932011-06-15 23:02:42 +0000596 // If __weak, we want to use a barrier under certain conditions.
597 if (lifetime == Qualifiers::OCL_Weak)
John McCalla07398e2011-06-16 04:16:24 +0000598 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCallf85e1932011-06-15 23:02:42 +0000599
600 // Otherwise just do a simple store.
601 else
David Chisnall7a7ee302012-01-16 17:27:18 +0000602 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000603 }
604
605 // Emit the initializer.
606 llvm::Value *value = 0;
607
608 switch (lifetime) {
609 case Qualifiers::OCL_None:
610 llvm_unreachable("present but none");
611
612 case Qualifiers::OCL_ExplicitNone:
613 // nothing to do
614 value = EmitScalarExpr(init);
615 break;
616
617 case Qualifiers::OCL_Strong: {
618 value = EmitARCRetainScalarExpr(init);
619 break;
620 }
621
622 case Qualifiers::OCL_Weak: {
623 // No way to optimize a producing initializer into this. It's not
624 // worth optimizing for, because the value will immediately
625 // disappear in the common case.
626 value = EmitScalarExpr(init);
627
John McCalla07398e2011-06-16 04:16:24 +0000628 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000629 if (accessedByInit)
John McCalla07398e2011-06-16 04:16:24 +0000630 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCallf85e1932011-06-15 23:02:42 +0000631 else
John McCalla07398e2011-06-16 04:16:24 +0000632 EmitARCInitWeak(lvalue.getAddress(), value);
John McCallf85e1932011-06-15 23:02:42 +0000633 return;
634 }
635
636 case Qualifiers::OCL_Autoreleasing:
637 value = EmitARCRetainAutoreleaseScalarExpr(init);
638 break;
639 }
640
John McCalla07398e2011-06-16 04:16:24 +0000641 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCallf85e1932011-06-15 23:02:42 +0000642
643 // If the variable might have been accessed by its initializer, we
644 // might have to initialize with a barrier. We have to do this for
645 // both __weak and __strong, but __weak got filtered out above.
646 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
John McCalla07398e2011-06-16 04:16:24 +0000647 llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
David Chisnall7a7ee302012-01-16 17:27:18 +0000648 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall5b07e802013-03-13 03:10:54 +0000649 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +0000650 return;
651 }
652
David Chisnall7a7ee302012-01-16 17:27:18 +0000653 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallf85e1932011-06-15 23:02:42 +0000654}
Chris Lattner94cd0112010-12-01 02:05:19 +0000655
John McCall7acddac2011-06-17 06:42:21 +0000656/// EmitScalarInit - Initialize the given lvalue with the given object.
657void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
658 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
659 if (!lifetime)
David Chisnall7a7ee302012-01-16 17:27:18 +0000660 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCall7acddac2011-06-17 06:42:21 +0000661
662 switch (lifetime) {
663 case Qualifiers::OCL_None:
664 llvm_unreachable("present but none");
665
666 case Qualifiers::OCL_ExplicitNone:
667 // nothing to do
668 break;
669
670 case Qualifiers::OCL_Strong:
671 init = EmitARCRetain(lvalue.getType(), init);
672 break;
673
674 case Qualifiers::OCL_Weak:
675 // Initialize and then skip the primitive store.
676 EmitARCInitWeak(lvalue.getAddress(), init);
677 return;
678
679 case Qualifiers::OCL_Autoreleasing:
680 init = EmitARCRetainAutorelease(lvalue.getType(), init);
681 break;
682 }
683
David Chisnall7a7ee302012-01-16 17:27:18 +0000684 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCall7acddac2011-06-17 06:42:21 +0000685}
686
Chris Lattner94cd0112010-12-01 02:05:19 +0000687/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
688/// non-zero parts of the specified initializer with equal or fewer than
689/// NumStores scalar stores.
690static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
691 unsigned &NumStores) {
Chris Lattner70b02942010-12-02 01:58:41 +0000692 // Zero and Undef never requires any extra stores.
693 if (isa<llvm::ConstantAggregateZero>(Init) ||
694 isa<llvm::ConstantPointerNull>(Init) ||
695 isa<llvm::UndefValue>(Init))
696 return true;
697 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
698 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
699 isa<llvm::ConstantExpr>(Init))
700 return Init->isNullValue() || NumStores--;
701
702 // See if we can emit each element.
703 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
704 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
705 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
706 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
707 return false;
708 }
709 return true;
710 }
Chris Lattnerf492cb12012-01-31 04:36:19 +0000711
712 if (llvm::ConstantDataSequential *CDS =
713 dyn_cast<llvm::ConstantDataSequential>(Init)) {
714 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
715 llvm::Constant *Elt = CDS->getElementAsConstant(i);
716 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
717 return false;
718 }
719 return true;
720 }
Eric Christophere1f54902011-08-23 22:38:00 +0000721
Chris Lattner94cd0112010-12-01 02:05:19 +0000722 // Anything else is hard and scary.
723 return false;
724}
725
726/// emitStoresForInitAfterMemset - For inits that
727/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
728/// stores that would be required.
729static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCall34695852011-02-22 06:44:22 +0000730 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer06d43682012-08-27 22:07:02 +0000731 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
732 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christophere1f54902011-08-23 22:38:00 +0000733
Chris Lattner70b02942010-12-02 01:58:41 +0000734 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
735 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
736 isa<llvm::ConstantExpr>(Init)) {
Chris Lattnerf492cb12012-01-31 04:36:19 +0000737 Builder.CreateStore(Init, Loc, isVolatile);
738 return;
739 }
740
741 if (llvm::ConstantDataSequential *CDS =
742 dyn_cast<llvm::ConstantDataSequential>(Init)) {
743 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
744 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramercfa07e32012-08-27 21:35:58 +0000745
746 // If necessary, get a pointer to the element and emit it.
747 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
748 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
749 isVolatile, Builder);
Chris Lattnerf492cb12012-01-31 04:36:19 +0000750 }
Chris Lattner70b02942010-12-02 01:58:41 +0000751 return;
752 }
Eric Christophere1f54902011-08-23 22:38:00 +0000753
Chris Lattner70b02942010-12-02 01:58:41 +0000754 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
755 "Unknown value type!");
Eric Christophere1f54902011-08-23 22:38:00 +0000756
Chris Lattner70b02942010-12-02 01:58:41 +0000757 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
758 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramercfa07e32012-08-27 21:35:58 +0000759
760 // If necessary, get a pointer to the element and emit it.
761 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
762 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
763 isVolatile, Builder);
Chris Lattner70b02942010-12-02 01:58:41 +0000764 }
Chris Lattner94cd0112010-12-01 02:05:19 +0000765}
766
767
768/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
769/// plus some stores to initialize a local variable instead of using a memcpy
770/// from a constant global. It is beneficial to use memset if the global is all
771/// zeros, or mostly zeros and large.
772static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
773 uint64_t GlobalSize) {
774 // If a global is all zeros, always use a memset.
775 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
776
Chris Lattner94cd0112010-12-01 02:05:19 +0000777 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
778 // do it if it will require 6 or fewer scalar stores.
779 // TODO: Should budget depends on the size? Avoiding a large global warrants
780 // plopping in more stores.
781 unsigned StoreBudget = 6;
782 uint64_t SizeLimit = 32;
Eric Christophere1f54902011-08-23 22:38:00 +0000783
784 return GlobalSize > SizeLimit &&
Chris Lattner94cd0112010-12-01 02:05:19 +0000785 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
786}
787
Nadav Rotem495cfa42013-03-23 06:43:35 +0000788/// Should we use the LLVM lifetime intrinsics for the given local variable?
789static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
790 unsigned Size) {
Alexey Samsonov4f01ed42013-04-02 13:19:46 +0000791 // Always emit lifetime markers in -fsanitize=use-after-scope mode.
792 if (CGF.getLangOpts().Sanitize.UseAfterScope)
793 return true;
Nadav Rotem495cfa42013-03-23 06:43:35 +0000794 // For now, only in optimized builds.
795 if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
796 return false;
797
798 // Limit the size of marked objects to 32 bytes. We don't want to increase
799 // compile time by marking tiny objects.
800 unsigned SizeThreshold = 32;
801
802 return Size > SizeThreshold;
803}
804
Chris Lattner94cd0112010-12-01 02:05:19 +0000805
Nick Lewyckya9de3fa2010-12-30 20:21:55 +0000806/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Reid Spencer5f016e22007-07-11 17:01:13 +0000807/// variable declaration with auto, register, or no storage class specifier.
Chris Lattner2621fd12008-05-08 05:58:21 +0000808/// These turn into simple stack objects, or GlobalValues depending on target.
John McCall34695852011-02-22 06:44:22 +0000809void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
810 AutoVarEmission emission = EmitAutoVarAlloca(D);
811 EmitAutoVarInit(emission);
812 EmitAutoVarCleanups(emission);
813}
Reid Spencer5f016e22007-07-11 17:01:13 +0000814
John McCall34695852011-02-22 06:44:22 +0000815/// EmitAutoVarAlloca - Emit the alloca and debug information for a
816/// local variable. Does not emit initalization or destruction.
817CodeGenFunction::AutoVarEmission
818CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
819 QualType Ty = D.getType();
820
821 AutoVarEmission emission(D);
822
823 bool isByRef = D.hasAttr<BlocksAttr>();
824 emission.IsByRef = isByRef;
825
826 CharUnits alignment = getContext().getDeclAlign(&D);
827 emission.Alignment = alignment;
828
John McCallbc8d40d2011-06-24 21:55:10 +0000829 // If the type is variably-modified, emit all the VLA sizes for it.
830 if (Ty->isVariablyModifiedType())
831 EmitVariablyModifiedType(Ty);
832
Reid Spencer5f016e22007-07-11 17:01:13 +0000833 llvm::Value *DeclPtr;
Eli Friedman3c2b3172008-02-15 12:20:59 +0000834 if (Ty->isConstantSizeType()) {
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000835 bool NRVO = getLangOpts().ElideConstructors &&
836 D.isNRVOVariable();
John McCall34695852011-02-22 06:44:22 +0000837
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000838 // If this value is a POD array or struct with a statically
839 // determinable constant initializer, there are optimizations we can do.
840 //
841 // TODO: We should constant-evaluate the initializer of any variable,
842 // as long as it is initialized by a constant expression. Currently,
843 // isConstantInitializer produces wrong answers for structs with
844 // reference or bitfield members, and a few other cases, and checking
845 // for POD-ness protects us from some of these.
846 if (D.getInit() &&
847 (Ty->isArrayType() || Ty->isRecordType()) &&
848 (Ty.isPODType(getContext()) ||
849 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
850 D.getInit()->isConstantInitializer(getContext(), false)) {
John McCall34695852011-02-22 06:44:22 +0000851
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000852 // If the variable's a const type, and it's neither an NRVO
853 // candidate nor a __block variable and has no mutable members,
854 // emit it as a global instead.
855 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
856 CGM.isTypeConstant(Ty, true)) {
857 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCall34695852011-02-22 06:44:22 +0000858
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000859 emission.Address = 0; // signal this condition to later callbacks
860 assert(emission.wasEmittedAsGlobal());
861 return emission;
Tanya Lattner59876c22009-11-04 01:18:09 +0000862 }
Eric Christophere1f54902011-08-23 22:38:00 +0000863
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000864 // Otherwise, tell the initialization code that we're in this case.
865 emission.IsConstantAggregate = true;
866 }
Eric Christophere1f54902011-08-23 22:38:00 +0000867
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000868 // A normal fixed sized variable becomes an alloca in the entry block,
869 // unless it's an NRVO variable.
870 llvm::Type *LTy = ConvertTypeForMem(Ty);
Eric Christophere1f54902011-08-23 22:38:00 +0000871
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000872 if (NRVO) {
873 // The named return value optimization: allocate this variable in the
874 // return slot, so that we can elide the copy when returning this
875 // variable (C++0x [class.copy]p34).
876 DeclPtr = ReturnValue;
Eric Christophere1f54902011-08-23 22:38:00 +0000877
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000878 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
879 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
880 // Create a flag that is used to indicate when the NRVO was applied
881 // to this variable. Set it to zero to indicate that NRVO was not
882 // applied.
883 llvm::Value *Zero = Builder.getFalse();
884 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
885 EnsureInsertPoint();
886 Builder.CreateStore(Zero, NRVOFlag);
Eric Christophere1f54902011-08-23 22:38:00 +0000887
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000888 // Record the NRVO flag for this variable.
889 NRVOFlags[&D] = NRVOFlag;
890 emission.NRVOFlag = NRVOFlag;
Nadav Rotem495cfa42013-03-23 06:43:35 +0000891 }
Douglas Gregord86c4772010-05-15 06:46:45 +0000892 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000893 } else {
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000894 if (isByRef)
895 LTy = BuildByRefType(&D);
896
897 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
898 Alloc->setName(D.getName());
899
900 CharUnits allocaAlignment = alignment;
901 if (isByRef)
902 allocaAlignment = std::max(allocaAlignment,
John McCall64aa4b32013-04-16 22:48:15 +0000903 getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000904 Alloc->setAlignment(allocaAlignment.getQuantity());
905 DeclPtr = Alloc;
906
907 // Emit a lifetime intrinsic if meaningful. There's no point
908 // in doing this if we don't have a valid insertion point (?).
909 uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
910 if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
911 llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
912
913 emission.SizeForLifetimeMarkers = sizeV;
914 llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
915 Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
916 ->setDoesNotThrow();
917 } else {
918 assert(!emission.useLifetimeMarkers());
919 }
Chris Lattner2621fd12008-05-08 05:58:21 +0000920 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000921 } else {
Daniel Dunbard286f052009-07-19 06:58:07 +0000922 EnsureInsertPoint();
923
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000924 if (!DidCallStackSave) {
Anders Carlsson5d463152008-12-12 07:38:43 +0000925 // Save the stack.
John McCalld16c2cf2011-02-08 08:22:06 +0000926 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Anders Carlsson5d463152008-12-12 07:38:43 +0000928 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
929 llvm::Value *V = Builder.CreateCall(F);
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Anders Carlsson5d463152008-12-12 07:38:43 +0000931 Builder.CreateStore(V, Stack);
Anders Carlsson5ecb1b92009-02-09 20:41:50 +0000932
933 DidCallStackSave = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000934
John McCalld8715092010-07-21 06:13:08 +0000935 // Push a cleanup block and restore the stack there.
John McCall3ad32c82011-01-28 08:37:24 +0000936 // FIXME: in general circumstances, this should be an EH cleanup.
John McCall1f0fca52010-07-21 07:22:38 +0000937 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
Anders Carlsson5d463152008-12-12 07:38:43 +0000938 }
Mike Stump1eb44332009-09-09 15:08:12 +0000939
John McCallbc8d40d2011-06-24 21:55:10 +0000940 llvm::Value *elementCount;
941 QualType elementType;
942 llvm::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson5d463152008-12-12 07:38:43 +0000943
Chris Lattner2acc6e32011-07-18 04:24:23 +0000944 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson5d463152008-12-12 07:38:43 +0000945
946 // Allocate memory for the array.
John McCallbc8d40d2011-06-24 21:55:10 +0000947 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
948 vla->setAlignment(alignment.getQuantity());
Anders Carlsson41f8a132009-09-26 18:16:06 +0000949
John McCallbc8d40d2011-06-24 21:55:10 +0000950 DeclPtr = vla;
Reid Spencer5f016e22007-07-11 17:01:13 +0000951 }
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000952
Reid Spencer5f016e22007-07-11 17:01:13 +0000953 llvm::Value *&DMEntry = LocalDeclMap[&D];
954 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
955 DMEntry = DeclPtr;
John McCall34695852011-02-22 06:44:22 +0000956 emission.Address = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000957
958 // Emit debug info for local var declaration.
Devang Patelc594abd2011-06-03 19:21:47 +0000959 if (HaveInsertPoint())
960 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +0000961 if (CGM.getCodeGenOpts().getDebugInfo()
962 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000963 DI->setLocation(D.getLocation());
Rafael Espindola6c82fc62013-03-26 18:41:47 +0000964 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
Alexey Samsonovfd00eec2012-05-04 07:39:27 +0000965 }
Devang Patelc594abd2011-06-03 19:21:47 +0000966 }
Sanjiv Guptacc9b1632008-05-30 10:30:31 +0000967
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000968 if (D.hasAttr<AnnotateAttr>())
969 EmitVarAnnotations(&D, emission.Address);
970
John McCall34695852011-02-22 06:44:22 +0000971 return emission;
972}
973
974/// Determines whether the given __block variable is potentially
975/// captured by the given expression.
976static bool isCapturedBy(const VarDecl &var, const Expr *e) {
977 // Skip the most common kinds of expressions that make
978 // hierarchy-walking expensive.
979 e = e->IgnoreParenCasts();
980
981 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
982 const BlockDecl *block = be->getBlockDecl();
983 for (BlockDecl::capture_const_iterator i = block->capture_begin(),
984 e = block->capture_end(); i != e; ++i) {
985 if (i->getVariable() == &var)
986 return true;
987 }
988
989 // No need to walk into the subexpressions.
990 return false;
991 }
992
Fariborz Jahanian5033be12011-08-23 16:47:15 +0000993 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
994 const CompoundStmt *CS = SE->getSubStmt();
Eric Christopherc6fad602011-08-23 23:44:09 +0000995 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
996 BE = CS->body_end(); BI != BE; ++BI)
Fariborz Jahanian045c8422011-08-25 00:06:26 +0000997 if (Expr *E = dyn_cast<Expr>((*BI))) {
Fariborz Jahanian5033be12011-08-23 16:47:15 +0000998 if (isCapturedBy(var, E))
999 return true;
Fariborz Jahanian045c8422011-08-25 00:06:26 +00001000 }
1001 else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
1002 // special case declarations
1003 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1004 I != E; ++I) {
1005 if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
1006 Expr *Init = VD->getInit();
1007 if (Init && isCapturedBy(var, Init))
1008 return true;
1009 }
1010 }
1011 }
1012 else
1013 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1014 // Later, provide code to poke into statements for capture analysis.
1015 return true;
Fariborz Jahanian5033be12011-08-23 16:47:15 +00001016 return false;
1017 }
Eric Christophere1f54902011-08-23 22:38:00 +00001018
John McCall34695852011-02-22 06:44:22 +00001019 for (Stmt::const_child_range children = e->children(); children; ++children)
1020 if (isCapturedBy(var, cast<Expr>(*children)))
1021 return true;
1022
1023 return false;
1024}
1025
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001026/// \brief Determine whether the given initializer is trivial in the sense
1027/// that it requires no code to be generated.
1028static bool isTrivialInitializer(const Expr *Init) {
1029 if (!Init)
1030 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001031
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001032 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1033 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1034 if (Constructor->isTrivial() &&
1035 Constructor->isDefaultConstructor() &&
1036 !Construct->requiresZeroInitialization())
1037 return true;
Eric Christophere1f54902011-08-23 22:38:00 +00001038
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001039 return false;
1040}
John McCall34695852011-02-22 06:44:22 +00001041void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001042 assert(emission.Variable && "emission was not valid!");
1043
John McCall34695852011-02-22 06:44:22 +00001044 // If this was emitted as a global constant, we're done.
1045 if (emission.wasEmittedAsGlobal()) return;
1046
John McCall57b3b6a2011-02-22 07:16:58 +00001047 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001048 QualType type = D.getType();
1049
Chris Lattner19785962007-07-12 00:39:48 +00001050 // If this local has an initializer, emit it now.
Daniel Dunbard286f052009-07-19 06:58:07 +00001051 const Expr *Init = D.getInit();
1052
1053 // If we are at an unreachable point, we don't need to emit the initializer
1054 // unless it contains a label.
1055 if (!HaveInsertPoint()) {
John McCall34695852011-02-22 06:44:22 +00001056 if (!Init || !ContainsLabel(Init)) return;
1057 EnsureInsertPoint();
Daniel Dunbard286f052009-07-19 06:58:07 +00001058 }
1059
John McCall5af02db2011-03-31 01:59:53 +00001060 // Initialize the structure of a __block variable.
1061 if (emission.IsByRef)
1062 emitByrefStructureInit(emission);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001063
Douglas Gregorbcc3e662011-07-01 21:08:19 +00001064 if (isTrivialInitializer(Init))
1065 return;
Eric Christophere1f54902011-08-23 22:38:00 +00001066
John McCall5af02db2011-03-31 01:59:53 +00001067 CharUnits alignment = emission.Alignment;
1068
John McCall34695852011-02-22 06:44:22 +00001069 // Check whether this is a byref variable that's potentially
1070 // captured and moved by its own initializer. If so, we'll need to
1071 // emit the initializer first, then copy into the variable.
1072 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1073
1074 llvm::Value *Loc =
1075 capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1076
Richard Smith51201882011-12-30 21:15:51 +00001077 llvm::Constant *constant = 0;
1078 if (emission.IsConstantAggregate) {
1079 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smith2d6a5672012-01-14 04:30:29 +00001080 constant = CGM.EmitConstantInit(D, this);
Richard Smith51201882011-12-30 21:15:51 +00001081 }
1082
1083 if (!constant) {
Eli Friedman6da2c712011-12-03 04:14:32 +00001084 LValue lv = MakeAddrLValue(Loc, type, alignment);
John McCalla07398e2011-06-16 04:16:24 +00001085 lv.setNonGC(true);
1086 return EmitExprAsInit(Init, &D, lv, capturedByInit);
1087 }
John McCall60d33652011-03-08 09:11:50 +00001088
John McCall34695852011-02-22 06:44:22 +00001089 // If this is a simple aggregate initialization, we can optimize it
1090 // in various ways.
John McCall60d33652011-03-08 09:11:50 +00001091 bool isVolatile = type.isVolatileQualified();
John McCall34695852011-02-22 06:44:22 +00001092
John McCall60d33652011-03-08 09:11:50 +00001093 llvm::Value *SizeVal =
Eric Christophere1f54902011-08-23 22:38:00 +00001094 llvm::ConstantInt::get(IntPtrTy,
John McCall60d33652011-03-08 09:11:50 +00001095 getContext().getTypeSizeInChars(type).getQuantity());
John McCall34695852011-02-22 06:44:22 +00001096
Chris Lattner2acc6e32011-07-18 04:24:23 +00001097 llvm::Type *BP = Int8PtrTy;
John McCall60d33652011-03-08 09:11:50 +00001098 if (Loc->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001099 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wang3ecd7852010-04-04 03:10:52 +00001100
John McCall60d33652011-03-08 09:11:50 +00001101 // If the initializer is all or mostly zeros, codegen with memset then do
1102 // a few stores afterward.
Eric Christophere1f54902011-08-23 22:38:00 +00001103 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmow25a6a842012-10-08 16:25:52 +00001104 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall60d33652011-03-08 09:11:50 +00001105 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1106 alignment.getQuantity(), isVolatile);
Benjamin Kramer06d43682012-08-27 22:07:02 +00001107 // Zero and undef don't require a stores.
1108 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall60d33652011-03-08 09:11:50 +00001109 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1110 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001111 }
John McCall60d33652011-03-08 09:11:50 +00001112 } else {
Eric Christophere1f54902011-08-23 22:38:00 +00001113 // Otherwise, create a temporary global with the initializer then
John McCall60d33652011-03-08 09:11:50 +00001114 // memcpy from the global to the alloca.
1115 std::string Name = GetStaticDeclName(*this, D, ".");
1116 llvm::GlobalVariable *GV =
1117 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopher736a9c22011-08-24 00:33:55 +00001118 llvm::GlobalValue::PrivateLinkage,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +00001119 constant, Name);
John McCall60d33652011-03-08 09:11:50 +00001120 GV->setAlignment(alignment.getQuantity());
Eli Friedman460980d2011-05-27 22:32:55 +00001121 GV->setUnnamedAddr(true);
Eric Christophere1f54902011-08-23 22:38:00 +00001122
John McCall60d33652011-03-08 09:11:50 +00001123 llvm::Value *SrcPtr = GV;
1124 if (SrcPtr->getType() != BP)
Benjamin Kramer578faa82011-09-27 21:06:10 +00001125 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall60d33652011-03-08 09:11:50 +00001126
1127 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1128 isVolatile);
1129 }
1130}
1131
1132/// Emit an expression as an initializer for a variable at the given
1133/// location. The expression is not necessarily the normal
1134/// initializer for the variable, and the address is not necessarily
1135/// its normal location.
1136///
1137/// \param init the initializing expression
1138/// \param var the variable to act as if we're initializing
1139/// \param loc the address to initialize; its type is a pointer
1140/// to the LLVM mapping of the variable's type
1141/// \param alignment the alignment of the address
1142/// \param capturedByInit true if the variable is a __block variable
1143/// whose address is potentially changed by the initializer
1144void CodeGenFunction::EmitExprAsInit(const Expr *init,
John McCallf85e1932011-06-15 23:02:42 +00001145 const ValueDecl *D,
John McCalla07398e2011-06-16 04:16:24 +00001146 LValue lvalue,
John McCall60d33652011-03-08 09:11:50 +00001147 bool capturedByInit) {
John McCallf85e1932011-06-15 23:02:42 +00001148 QualType type = D->getType();
John McCall60d33652011-03-08 09:11:50 +00001149
1150 if (type->isReferenceType()) {
John McCalla07398e2011-06-16 04:16:24 +00001151 RValue rvalue = EmitReferenceBindingToExpr(init, D);
Eric Christophere1f54902011-08-23 22:38:00 +00001152 if (capturedByInit)
John McCalla07398e2011-06-16 04:16:24 +00001153 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Chisnall7a7ee302012-01-16 17:27:18 +00001154 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall9d232c82013-03-07 21:37:08 +00001155 return;
1156 }
1157 switch (getEvaluationKind(type)) {
1158 case TEK_Scalar:
John McCalla07398e2011-06-16 04:16:24 +00001159 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall9d232c82013-03-07 21:37:08 +00001160 return;
1161 case TEK_Complex: {
John McCall60d33652011-03-08 09:11:50 +00001162 ComplexPairTy complex = EmitComplexExpr(init);
John McCalla07398e2011-06-16 04:16:24 +00001163 if (capturedByInit)
1164 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall9d232c82013-03-07 21:37:08 +00001165 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1166 return;
1167 }
1168 case TEK_Aggregate:
John McCall9eda3ab2013-03-07 21:37:17 +00001169 if (type->isAtomicType()) {
1170 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1171 } else {
1172 // TODO: how can we delay here if D is captured by its initializer?
1173 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier649b4a12012-03-29 17:37:10 +00001174 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001175 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001176 AggValueSlot::IsNotAliased));
John McCall9eda3ab2013-03-07 21:37:17 +00001177 }
Sebastian Redl972edf02012-02-19 16:03:09 +00001178 MaybeEmitStdInitializerListCleanup(lvalue.getAddress(), init);
John McCall9d232c82013-03-07 21:37:08 +00001179 return;
Fariborz Jahanian20e1c7e2010-03-12 21:40:43 +00001180 }
John McCall9d232c82013-03-07 21:37:08 +00001181 llvm_unreachable("bad evaluation kind");
John McCall34695852011-02-22 06:44:22 +00001182}
John McCallf1549f62010-07-06 01:34:17 +00001183
John McCallbdc4d802011-07-09 01:37:26 +00001184/// Enter a destroy cleanup for the given local variable.
1185void CodeGenFunction::emitAutoVarTypeCleanup(
1186 const CodeGenFunction::AutoVarEmission &emission,
1187 QualType::DestructionKind dtorKind) {
1188 assert(dtorKind != QualType::DK_none);
1189
1190 // Note that for __block variables, we want to destroy the
1191 // original stack object, not the possibly forwarded object.
1192 llvm::Value *addr = emission.getObjectAddress(*this);
1193
1194 const VarDecl *var = emission.Variable;
1195 QualType type = var->getType();
1196
1197 CleanupKind cleanupKind = NormalAndEHCleanup;
1198 CodeGenFunction::Destroyer *destroyer = 0;
1199
1200 switch (dtorKind) {
1201 case QualType::DK_none:
1202 llvm_unreachable("no cleanup for trivially-destructible variable");
1203
1204 case QualType::DK_cxx_destructor:
1205 // If there's an NRVO flag on the emission, we need a different
1206 // cleanup.
1207 if (emission.NRVOFlag) {
1208 assert(!type->isArrayType());
1209 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1210 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1211 emission.NRVOFlag);
1212 return;
1213 }
1214 break;
1215
1216 case QualType::DK_objc_strong_lifetime:
1217 // Suppress cleanups for pseudo-strong variables.
1218 if (var->isARCPseudoStrong()) return;
Eric Christophere1f54902011-08-23 22:38:00 +00001219
John McCallbdc4d802011-07-09 01:37:26 +00001220 // Otherwise, consider whether to use an EH cleanup or not.
1221 cleanupKind = getARCCleanupKind();
1222
1223 // Use the imprecise destroyer by default.
1224 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1225 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1226 break;
1227
1228 case QualType::DK_objc_weak_lifetime:
1229 break;
1230 }
1231
1232 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001233 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall2673c682011-07-11 08:38:19 +00001234
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00001235 // Use an EH cleanup in array destructors iff the destructor itself
John McCall2673c682011-07-11 08:38:19 +00001236 // is being pushed as an EH cleanup.
1237 bool useEHCleanup = (cleanupKind & EHCleanup);
1238 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1239 useEHCleanup);
John McCallbdc4d802011-07-09 01:37:26 +00001240}
1241
John McCall34695852011-02-22 06:44:22 +00001242void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall57b3b6a2011-02-22 07:16:58 +00001243 assert(emission.Variable && "emission was not valid!");
1244
John McCall34695852011-02-22 06:44:22 +00001245 // If this was emitted as a global constant, we're done.
1246 if (emission.wasEmittedAsGlobal()) return;
1247
John McCall38baeab2012-04-13 18:44:05 +00001248 // If we don't have an insertion point, we're done. Sema prevents
1249 // us from jumping into any of these scopes anyway.
1250 if (!HaveInsertPoint()) return;
1251
John McCall57b3b6a2011-02-22 07:16:58 +00001252 const VarDecl &D = *emission.Variable;
John McCall34695852011-02-22 06:44:22 +00001253
Nadav Rotem495cfa42013-03-23 06:43:35 +00001254 // Make sure we call @llvm.lifetime.end. This needs to happen
1255 // *last*, so the cleanup needs to be pushed *first*.
1256 if (emission.useLifetimeMarkers()) {
1257 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1258 emission.getAllocatedAddress(),
1259 emission.getSizeForLifetimeMarkers());
1260 }
1261
John McCallbdc4d802011-07-09 01:37:26 +00001262 // Check the type for a cleanup.
1263 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1264 emitAutoVarTypeCleanup(emission, dtorKind);
John McCallf85e1932011-06-15 23:02:42 +00001265
John McCall0c24c802011-06-24 23:21:27 +00001266 // In GC mode, honor objc_precise_lifetime.
David Blaikie4e4d0842012-03-11 07:00:24 +00001267 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall0c24c802011-06-24 23:21:27 +00001268 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1269 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1270 }
1271
John McCall34695852011-02-22 06:44:22 +00001272 // Handle the cleanup attribute.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001273 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlsson69c68b72009-02-07 23:51:38 +00001274 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001275
John McCall34695852011-02-22 06:44:22 +00001276 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001277 assert(F && "Could not find function!");
Mike Stump1eb44332009-09-09 15:08:12 +00001278
John McCallde5d3c72012-02-17 03:33:10 +00001279 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCall34695852011-02-22 06:44:22 +00001280 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlsson69c68b72009-02-07 23:51:38 +00001281 }
Mike Stump797b6322009-03-05 01:23:13 +00001282
John McCall34695852011-02-22 06:44:22 +00001283 // If this is a block variable, call _Block_object_destroy
1284 // (on the unforwarded address).
John McCall5af02db2011-03-31 01:59:53 +00001285 if (emission.IsByRef)
1286 enterByrefCleanup(emission);
Reid Spencer5f016e22007-07-11 17:01:13 +00001287}
1288
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001289CodeGenFunction::Destroyer *
John McCallbdc4d802011-07-09 01:37:26 +00001290CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1291 switch (kind) {
1292 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCall0850e8d2011-07-09 09:09:00 +00001293 case QualType::DK_cxx_destructor:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001294 return destroyCXXObject;
John McCall0850e8d2011-07-09 09:09:00 +00001295 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001296 return destroyARCStrongPrecise;
John McCall0850e8d2011-07-09 09:09:00 +00001297 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001298 return destroyARCWeak;
John McCallbdc4d802011-07-09 01:37:26 +00001299 }
Matt Beaumont-Gayba4be252012-01-27 00:46:27 +00001300 llvm_unreachable("Unknown DestructionKind");
John McCallbdc4d802011-07-09 01:37:26 +00001301}
1302
John McCall074cae02013-02-01 05:11:40 +00001303/// pushEHDestroy - Push the standard destructor for the given type as
1304/// an EH-only cleanup.
1305void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1306 llvm::Value *addr, QualType type) {
1307 assert(dtorKind && "cannot push destructor for trivial type");
1308 assert(needsEHCleanup(dtorKind));
1309
1310 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1311}
1312
1313/// pushDestroy - Push the standard destructor for the given type as
1314/// at least a normal cleanup.
John McCall9928c482011-07-12 16:41:08 +00001315void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1316 llvm::Value *addr, QualType type) {
1317 assert(dtorKind && "cannot push destructor for trivial type");
1318
1319 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1320 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1321 cleanupKind & EHCleanup);
1322}
1323
John McCallbdc4d802011-07-09 01:37:26 +00001324void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001325 QualType type, Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001326 bool useEHCleanupForArray) {
John McCall9928c482011-07-12 16:41:08 +00001327 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1328 destroyer, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001329}
1330
John McCall2673c682011-07-11 08:38:19 +00001331/// emitDestroy - Immediately perform the destruction of the given
1332/// object.
1333///
1334/// \param addr - the address of the object; a type*
1335/// \param type - the type of the object; if an array type, all
1336/// objects are destroyed in reverse order
1337/// \param destroyer - the function to call to destroy individual
1338/// elements
1339/// \param useEHCleanupForArray - whether an EH cleanup should be
1340/// used when destroying array elements, in case one of the
1341/// destructions throws an exception
John McCallbdc4d802011-07-09 01:37:26 +00001342void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001343 Destroyer *destroyer,
John McCall2673c682011-07-11 08:38:19 +00001344 bool useEHCleanupForArray) {
John McCallbdc4d802011-07-09 01:37:26 +00001345 const ArrayType *arrayType = getContext().getAsArrayType(type);
1346 if (!arrayType)
1347 return destroyer(*this, addr, type);
1348
1349 llvm::Value *begin = addr;
1350 llvm::Value *length = emitArrayLength(arrayType, type, begin);
John McCallfbf780a2011-07-13 08:09:46 +00001351
1352 // Normally we have to check whether the array is zero-length.
1353 bool checkZeroLength = true;
1354
1355 // But if the array length is constant, we can suppress that.
1356 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1357 // ...and if it's constant zero, we can just skip the entire thing.
1358 if (constLength->isZero()) return;
1359 checkZeroLength = false;
1360 }
1361
John McCallbdc4d802011-07-09 01:37:26 +00001362 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCallfbf780a2011-07-13 08:09:46 +00001363 emitArrayDestroy(begin, end, type, destroyer,
1364 checkZeroLength, useEHCleanupForArray);
John McCallbdc4d802011-07-09 01:37:26 +00001365}
1366
John McCall2673c682011-07-11 08:38:19 +00001367/// emitArrayDestroy - Destroys all the elements of the given array,
1368/// beginning from last to first. The array cannot be zero-length.
1369///
1370/// \param begin - a type* denoting the first element of the array
1371/// \param end - a type* denoting one past the end of the array
1372/// \param type - the element type of the array
1373/// \param destroyer - the function to call to destroy elements
1374/// \param useEHCleanup - whether to push an EH cleanup to destroy
1375/// the remaining elements in case the destruction of a single
1376/// element throws
John McCallbdc4d802011-07-09 01:37:26 +00001377void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1378 llvm::Value *end,
1379 QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001380 Destroyer *destroyer,
John McCallfbf780a2011-07-13 08:09:46 +00001381 bool checkZeroLength,
John McCall2673c682011-07-11 08:38:19 +00001382 bool useEHCleanup) {
John McCallbdc4d802011-07-09 01:37:26 +00001383 assert(!type->isArrayType());
1384
1385 // The basic structure here is a do-while loop, because we don't
1386 // need to check for the zero-element case.
1387 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1388 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1389
John McCallfbf780a2011-07-13 08:09:46 +00001390 if (checkZeroLength) {
1391 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1392 "arraydestroy.isempty");
1393 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1394 }
1395
John McCallbdc4d802011-07-09 01:37:26 +00001396 // Enter the loop body, making that address the current address.
1397 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1398 EmitBlock(bodyBB);
1399 llvm::PHINode *elementPast =
1400 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1401 elementPast->addIncoming(end, entryBB);
1402
1403 // Shift the address back by one element.
1404 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1405 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1406 "arraydestroy.element");
1407
John McCall2673c682011-07-11 08:38:19 +00001408 if (useEHCleanup)
1409 pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1410
John McCallbdc4d802011-07-09 01:37:26 +00001411 // Perform the actual destruction there.
1412 destroyer(*this, element, type);
1413
John McCall2673c682011-07-11 08:38:19 +00001414 if (useEHCleanup)
1415 PopCleanupBlock();
1416
John McCallbdc4d802011-07-09 01:37:26 +00001417 // Check whether we've reached the end.
1418 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1419 Builder.CreateCondBr(done, doneBB, bodyBB);
1420 elementPast->addIncoming(element, Builder.GetInsertBlock());
1421
1422 // Done.
1423 EmitBlock(doneBB);
1424}
1425
John McCall2673c682011-07-11 08:38:19 +00001426/// Perform partial array destruction as if in an EH cleanup. Unlike
1427/// emitArrayDestroy, the element type here may still be an array type.
John McCall2673c682011-07-11 08:38:19 +00001428static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1429 llvm::Value *begin, llvm::Value *end,
1430 QualType type,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001431 CodeGenFunction::Destroyer *destroyer) {
John McCall2673c682011-07-11 08:38:19 +00001432 // If the element type is itself an array, drill down.
John McCallfbf780a2011-07-13 08:09:46 +00001433 unsigned arrayDepth = 0;
John McCall2673c682011-07-11 08:38:19 +00001434 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1435 // VLAs don't require a GEP index to walk into.
1436 if (!isa<VariableArrayType>(arrayType))
John McCallfbf780a2011-07-13 08:09:46 +00001437 arrayDepth++;
John McCall2673c682011-07-11 08:38:19 +00001438 type = arrayType->getElementType();
1439 }
John McCallfbf780a2011-07-13 08:09:46 +00001440
1441 if (arrayDepth) {
1442 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1443
Chris Lattner5f9e2722011-07-23 10:55:15 +00001444 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001445 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1446 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall2673c682011-07-11 08:38:19 +00001447 }
1448
John McCallfbf780a2011-07-13 08:09:46 +00001449 // Destroy the array. We don't ever need an EH cleanup because we
1450 // assume that we're in an EH cleanup ourselves, so a throwing
1451 // destructor causes an immediate terminate.
1452 CGF.emitArrayDestroy(begin, end, type, destroyer,
1453 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall2673c682011-07-11 08:38:19 +00001454}
1455
John McCallbdc4d802011-07-09 01:37:26 +00001456namespace {
John McCall2673c682011-07-11 08:38:19 +00001457 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1458 /// array destroy where the end pointer is regularly determined and
1459 /// does not need to be loaded from a local.
1460 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1461 llvm::Value *ArrayBegin;
1462 llvm::Value *ArrayEnd;
1463 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001464 CodeGenFunction::Destroyer *Destroyer;
John McCall2673c682011-07-11 08:38:19 +00001465 public:
1466 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1467 QualType elementType,
1468 CodeGenFunction::Destroyer *destroyer)
1469 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001470 ElementType(elementType), Destroyer(destroyer) {}
John McCall2673c682011-07-11 08:38:19 +00001471
John McCallad346f42011-07-12 20:27:29 +00001472 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall2673c682011-07-11 08:38:19 +00001473 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1474 ElementType, Destroyer);
1475 }
1476 };
1477
1478 /// IrregularPartialArrayDestroy - a cleanup which performs a
1479 /// partial array destroy where the end pointer is irregularly
1480 /// determined and must be loaded from a local.
1481 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
John McCallbdc4d802011-07-09 01:37:26 +00001482 llvm::Value *ArrayBegin;
1483 llvm::Value *ArrayEndPointer;
1484 QualType ElementType;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001485 CodeGenFunction::Destroyer *Destroyer;
John McCallbdc4d802011-07-09 01:37:26 +00001486 public:
John McCall2673c682011-07-11 08:38:19 +00001487 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1488 llvm::Value *arrayEndPointer,
1489 QualType elementType,
1490 CodeGenFunction::Destroyer *destroyer)
John McCallbdc4d802011-07-09 01:37:26 +00001491 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001492 ElementType(elementType), Destroyer(destroyer) {}
John McCallbdc4d802011-07-09 01:37:26 +00001493
John McCallad346f42011-07-12 20:27:29 +00001494 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallbdc4d802011-07-09 01:37:26 +00001495 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall2673c682011-07-11 08:38:19 +00001496 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1497 ElementType, Destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001498 }
1499 };
1500}
1501
John McCall2673c682011-07-11 08:38:19 +00001502/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCallbdc4d802011-07-09 01:37:26 +00001503/// already-constructed elements of the given array. The cleanup
John McCall2673c682011-07-11 08:38:19 +00001504/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001505///
John McCallbdc4d802011-07-09 01:37:26 +00001506/// \param elementType - the immediate element type of the array;
1507/// possibly still an array type
John McCall9928c482011-07-12 16:41:08 +00001508void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall2673c682011-07-11 08:38:19 +00001509 llvm::Value *arrayEndPointer,
1510 QualType elementType,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001511 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001512 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1513 arrayBegin, arrayEndPointer,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001514 elementType, destroyer);
John McCall2673c682011-07-11 08:38:19 +00001515}
1516
1517/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1518/// already-constructed elements of the given array. The cleanup
1519/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christophere1f54902011-08-23 22:38:00 +00001520///
John McCall2673c682011-07-11 08:38:19 +00001521/// \param elementType - the immediate element type of the array;
1522/// possibly still an array type
John McCall2673c682011-07-11 08:38:19 +00001523void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1524 llvm::Value *arrayEnd,
1525 QualType elementType,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001526 Destroyer *destroyer) {
John McCall9928c482011-07-12 16:41:08 +00001527 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall2673c682011-07-11 08:38:19 +00001528 arrayBegin, arrayEnd,
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001529 elementType, destroyer);
John McCallbdc4d802011-07-09 01:37:26 +00001530}
1531
Nadav Rotem495cfa42013-03-23 06:43:35 +00001532/// Lazily declare the @llvm.lifetime.start intrinsic.
1533llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1534 if (LifetimeStartFn) return LifetimeStartFn;
1535 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1536 llvm::Intrinsic::lifetime_start);
1537 return LifetimeStartFn;
1538}
1539
1540/// Lazily declare the @llvm.lifetime.end intrinsic.
1541llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1542 if (LifetimeEndFn) return LifetimeEndFn;
1543 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1544 llvm::Intrinsic::lifetime_end);
1545 return LifetimeEndFn;
1546}
1547
John McCallf85e1932011-06-15 23:02:42 +00001548namespace {
1549 /// A cleanup to perform a release of an object at the end of a
1550 /// function. This is used to balance out the incoming +1 of a
1551 /// ns_consumed argument when we can't reasonably do that just by
1552 /// not doing the initial retain for a __block argument.
1553 struct ConsumeARCParameter : EHScopeStack::Cleanup {
John McCall5b07e802013-03-13 03:10:54 +00001554 ConsumeARCParameter(llvm::Value *param,
1555 ARCPreciseLifetime_t precise)
1556 : Param(param), Precise(precise) {}
John McCallf85e1932011-06-15 23:02:42 +00001557
1558 llvm::Value *Param;
John McCall5b07e802013-03-13 03:10:54 +00001559 ARCPreciseLifetime_t Precise;
John McCallf85e1932011-06-15 23:02:42 +00001560
John McCallad346f42011-07-12 20:27:29 +00001561 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall5b07e802013-03-13 03:10:54 +00001562 CGF.EmitARCRelease(Param, Precise);
John McCallf85e1932011-06-15 23:02:42 +00001563 }
1564 };
1565}
1566
Mike Stump1eb44332009-09-09 15:08:12 +00001567/// Emit an alloca (or GlobalValue depending on target)
Chris Lattner2621fd12008-05-08 05:58:21 +00001568/// for the specified parameter and set up LocalDeclMap.
Devang Patel093ac462011-03-03 20:13:15 +00001569void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1570 unsigned ArgNo) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001571 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +00001572 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001573 "Invalid argument to EmitParmDecl");
John McCall8178df32011-02-22 22:38:33 +00001574
1575 Arg->setName(D.getName());
1576
Adrian Prantl836e7c92013-03-14 17:53:33 +00001577 QualType Ty = D.getType();
1578
John McCall8178df32011-02-22 22:38:33 +00001579 // Use better IR generation for certain implicit parameters.
1580 if (isa<ImplicitParamDecl>(D)) {
1581 // The only implicit argument a block has is its literal.
1582 if (BlockInfo) {
1583 LocalDeclMap[&D] = Arg;
Adrian Prantl836e7c92013-03-14 17:53:33 +00001584 llvm::Value *LocalAddr = 0;
1585 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
Adrian Prantl9b97adf2013-03-29 19:20:35 +00001586 // Allocate a stack slot to let the debug info survive the RA.
Adrian Prantl836e7c92013-03-14 17:53:33 +00001587 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1588 D.getName() + ".addr");
1589 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1590 LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1591 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1592 LocalAddr = Builder.CreateLoad(Alloc);
1593 }
John McCall8178df32011-02-22 22:38:33 +00001594
1595 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +00001596 if (CGM.getCodeGenOpts().getDebugInfo()
1597 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001598 DI->setLocation(D.getLocation());
Adrian Prantl836e7c92013-03-14 17:53:33 +00001599 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, LocalAddr, Builder);
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001600 }
John McCall8178df32011-02-22 22:38:33 +00001601 }
1602
1603 return;
1604 }
1605 }
1606
Reid Spencer5f016e22007-07-11 17:01:13 +00001607 llvm::Value *DeclPtr;
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001608 // If this is an aggregate or variable sized value, reuse the input pointer.
1609 if (!Ty->isConstantSizeType() ||
John McCall9d232c82013-03-07 21:37:08 +00001610 !CodeGenFunction::hasScalarEvaluationKind(Ty)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 DeclPtr = Arg;
Reid Spencer5f016e22007-07-11 17:01:13 +00001612 } else {
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001613 // Otherwise, create a temporary to hold the value.
Eli Friedmanddfb8d12011-11-03 20:31:28 +00001614 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1615 D.getName() + ".addr");
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001616 CharUnits Align = getContext().getDeclAlign(&D);
1617 Alloc->setAlignment(Align.getQuantity());
Eli Friedmanddfb8d12011-11-03 20:31:28 +00001618 DeclPtr = Alloc;
Mike Stump1eb44332009-09-09 15:08:12 +00001619
John McCallf85e1932011-06-15 23:02:42 +00001620 bool doStore = true;
1621
1622 Qualifiers qs = Ty.getQualifiers();
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001623 LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
John McCallf85e1932011-06-15 23:02:42 +00001624 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1625 // We honor __attribute__((ns_consumed)) for types with lifetime.
1626 // For __strong, it's handled by just skipping the initial retain;
1627 // otherwise we have to balance out the initial +1 with an extra
1628 // cleanup to do the release at the end of the function.
1629 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1630
1631 // 'self' is always formally __strong, but if this is not an
1632 // init method then we don't want to retain it.
John McCall7acddac2011-06-17 06:42:21 +00001633 if (D.isARCPseudoStrong()) {
John McCallf85e1932011-06-15 23:02:42 +00001634 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1635 assert(&D == method->getSelfDecl());
John McCall7acddac2011-06-17 06:42:21 +00001636 assert(lt == Qualifiers::OCL_Strong);
1637 assert(qs.hasConst());
John McCallf85e1932011-06-15 23:02:42 +00001638 assert(method->getMethodFamily() != OMF_init);
John McCall175d6592011-06-15 23:40:09 +00001639 (void) method;
John McCallf85e1932011-06-15 23:02:42 +00001640 lt = Qualifiers::OCL_ExplicitNone;
1641 }
1642
1643 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001644 if (!isConsumed) {
1645 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1646 // use objc_storeStrong(&dest, value) for retaining the
1647 // object. But first, store a null into 'dest' because
1648 // objc_storeStrong attempts to release its old value.
1649 llvm::Value * Null = CGM.EmitNullConstant(D.getType());
1650 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1651 EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
1652 doStore = false;
1653 }
1654 else
John McCallf85e1932011-06-15 23:02:42 +00001655 // Don't use objc_retainBlock for block pointers, because we
1656 // don't want to Block_copy something just because we got it
1657 // as a parameter.
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001658 Arg = EmitARCRetainNonBlock(Arg);
1659 }
John McCallf85e1932011-06-15 23:02:42 +00001660 } else {
1661 // Push the cleanup for a consumed parameter.
John McCall5b07e802013-03-13 03:10:54 +00001662 if (isConsumed) {
1663 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1664 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1665 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1666 precise);
1667 }
John McCallf85e1932011-06-15 23:02:42 +00001668
1669 if (lt == Qualifiers::OCL_Weak) {
1670 EmitARCInitWeak(DeclPtr, Arg);
Chad Rosier7acebfb2012-02-18 01:20:35 +00001671 doStore = false; // The weak init is a store, no need to do two.
John McCallf85e1932011-06-15 23:02:42 +00001672 }
1673 }
1674
1675 // Enter the cleanup scope.
1676 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1677 }
1678
Daniel Dunbare86bcf02010-02-08 22:53:07 +00001679 // Store the initial value into the alloca.
Fariborz Jahanian41a6a3e2013-02-21 00:40:10 +00001680 if (doStore)
David Chisnall7a7ee302012-01-16 17:27:18 +00001681 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
Reid Spencer5f016e22007-07-11 17:01:13 +00001682 }
1683
1684 llvm::Value *&DMEntry = LocalDeclMap[&D];
1685 assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1686 DMEntry = DeclPtr;
Sanjiv Guptacc9b1632008-05-30 10:30:31 +00001687
1688 // Emit debug info for param declaration.
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001689 if (CGDebugInfo *DI = getDebugInfo()) {
Douglas Gregor4cdad312012-10-23 20:05:01 +00001690 if (CGM.getCodeGenOpts().getDebugInfo()
1691 >= CodeGenOptions::LimitedDebugInfo) {
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001692 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1693 }
1694 }
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001695
1696 if (D.hasAttr<AnnotateAttr>())
1697 EmitVarAnnotations(&D, DeclPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001698}