blob: 3d84b262a8fe278c245521704e8c6a0d5d8de0ad [file] [log] [blame]
Chris Lattner84915fa2007-06-02 04:16:21 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner84915fa2007-06-02 04:16:21 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Decl nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
John McCall7f416cc2015-09-08 08:05:57 +000015#include "CGBlocks.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000016#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGDebugInfo.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000018#include "CGOpenCLRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "CodeGenModule.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000020#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000021#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000022#include "clang/AST/Decl.h"
Anders Carlsson4c03d982008-08-25 01:38:19 +000023#include "clang/AST/DeclObjC.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000024#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000025#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000026#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000027#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000028#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/GlobalVariable.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/Type.h"
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +000032
Chris Lattner84915fa2007-06-02 04:16:21 +000033using namespace clang;
34using namespace CodeGen;
35
Chris Lattner1ad38f82007-06-09 01:20:56 +000036void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000037 switch (D.getKind()) {
David Majnemerd9b1a4f2015-11-04 03:40:30 +000038 case Decl::BuiltinTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000039 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +000040 case Decl::ExternCContext:
Douglas Gregor19043f02010-04-23 02:02:43 +000041 case Decl::Namespace:
42 case Decl::UnresolvedUsingTypename:
43 case Decl::ClassTemplateSpecialization:
44 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000045 case Decl::VarTemplateSpecialization:
46 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000047 case Decl::TemplateTypeParm:
48 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000049 case Decl::NonTypeTemplateParm:
Douglas Gregor19043f02010-04-23 02:02:43 +000050 case Decl::CXXMethod:
51 case Decl::CXXConstructor:
52 case Decl::CXXDestructor:
53 case Decl::CXXConversion:
54 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000055 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000056 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000057 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000058 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000059 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000060 case Decl::ImplicitParam:
61 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000062 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000063 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000064 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000065 case Decl::TemplateTemplateParm:
66 case Decl::ObjCMethod:
67 case Decl::ObjCCategory:
68 case Decl::ObjCProtocol:
69 case Decl::ObjCInterface:
70 case Decl::ObjCCategoryImpl:
71 case Decl::ObjCImplementation:
72 case Decl::ObjCProperty:
73 case Decl::ObjCCompatibleAlias:
Abramo Bagnarad7340582010-06-05 05:09:32 +000074 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000075 case Decl::LinkageSpec:
76 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000077 case Decl::FileScopeAsm:
78 case Decl::Friend:
79 case Decl::FriendTemplate:
80 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000081 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000082 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000083 case Decl::UsingShadow:
Douglas Gregor85f3f952015-07-07 03:57:15 +000084 case Decl::ObjCTypeParam:
David Blaikie83d382b2011-09-23 05:06:16 +000085 llvm_unreachable("Declaration should not be in declstmts!");
Chris Lattner84915fa2007-06-02 04:16:21 +000086 case Decl::Function: // void X();
David Blaikiebe822ed2015-07-01 18:07:22 +000087 case Decl::Record: // struct/union/class X;
Chris Lattner84915fa2007-06-02 04:16:21 +000088 case Decl::Enum: // enum X;
Mike Stump11289f42009-09-09 15:08:12 +000089 case Decl::EnumConstant: // enum ? { X = ? }
David Blaikiebe822ed2015-07-01 18:07:22 +000090 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +000091 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +000092 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +000093 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +000094 case Decl::OMPThreadPrivate:
Alexey Bataev90c228f2016-02-08 09:29:13 +000095 case Decl::OMPCapturedField:
Michael Han84324352013-02-22 17:15:32 +000096 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +000097 // None of these decls require codegen support.
98 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +000099
David Blaikief121b932013-05-20 22:50:41 +0000100 case Decl::NamespaceAlias:
101 if (CGDebugInfo *DI = getDebugInfo())
102 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
103 return;
David Blaikiebd483762013-05-20 04:58:53 +0000104 case Decl::Using: // using X; [C++]
105 if (CGDebugInfo *DI = getDebugInfo())
106 DI->EmitUsingDecl(cast<UsingDecl>(D));
107 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000108 case Decl::UsingDirective: // using namespace X; [C++]
109 if (CGDebugInfo *DI = getDebugInfo())
110 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
111 return;
Daniel Dunbara7998072008-08-29 17:28:43 +0000112 case Decl::Var: {
113 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000114 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000115 "Should not see file-scope variables inside a function!");
John McCall1c9c3fd2010-10-15 04:57:14 +0000116 return EmitVarDecl(VD);
Chris Lattner84915fa2007-06-02 04:16:21 +0000117 }
Mike Stump11289f42009-09-09 15:08:12 +0000118
Richard Smithdda56e42011-04-15 14:24:37 +0000119 case Decl::Typedef: // typedef int X;
120 case Decl::TypeAlias: { // using X = int; [C++0x]
121 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000122 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000123
Anders Carlsson5d985f52008-12-20 21:51:53 +0000124 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000125 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000126 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000127 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000128}
Chris Lattner03df1222007-06-02 04:53:11 +0000129
John McCall1c9c3fd2010-10-15 04:57:14 +0000130/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000131/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000132void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000133 if (D.isStaticLocal()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000134 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000135 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000136
David Majnemer27d69db2014-04-28 22:17:59 +0000137 // FIXME: We need to force the emission/use of a guard variable for
138 // some variables even if we can constant-evaluate them because
139 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000140
John McCall1c9c3fd2010-10-15 04:57:14 +0000141 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000142 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000143
144 if (D.hasExternalStorage())
Lauro Ramos Venanciobada8d42008-02-16 22:30:38 +0000145 // Don't emit it now, allow it to be emitted lazily on its first use.
146 return;
Daniel Dunbar0ca16602009-04-14 02:25:56 +0000147
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000148 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000149 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
150
151 assert(D.hasLocalStorage());
152 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000153}
154
Reid Kleckner453e0562014-10-08 01:07:54 +0000155static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
156 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000157 return CGM.getMangledName(&D).str();
158
Reid Kleckner453e0562014-10-08 01:07:54 +0000159 // If this isn't C++, we don't need a mangled name, just a pretty one.
160 assert(!D.isExternallyVisible() && "name shouldn't matter");
161 std::string ContextName;
162 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000163 if (auto *CD = dyn_cast<CapturedDecl>(DC))
164 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000165 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000166 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000167 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
168 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
169 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
170 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000171 else
David Blaikie83d382b2011-09-23 05:06:16 +0000172 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000173
Reid Kleckner453e0562014-10-08 01:07:54 +0000174 ContextName += "." + D.getNameAsString();
175 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000176}
177
Reid Kleckner453e0562014-10-08 01:07:54 +0000178llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
179 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
180 // In general, we don't always emit static var decls once before we reference
181 // them. It is possible to reference them before emitting the function that
182 // contains them, and it is possible to emit the containing function multiple
183 // times.
184 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
185 return ExistingGV;
186
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000187 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000188 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000189
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000190 // Use the label if the variable is renamed with the asm-label extension.
191 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000192 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000193 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000194 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000195 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000196
Reid Kleckner453e0562014-10-08 01:07:54 +0000197 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000198 unsigned AddrSpace =
Reid Kleckner453e0562014-10-08 01:07:54 +0000199 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000200
201 // Local address space cannot have an initializer.
202 llvm::Constant *Init = nullptr;
203 if (Ty.getAddressSpace() != LangAS::opencl_local)
204 Init = EmitNullConstant(Ty);
205 else
206 Init = llvm::UndefValue::get(LTy);
207
Anders Carlssone33eed52009-09-26 18:16:06 +0000208 llvm::GlobalVariable *GV =
Reid Kleckner453e0562014-10-08 01:07:54 +0000209 new llvm::GlobalVariable(getModule(), LTy,
Anders Carlssone33eed52009-09-26 18:16:06 +0000210 Ty.isConstant(getContext()), Linkage,
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000211 Init, Name, nullptr,
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000212 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000213 AddrSpace);
Ken Dyck160146e2010-01-27 17:10:57 +0000214 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Reid Kleckner453e0562014-10-08 01:07:54 +0000215 setGlobalVisibility(GV, &D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000216
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000217 if (supportsCOMDAT() && GV->isWeakForLinker())
218 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000219
Richard Smithfd3834f2013-04-13 02:43:54 +0000220 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000221 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000222
Hans Wennborgef2272c2014-06-18 15:55:13 +0000223 if (D.isExternallyVisible()) {
224 if (D.hasAttr<DLLImportAttr>())
225 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
226 else if (D.hasAttr<DLLExportAttr>())
227 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
228 }
229
Eli Benderskycb399432014-03-24 22:05:38 +0000230 // Make sure the result is of the correct type.
Reid Kleckner453e0562014-10-08 01:07:54 +0000231 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
232 llvm::Constant *Addr = GV;
Eli Benderskycb399432014-03-24 22:05:38 +0000233 if (AddrSpace != ExpectedAddrSpace) {
234 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
Reid Kleckner453e0562014-10-08 01:07:54 +0000235 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
Eli Benderskycb399432014-03-24 22:05:38 +0000236 }
237
Reid Kleckner453e0562014-10-08 01:07:54 +0000238 setStaticLocalDeclAddress(&D, Addr);
239
240 // Ensure that the static local gets initialized by making sure the parent
241 // function gets emitted eventually.
242 const Decl *DC = cast<Decl>(D.getDeclContext());
243
244 // We can't name blocks or captured statements directly, so try to emit their
245 // parents.
246 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
247 DC = DC->getNonClosureContext();
248 // FIXME: Ensure that global blocks get emitted.
249 if (!DC)
250 return Addr;
251 }
252
253 GlobalDecl GD;
254 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
255 GD = GlobalDecl(CD, Ctor_Base);
256 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
257 GD = GlobalDecl(DD, Dtor_Base);
258 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
259 GD = GlobalDecl(FD);
260 else {
261 // Don't do anything for Obj-C method decls or global closures. We should
262 // never defer them.
263 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
264 }
265 if (GD.getDecl())
266 (void)GetAddrOfGlobal(GD);
267
268 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000269}
270
Richard Smith6331c402012-02-13 22:16:19 +0000271/// hasNontrivialDestruction - Determine whether a type's destruction is
272/// non-trivial. If so, and the variable uses static initialization, we must
273/// register its destructor to run on exit.
274static bool hasNontrivialDestruction(QualType T) {
275 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
276 return RD && !RD->hasTrivialDestructor();
277}
278
Chandler Carruth84537952012-03-30 19:44:53 +0000279/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
280/// global variable that has already been created for it. If the initializer
281/// has a different type than GV does, this may free GV and return a different
282/// one. Otherwise it just returns GV.
283llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000284CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000285 llvm::GlobalVariable *GV) {
286 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCall70013b62010-07-15 23:40:35 +0000287
Chris Lattnere99c1102009-12-05 08:22:11 +0000288 // If constant emission failed, then this should be a C++ static
289 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000290 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000291 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000292 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall68ff0372010-09-08 01:44:27 +0000293 else if (Builder.GetInsertBlock()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000294 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000295 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000296 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000297
Chandler Carruth84537952012-03-30 19:44:53 +0000298 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000299 }
Chandler Carruth84537952012-03-30 19:44:53 +0000300 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000301 }
John McCall70013b62010-07-15 23:40:35 +0000302
Chris Lattnere99c1102009-12-05 08:22:11 +0000303 // The initializer may differ in type from the global. Rewrite
304 // the global to match the initializer. (We have to do this
305 // because some types, like unions, can't be completely represented
306 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000307 if (GV->getType()->getElementType() != Init->getType()) {
308 llvm::GlobalVariable *OldGV = GV;
309
310 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
311 OldGV->isConstant(),
312 OldGV->getLinkage(), Init, "",
313 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000314 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000315 CGM.getContext().getTargetAddressSpace(D.getType()));
316 GV->setVisibility(OldGV->getVisibility());
Reid Klecknereab97d32015-07-20 20:35:30 +0000317 GV->setComdat(OldGV->getComdat());
Eric Christopher31ab1302011-08-23 22:38:00 +0000318
Chris Lattnere99c1102009-12-05 08:22:11 +0000319 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000320 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000321
Chris Lattnere99c1102009-12-05 08:22:11 +0000322 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000323 llvm::Constant *NewPtrForOldDecl =
324 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
325 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000326
Chris Lattnere99c1102009-12-05 08:22:11 +0000327 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000328 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000329 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000330
Chandler Carruth84537952012-03-30 19:44:53 +0000331 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
332 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000333
334 if (hasNontrivialDestruction(D.getType())) {
335 // We have a constant initializer, but a nontrivial destructor. We still
336 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000337 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000338 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000339 }
340
Chandler Carruth84537952012-03-30 19:44:53 +0000341 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000342}
343
John McCall1c9c3fd2010-10-15 04:57:14 +0000344void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000345 llvm::GlobalValue::LinkageTypes Linkage) {
John McCallb88a5662012-03-30 21:00:39 +0000346 // Check to see if we already have a global variable for this
347 // declaration. This can happen when double-emitting function
348 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000349 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
John McCall7f416cc2015-09-08 08:05:57 +0000350 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara374e602009-02-25 19:45:19 +0000351
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000352 // Store into LocalDeclMap before generating initializer to handle
353 // circular references.
John McCall7f416cc2015-09-08 08:05:57 +0000354 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000355
John McCall4a39ab82010-05-04 20:45:42 +0000356 // We can't have a VLA here, but we can have a pointer to a VLA,
357 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000358 // Make sure to evaluate VLA bounds now so that we have them for later.
359 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000360 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000361
John McCallb88a5662012-03-30 21:00:39 +0000362 // Save the type in case adding the initializer forces a type change.
363 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000364
Eli Benderskycb399432014-03-24 22:05:38 +0000365 llvm::GlobalVariable *var =
366 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Chris Lattnere99c1102009-12-05 08:22:11 +0000367 // If this value has an initializer, emit it.
368 if (D.getInit())
John McCallb88a5662012-03-30 21:00:39 +0000369 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000370
John McCall7f416cc2015-09-08 08:05:57 +0000371 var->setAlignment(alignment.getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000372
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000373 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000374 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000375
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000376 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000377 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000378
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000379 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000380 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000381
Chandler Carruth84537952012-03-30 19:44:53 +0000382 // We may have to cast the constant because of the initializer
383 // mismatch above.
384 //
385 // FIXME: It is really dangerous to store this in the map; if anyone
386 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000387 llvm::Constant *castedAddr =
388 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCall7f416cc2015-09-08 08:05:57 +0000389 if (var != castedAddr)
390 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCallb88a5662012-03-30 21:00:39 +0000391 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000392
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000393 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000394
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000395 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000396 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000397 if (DI &&
Benjamin Kramer8c305922016-02-02 11:06:51 +0000398 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000399 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000400 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000401 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000402}
Mike Stump11289f42009-09-09 15:08:12 +0000403
John McCall2b7fc382010-07-13 20:32:21 +0000404namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000405 struct DestroyObject final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000406 DestroyObject(Address addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000407 CodeGenFunction::Destroyer *destroyer,
408 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000409 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000410 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000411
John McCall7f416cc2015-09-08 08:05:57 +0000412 Address addr;
John McCall82fe67b2011-07-09 01:37:26 +0000413 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000414 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000415 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000416
Craig Topper4f12f102014-03-12 06:41:41 +0000417 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000418 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000419 bool useEHCleanupForArray =
420 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000421
422 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000423 }
424 };
425
David Blaikie7e70d682015-08-18 22:40:54 +0000426 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000427 DestroyNRVOVariable(Address addr,
John McCall82fe67b2011-07-09 01:37:26 +0000428 const CXXDestructorDecl *Dtor,
429 llvm::Value *NRVOFlag)
430 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000431
432 const CXXDestructorDecl *Dtor;
433 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000434 Address Loc;
John McCall2b7fc382010-07-13 20:32:21 +0000435
Craig Topper4f12f102014-03-12 06:41:41 +0000436 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000437 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000438 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000439
Craig Topper8a13c412014-05-21 05:09:00 +0000440 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000441 if (NRVO) {
442 // If we exited via NRVO, we skip the destructor call.
443 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
444 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000445 llvm::Value *DidNRVO =
446 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000447 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
448 CGF.EmitBlock(RunDtorBB);
449 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000450
John McCall2b7fc382010-07-13 20:32:21 +0000451 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +0000452 /*ForVirtualBase=*/false,
453 /*Delegating=*/false,
454 Loc);
John McCall2b7fc382010-07-13 20:32:21 +0000455
456 if (NRVO) CGF.EmitBlock(SkipDtorBB);
457 }
458 };
John McCall2b7fc382010-07-13 20:32:21 +0000459
David Blaikie7e70d682015-08-18 22:40:54 +0000460 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000461 Address Stack;
462 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000463 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000464 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000465 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
466 CGF.Builder.CreateCall(F, V);
467 }
468 };
469
David Blaikie7e70d682015-08-18 22:40:54 +0000470 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000471 const VarDecl &Var;
472 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
473
Craig Topper4f12f102014-03-12 06:41:41 +0000474 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000475 // Compute the address of the local variable, in case it's a
476 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000477 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
478 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000479 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
480 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000481 CGF.EmitExtendGCLifetime(value);
482 }
483 };
484
David Blaikie7e70d682015-08-18 22:40:54 +0000485 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000486 llvm::Constant *CleanupFn;
487 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000488 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000489
John McCalla464ff92010-07-21 06:13:08 +0000490 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000491 const VarDecl *Var)
492 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000493
Craig Topper4f12f102014-03-12 06:41:41 +0000494 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000495 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
496 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000497 // Compute the address of the local variable, in case it's a byref
498 // or something.
John McCall7f416cc2015-09-08 08:05:57 +0000499 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCallc533cb72011-02-22 06:44:22 +0000500
John McCalla464ff92010-07-21 06:13:08 +0000501 // In some cases, the type of the function argument will be different from
502 // the type of the pointer. An example of this is
503 // void f(void* arg);
504 // __attribute__((cleanup(f))) void *g;
505 //
506 // To fix this we insert a bitcast here.
507 QualType ArgTy = FnInfo.arg_begin()->type;
508 llvm::Value *Arg =
509 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
510
511 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000512 Args.add(RValue::get(Arg),
513 CGF.getContext().getPointerType(Var.getType()));
John McCalla464ff92010-07-21 06:13:08 +0000514 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
515 }
516 };
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000517
518 /// A cleanup to call @llvm.lifetime.end.
David Blaikie7e70d682015-08-18 22:40:54 +0000519 class CallLifetimeEnd final : public EHScopeStack::Cleanup {
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000520 llvm::Value *Addr;
521 llvm::Value *Size;
522 public:
John McCall7f416cc2015-09-08 08:05:57 +0000523 CallLifetimeEnd(Address addr, llvm::Value *size)
524 : Addr(addr.getPointer()), Size(size) {}
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000525
526 void Emit(CodeGenFunction &CGF, Flags flags) override {
David Majnemerdc012fa2015-04-22 21:38:15 +0000527 CGF.EmitLifetimeEnd(Size, Addr);
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000528 }
529 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000530} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000531
John McCall31168b02011-06-15 23:02:42 +0000532/// EmitAutoVarWithLifetime - Does the setup required for an automatic
533/// variable with lifetime.
534static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000535 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000536 Qualifiers::ObjCLifetime lifetime) {
537 switch (lifetime) {
538 case Qualifiers::OCL_None:
539 llvm_unreachable("present but none");
540
541 case Qualifiers::OCL_ExplicitNone:
542 // nothing to do
543 break;
544
545 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000546 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000547 (var.hasAttr<ObjCPreciseLifetimeAttr>()
548 ? CodeGenFunction::destroyARCStrongPrecise
549 : CodeGenFunction::destroyARCStrongImprecise);
550
551 CleanupKind cleanupKind = CGF.getARCCleanupKind();
552 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
553 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000554 break;
555 }
556 case Qualifiers::OCL_Autoreleasing:
557 // nothing to do
558 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000559
John McCall31168b02011-06-15 23:02:42 +0000560 case Qualifiers::OCL_Weak:
561 // __weak objects always get EH cleanups; otherwise, exceptions
562 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000563 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
564 CodeGenFunction::destroyARCWeak,
565 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000566 break;
567 }
568}
569
570static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
571 if (const Expr *e = dyn_cast<Expr>(s)) {
572 // Skip the most common kinds of expressions that make
573 // hierarchy-walking expensive.
574 s = e = e->IgnoreParenCasts();
575
576 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
577 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000578 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
579 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000580 for (const auto &I : block->captures()) {
581 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000582 return true;
583 }
584 }
John McCall31168b02011-06-15 23:02:42 +0000585 }
586
Benjamin Kramer642f1732015-07-02 21:03:14 +0000587 for (const Stmt *SubStmt : s->children())
588 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
589 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000590 return true;
591
592 return false;
593}
594
595static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
596 if (!decl) return false;
597 if (!isa<VarDecl>(decl)) return false;
598 const VarDecl *var = cast<VarDecl>(decl);
599 return isAccessedBy(*var, e);
600}
601
John McCallf8a9b662015-10-21 18:06:31 +0000602static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
603 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000604 bool needsCast = false;
605
John McCallf8a9b662015-10-21 18:06:31 +0000606 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
607 switch (castExpr->getCastKind()) {
608 // Look through casts that don't require representation changes.
609 case CK_NoOp:
610 case CK_BitCast:
611 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000612 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000613 break;
614
615 // If we find an l-value to r-value cast from a __weak variable,
616 // emit this operation as a copy or move.
617 case CK_LValueToRValue: {
618 const Expr *srcExpr = castExpr->getSubExpr();
619 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
620 return false;
621
622 // Emit the source l-value.
623 LValue srcLV = CGF.EmitLValue(srcExpr);
624
John McCall0204e342015-11-16 22:11:41 +0000625 // Handle a formal type change to avoid asserting.
626 auto srcAddr = srcLV.getAddress();
627 if (needsCast) {
628 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
629 destLV.getAddress().getElementType());
630 }
631
John McCallf8a9b662015-10-21 18:06:31 +0000632 // If it was an l-value, use objc_copyWeak.
633 if (srcExpr->getValueKind() == VK_LValue) {
John McCall0204e342015-11-16 22:11:41 +0000634 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000635 } else {
636 assert(srcExpr->getValueKind() == VK_XValue);
John McCall0204e342015-11-16 22:11:41 +0000637 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000638 }
639 return true;
640 }
641
642 // Stop at anything else.
643 default:
644 return false;
645 }
646
647 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000648 }
649 return false;
650}
651
John McCall1553b192011-06-16 04:16:24 +0000652static void drillIntoBlockVariable(CodeGenFunction &CGF,
653 LValue &lvalue,
654 const VarDecl *var) {
John McCall7f416cc2015-09-08 08:05:57 +0000655 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCall1553b192011-06-16 04:16:24 +0000656}
657
David Blaikie73ca5692014-12-09 00:32:22 +0000658void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000659 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000660 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000661 if (!lifetime) {
662 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000663 if (capturedByInit)
664 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +0000665 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000666 return;
667 }
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000668
669 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
670 init = DIE->getExpr();
671
John McCall31168b02011-06-15 23:02:42 +0000672 // If we're emitting a value with lifetime, we have to do the
673 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000674 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
675 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000676 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000677 }
678 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000679
680 // We have to maintain the illusion that the variable is
681 // zero-initialized. If the variable might be accessed in its
682 // initializer, zero-initialize before running the initializer, then
683 // actually perform the initialization with an assign.
684 bool accessedByInit = false;
685 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000686 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000687 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000688 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000689 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000690 if (capturedByInit) {
691 // We can use a simple GEP for this because it can't have been
692 // moved yet.
John McCall7f416cc2015-09-08 08:05:57 +0000693 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
694 cast<VarDecl>(D),
695 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000696 }
697
John McCall7f416cc2015-09-08 08:05:57 +0000698 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
John McCall31168b02011-06-15 23:02:42 +0000699 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000700
John McCall31168b02011-06-15 23:02:42 +0000701 // If __weak, we want to use a barrier under certain conditions.
702 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000703 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000704
705 // Otherwise just do a simple store.
706 else
David Chisnallfa35df62012-01-16 17:27:18 +0000707 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000708 }
709
710 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000711 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000712
713 switch (lifetime) {
714 case Qualifiers::OCL_None:
715 llvm_unreachable("present but none");
716
717 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000718 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000719 break;
720
721 case Qualifiers::OCL_Strong: {
722 value = EmitARCRetainScalarExpr(init);
723 break;
724 }
725
726 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000727 // If it's not accessed by the initializer, try to emit the
728 // initialization with a copy or move.
729 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
730 return;
731 }
732
John McCall31168b02011-06-15 23:02:42 +0000733 // No way to optimize a producing initializer into this. It's not
734 // worth optimizing for, because the value will immediately
735 // disappear in the common case.
736 value = EmitScalarExpr(init);
737
John McCall1553b192011-06-16 04:16:24 +0000738 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000739 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000740 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000741 else
John McCall1553b192011-06-16 04:16:24 +0000742 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000743 return;
744 }
745
746 case Qualifiers::OCL_Autoreleasing:
747 value = EmitARCRetainAutoreleaseScalarExpr(init);
748 break;
749 }
750
John McCall1553b192011-06-16 04:16:24 +0000751 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000752
753 // If the variable might have been accessed by its initializer, we
754 // might have to initialize with a barrier. We have to do this for
755 // both __weak and __strong, but __weak got filtered out above.
756 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000757 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000758 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000759 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000760 return;
761 }
762
David Chisnallfa35df62012-01-16 17:27:18 +0000763 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000764}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000765
John McCalld4631322011-06-17 06:42:21 +0000766/// EmitScalarInit - Initialize the given lvalue with the given object.
767void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
768 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
769 if (!lifetime)
David Chisnallfa35df62012-01-16 17:27:18 +0000770 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCalld4631322011-06-17 06:42:21 +0000771
772 switch (lifetime) {
773 case Qualifiers::OCL_None:
774 llvm_unreachable("present but none");
775
776 case Qualifiers::OCL_ExplicitNone:
777 // nothing to do
778 break;
779
780 case Qualifiers::OCL_Strong:
781 init = EmitARCRetain(lvalue.getType(), init);
782 break;
783
784 case Qualifiers::OCL_Weak:
785 // Initialize and then skip the primitive store.
786 EmitARCInitWeak(lvalue.getAddress(), init);
787 return;
788
789 case Qualifiers::OCL_Autoreleasing:
790 init = EmitARCRetainAutorelease(lvalue.getType(), init);
791 break;
792 }
793
David Chisnallfa35df62012-01-16 17:27:18 +0000794 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCalld4631322011-06-17 06:42:21 +0000795}
796
Chris Lattnerb85025f2010-12-01 02:05:19 +0000797/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
798/// non-zero parts of the specified initializer with equal or fewer than
799/// NumStores scalar stores.
800static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
801 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000802 // Zero and Undef never requires any extra stores.
803 if (isa<llvm::ConstantAggregateZero>(Init) ||
804 isa<llvm::ConstantPointerNull>(Init) ||
805 isa<llvm::UndefValue>(Init))
806 return true;
807 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
808 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
809 isa<llvm::ConstantExpr>(Init))
810 return Init->isNullValue() || NumStores--;
811
812 // See if we can emit each element.
813 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
814 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
815 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
816 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
817 return false;
818 }
819 return true;
820 }
Chris Lattner236b3572012-01-31 04:36:19 +0000821
822 if (llvm::ConstantDataSequential *CDS =
823 dyn_cast<llvm::ConstantDataSequential>(Init)) {
824 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
825 llvm::Constant *Elt = CDS->getElementAsConstant(i);
826 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
827 return false;
828 }
829 return true;
830 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000831
Chris Lattnerb85025f2010-12-01 02:05:19 +0000832 // Anything else is hard and scary.
833 return false;
834}
835
836/// emitStoresForInitAfterMemset - For inits that
837/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
838/// stores that would be required.
839static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000840 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000841 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
842 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000843
Chris Lattnere6af8862010-12-02 01:58:41 +0000844 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
845 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
846 isa<llvm::ConstantExpr>(Init)) {
John McCall7f416cc2015-09-08 08:05:57 +0000847 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000848 return;
849 }
850
851 if (llvm::ConstantDataSequential *CDS =
852 dyn_cast<llvm::ConstantDataSequential>(Init)) {
853 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
854 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000855
856 // If necessary, get a pointer to the element and emit it.
857 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000858 emitStoresForInitAfterMemset(
859 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
860 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000861 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000862 return;
863 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000864
Chris Lattnere6af8862010-12-02 01:58:41 +0000865 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
866 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000867
Chris Lattnere6af8862010-12-02 01:58:41 +0000868 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
869 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000870
871 // If necessary, get a pointer to the element and emit it.
872 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000873 emitStoresForInitAfterMemset(
874 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
875 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000876 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000877}
878
Chris Lattnerb85025f2010-12-01 02:05:19 +0000879/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
880/// plus some stores to initialize a local variable instead of using a memcpy
881/// from a constant global. It is beneficial to use memset if the global is all
882/// zeros, or mostly zeros and large.
883static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
884 uint64_t GlobalSize) {
885 // If a global is all zeros, always use a memset.
886 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
887
Chris Lattnerb85025f2010-12-01 02:05:19 +0000888 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
889 // do it if it will require 6 or fewer scalar stores.
890 // TODO: Should budget depends on the size? Avoiding a large global warrants
891 // plopping in more stores.
892 unsigned StoreBudget = 6;
893 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000894
895 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000896 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
897}
898
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000899/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000900/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000901/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000902void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
903 AutoVarEmission emission = EmitAutoVarAlloca(D);
904 EmitAutoVarInit(emission);
905 EmitAutoVarCleanups(emission);
906}
Chris Lattner03df1222007-06-02 04:53:11 +0000907
David Majnemerdc012fa2015-04-22 21:38:15 +0000908/// Emit a lifetime.begin marker if some criteria are satisfied.
909/// \return a pointer to the temporary size Value if a marker was emitted, null
910/// otherwise
911llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
912 llvm::Value *Addr) {
913 // For now, only in optimized builds.
914 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
915 return nullptr;
916
Reid Kleckner1ef49212015-04-23 18:07:13 +0000917 // Disable lifetime markers in msan builds.
918 // FIXME: Remove this when msan works with lifetime markers.
919 if (getLangOpts().Sanitize.has(SanitizerKind::Memory))
920 return nullptr;
921
David Majnemerdc012fa2015-04-22 21:38:15 +0000922 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000923 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
924 llvm::CallInst *C =
925 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000926 C->setDoesNotThrow();
927 return SizeV;
928}
929
930void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000931 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
932 llvm::CallInst *C =
933 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000934 C->setDoesNotThrow();
935}
936
John McCallc533cb72011-02-22 06:44:22 +0000937/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000938/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +0000939CodeGenFunction::AutoVarEmission
940CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
941 QualType Ty = D.getType();
942
943 AutoVarEmission emission(D);
944
945 bool isByRef = D.hasAttr<BlocksAttr>();
946 emission.IsByRef = isByRef;
947
948 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +0000949
John McCall23c29fe2011-06-24 21:55:10 +0000950 // If the type is variably-modified, emit all the VLA sizes for it.
951 if (Ty->isVariablyModifiedType())
952 EmitVariablyModifiedType(Ty);
953
John McCall7f416cc2015-09-08 08:05:57 +0000954 Address address = Address::invalid();
Eli Friedmana682d392008-02-15 12:20:59 +0000955 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000956 bool NRVO = getLangOpts().ElideConstructors &&
957 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +0000958
Richard Smith2bcde3a2013-06-02 00:09:52 +0000959 // If this value is an array or struct with a statically determinable
960 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +0000961 //
962 // TODO: We should constant-evaluate the initializer of any variable,
963 // as long as it is initialized by a constant expression. Currently,
964 // isConstantInitializer produces wrong answers for structs with
965 // reference or bitfield members, and a few other cases, and checking
966 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +0000967 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
968 (D.isConstexpr() ||
969 ((Ty.isPODType(getContext()) ||
970 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
971 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +0000972
Rafael Espindola609f5d92013-03-26 18:41:47 +0000973 // If the variable's a const type, and it's neither an NRVO
974 // candidate nor a __block variable and has no mutable members,
975 // emit it as a global instead.
976 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
977 CGM.isTypeConstant(Ty, true)) {
978 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +0000979
John McCall7f416cc2015-09-08 08:05:57 +0000980 // Signal this condition to later callbacks.
981 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +0000982 assert(emission.wasEmittedAsGlobal());
983 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +0000984 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000985
Rafael Espindola609f5d92013-03-26 18:41:47 +0000986 // Otherwise, tell the initialization code that we're in this case.
987 emission.IsConstantAggregate = true;
988 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000989
Rafael Espindola609f5d92013-03-26 18:41:47 +0000990 // A normal fixed sized variable becomes an alloca in the entry block,
991 // unless it's an NRVO variable.
Eric Christopher31ab1302011-08-23 22:38:00 +0000992
Rafael Espindola609f5d92013-03-26 18:41:47 +0000993 if (NRVO) {
994 // The named return value optimization: allocate this variable in the
995 // return slot, so that we can elide the copy when returning this
996 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +0000997 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +0000998
Rafael Espindola609f5d92013-03-26 18:41:47 +0000999 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1000 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
1001 // Create a flag that is used to indicate when the NRVO was applied
1002 // to this variable. Set it to zero to indicate that NRVO was not
1003 // applied.
1004 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +00001005 Address NRVOFlag =
1006 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +00001007 EnsureInsertPoint();
1008 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +00001009
Rafael Espindola609f5d92013-03-26 18:41:47 +00001010 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +00001011 NRVOFlags[&D] = NRVOFlag.getPointer();
1012 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +00001013 }
Douglas Gregor290c93e2010-05-15 06:46:45 +00001014 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001015 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001016 CharUnits allocaAlignment;
1017 llvm::Type *allocaTy;
1018 if (isByRef) {
1019 auto &byrefInfo = getBlockByrefInfo(&D);
1020 allocaTy = byrefInfo.Type;
1021 allocaAlignment = byrefInfo.ByrefAlignment;
1022 } else {
1023 allocaTy = ConvertTypeForMem(Ty);
1024 allocaAlignment = alignment;
1025 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001026
John McCall999110f2015-09-08 09:18:30 +00001027 // Create the alloca. Note that we set the name separately from
1028 // building the instruction so that it's there even in no-asserts
1029 // builds.
1030 address = CreateTempAlloca(allocaTy, allocaAlignment);
1031 address.getPointer()->setName(D.getName());
Rafael Espindola609f5d92013-03-26 18:41:47 +00001032
Reid Kleckner1f88e932015-10-07 21:03:41 +00001033 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1034 // the catch parameter starts in the catchpad instruction, and we can't
1035 // insert code in those basic blocks.
1036 bool IsMSCatchParam =
1037 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1038
Rafael Espindola609f5d92013-03-26 18:41:47 +00001039 // Emit a lifetime intrinsic if meaningful. There's no point
1040 // in doing this if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001041 if (HaveInsertPoint() && !IsMSCatchParam) {
John McCall7f416cc2015-09-08 08:05:57 +00001042 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1043 emission.SizeForLifetimeMarkers =
1044 EmitLifetimeStart(size, address.getPointer());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001045 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001046 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001047 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001048 }
Chris Lattner03df1222007-06-02 04:53:11 +00001049 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001050 EnsureInsertPoint();
1051
Anders Carlsson15949b32009-02-09 20:41:50 +00001052 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001053 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001054 Address Stack =
1055 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001056
Anders Carlsson30032882008-12-12 07:38:43 +00001057 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001058 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001059 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001060
1061 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001062
John McCalla464ff92010-07-21 06:13:08 +00001063 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001064 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001065 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001066 }
Mike Stump11289f42009-09-09 15:08:12 +00001067
John McCall23c29fe2011-06-24 21:55:10 +00001068 llvm::Value *elementCount;
1069 QualType elementType;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001070 std::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +00001071
Chris Lattner2192fe52011-07-18 04:24:23 +00001072 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +00001073
1074 // Allocate memory for the array.
John McCall23c29fe2011-06-24 21:55:10 +00001075 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1076 vla->setAlignment(alignment.getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +00001077
John McCall7f416cc2015-09-08 08:05:57 +00001078 address = Address(vla, alignment);
Chris Lattner03df1222007-06-02 04:53:11 +00001079 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001080
John McCall7f416cc2015-09-08 08:05:57 +00001081 setAddrOfLocalVar(&D, address);
1082 emission.Addr = address;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001083
1084 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +00001085 if (HaveInsertPoint())
1086 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001087 if (CGM.getCodeGenOpts().getDebugInfo() >=
1088 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001089 DI->setLocation(D.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001090 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001091 }
Devang Patel887e2152011-06-03 19:21:47 +00001092 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001093
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001094 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001095 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001096
John McCallc533cb72011-02-22 06:44:22 +00001097 return emission;
1098}
1099
1100/// Determines whether the given __block variable is potentially
1101/// captured by the given expression.
1102static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1103 // Skip the most common kinds of expressions that make
1104 // hierarchy-walking expensive.
1105 e = e->IgnoreParenCasts();
1106
1107 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1108 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +00001109 for (const auto &I : block->captures()) {
1110 if (I.getVariable() == &var)
John McCallc533cb72011-02-22 06:44:22 +00001111 return true;
1112 }
1113
1114 // No need to walk into the subexpressions.
1115 return false;
1116 }
1117
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001118 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1119 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001120 for (const auto *BI : CS->body())
1121 if (const auto *E = dyn_cast<Expr>(BI)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001122 if (isCapturedBy(var, E))
1123 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001124 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001125 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001126 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001127 for (const auto *I : DS->decls()) {
1128 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1129 const Expr *Init = VD->getInit();
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001130 if (Init && isCapturedBy(var, Init))
1131 return true;
1132 }
1133 }
1134 }
1135 else
1136 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1137 // Later, provide code to poke into statements for capture analysis.
1138 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001139 return false;
1140 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001141
Benjamin Kramer642f1732015-07-02 21:03:14 +00001142 for (const Stmt *SubStmt : e->children())
1143 if (isCapturedBy(var, cast<Expr>(SubStmt)))
John McCallc533cb72011-02-22 06:44:22 +00001144 return true;
1145
1146 return false;
1147}
1148
Douglas Gregor82e1af22011-07-01 21:08:19 +00001149/// \brief Determine whether the given initializer is trivial in the sense
1150/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001151bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001152 if (!Init)
1153 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001154
Douglas Gregor82e1af22011-07-01 21:08:19 +00001155 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1156 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1157 if (Constructor->isTrivial() &&
1158 Constructor->isDefaultConstructor() &&
1159 !Construct->requiresZeroInitialization())
1160 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001161
Douglas Gregor82e1af22011-07-01 21:08:19 +00001162 return false;
1163}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001164
John McCallc533cb72011-02-22 06:44:22 +00001165void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001166 assert(emission.Variable && "emission was not valid!");
1167
John McCallc533cb72011-02-22 06:44:22 +00001168 // If this was emitted as a global constant, we're done.
1169 if (emission.wasEmittedAsGlobal()) return;
1170
John McCall9e2e22f2011-02-22 07:16:58 +00001171 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001172 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001173 QualType type = D.getType();
1174
Chris Lattner07eb7332007-07-12 00:39:48 +00001175 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001176 const Expr *Init = D.getInit();
1177
1178 // If we are at an unreachable point, we don't need to emit the initializer
1179 // unless it contains a label.
1180 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001181 if (!Init || !ContainsLabel(Init)) return;
1182 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001183 }
1184
John McCall73064872011-03-31 01:59:53 +00001185 // Initialize the structure of a __block variable.
1186 if (emission.IsByRef)
1187 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001188
Douglas Gregor82e1af22011-07-01 21:08:19 +00001189 if (isTrivialInitializer(Init))
1190 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001191
John McCallc533cb72011-02-22 06:44:22 +00001192 // Check whether this is a byref variable that's potentially
1193 // captured and moved by its own initializer. If so, we'll need to
1194 // emit the initializer first, then copy into the variable.
1195 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1196
John McCall7f416cc2015-09-08 08:05:57 +00001197 Address Loc =
1198 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
John McCallc533cb72011-02-22 06:44:22 +00001199
Craig Topper8a13c412014-05-21 05:09:00 +00001200 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001201 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001202 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smithdafff942012-01-14 04:30:29 +00001203 constant = CGM.EmitConstantInit(D, this);
Richard Smithfddd3842011-12-30 21:15:51 +00001204 }
1205
1206 if (!constant) {
John McCall7f416cc2015-09-08 08:05:57 +00001207 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001208 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001209 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001210 }
John McCall91ca10f2011-03-08 09:11:50 +00001211
Richard Smith2bcde3a2013-06-02 00:09:52 +00001212 if (!emission.IsConstantAggregate) {
1213 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001214 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001215 lv.setNonGC(true);
1216 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1217 }
1218
John McCallc533cb72011-02-22 06:44:22 +00001219 // If this is a simple aggregate initialization, we can optimize it
1220 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001221 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001222
John McCall91ca10f2011-03-08 09:11:50 +00001223 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001224 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001225 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001226
Chris Lattner2192fe52011-07-18 04:24:23 +00001227 llvm::Type *BP = Int8PtrTy;
John McCall7f416cc2015-09-08 08:05:57 +00001228 if (Loc.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001229 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001230
John McCall91ca10f2011-03-08 09:11:50 +00001231 // If the initializer is all or mostly zeros, codegen with memset then do
1232 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001233 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001234 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall91ca10f2011-03-08 09:11:50 +00001235 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
John McCall7f416cc2015-09-08 08:05:57 +00001236 isVolatile);
Benjamin Kramer29f9a002012-08-27 22:07:02 +00001237 // Zero and undef don't require a stores.
1238 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall91ca10f2011-03-08 09:11:50 +00001239 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001240 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1241 isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001242 }
John McCall91ca10f2011-03-08 09:11:50 +00001243 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001244 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001245 // memcpy from the global to the alloca.
Reid Kleckner453e0562014-10-08 01:07:54 +00001246 std::string Name = getStaticDeclName(CGM, D);
John McCall91ca10f2011-03-08 09:11:50 +00001247 llvm::GlobalVariable *GV =
1248 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001249 llvm::GlobalValue::PrivateLinkage,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001250 constant, Name);
John McCall7f416cc2015-09-08 08:05:57 +00001251 GV->setAlignment(Loc.getAlignment().getQuantity());
Eli Friedmanb8578422011-05-27 22:32:55 +00001252 GV->setUnnamedAddr(true);
Eric Christopher31ab1302011-08-23 22:38:00 +00001253
John McCall7f416cc2015-09-08 08:05:57 +00001254 Address SrcPtr = Address(GV, Loc.getAlignment());
1255 if (SrcPtr.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001256 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001257
John McCall7f416cc2015-09-08 08:05:57 +00001258 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
John McCall91ca10f2011-03-08 09:11:50 +00001259 }
1260}
1261
1262/// Emit an expression as an initializer for a variable at the given
1263/// location. The expression is not necessarily the normal
1264/// initializer for the variable, and the address is not necessarily
1265/// its normal location.
1266///
1267/// \param init the initializing expression
1268/// \param var the variable to act as if we're initializing
1269/// \param loc the address to initialize; its type is a pointer
1270/// to the LLVM mapping of the variable's type
1271/// \param alignment the alignment of the address
1272/// \param capturedByInit true if the variable is a __block variable
1273/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001274void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001275 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001276 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001277
1278 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001279 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001280 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001281 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001282 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001283 return;
1284 }
1285 switch (getEvaluationKind(type)) {
1286 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001287 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001288 return;
1289 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001290 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001291 if (capturedByInit)
1292 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001293 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001294 return;
1295 }
1296 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001297 if (type->isAtomicType()) {
1298 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1299 } else {
1300 // TODO: how can we delay here if D is captured by its initializer?
1301 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001302 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001303 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001304 AggValueSlot::IsNotAliased));
John McCalla8ec7eb2013-03-07 21:37:17 +00001305 }
John McCall47fb9502013-03-07 21:37:08 +00001306 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001307 }
John McCall47fb9502013-03-07 21:37:08 +00001308 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001309}
John McCallbd309292010-07-06 01:34:17 +00001310
John McCall82fe67b2011-07-09 01:37:26 +00001311/// Enter a destroy cleanup for the given local variable.
1312void CodeGenFunction::emitAutoVarTypeCleanup(
1313 const CodeGenFunction::AutoVarEmission &emission,
1314 QualType::DestructionKind dtorKind) {
1315 assert(dtorKind != QualType::DK_none);
1316
1317 // Note that for __block variables, we want to destroy the
1318 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001319 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001320
1321 const VarDecl *var = emission.Variable;
1322 QualType type = var->getType();
1323
1324 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001325 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001326
1327 switch (dtorKind) {
1328 case QualType::DK_none:
1329 llvm_unreachable("no cleanup for trivially-destructible variable");
1330
1331 case QualType::DK_cxx_destructor:
1332 // If there's an NRVO flag on the emission, we need a different
1333 // cleanup.
1334 if (emission.NRVOFlag) {
1335 assert(!type->isArrayType());
1336 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +00001337 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1338 dtor, emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001339 return;
1340 }
1341 break;
1342
1343 case QualType::DK_objc_strong_lifetime:
1344 // Suppress cleanups for pseudo-strong variables.
1345 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001346
John McCall82fe67b2011-07-09 01:37:26 +00001347 // Otherwise, consider whether to use an EH cleanup or not.
1348 cleanupKind = getARCCleanupKind();
1349
1350 // Use the imprecise destroyer by default.
1351 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1352 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1353 break;
1354
1355 case QualType::DK_objc_weak_lifetime:
1356 break;
1357 }
1358
1359 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001360 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001361
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001362 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001363 // is being pushed as an EH cleanup.
1364 bool useEHCleanup = (cleanupKind & EHCleanup);
1365 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1366 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001367}
1368
John McCallc533cb72011-02-22 06:44:22 +00001369void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001370 assert(emission.Variable && "emission was not valid!");
1371
John McCallc533cb72011-02-22 06:44:22 +00001372 // If this was emitted as a global constant, we're done.
1373 if (emission.wasEmittedAsGlobal()) return;
1374
John McCall8c38d352012-04-13 18:44:05 +00001375 // If we don't have an insertion point, we're done. Sema prevents
1376 // us from jumping into any of these scopes anyway.
1377 if (!HaveInsertPoint()) return;
1378
John McCall9e2e22f2011-02-22 07:16:58 +00001379 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001380
Nadav Rotem1da30942013-03-23 06:43:35 +00001381 // Make sure we call @llvm.lifetime.end. This needs to happen
1382 // *last*, so the cleanup needs to be pushed *first*.
1383 if (emission.useLifetimeMarkers()) {
1384 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1385 emission.getAllocatedAddress(),
1386 emission.getSizeForLifetimeMarkers());
David Majnemerdc012fa2015-04-22 21:38:15 +00001387 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
1388 cleanup.setLifetimeMarker();
Nadav Rotem1da30942013-03-23 06:43:35 +00001389 }
1390
John McCall82fe67b2011-07-09 01:37:26 +00001391 // Check the type for a cleanup.
1392 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1393 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001394
John McCall1bd25562011-06-24 23:21:27 +00001395 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001396 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001397 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1398 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1399 }
1400
John McCallc533cb72011-02-22 06:44:22 +00001401 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001402 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001403 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001404
John McCallc533cb72011-02-22 06:44:22 +00001405 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001406 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001407
John McCalla729c622012-02-17 03:33:10 +00001408 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001409 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001410 }
Mike Stump626aecc2009-03-05 01:23:13 +00001411
John McCallc533cb72011-02-22 06:44:22 +00001412 // If this is a block variable, call _Block_object_destroy
1413 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001414 if (emission.IsByRef)
1415 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001416}
Chris Lattner53621a52007-06-13 20:44:40 +00001417
Peter Collingbourne1425b452012-01-26 03:33:36 +00001418CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001419CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1420 switch (kind) {
1421 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001422 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001423 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001424 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001425 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001426 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001427 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001428 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001429 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001430}
1431
John McCall12cc42a2013-02-01 05:11:40 +00001432/// pushEHDestroy - Push the standard destructor for the given type as
1433/// an EH-only cleanup.
1434void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001435 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00001436 assert(dtorKind && "cannot push destructor for trivial type");
1437 assert(needsEHCleanup(dtorKind));
1438
1439 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1440}
1441
1442/// pushDestroy - Push the standard destructor for the given type as
1443/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001444void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001445 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00001446 assert(dtorKind && "cannot push destructor for trivial type");
1447
1448 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1449 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1450 cleanupKind & EHCleanup);
1451}
1452
John McCall7f416cc2015-09-08 08:05:57 +00001453void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001454 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001455 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001456 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1457 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001458}
1459
John McCall7f416cc2015-09-08 08:05:57 +00001460void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001461 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1462}
1463
Richard Smith736a9472013-06-12 20:42:33 +00001464void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00001465 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00001466 Destroyer *destroyer, bool useEHCleanupForArray) {
1467 assert(!isInConditionalBranch() &&
1468 "performing lifetime extension from within conditional");
1469
1470 // Push an EH-only cleanup for the object now.
1471 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1472 // around in case a temporary's destructor throws an exception.
1473 if (cleanupKind & EHCleanup)
1474 EHStack.pushCleanup<DestroyObject>(
1475 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1476 destroyer, useEHCleanupForArray);
1477
1478 // Remember that we need to push a full cleanup for the object at the
1479 // end of the full-expression.
1480 pushCleanupAfterFullExpr<DestroyObject>(
1481 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1482}
1483
John McCall178360e2011-07-11 08:38:19 +00001484/// emitDestroy - Immediately perform the destruction of the given
1485/// object.
1486///
1487/// \param addr - the address of the object; a type*
1488/// \param type - the type of the object; if an array type, all
1489/// objects are destroyed in reverse order
1490/// \param destroyer - the function to call to destroy individual
1491/// elements
1492/// \param useEHCleanupForArray - whether an EH cleanup should be
1493/// used when destroying array elements, in case one of the
1494/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00001495void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001496 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001497 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001498 const ArrayType *arrayType = getContext().getAsArrayType(type);
1499 if (!arrayType)
1500 return destroyer(*this, addr, type);
1501
John McCall7f416cc2015-09-08 08:05:57 +00001502 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1503
1504 CharUnits elementAlign =
1505 addr.getAlignment()
1506 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00001507
1508 // Normally we have to check whether the array is zero-length.
1509 bool checkZeroLength = true;
1510
1511 // But if the array length is constant, we can suppress that.
1512 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1513 // ...and if it's constant zero, we can just skip the entire thing.
1514 if (constLength->isZero()) return;
1515 checkZeroLength = false;
1516 }
1517
John McCall7f416cc2015-09-08 08:05:57 +00001518 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00001519 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00001520 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001521 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001522}
1523
John McCall178360e2011-07-11 08:38:19 +00001524/// emitArrayDestroy - Destroys all the elements of the given array,
1525/// beginning from last to first. The array cannot be zero-length.
1526///
1527/// \param begin - a type* denoting the first element of the array
1528/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001529/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00001530/// \param destroyer - the function to call to destroy elements
1531/// \param useEHCleanup - whether to push an EH cleanup to destroy
1532/// the remaining elements in case the destruction of a single
1533/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001534void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1535 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001536 QualType elementType,
1537 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001538 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001539 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001540 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00001541 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00001542
1543 // The basic structure here is a do-while loop, because we don't
1544 // need to check for the zero-element case.
1545 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1546 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1547
John McCall97eab0a2011-07-13 08:09:46 +00001548 if (checkZeroLength) {
1549 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1550 "arraydestroy.isempty");
1551 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1552 }
1553
John McCall82fe67b2011-07-09 01:37:26 +00001554 // Enter the loop body, making that address the current address.
1555 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1556 EmitBlock(bodyBB);
1557 llvm::PHINode *elementPast =
1558 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1559 elementPast->addIncoming(end, entryBB);
1560
1561 // Shift the address back by one element.
1562 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1563 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1564 "arraydestroy.element");
1565
John McCall178360e2011-07-11 08:38:19 +00001566 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00001567 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1568 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001569
John McCall82fe67b2011-07-09 01:37:26 +00001570 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00001571 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00001572
John McCall178360e2011-07-11 08:38:19 +00001573 if (useEHCleanup)
1574 PopCleanupBlock();
1575
John McCall82fe67b2011-07-09 01:37:26 +00001576 // Check whether we've reached the end.
1577 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1578 Builder.CreateCondBr(done, doneBB, bodyBB);
1579 elementPast->addIncoming(element, Builder.GetInsertBlock());
1580
1581 // Done.
1582 EmitBlock(doneBB);
1583}
1584
John McCall178360e2011-07-11 08:38:19 +00001585/// Perform partial array destruction as if in an EH cleanup. Unlike
1586/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001587static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1588 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001589 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001590 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001591 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001592 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001593 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1594 // VLAs don't require a GEP index to walk into.
1595 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001596 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001597 type = arrayType->getElementType();
1598 }
John McCall97eab0a2011-07-13 08:09:46 +00001599
1600 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00001601 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00001602
John McCallf0f0b7a2015-09-14 18:57:08 +00001603 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001604 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1605 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001606 }
1607
John McCall97eab0a2011-07-13 08:09:46 +00001608 // Destroy the array. We don't ever need an EH cleanup because we
1609 // assume that we're in an EH cleanup ourselves, so a throwing
1610 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00001611 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001612 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001613}
1614
John McCall82fe67b2011-07-09 01:37:26 +00001615namespace {
John McCall178360e2011-07-11 08:38:19 +00001616 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1617 /// array destroy where the end pointer is regularly determined and
1618 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001619 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00001620 llvm::Value *ArrayBegin;
1621 llvm::Value *ArrayEnd;
1622 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001623 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001624 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00001625 public:
1626 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001627 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001628 CodeGenFunction::Destroyer *destroyer)
1629 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00001630 ElementType(elementType), Destroyer(destroyer),
1631 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00001632
Craig Topper4f12f102014-03-12 06:41:41 +00001633 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001634 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001635 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00001636 }
1637 };
1638
1639 /// IrregularPartialArrayDestroy - a cleanup which performs a
1640 /// partial array destroy where the end pointer is irregularly
1641 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001642 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001643 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00001644 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00001645 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001646 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001647 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00001648 public:
John McCall178360e2011-07-11 08:38:19 +00001649 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001650 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001651 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001652 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001653 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001654 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00001655 ElementType(elementType), Destroyer(destroyer),
1656 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00001657
Craig Topper4f12f102014-03-12 06:41:41 +00001658 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001659 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001660 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001661 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001662 }
1663 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001664} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00001665
John McCall178360e2011-07-11 08:38:19 +00001666/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001667/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001668/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001669///
John McCall82fe67b2011-07-09 01:37:26 +00001670/// \param elementType - the immediate element type of the array;
1671/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001672void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001673 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001674 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001675 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001676 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001677 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1678 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00001679 elementType, elementAlign,
1680 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001681}
1682
1683/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1684/// already-constructed elements of the given array. The cleanup
1685/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001686///
John McCall178360e2011-07-11 08:38:19 +00001687/// \param elementType - the immediate element type of the array;
1688/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001689void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1690 llvm::Value *arrayEnd,
1691 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001692 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001693 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001694 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001695 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001696 elementType, elementAlign,
1697 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001698}
1699
Nadav Rotem1da30942013-03-23 06:43:35 +00001700/// Lazily declare the @llvm.lifetime.start intrinsic.
1701llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1702 if (LifetimeStartFn) return LifetimeStartFn;
1703 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1704 llvm::Intrinsic::lifetime_start);
1705 return LifetimeStartFn;
1706}
1707
1708/// Lazily declare the @llvm.lifetime.end intrinsic.
1709llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1710 if (LifetimeEndFn) return LifetimeEndFn;
1711 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1712 llvm::Intrinsic::lifetime_end);
1713 return LifetimeEndFn;
1714}
1715
John McCall31168b02011-06-15 23:02:42 +00001716namespace {
1717 /// A cleanup to perform a release of an object at the end of a
1718 /// function. This is used to balance out the incoming +1 of a
1719 /// ns_consumed argument when we can't reasonably do that just by
1720 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00001721 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001722 ConsumeARCParameter(llvm::Value *param,
1723 ARCPreciseLifetime_t precise)
1724 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001725
1726 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001727 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001728
Craig Topper4f12f102014-03-12 06:41:41 +00001729 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001730 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001731 }
1732 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001733} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00001734
Mike Stump11289f42009-09-09 15:08:12 +00001735/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001736/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00001737void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1738 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001739 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001740 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001741 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001742
John McCall7f416cc2015-09-08 08:05:57 +00001743 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00001744
Adrian Prantl51936dd2013-03-14 17:53:33 +00001745 QualType Ty = D.getType();
1746
John McCall147d0212011-02-22 22:38:33 +00001747 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00001748 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00001749 // The only implicit argument a block has is its literal.
John McCall7f416cc2015-09-08 08:05:57 +00001750 // We assume this is always passed directly.
John McCall147d0212011-02-22 22:38:33 +00001751 if (BlockInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001752 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
John McCall147d0212011-02-22 22:38:33 +00001753 return;
1754 }
1755 }
1756
John McCall7f416cc2015-09-08 08:05:57 +00001757 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001758 bool DoStore = false;
1759 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001760 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001761 if (Arg.isIndirect()) {
1762 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001763 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00001764 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001765 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00001766 if (DeclPtr.getType() != IRTy)
1767 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1768
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001769 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00001770 // Don't push a cleanup in a thunk for a method that will also emit a
1771 // cleanup.
1772 if (!IsScalar && !CurFuncIsThunk &&
Reid Kleckner739756c2013-12-04 19:23:12 +00001773 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001774 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1775 if (RD && RD->hasNonTrivialDestructor())
1776 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001777 }
Chris Lattner53621a52007-06-13 20:44:40 +00001778 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001779 // Otherwise, create a temporary to hold the value.
John McCall7f416cc2015-09-08 08:05:57 +00001780 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1781 D.getName() + ".addr");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001782 DoStore = true;
1783 }
Mike Stump11289f42009-09-09 15:08:12 +00001784
John McCall7f416cc2015-09-08 08:05:57 +00001785 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1786
1787 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001788 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00001789 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001790 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1791 // We honor __attribute__((ns_consumed)) for types with lifetime.
1792 // For __strong, it's handled by just skipping the initial retain;
1793 // otherwise we have to balance out the initial +1 with an extra
1794 // cleanup to do the release at the end of the function.
1795 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1796
1797 // 'self' is always formally __strong, but if this is not an
1798 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001799 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001800 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1801 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001802 assert(lt == Qualifiers::OCL_Strong);
1803 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001804 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001805 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001806 lt = Qualifiers::OCL_ExplicitNone;
1807 }
1808
1809 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001810 if (!isConsumed) {
1811 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1812 // use objc_storeStrong(&dest, value) for retaining the
1813 // object. But first, store a null into 'dest' because
1814 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001815 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001816 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
John McCall7f416cc2015-09-08 08:05:57 +00001817 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001818 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001819 }
1820 else
John McCall31168b02011-06-15 23:02:42 +00001821 // Don't use objc_retainBlock for block pointers, because we
1822 // don't want to Block_copy something just because we got it
1823 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00001824 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001825 }
John McCall31168b02011-06-15 23:02:42 +00001826 } else {
1827 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00001828 if (isConsumed) {
1829 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1830 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00001831 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00001832 precise);
1833 }
John McCall31168b02011-06-15 23:02:42 +00001834
1835 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00001836 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001837 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001838 }
1839 }
1840
1841 // Enter the cleanup scope.
1842 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1843 }
Chris Lattner53621a52007-06-13 20:44:40 +00001844 }
1845
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001846 // Store the initial value into the alloca.
1847 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00001848 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001849
John McCall7f416cc2015-09-08 08:05:57 +00001850 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001851
1852 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001853 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001854 if (CGM.getCodeGenOpts().getDebugInfo() >=
1855 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001856 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001857 }
1858 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001859
1860 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001861 EmitVarAnnotations(&D, DeclPtr.getPointer());
Chris Lattner53621a52007-06-13 20:44:40 +00001862}