blob: 36d20cca380759a0462ed1b6d7ae184c5cc1c836 [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"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000024#include "clang/AST/DeclOpenMP.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000025#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000026#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000027#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000028#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/Type.h"
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +000033
Chris Lattner84915fa2007-06-02 04:16:21 +000034using namespace clang;
35using namespace CodeGen;
36
Chris Lattner1ad38f82007-06-09 01:20:56 +000037void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000038 switch (D.getKind()) {
David Majnemerd9b1a4f2015-11-04 03:40:30 +000039 case Decl::BuiltinTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000040 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +000041 case Decl::ExternCContext:
Douglas Gregor19043f02010-04-23 02:02:43 +000042 case Decl::Namespace:
43 case Decl::UnresolvedUsingTypename:
44 case Decl::ClassTemplateSpecialization:
45 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000046 case Decl::VarTemplateSpecialization:
47 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000048 case Decl::TemplateTypeParm:
49 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000050 case Decl::NonTypeTemplateParm:
Douglas Gregor19043f02010-04-23 02:02:43 +000051 case Decl::CXXMethod:
52 case Decl::CXXConstructor:
53 case Decl::CXXDestructor:
54 case Decl::CXXConversion:
55 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000056 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000057 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000058 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000059 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000060 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000061 case Decl::ImplicitParam:
62 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000063 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000064 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000065 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000066 case Decl::TemplateTemplateParm:
67 case Decl::ObjCMethod:
68 case Decl::ObjCCategory:
69 case Decl::ObjCProtocol:
70 case Decl::ObjCInterface:
71 case Decl::ObjCCategoryImpl:
72 case Decl::ObjCImplementation:
73 case Decl::ObjCProperty:
74 case Decl::ObjCCompatibleAlias:
Nico Weber66220292016-03-02 17:28:48 +000075 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +000076 case Decl::PragmaDetectMismatch:
Abramo Bagnarad7340582010-06-05 05:09:32 +000077 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000078 case Decl::LinkageSpec:
79 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000080 case Decl::FileScopeAsm:
81 case Decl::Friend:
82 case Decl::FriendTemplate:
83 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000084 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000085 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000086 case Decl::UsingShadow:
Douglas Gregor85f3f952015-07-07 03:57:15 +000087 case Decl::ObjCTypeParam:
David Blaikie83d382b2011-09-23 05:06:16 +000088 llvm_unreachable("Declaration should not be in declstmts!");
Hans Wennborg8a118b62016-02-23 19:10:16 +000089 case Decl::Function: // void X();
90 case Decl::Record: // struct/union/class X;
91 case Decl::Enum: // enum X;
92 case Decl::EnumConstant: // enum ? { X = ? }
93 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +000094 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +000095 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +000096 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +000097 case Decl::OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +000098 case Decl::OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +000099 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +0000100 // None of these decls require codegen support.
101 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +0000102
David Blaikief121b932013-05-20 22:50:41 +0000103 case Decl::NamespaceAlias:
104 if (CGDebugInfo *DI = getDebugInfo())
Hans Wennborg8a118b62016-02-23 19:10:16 +0000105 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
David Blaikief121b932013-05-20 22:50:41 +0000106 return;
David Blaikiebd483762013-05-20 04:58:53 +0000107 case Decl::Using: // using X; [C++]
108 if (CGDebugInfo *DI = getDebugInfo())
Hans Wennborg8a118b62016-02-23 19:10:16 +0000109 DI->EmitUsingDecl(cast<UsingDecl>(D));
David Blaikiebd483762013-05-20 04:58:53 +0000110 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000111 case Decl::UsingDirective: // using namespace X; [C++]
112 if (CGDebugInfo *DI = getDebugInfo())
113 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
114 return;
Daniel Dunbara7998072008-08-29 17:28:43 +0000115 case Decl::Var: {
116 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000117 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000118 "Should not see file-scope variables inside a function!");
John McCall1c9c3fd2010-10-15 04:57:14 +0000119 return EmitVarDecl(VD);
Chris Lattner84915fa2007-06-02 04:16:21 +0000120 }
Mike Stump11289f42009-09-09 15:08:12 +0000121
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000122 case Decl::OMPDeclareReduction:
123 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D));
124
Richard Smithdda56e42011-04-15 14:24:37 +0000125 case Decl::Typedef: // typedef int X;
126 case Decl::TypeAlias: { // using X = int; [C++0x]
127 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000128 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000129
Anders Carlsson5d985f52008-12-20 21:51:53 +0000130 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000131 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000132 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000133 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000134}
Chris Lattner03df1222007-06-02 04:53:11 +0000135
John McCall1c9c3fd2010-10-15 04:57:14 +0000136/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000137/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000138void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000139 if (D.isStaticLocal()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000140 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000141 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000142
David Majnemer27d69db2014-04-28 22:17:59 +0000143 // FIXME: We need to force the emission/use of a guard variable for
144 // some variables even if we can constant-evaluate them because
145 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000146
John McCall1c9c3fd2010-10-15 04:57:14 +0000147 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000148 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000149
150 if (D.hasExternalStorage())
Lauro Ramos Venanciobada8d42008-02-16 22:30:38 +0000151 // Don't emit it now, allow it to be emitted lazily on its first use.
152 return;
Daniel Dunbar0ca16602009-04-14 02:25:56 +0000153
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000154 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000155 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
156
157 assert(D.hasLocalStorage());
158 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000159}
160
Reid Kleckner453e0562014-10-08 01:07:54 +0000161static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
162 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000163 return CGM.getMangledName(&D).str();
164
Reid Kleckner453e0562014-10-08 01:07:54 +0000165 // If this isn't C++, we don't need a mangled name, just a pretty one.
166 assert(!D.isExternallyVisible() && "name shouldn't matter");
167 std::string ContextName;
168 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000169 if (auto *CD = dyn_cast<CapturedDecl>(DC))
170 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000171 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000172 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000173 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
174 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
175 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
176 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000177 else
David Blaikie83d382b2011-09-23 05:06:16 +0000178 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000179
Reid Kleckner453e0562014-10-08 01:07:54 +0000180 ContextName += "." + D.getNameAsString();
181 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000182}
183
Reid Kleckner453e0562014-10-08 01:07:54 +0000184llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
185 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
186 // In general, we don't always emit static var decls once before we reference
187 // them. It is possible to reference them before emitting the function that
188 // contains them, and it is possible to emit the containing function multiple
189 // times.
190 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
191 return ExistingGV;
192
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000193 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000194 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000195
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000196 // Use the label if the variable is renamed with the asm-label extension.
197 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000198 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000199 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000200 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000201 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000202
Reid Kleckner453e0562014-10-08 01:07:54 +0000203 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000204 unsigned AddrSpace =
Reid Kleckner453e0562014-10-08 01:07:54 +0000205 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000206
207 // Local address space cannot have an initializer.
208 llvm::Constant *Init = nullptr;
209 if (Ty.getAddressSpace() != LangAS::opencl_local)
210 Init = EmitNullConstant(Ty);
211 else
212 Init = llvm::UndefValue::get(LTy);
213
Anders Carlssone33eed52009-09-26 18:16:06 +0000214 llvm::GlobalVariable *GV =
Reid Kleckner453e0562014-10-08 01:07:54 +0000215 new llvm::GlobalVariable(getModule(), LTy,
Anders Carlssone33eed52009-09-26 18:16:06 +0000216 Ty.isConstant(getContext()), Linkage,
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000217 Init, Name, nullptr,
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000218 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000219 AddrSpace);
Ken Dyck160146e2010-01-27 17:10:57 +0000220 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Reid Kleckner453e0562014-10-08 01:07:54 +0000221 setGlobalVisibility(GV, &D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000222
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000223 if (supportsCOMDAT() && GV->isWeakForLinker())
224 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000225
Richard Smithfd3834f2013-04-13 02:43:54 +0000226 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000227 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000228
Hans Wennborgef2272c2014-06-18 15:55:13 +0000229 if (D.isExternallyVisible()) {
230 if (D.hasAttr<DLLImportAttr>())
231 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
232 else if (D.hasAttr<DLLExportAttr>())
233 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
234 }
235
Eli Benderskycb399432014-03-24 22:05:38 +0000236 // Make sure the result is of the correct type.
Reid Kleckner453e0562014-10-08 01:07:54 +0000237 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
238 llvm::Constant *Addr = GV;
Eli Benderskycb399432014-03-24 22:05:38 +0000239 if (AddrSpace != ExpectedAddrSpace) {
240 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
Reid Kleckner453e0562014-10-08 01:07:54 +0000241 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
Eli Benderskycb399432014-03-24 22:05:38 +0000242 }
243
Reid Kleckner453e0562014-10-08 01:07:54 +0000244 setStaticLocalDeclAddress(&D, Addr);
245
246 // Ensure that the static local gets initialized by making sure the parent
247 // function gets emitted eventually.
248 const Decl *DC = cast<Decl>(D.getDeclContext());
249
250 // We can't name blocks or captured statements directly, so try to emit their
251 // parents.
252 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
253 DC = DC->getNonClosureContext();
254 // FIXME: Ensure that global blocks get emitted.
255 if (!DC)
256 return Addr;
257 }
258
259 GlobalDecl GD;
260 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
261 GD = GlobalDecl(CD, Ctor_Base);
262 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
263 GD = GlobalDecl(DD, Dtor_Base);
264 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
265 GD = GlobalDecl(FD);
266 else {
267 // Don't do anything for Obj-C method decls or global closures. We should
268 // never defer them.
269 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
270 }
271 if (GD.getDecl())
272 (void)GetAddrOfGlobal(GD);
273
274 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000275}
276
Richard Smith6331c402012-02-13 22:16:19 +0000277/// hasNontrivialDestruction - Determine whether a type's destruction is
278/// non-trivial. If so, and the variable uses static initialization, we must
279/// register its destructor to run on exit.
280static bool hasNontrivialDestruction(QualType T) {
281 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
282 return RD && !RD->hasTrivialDestructor();
283}
284
Chandler Carruth84537952012-03-30 19:44:53 +0000285/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
286/// global variable that has already been created for it. If the initializer
287/// has a different type than GV does, this may free GV and return a different
288/// one. Otherwise it just returns GV.
289llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000290CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000291 llvm::GlobalVariable *GV) {
292 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCall70013b62010-07-15 23:40:35 +0000293
Chris Lattnere99c1102009-12-05 08:22:11 +0000294 // If constant emission failed, then this should be a C++ static
295 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000296 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000297 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000298 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall68ff0372010-09-08 01:44:27 +0000299 else if (Builder.GetInsertBlock()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000300 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000301 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000302 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000303
Chandler Carruth84537952012-03-30 19:44:53 +0000304 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000305 }
Chandler Carruth84537952012-03-30 19:44:53 +0000306 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000307 }
John McCall70013b62010-07-15 23:40:35 +0000308
Chris Lattnere99c1102009-12-05 08:22:11 +0000309 // The initializer may differ in type from the global. Rewrite
310 // the global to match the initializer. (We have to do this
311 // because some types, like unions, can't be completely represented
312 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000313 if (GV->getType()->getElementType() != Init->getType()) {
314 llvm::GlobalVariable *OldGV = GV;
315
316 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
317 OldGV->isConstant(),
318 OldGV->getLinkage(), Init, "",
319 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000320 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000321 CGM.getContext().getTargetAddressSpace(D.getType()));
322 GV->setVisibility(OldGV->getVisibility());
Reid Klecknereab97d32015-07-20 20:35:30 +0000323 GV->setComdat(OldGV->getComdat());
Eric Christopher31ab1302011-08-23 22:38:00 +0000324
Chris Lattnere99c1102009-12-05 08:22:11 +0000325 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000326 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000327
Chris Lattnere99c1102009-12-05 08:22:11 +0000328 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000329 llvm::Constant *NewPtrForOldDecl =
330 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
331 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000332
Chris Lattnere99c1102009-12-05 08:22:11 +0000333 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000334 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000335 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000336
Chandler Carruth84537952012-03-30 19:44:53 +0000337 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
338 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000339
340 if (hasNontrivialDestruction(D.getType())) {
341 // We have a constant initializer, but a nontrivial destructor. We still
342 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000343 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000344 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000345 }
346
Chandler Carruth84537952012-03-30 19:44:53 +0000347 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000348}
349
John McCall1c9c3fd2010-10-15 04:57:14 +0000350void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000351 llvm::GlobalValue::LinkageTypes Linkage) {
John McCallb88a5662012-03-30 21:00:39 +0000352 // Check to see if we already have a global variable for this
353 // declaration. This can happen when double-emitting function
354 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000355 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
John McCall7f416cc2015-09-08 08:05:57 +0000356 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara374e602009-02-25 19:45:19 +0000357
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000358 // Store into LocalDeclMap before generating initializer to handle
359 // circular references.
John McCall7f416cc2015-09-08 08:05:57 +0000360 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000361
John McCall4a39ab82010-05-04 20:45:42 +0000362 // We can't have a VLA here, but we can have a pointer to a VLA,
363 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000364 // Make sure to evaluate VLA bounds now so that we have them for later.
365 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000366 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000367
John McCallb88a5662012-03-30 21:00:39 +0000368 // Save the type in case adding the initializer forces a type change.
369 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000370
Eli Benderskycb399432014-03-24 22:05:38 +0000371 llvm::GlobalVariable *var =
372 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Chris Lattnere99c1102009-12-05 08:22:11 +0000373 // If this value has an initializer, emit it.
374 if (D.getInit())
John McCallb88a5662012-03-30 21:00:39 +0000375 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000376
John McCall7f416cc2015-09-08 08:05:57 +0000377 var->setAlignment(alignment.getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000378
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000379 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000380 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000381
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000382 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000383 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000384
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000385 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000386 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000387
Chandler Carruth84537952012-03-30 19:44:53 +0000388 // We may have to cast the constant because of the initializer
389 // mismatch above.
390 //
391 // FIXME: It is really dangerous to store this in the map; if anyone
392 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000393 llvm::Constant *castedAddr =
394 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCall7f416cc2015-09-08 08:05:57 +0000395 if (var != castedAddr)
396 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCallb88a5662012-03-30 21:00:39 +0000397 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000398
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000399 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000400
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000401 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000402 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000403 if (DI &&
Benjamin Kramer8c305922016-02-02 11:06:51 +0000404 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000405 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000406 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000407 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000408}
Mike Stump11289f42009-09-09 15:08:12 +0000409
John McCall2b7fc382010-07-13 20:32:21 +0000410namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000411 struct DestroyObject final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000412 DestroyObject(Address addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000413 CodeGenFunction::Destroyer *destroyer,
414 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000415 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000416 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000417
John McCall7f416cc2015-09-08 08:05:57 +0000418 Address addr;
John McCall82fe67b2011-07-09 01:37:26 +0000419 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000420 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000421 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000422
Craig Topper4f12f102014-03-12 06:41:41 +0000423 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000424 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000425 bool useEHCleanupForArray =
426 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000427
428 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000429 }
430 };
431
David Blaikie7e70d682015-08-18 22:40:54 +0000432 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000433 DestroyNRVOVariable(Address addr,
John McCall82fe67b2011-07-09 01:37:26 +0000434 const CXXDestructorDecl *Dtor,
435 llvm::Value *NRVOFlag)
436 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000437
438 const CXXDestructorDecl *Dtor;
439 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000440 Address Loc;
John McCall2b7fc382010-07-13 20:32:21 +0000441
Craig Topper4f12f102014-03-12 06:41:41 +0000442 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000443 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000444 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000445
Craig Topper8a13c412014-05-21 05:09:00 +0000446 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000447 if (NRVO) {
448 // If we exited via NRVO, we skip the destructor call.
449 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
450 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000451 llvm::Value *DidNRVO =
452 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000453 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
454 CGF.EmitBlock(RunDtorBB);
455 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000456
John McCall2b7fc382010-07-13 20:32:21 +0000457 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +0000458 /*ForVirtualBase=*/false,
459 /*Delegating=*/false,
460 Loc);
John McCall2b7fc382010-07-13 20:32:21 +0000461
462 if (NRVO) CGF.EmitBlock(SkipDtorBB);
463 }
464 };
John McCall2b7fc382010-07-13 20:32:21 +0000465
David Blaikie7e70d682015-08-18 22:40:54 +0000466 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000467 Address Stack;
468 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000469 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000470 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000471 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
472 CGF.Builder.CreateCall(F, V);
473 }
474 };
475
David Blaikie7e70d682015-08-18 22:40:54 +0000476 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000477 const VarDecl &Var;
478 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
479
Craig Topper4f12f102014-03-12 06:41:41 +0000480 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000481 // Compute the address of the local variable, in case it's a
482 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000483 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
484 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000485 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
486 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000487 CGF.EmitExtendGCLifetime(value);
488 }
489 };
490
David Blaikie7e70d682015-08-18 22:40:54 +0000491 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000492 llvm::Constant *CleanupFn;
493 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000494 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000495
John McCalla464ff92010-07-21 06:13:08 +0000496 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000497 const VarDecl *Var)
498 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000499
Craig Topper4f12f102014-03-12 06:41:41 +0000500 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000501 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
502 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000503 // Compute the address of the local variable, in case it's a byref
504 // or something.
John McCall7f416cc2015-09-08 08:05:57 +0000505 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCallc533cb72011-02-22 06:44:22 +0000506
John McCalla464ff92010-07-21 06:13:08 +0000507 // In some cases, the type of the function argument will be different from
508 // the type of the pointer. An example of this is
509 // void f(void* arg);
510 // __attribute__((cleanup(f))) void *g;
511 //
512 // To fix this we insert a bitcast here.
513 QualType ArgTy = FnInfo.arg_begin()->type;
514 llvm::Value *Arg =
515 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
516
517 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000518 Args.add(RValue::get(Arg),
519 CGF.getContext().getPointerType(Var.getType()));
John McCalla464ff92010-07-21 06:13:08 +0000520 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
521 }
522 };
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000523
524 /// A cleanup to call @llvm.lifetime.end.
David Blaikie7e70d682015-08-18 22:40:54 +0000525 class CallLifetimeEnd final : public EHScopeStack::Cleanup {
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000526 llvm::Value *Addr;
527 llvm::Value *Size;
528 public:
John McCall7f416cc2015-09-08 08:05:57 +0000529 CallLifetimeEnd(Address addr, llvm::Value *size)
530 : Addr(addr.getPointer()), Size(size) {}
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000531
532 void Emit(CodeGenFunction &CGF, Flags flags) override {
David Majnemerdc012fa2015-04-22 21:38:15 +0000533 CGF.EmitLifetimeEnd(Size, Addr);
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000534 }
535 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000536} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000537
John McCall31168b02011-06-15 23:02:42 +0000538/// EmitAutoVarWithLifetime - Does the setup required for an automatic
539/// variable with lifetime.
540static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000541 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000542 Qualifiers::ObjCLifetime lifetime) {
543 switch (lifetime) {
544 case Qualifiers::OCL_None:
545 llvm_unreachable("present but none");
546
547 case Qualifiers::OCL_ExplicitNone:
548 // nothing to do
549 break;
550
551 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000552 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000553 (var.hasAttr<ObjCPreciseLifetimeAttr>()
554 ? CodeGenFunction::destroyARCStrongPrecise
555 : CodeGenFunction::destroyARCStrongImprecise);
556
557 CleanupKind cleanupKind = CGF.getARCCleanupKind();
558 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
559 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000560 break;
561 }
562 case Qualifiers::OCL_Autoreleasing:
563 // nothing to do
564 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000565
John McCall31168b02011-06-15 23:02:42 +0000566 case Qualifiers::OCL_Weak:
567 // __weak objects always get EH cleanups; otherwise, exceptions
568 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000569 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
570 CodeGenFunction::destroyARCWeak,
571 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000572 break;
573 }
574}
575
576static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
577 if (const Expr *e = dyn_cast<Expr>(s)) {
578 // Skip the most common kinds of expressions that make
579 // hierarchy-walking expensive.
580 s = e = e->IgnoreParenCasts();
581
582 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
583 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000584 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
585 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000586 for (const auto &I : block->captures()) {
587 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000588 return true;
589 }
590 }
John McCall31168b02011-06-15 23:02:42 +0000591 }
592
Benjamin Kramer642f1732015-07-02 21:03:14 +0000593 for (const Stmt *SubStmt : s->children())
594 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
595 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000596 return true;
597
598 return false;
599}
600
601static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
602 if (!decl) return false;
603 if (!isa<VarDecl>(decl)) return false;
604 const VarDecl *var = cast<VarDecl>(decl);
605 return isAccessedBy(*var, e);
606}
607
John McCallf8a9b662015-10-21 18:06:31 +0000608static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
609 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000610 bool needsCast = false;
611
John McCallf8a9b662015-10-21 18:06:31 +0000612 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
613 switch (castExpr->getCastKind()) {
614 // Look through casts that don't require representation changes.
615 case CK_NoOp:
616 case CK_BitCast:
617 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000618 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000619 break;
620
621 // If we find an l-value to r-value cast from a __weak variable,
622 // emit this operation as a copy or move.
623 case CK_LValueToRValue: {
624 const Expr *srcExpr = castExpr->getSubExpr();
625 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
626 return false;
627
628 // Emit the source l-value.
629 LValue srcLV = CGF.EmitLValue(srcExpr);
630
John McCall0204e342015-11-16 22:11:41 +0000631 // Handle a formal type change to avoid asserting.
632 auto srcAddr = srcLV.getAddress();
633 if (needsCast) {
634 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
635 destLV.getAddress().getElementType());
636 }
637
John McCallf8a9b662015-10-21 18:06:31 +0000638 // If it was an l-value, use objc_copyWeak.
639 if (srcExpr->getValueKind() == VK_LValue) {
John McCall0204e342015-11-16 22:11:41 +0000640 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000641 } else {
642 assert(srcExpr->getValueKind() == VK_XValue);
John McCall0204e342015-11-16 22:11:41 +0000643 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000644 }
645 return true;
646 }
647
648 // Stop at anything else.
649 default:
650 return false;
651 }
652
653 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000654 }
655 return false;
656}
657
John McCall1553b192011-06-16 04:16:24 +0000658static void drillIntoBlockVariable(CodeGenFunction &CGF,
659 LValue &lvalue,
660 const VarDecl *var) {
John McCall7f416cc2015-09-08 08:05:57 +0000661 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCall1553b192011-06-16 04:16:24 +0000662}
663
David Blaikie73ca5692014-12-09 00:32:22 +0000664void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000665 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000666 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000667 if (!lifetime) {
668 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000669 if (capturedByInit)
670 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +0000671 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000672 return;
673 }
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000674
675 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
676 init = DIE->getExpr();
677
John McCall31168b02011-06-15 23:02:42 +0000678 // If we're emitting a value with lifetime, we have to do the
679 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000680 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
681 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000682 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000683 }
684 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000685
686 // We have to maintain the illusion that the variable is
687 // zero-initialized. If the variable might be accessed in its
688 // initializer, zero-initialize before running the initializer, then
689 // actually perform the initialization with an assign.
690 bool accessedByInit = false;
691 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000692 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000693 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000694 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000695 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000696 if (capturedByInit) {
697 // We can use a simple GEP for this because it can't have been
698 // moved yet.
John McCall7f416cc2015-09-08 08:05:57 +0000699 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
700 cast<VarDecl>(D),
701 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000702 }
703
John McCall7f416cc2015-09-08 08:05:57 +0000704 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
John McCall31168b02011-06-15 23:02:42 +0000705 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000706
John McCall31168b02011-06-15 23:02:42 +0000707 // If __weak, we want to use a barrier under certain conditions.
708 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000709 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000710
711 // Otherwise just do a simple store.
712 else
David Chisnallfa35df62012-01-16 17:27:18 +0000713 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000714 }
715
716 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000717 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000718
719 switch (lifetime) {
720 case Qualifiers::OCL_None:
721 llvm_unreachable("present but none");
722
723 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000724 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000725 break;
726
727 case Qualifiers::OCL_Strong: {
728 value = EmitARCRetainScalarExpr(init);
729 break;
730 }
731
732 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000733 // If it's not accessed by the initializer, try to emit the
734 // initialization with a copy or move.
735 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
736 return;
737 }
738
John McCall31168b02011-06-15 23:02:42 +0000739 // No way to optimize a producing initializer into this. It's not
740 // worth optimizing for, because the value will immediately
741 // disappear in the common case.
742 value = EmitScalarExpr(init);
743
John McCall1553b192011-06-16 04:16:24 +0000744 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000745 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000746 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000747 else
John McCall1553b192011-06-16 04:16:24 +0000748 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000749 return;
750 }
751
752 case Qualifiers::OCL_Autoreleasing:
753 value = EmitARCRetainAutoreleaseScalarExpr(init);
754 break;
755 }
756
John McCall1553b192011-06-16 04:16:24 +0000757 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000758
759 // If the variable might have been accessed by its initializer, we
760 // might have to initialize with a barrier. We have to do this for
761 // both __weak and __strong, but __weak got filtered out above.
762 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000763 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000764 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000765 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000766 return;
767 }
768
David Chisnallfa35df62012-01-16 17:27:18 +0000769 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000770}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000771
John McCalld4631322011-06-17 06:42:21 +0000772/// EmitScalarInit - Initialize the given lvalue with the given object.
773void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
774 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
775 if (!lifetime)
David Chisnallfa35df62012-01-16 17:27:18 +0000776 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCalld4631322011-06-17 06:42:21 +0000777
778 switch (lifetime) {
779 case Qualifiers::OCL_None:
780 llvm_unreachable("present but none");
781
782 case Qualifiers::OCL_ExplicitNone:
783 // nothing to do
784 break;
785
786 case Qualifiers::OCL_Strong:
787 init = EmitARCRetain(lvalue.getType(), init);
788 break;
789
790 case Qualifiers::OCL_Weak:
791 // Initialize and then skip the primitive store.
792 EmitARCInitWeak(lvalue.getAddress(), init);
793 return;
794
795 case Qualifiers::OCL_Autoreleasing:
796 init = EmitARCRetainAutorelease(lvalue.getType(), init);
797 break;
798 }
799
David Chisnallfa35df62012-01-16 17:27:18 +0000800 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCalld4631322011-06-17 06:42:21 +0000801}
802
Chris Lattnerb85025f2010-12-01 02:05:19 +0000803/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
804/// non-zero parts of the specified initializer with equal or fewer than
805/// NumStores scalar stores.
806static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
807 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000808 // Zero and Undef never requires any extra stores.
809 if (isa<llvm::ConstantAggregateZero>(Init) ||
810 isa<llvm::ConstantPointerNull>(Init) ||
811 isa<llvm::UndefValue>(Init))
812 return true;
813 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
814 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
815 isa<llvm::ConstantExpr>(Init))
816 return Init->isNullValue() || NumStores--;
817
818 // See if we can emit each element.
819 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
820 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
821 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
822 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
823 return false;
824 }
825 return true;
826 }
Chris Lattner236b3572012-01-31 04:36:19 +0000827
828 if (llvm::ConstantDataSequential *CDS =
829 dyn_cast<llvm::ConstantDataSequential>(Init)) {
830 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
831 llvm::Constant *Elt = CDS->getElementAsConstant(i);
832 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
833 return false;
834 }
835 return true;
836 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000837
Chris Lattnerb85025f2010-12-01 02:05:19 +0000838 // Anything else is hard and scary.
839 return false;
840}
841
842/// emitStoresForInitAfterMemset - For inits that
843/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
844/// stores that would be required.
845static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000846 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000847 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
848 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000849
Chris Lattnere6af8862010-12-02 01:58:41 +0000850 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
851 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
852 isa<llvm::ConstantExpr>(Init)) {
John McCall7f416cc2015-09-08 08:05:57 +0000853 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000854 return;
855 }
856
857 if (llvm::ConstantDataSequential *CDS =
858 dyn_cast<llvm::ConstantDataSequential>(Init)) {
859 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
860 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000861
862 // If necessary, get a pointer to the element and emit it.
863 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000864 emitStoresForInitAfterMemset(
865 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
866 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000867 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000868 return;
869 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000870
Chris Lattnere6af8862010-12-02 01:58:41 +0000871 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
872 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000873
Chris Lattnere6af8862010-12-02 01:58:41 +0000874 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
875 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000876
877 // If necessary, get a pointer to the element and emit it.
878 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000879 emitStoresForInitAfterMemset(
880 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
881 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000882 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000883}
884
Chris Lattnerb85025f2010-12-01 02:05:19 +0000885/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
886/// plus some stores to initialize a local variable instead of using a memcpy
887/// from a constant global. It is beneficial to use memset if the global is all
888/// zeros, or mostly zeros and large.
889static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
890 uint64_t GlobalSize) {
891 // If a global is all zeros, always use a memset.
892 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
893
Chris Lattnerb85025f2010-12-01 02:05:19 +0000894 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
895 // do it if it will require 6 or fewer scalar stores.
896 // TODO: Should budget depends on the size? Avoiding a large global warrants
897 // plopping in more stores.
898 unsigned StoreBudget = 6;
899 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000900
901 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000902 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
903}
904
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000905/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000906/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000907/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000908void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
909 AutoVarEmission emission = EmitAutoVarAlloca(D);
910 EmitAutoVarInit(emission);
911 EmitAutoVarCleanups(emission);
912}
Chris Lattner03df1222007-06-02 04:53:11 +0000913
David Majnemerdc012fa2015-04-22 21:38:15 +0000914/// Emit a lifetime.begin marker if some criteria are satisfied.
915/// \return a pointer to the temporary size Value if a marker was emitted, null
916/// otherwise
917llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
918 llvm::Value *Addr) {
919 // For now, only in optimized builds.
920 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
921 return nullptr;
922
Reid Kleckner1ef49212015-04-23 18:07:13 +0000923 // Disable lifetime markers in msan builds.
924 // FIXME: Remove this when msan works with lifetime markers.
925 if (getLangOpts().Sanitize.has(SanitizerKind::Memory))
926 return nullptr;
927
David Majnemerdc012fa2015-04-22 21:38:15 +0000928 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000929 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
930 llvm::CallInst *C =
931 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000932 C->setDoesNotThrow();
933 return SizeV;
934}
935
936void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000937 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
938 llvm::CallInst *C =
939 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000940 C->setDoesNotThrow();
941}
942
John McCallc533cb72011-02-22 06:44:22 +0000943/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000944/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +0000945CodeGenFunction::AutoVarEmission
946CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
947 QualType Ty = D.getType();
948
949 AutoVarEmission emission(D);
950
951 bool isByRef = D.hasAttr<BlocksAttr>();
952 emission.IsByRef = isByRef;
953
954 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +0000955
John McCall23c29fe2011-06-24 21:55:10 +0000956 // If the type is variably-modified, emit all the VLA sizes for it.
957 if (Ty->isVariablyModifiedType())
958 EmitVariablyModifiedType(Ty);
959
John McCall7f416cc2015-09-08 08:05:57 +0000960 Address address = Address::invalid();
Eli Friedmana682d392008-02-15 12:20:59 +0000961 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000962 bool NRVO = getLangOpts().ElideConstructors &&
963 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +0000964
Richard Smith2bcde3a2013-06-02 00:09:52 +0000965 // If this value is an array or struct with a statically determinable
966 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +0000967 //
968 // TODO: We should constant-evaluate the initializer of any variable,
969 // as long as it is initialized by a constant expression. Currently,
970 // isConstantInitializer produces wrong answers for structs with
971 // reference or bitfield members, and a few other cases, and checking
972 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +0000973 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
974 (D.isConstexpr() ||
975 ((Ty.isPODType(getContext()) ||
976 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
977 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +0000978
Rafael Espindola609f5d92013-03-26 18:41:47 +0000979 // If the variable's a const type, and it's neither an NRVO
980 // candidate nor a __block variable and has no mutable members,
981 // emit it as a global instead.
982 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
983 CGM.isTypeConstant(Ty, true)) {
984 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +0000985
John McCall7f416cc2015-09-08 08:05:57 +0000986 // Signal this condition to later callbacks.
987 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +0000988 assert(emission.wasEmittedAsGlobal());
989 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +0000990 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000991
Rafael Espindola609f5d92013-03-26 18:41:47 +0000992 // Otherwise, tell the initialization code that we're in this case.
993 emission.IsConstantAggregate = true;
994 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000995
Rafael Espindola609f5d92013-03-26 18:41:47 +0000996 // A normal fixed sized variable becomes an alloca in the entry block,
997 // unless it's an NRVO variable.
Eric Christopher31ab1302011-08-23 22:38:00 +0000998
Rafael Espindola609f5d92013-03-26 18:41:47 +0000999 if (NRVO) {
1000 // The named return value optimization: allocate this variable in the
1001 // return slot, so that we can elide the copy when returning this
1002 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +00001003 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +00001004
Rafael Espindola609f5d92013-03-26 18:41:47 +00001005 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1006 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
1007 // Create a flag that is used to indicate when the NRVO was applied
1008 // to this variable. Set it to zero to indicate that NRVO was not
1009 // applied.
1010 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +00001011 Address NRVOFlag =
1012 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +00001013 EnsureInsertPoint();
1014 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +00001015
Rafael Espindola609f5d92013-03-26 18:41:47 +00001016 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +00001017 NRVOFlags[&D] = NRVOFlag.getPointer();
1018 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +00001019 }
Douglas Gregor290c93e2010-05-15 06:46:45 +00001020 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001021 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001022 CharUnits allocaAlignment;
1023 llvm::Type *allocaTy;
1024 if (isByRef) {
1025 auto &byrefInfo = getBlockByrefInfo(&D);
1026 allocaTy = byrefInfo.Type;
1027 allocaAlignment = byrefInfo.ByrefAlignment;
1028 } else {
1029 allocaTy = ConvertTypeForMem(Ty);
1030 allocaAlignment = alignment;
1031 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001032
John McCall999110f2015-09-08 09:18:30 +00001033 // Create the alloca. Note that we set the name separately from
1034 // building the instruction so that it's there even in no-asserts
1035 // builds.
1036 address = CreateTempAlloca(allocaTy, allocaAlignment);
1037 address.getPointer()->setName(D.getName());
Rafael Espindola609f5d92013-03-26 18:41:47 +00001038
Reid Kleckner1f88e932015-10-07 21:03:41 +00001039 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1040 // the catch parameter starts in the catchpad instruction, and we can't
1041 // insert code in those basic blocks.
1042 bool IsMSCatchParam =
1043 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1044
Rafael Espindola609f5d92013-03-26 18:41:47 +00001045 // Emit a lifetime intrinsic if meaningful. There's no point
1046 // in doing this if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001047 if (HaveInsertPoint() && !IsMSCatchParam) {
John McCall7f416cc2015-09-08 08:05:57 +00001048 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1049 emission.SizeForLifetimeMarkers =
1050 EmitLifetimeStart(size, address.getPointer());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001051 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001052 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001053 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001054 }
Chris Lattner03df1222007-06-02 04:53:11 +00001055 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001056 EnsureInsertPoint();
1057
Anders Carlsson15949b32009-02-09 20:41:50 +00001058 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001059 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001060 Address Stack =
1061 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001062
Anders Carlsson30032882008-12-12 07:38:43 +00001063 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001064 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001065 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001066
1067 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001068
John McCalla464ff92010-07-21 06:13:08 +00001069 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001070 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001071 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001072 }
Mike Stump11289f42009-09-09 15:08:12 +00001073
John McCall23c29fe2011-06-24 21:55:10 +00001074 llvm::Value *elementCount;
1075 QualType elementType;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001076 std::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +00001077
Chris Lattner2192fe52011-07-18 04:24:23 +00001078 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +00001079
1080 // Allocate memory for the array.
John McCall23c29fe2011-06-24 21:55:10 +00001081 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1082 vla->setAlignment(alignment.getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +00001083
John McCall7f416cc2015-09-08 08:05:57 +00001084 address = Address(vla, alignment);
Chris Lattner03df1222007-06-02 04:53:11 +00001085 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001086
John McCall7f416cc2015-09-08 08:05:57 +00001087 setAddrOfLocalVar(&D, address);
1088 emission.Addr = address;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001089
1090 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +00001091 if (HaveInsertPoint())
1092 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001093 if (CGM.getCodeGenOpts().getDebugInfo() >=
1094 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001095 DI->setLocation(D.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001096 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001097 }
Devang Patel887e2152011-06-03 19:21:47 +00001098 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001099
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001100 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001101 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001102
John McCallc533cb72011-02-22 06:44:22 +00001103 return emission;
1104}
1105
1106/// Determines whether the given __block variable is potentially
1107/// captured by the given expression.
1108static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1109 // Skip the most common kinds of expressions that make
1110 // hierarchy-walking expensive.
1111 e = e->IgnoreParenCasts();
1112
1113 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1114 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +00001115 for (const auto &I : block->captures()) {
1116 if (I.getVariable() == &var)
John McCallc533cb72011-02-22 06:44:22 +00001117 return true;
1118 }
1119
1120 // No need to walk into the subexpressions.
1121 return false;
1122 }
1123
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001124 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1125 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001126 for (const auto *BI : CS->body())
1127 if (const auto *E = dyn_cast<Expr>(BI)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001128 if (isCapturedBy(var, E))
1129 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001130 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001131 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001132 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001133 for (const auto *I : DS->decls()) {
1134 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1135 const Expr *Init = VD->getInit();
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001136 if (Init && isCapturedBy(var, Init))
1137 return true;
1138 }
1139 }
1140 }
1141 else
1142 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1143 // Later, provide code to poke into statements for capture analysis.
1144 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001145 return false;
1146 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001147
Benjamin Kramer642f1732015-07-02 21:03:14 +00001148 for (const Stmt *SubStmt : e->children())
1149 if (isCapturedBy(var, cast<Expr>(SubStmt)))
John McCallc533cb72011-02-22 06:44:22 +00001150 return true;
1151
1152 return false;
1153}
1154
Douglas Gregor82e1af22011-07-01 21:08:19 +00001155/// \brief Determine whether the given initializer is trivial in the sense
1156/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001157bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001158 if (!Init)
1159 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001160
Douglas Gregor82e1af22011-07-01 21:08:19 +00001161 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1162 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1163 if (Constructor->isTrivial() &&
1164 Constructor->isDefaultConstructor() &&
1165 !Construct->requiresZeroInitialization())
1166 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001167
Douglas Gregor82e1af22011-07-01 21:08:19 +00001168 return false;
1169}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001170
John McCallc533cb72011-02-22 06:44:22 +00001171void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001172 assert(emission.Variable && "emission was not valid!");
1173
John McCallc533cb72011-02-22 06:44:22 +00001174 // If this was emitted as a global constant, we're done.
1175 if (emission.wasEmittedAsGlobal()) return;
1176
John McCall9e2e22f2011-02-22 07:16:58 +00001177 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001178 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001179 QualType type = D.getType();
1180
Chris Lattner07eb7332007-07-12 00:39:48 +00001181 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001182 const Expr *Init = D.getInit();
1183
1184 // If we are at an unreachable point, we don't need to emit the initializer
1185 // unless it contains a label.
1186 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001187 if (!Init || !ContainsLabel(Init)) return;
1188 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001189 }
1190
John McCall73064872011-03-31 01:59:53 +00001191 // Initialize the structure of a __block variable.
1192 if (emission.IsByRef)
1193 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001194
Douglas Gregor82e1af22011-07-01 21:08:19 +00001195 if (isTrivialInitializer(Init))
1196 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001197
John McCallc533cb72011-02-22 06:44:22 +00001198 // Check whether this is a byref variable that's potentially
1199 // captured and moved by its own initializer. If so, we'll need to
1200 // emit the initializer first, then copy into the variable.
1201 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1202
John McCall7f416cc2015-09-08 08:05:57 +00001203 Address Loc =
1204 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
John McCallc533cb72011-02-22 06:44:22 +00001205
Craig Topper8a13c412014-05-21 05:09:00 +00001206 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001207 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001208 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smithdafff942012-01-14 04:30:29 +00001209 constant = CGM.EmitConstantInit(D, this);
Richard Smithfddd3842011-12-30 21:15:51 +00001210 }
1211
1212 if (!constant) {
John McCall7f416cc2015-09-08 08:05:57 +00001213 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001214 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001215 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001216 }
John McCall91ca10f2011-03-08 09:11:50 +00001217
Richard Smith2bcde3a2013-06-02 00:09:52 +00001218 if (!emission.IsConstantAggregate) {
1219 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001220 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001221 lv.setNonGC(true);
1222 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1223 }
1224
John McCallc533cb72011-02-22 06:44:22 +00001225 // If this is a simple aggregate initialization, we can optimize it
1226 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001227 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001228
John McCall91ca10f2011-03-08 09:11:50 +00001229 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001230 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001231 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001232
Chris Lattner2192fe52011-07-18 04:24:23 +00001233 llvm::Type *BP = Int8PtrTy;
John McCall7f416cc2015-09-08 08:05:57 +00001234 if (Loc.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001235 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001236
John McCall91ca10f2011-03-08 09:11:50 +00001237 // If the initializer is all or mostly zeros, codegen with memset then do
1238 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001239 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001240 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall91ca10f2011-03-08 09:11:50 +00001241 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
John McCall7f416cc2015-09-08 08:05:57 +00001242 isVolatile);
Benjamin Kramer29f9a002012-08-27 22:07:02 +00001243 // Zero and undef don't require a stores.
1244 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall91ca10f2011-03-08 09:11:50 +00001245 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001246 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1247 isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001248 }
John McCall91ca10f2011-03-08 09:11:50 +00001249 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001250 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001251 // memcpy from the global to the alloca.
Reid Kleckner453e0562014-10-08 01:07:54 +00001252 std::string Name = getStaticDeclName(CGM, D);
John McCall91ca10f2011-03-08 09:11:50 +00001253 llvm::GlobalVariable *GV =
1254 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001255 llvm::GlobalValue::PrivateLinkage,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001256 constant, Name);
John McCall7f416cc2015-09-08 08:05:57 +00001257 GV->setAlignment(Loc.getAlignment().getQuantity());
Eli Friedmanb8578422011-05-27 22:32:55 +00001258 GV->setUnnamedAddr(true);
Eric Christopher31ab1302011-08-23 22:38:00 +00001259
John McCall7f416cc2015-09-08 08:05:57 +00001260 Address SrcPtr = Address(GV, Loc.getAlignment());
1261 if (SrcPtr.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001262 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001263
John McCall7f416cc2015-09-08 08:05:57 +00001264 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
John McCall91ca10f2011-03-08 09:11:50 +00001265 }
1266}
1267
1268/// Emit an expression as an initializer for a variable at the given
1269/// location. The expression is not necessarily the normal
1270/// initializer for the variable, and the address is not necessarily
1271/// its normal location.
1272///
1273/// \param init the initializing expression
1274/// \param var the variable to act as if we're initializing
1275/// \param loc the address to initialize; its type is a pointer
1276/// to the LLVM mapping of the variable's type
1277/// \param alignment the alignment of the address
1278/// \param capturedByInit true if the variable is a __block variable
1279/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001280void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001281 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001282 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001283
1284 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001285 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001286 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001287 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001288 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001289 return;
1290 }
1291 switch (getEvaluationKind(type)) {
1292 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001293 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001294 return;
1295 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001296 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001297 if (capturedByInit)
1298 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001299 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001300 return;
1301 }
1302 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001303 if (type->isAtomicType()) {
1304 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1305 } else {
1306 // TODO: how can we delay here if D is captured by its initializer?
1307 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001308 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001309 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001310 AggValueSlot::IsNotAliased));
John McCalla8ec7eb2013-03-07 21:37:17 +00001311 }
John McCall47fb9502013-03-07 21:37:08 +00001312 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001313 }
John McCall47fb9502013-03-07 21:37:08 +00001314 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001315}
John McCallbd309292010-07-06 01:34:17 +00001316
John McCall82fe67b2011-07-09 01:37:26 +00001317/// Enter a destroy cleanup for the given local variable.
1318void CodeGenFunction::emitAutoVarTypeCleanup(
1319 const CodeGenFunction::AutoVarEmission &emission,
1320 QualType::DestructionKind dtorKind) {
1321 assert(dtorKind != QualType::DK_none);
1322
1323 // Note that for __block variables, we want to destroy the
1324 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001325 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001326
1327 const VarDecl *var = emission.Variable;
1328 QualType type = var->getType();
1329
1330 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001331 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001332
1333 switch (dtorKind) {
1334 case QualType::DK_none:
1335 llvm_unreachable("no cleanup for trivially-destructible variable");
1336
1337 case QualType::DK_cxx_destructor:
1338 // If there's an NRVO flag on the emission, we need a different
1339 // cleanup.
1340 if (emission.NRVOFlag) {
1341 assert(!type->isArrayType());
1342 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +00001343 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1344 dtor, emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001345 return;
1346 }
1347 break;
1348
1349 case QualType::DK_objc_strong_lifetime:
1350 // Suppress cleanups for pseudo-strong variables.
1351 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001352
John McCall82fe67b2011-07-09 01:37:26 +00001353 // Otherwise, consider whether to use an EH cleanup or not.
1354 cleanupKind = getARCCleanupKind();
1355
1356 // Use the imprecise destroyer by default.
1357 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1358 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1359 break;
1360
1361 case QualType::DK_objc_weak_lifetime:
1362 break;
1363 }
1364
1365 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001366 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001367
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001368 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001369 // is being pushed as an EH cleanup.
1370 bool useEHCleanup = (cleanupKind & EHCleanup);
1371 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1372 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001373}
1374
John McCallc533cb72011-02-22 06:44:22 +00001375void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001376 assert(emission.Variable && "emission was not valid!");
1377
John McCallc533cb72011-02-22 06:44:22 +00001378 // If this was emitted as a global constant, we're done.
1379 if (emission.wasEmittedAsGlobal()) return;
1380
John McCall8c38d352012-04-13 18:44:05 +00001381 // If we don't have an insertion point, we're done. Sema prevents
1382 // us from jumping into any of these scopes anyway.
1383 if (!HaveInsertPoint()) return;
1384
John McCall9e2e22f2011-02-22 07:16:58 +00001385 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001386
Nadav Rotem1da30942013-03-23 06:43:35 +00001387 // Make sure we call @llvm.lifetime.end. This needs to happen
1388 // *last*, so the cleanup needs to be pushed *first*.
1389 if (emission.useLifetimeMarkers()) {
1390 EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1391 emission.getAllocatedAddress(),
1392 emission.getSizeForLifetimeMarkers());
David Majnemerdc012fa2015-04-22 21:38:15 +00001393 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
1394 cleanup.setLifetimeMarker();
Nadav Rotem1da30942013-03-23 06:43:35 +00001395 }
1396
John McCall82fe67b2011-07-09 01:37:26 +00001397 // Check the type for a cleanup.
1398 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1399 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001400
John McCall1bd25562011-06-24 23:21:27 +00001401 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001402 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001403 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1404 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1405 }
1406
John McCallc533cb72011-02-22 06:44:22 +00001407 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001408 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001409 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001410
John McCallc533cb72011-02-22 06:44:22 +00001411 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001412 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001413
John McCalla729c622012-02-17 03:33:10 +00001414 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001415 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001416 }
Mike Stump626aecc2009-03-05 01:23:13 +00001417
John McCallc533cb72011-02-22 06:44:22 +00001418 // If this is a block variable, call _Block_object_destroy
1419 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001420 if (emission.IsByRef)
1421 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001422}
Chris Lattner53621a52007-06-13 20:44:40 +00001423
Peter Collingbourne1425b452012-01-26 03:33:36 +00001424CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001425CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1426 switch (kind) {
1427 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001428 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001429 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001430 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001431 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001432 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001433 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001434 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001435 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001436}
1437
John McCall12cc42a2013-02-01 05:11:40 +00001438/// pushEHDestroy - Push the standard destructor for the given type as
1439/// an EH-only cleanup.
1440void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001441 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00001442 assert(dtorKind && "cannot push destructor for trivial type");
1443 assert(needsEHCleanup(dtorKind));
1444
1445 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1446}
1447
1448/// pushDestroy - Push the standard destructor for the given type as
1449/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001450void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001451 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00001452 assert(dtorKind && "cannot push destructor for trivial type");
1453
1454 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1455 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1456 cleanupKind & EHCleanup);
1457}
1458
John McCall7f416cc2015-09-08 08:05:57 +00001459void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001460 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001461 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001462 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1463 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001464}
1465
John McCall7f416cc2015-09-08 08:05:57 +00001466void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001467 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1468}
1469
Richard Smith736a9472013-06-12 20:42:33 +00001470void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00001471 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00001472 Destroyer *destroyer, bool useEHCleanupForArray) {
1473 assert(!isInConditionalBranch() &&
1474 "performing lifetime extension from within conditional");
1475
1476 // Push an EH-only cleanup for the object now.
1477 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1478 // around in case a temporary's destructor throws an exception.
1479 if (cleanupKind & EHCleanup)
1480 EHStack.pushCleanup<DestroyObject>(
1481 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1482 destroyer, useEHCleanupForArray);
1483
1484 // Remember that we need to push a full cleanup for the object at the
1485 // end of the full-expression.
1486 pushCleanupAfterFullExpr<DestroyObject>(
1487 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1488}
1489
John McCall178360e2011-07-11 08:38:19 +00001490/// emitDestroy - Immediately perform the destruction of the given
1491/// object.
1492///
1493/// \param addr - the address of the object; a type*
1494/// \param type - the type of the object; if an array type, all
1495/// objects are destroyed in reverse order
1496/// \param destroyer - the function to call to destroy individual
1497/// elements
1498/// \param useEHCleanupForArray - whether an EH cleanup should be
1499/// used when destroying array elements, in case one of the
1500/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00001501void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001502 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001503 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001504 const ArrayType *arrayType = getContext().getAsArrayType(type);
1505 if (!arrayType)
1506 return destroyer(*this, addr, type);
1507
John McCall7f416cc2015-09-08 08:05:57 +00001508 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1509
1510 CharUnits elementAlign =
1511 addr.getAlignment()
1512 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00001513
1514 // Normally we have to check whether the array is zero-length.
1515 bool checkZeroLength = true;
1516
1517 // But if the array length is constant, we can suppress that.
1518 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1519 // ...and if it's constant zero, we can just skip the entire thing.
1520 if (constLength->isZero()) return;
1521 checkZeroLength = false;
1522 }
1523
John McCall7f416cc2015-09-08 08:05:57 +00001524 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00001525 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00001526 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001527 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001528}
1529
John McCall178360e2011-07-11 08:38:19 +00001530/// emitArrayDestroy - Destroys all the elements of the given array,
1531/// beginning from last to first. The array cannot be zero-length.
1532///
1533/// \param begin - a type* denoting the first element of the array
1534/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001535/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00001536/// \param destroyer - the function to call to destroy elements
1537/// \param useEHCleanup - whether to push an EH cleanup to destroy
1538/// the remaining elements in case the destruction of a single
1539/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001540void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1541 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001542 QualType elementType,
1543 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001544 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001545 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001546 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00001547 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00001548
1549 // The basic structure here is a do-while loop, because we don't
1550 // need to check for the zero-element case.
1551 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1552 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1553
John McCall97eab0a2011-07-13 08:09:46 +00001554 if (checkZeroLength) {
1555 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1556 "arraydestroy.isempty");
1557 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1558 }
1559
John McCall82fe67b2011-07-09 01:37:26 +00001560 // Enter the loop body, making that address the current address.
1561 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1562 EmitBlock(bodyBB);
1563 llvm::PHINode *elementPast =
1564 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1565 elementPast->addIncoming(end, entryBB);
1566
1567 // Shift the address back by one element.
1568 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1569 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1570 "arraydestroy.element");
1571
John McCall178360e2011-07-11 08:38:19 +00001572 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00001573 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1574 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001575
John McCall82fe67b2011-07-09 01:37:26 +00001576 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00001577 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00001578
John McCall178360e2011-07-11 08:38:19 +00001579 if (useEHCleanup)
1580 PopCleanupBlock();
1581
John McCall82fe67b2011-07-09 01:37:26 +00001582 // Check whether we've reached the end.
1583 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1584 Builder.CreateCondBr(done, doneBB, bodyBB);
1585 elementPast->addIncoming(element, Builder.GetInsertBlock());
1586
1587 // Done.
1588 EmitBlock(doneBB);
1589}
1590
John McCall178360e2011-07-11 08:38:19 +00001591/// Perform partial array destruction as if in an EH cleanup. Unlike
1592/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001593static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1594 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001595 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001596 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001597 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001598 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001599 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1600 // VLAs don't require a GEP index to walk into.
1601 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001602 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001603 type = arrayType->getElementType();
1604 }
John McCall97eab0a2011-07-13 08:09:46 +00001605
1606 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00001607 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00001608
John McCallf0f0b7a2015-09-14 18:57:08 +00001609 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001610 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1611 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001612 }
1613
John McCall97eab0a2011-07-13 08:09:46 +00001614 // Destroy the array. We don't ever need an EH cleanup because we
1615 // assume that we're in an EH cleanup ourselves, so a throwing
1616 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00001617 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001618 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001619}
1620
John McCall82fe67b2011-07-09 01:37:26 +00001621namespace {
John McCall178360e2011-07-11 08:38:19 +00001622 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1623 /// array destroy where the end pointer is regularly determined and
1624 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001625 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00001626 llvm::Value *ArrayBegin;
1627 llvm::Value *ArrayEnd;
1628 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001629 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001630 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00001631 public:
1632 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001633 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001634 CodeGenFunction::Destroyer *destroyer)
1635 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00001636 ElementType(elementType), Destroyer(destroyer),
1637 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00001638
Craig Topper4f12f102014-03-12 06:41:41 +00001639 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001640 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001641 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00001642 }
1643 };
1644
1645 /// IrregularPartialArrayDestroy - a cleanup which performs a
1646 /// partial array destroy where the end pointer is irregularly
1647 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001648 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001649 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00001650 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00001651 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001652 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001653 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00001654 public:
John McCall178360e2011-07-11 08:38:19 +00001655 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001656 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001657 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001658 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001659 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001660 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00001661 ElementType(elementType), Destroyer(destroyer),
1662 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00001663
Craig Topper4f12f102014-03-12 06:41:41 +00001664 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001665 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001666 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001667 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001668 }
1669 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001670} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00001671
John McCall178360e2011-07-11 08:38:19 +00001672/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001673/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001674/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001675///
John McCall82fe67b2011-07-09 01:37:26 +00001676/// \param elementType - the immediate element type of the array;
1677/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001678void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001679 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001680 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001681 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001682 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001683 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1684 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00001685 elementType, elementAlign,
1686 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001687}
1688
1689/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1690/// already-constructed elements of the given array. The cleanup
1691/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001692///
John McCall178360e2011-07-11 08:38:19 +00001693/// \param elementType - the immediate element type of the array;
1694/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001695void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1696 llvm::Value *arrayEnd,
1697 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001698 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001699 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001700 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001701 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001702 elementType, elementAlign,
1703 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001704}
1705
Nadav Rotem1da30942013-03-23 06:43:35 +00001706/// Lazily declare the @llvm.lifetime.start intrinsic.
1707llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1708 if (LifetimeStartFn) return LifetimeStartFn;
1709 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1710 llvm::Intrinsic::lifetime_start);
1711 return LifetimeStartFn;
1712}
1713
1714/// Lazily declare the @llvm.lifetime.end intrinsic.
1715llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1716 if (LifetimeEndFn) return LifetimeEndFn;
1717 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1718 llvm::Intrinsic::lifetime_end);
1719 return LifetimeEndFn;
1720}
1721
John McCall31168b02011-06-15 23:02:42 +00001722namespace {
1723 /// A cleanup to perform a release of an object at the end of a
1724 /// function. This is used to balance out the incoming +1 of a
1725 /// ns_consumed argument when we can't reasonably do that just by
1726 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00001727 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001728 ConsumeARCParameter(llvm::Value *param,
1729 ARCPreciseLifetime_t precise)
1730 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001731
1732 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001733 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001734
Craig Topper4f12f102014-03-12 06:41:41 +00001735 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001736 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001737 }
1738 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001739} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00001740
Mike Stump11289f42009-09-09 15:08:12 +00001741/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001742/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00001743void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1744 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001745 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001746 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001747 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001748
John McCall7f416cc2015-09-08 08:05:57 +00001749 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00001750
Adrian Prantl51936dd2013-03-14 17:53:33 +00001751 QualType Ty = D.getType();
1752
John McCall147d0212011-02-22 22:38:33 +00001753 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00001754 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00001755 // The only implicit argument a block has is its literal.
John McCall7f416cc2015-09-08 08:05:57 +00001756 // We assume this is always passed directly.
John McCall147d0212011-02-22 22:38:33 +00001757 if (BlockInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001758 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
John McCall147d0212011-02-22 22:38:33 +00001759 return;
1760 }
1761 }
1762
John McCall7f416cc2015-09-08 08:05:57 +00001763 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001764 bool DoStore = false;
1765 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001766 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001767 if (Arg.isIndirect()) {
1768 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001769 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00001770 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001771 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00001772 if (DeclPtr.getType() != IRTy)
1773 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1774
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001775 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00001776 // Don't push a cleanup in a thunk for a method that will also emit a
1777 // cleanup.
1778 if (!IsScalar && !CurFuncIsThunk &&
Reid Kleckner739756c2013-12-04 19:23:12 +00001779 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001780 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1781 if (RD && RD->hasNonTrivialDestructor())
1782 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001783 }
Chris Lattner53621a52007-06-13 20:44:40 +00001784 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001785 // Otherwise, create a temporary to hold the value.
John McCall7f416cc2015-09-08 08:05:57 +00001786 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1787 D.getName() + ".addr");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001788 DoStore = true;
1789 }
Mike Stump11289f42009-09-09 15:08:12 +00001790
John McCall7f416cc2015-09-08 08:05:57 +00001791 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1792
1793 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001794 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00001795 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001796 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1797 // We honor __attribute__((ns_consumed)) for types with lifetime.
1798 // For __strong, it's handled by just skipping the initial retain;
1799 // otherwise we have to balance out the initial +1 with an extra
1800 // cleanup to do the release at the end of the function.
1801 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1802
1803 // 'self' is always formally __strong, but if this is not an
1804 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001805 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001806 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1807 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001808 assert(lt == Qualifiers::OCL_Strong);
1809 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001810 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001811 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001812 lt = Qualifiers::OCL_ExplicitNone;
1813 }
1814
1815 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001816 if (!isConsumed) {
1817 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1818 // use objc_storeStrong(&dest, value) for retaining the
1819 // object. But first, store a null into 'dest' because
1820 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001821 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001822 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
John McCall7f416cc2015-09-08 08:05:57 +00001823 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001824 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001825 }
1826 else
John McCall31168b02011-06-15 23:02:42 +00001827 // Don't use objc_retainBlock for block pointers, because we
1828 // don't want to Block_copy something just because we got it
1829 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00001830 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001831 }
John McCall31168b02011-06-15 23:02:42 +00001832 } else {
1833 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00001834 if (isConsumed) {
1835 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1836 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00001837 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00001838 precise);
1839 }
John McCall31168b02011-06-15 23:02:42 +00001840
1841 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00001842 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001843 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001844 }
1845 }
1846
1847 // Enter the cleanup scope.
1848 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1849 }
Chris Lattner53621a52007-06-13 20:44:40 +00001850 }
1851
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001852 // Store the initial value into the alloca.
1853 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00001854 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001855
John McCall7f416cc2015-09-08 08:05:57 +00001856 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001857
1858 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001859 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001860 if (CGM.getCodeGenOpts().getDebugInfo() >=
1861 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001862 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001863 }
1864 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001865
1866 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001867 EmitVarAnnotations(&D, DeclPtr.getPointer());
Chris Lattner53621a52007-06-13 20:44:40 +00001868}
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001869
1870void CodeGenModule::EmitOMPDeclareReduction(
1871 const OMPDeclareReductionDecl * /*D*/) {}
1872