blob: a7920473d7c85279c6fa6cc1fc721a0afa58982d [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"
Reid Klecknere5a321b2016-09-07 18:21:30 +000016#include "CGCXXABI.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000017#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGDebugInfo.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000019#include "CGOpenCLRuntime.h"
Alexey Bataevc5b1d322016-03-04 09:22:22 +000020#include "CGOpenMPRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "CodeGenModule.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000022#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000023#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000024#include "clang/AST/Decl.h"
Anders Carlsson4c03d982008-08-25 01:38:19 +000025#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000026#include "clang/AST/DeclOpenMP.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000027#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000028#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000029#include "clang/CodeGen/CGFunctionInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000030#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/Type.h"
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +000035
Chris Lattner84915fa2007-06-02 04:16:21 +000036using namespace clang;
37using namespace CodeGen;
38
Chris Lattner1ad38f82007-06-09 01:20:56 +000039void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000040 switch (D.getKind()) {
David Majnemerd9b1a4f2015-11-04 03:40:30 +000041 case Decl::BuiltinTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000042 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +000043 case Decl::ExternCContext:
Douglas Gregor19043f02010-04-23 02:02:43 +000044 case Decl::Namespace:
45 case Decl::UnresolvedUsingTypename:
46 case Decl::ClassTemplateSpecialization:
47 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000048 case Decl::VarTemplateSpecialization:
49 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000050 case Decl::TemplateTypeParm:
51 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000052 case Decl::NonTypeTemplateParm:
Douglas Gregor19043f02010-04-23 02:02:43 +000053 case Decl::CXXMethod:
54 case Decl::CXXConstructor:
55 case Decl::CXXDestructor:
56 case Decl::CXXConversion:
57 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000058 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000059 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000060 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000061 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000062 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000063 case Decl::ImplicitParam:
64 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000065 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000066 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000067 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000068 case Decl::TemplateTemplateParm:
69 case Decl::ObjCMethod:
70 case Decl::ObjCCategory:
71 case Decl::ObjCProtocol:
72 case Decl::ObjCInterface:
73 case Decl::ObjCCategoryImpl:
74 case Decl::ObjCImplementation:
75 case Decl::ObjCProperty:
76 case Decl::ObjCCompatibleAlias:
Nico Weber66220292016-03-02 17:28:48 +000077 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +000078 case Decl::PragmaDetectMismatch:
Abramo Bagnarad7340582010-06-05 05:09:32 +000079 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000080 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +000081 case Decl::Export:
Douglas Gregor19043f02010-04-23 02:02:43 +000082 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000083 case Decl::FileScopeAsm:
84 case Decl::Friend:
85 case Decl::FriendTemplate:
86 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000087 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000088 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000089 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +000090 case Decl::ConstructorUsingShadow:
Douglas Gregor85f3f952015-07-07 03:57:15 +000091 case Decl::ObjCTypeParam:
Richard Smithda383632016-08-15 01:33:41 +000092 case Decl::Binding:
David Blaikie83d382b2011-09-23 05:06:16 +000093 llvm_unreachable("Declaration should not be in declstmts!");
Amjad Abouddc4531e2016-04-30 01:44:38 +000094 case Decl::Function: // void X();
95 case Decl::Record: // struct/union/class X;
96 case Decl::Enum: // enum X;
97 case Decl::EnumConstant: // enum ? { X = ? }
98 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +000099 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +0000100 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +0000101 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000102 case Decl::OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000103 case Decl::OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +0000104 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +0000105 // None of these decls require codegen support.
106 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +0000107
David Blaikief121b932013-05-20 22:50:41 +0000108 case Decl::NamespaceAlias:
109 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000110 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
David Blaikief121b932013-05-20 22:50:41 +0000111 return;
David Blaikiebd483762013-05-20 04:58:53 +0000112 case Decl::Using: // using X; [C++]
113 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000114 DI->EmitUsingDecl(cast<UsingDecl>(D));
David Blaikiebd483762013-05-20 04:58:53 +0000115 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000116 case Decl::UsingDirective: // using namespace X; [C++]
117 if (CGDebugInfo *DI = getDebugInfo())
118 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
119 return;
Richard Smithbdb84f32016-07-22 23:36:59 +0000120 case Decl::Var:
121 case Decl::Decomposition: {
Daniel Dunbara7998072008-08-29 17:28:43 +0000122 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000123 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000124 "Should not see file-scope variables inside a function!");
Richard Smithda383632016-08-15 01:33:41 +0000125 EmitVarDecl(VD);
126 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
127 for (auto *B : DD->bindings())
128 if (auto *HD = B->getHoldingVar())
129 EmitVarDecl(*HD);
130 return;
Chris Lattner84915fa2007-06-02 04:16:21 +0000131 }
Mike Stump11289f42009-09-09 15:08:12 +0000132
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000133 case Decl::OMPDeclareReduction:
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000134 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000135
Richard Smithdda56e42011-04-15 14:24:37 +0000136 case Decl::Typedef: // typedef int X;
137 case Decl::TypeAlias: { // using X = int; [C++0x]
138 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000139 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000140
Anders Carlsson5d985f52008-12-20 21:51:53 +0000141 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000142 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000143 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000144 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000145}
Chris Lattner03df1222007-06-02 04:53:11 +0000146
John McCall1c9c3fd2010-10-15 04:57:14 +0000147/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000148/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000149void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000150 if (D.isStaticLocal()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000151 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000152 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000153
David Majnemer27d69db2014-04-28 22:17:59 +0000154 // FIXME: We need to force the emission/use of a guard variable for
155 // some variables even if we can constant-evaluate them because
156 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000157
John McCall1c9c3fd2010-10-15 04:57:14 +0000158 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000159 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000160
161 if (D.hasExternalStorage())
Lauro Ramos Venanciobada8d42008-02-16 22:30:38 +0000162 // Don't emit it now, allow it to be emitted lazily on its first use.
163 return;
Daniel Dunbar0ca16602009-04-14 02:25:56 +0000164
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000165 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000166 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
167
168 assert(D.hasLocalStorage());
169 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000170}
171
Reid Kleckner453e0562014-10-08 01:07:54 +0000172static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
173 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000174 return CGM.getMangledName(&D).str();
175
Reid Kleckner453e0562014-10-08 01:07:54 +0000176 // If this isn't C++, we don't need a mangled name, just a pretty one.
177 assert(!D.isExternallyVisible() && "name shouldn't matter");
178 std::string ContextName;
179 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000180 if (auto *CD = dyn_cast<CapturedDecl>(DC))
181 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000182 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000183 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000184 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
185 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
186 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
187 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000188 else
David Blaikie83d382b2011-09-23 05:06:16 +0000189 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000190
Reid Kleckner453e0562014-10-08 01:07:54 +0000191 ContextName += "." + D.getNameAsString();
192 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000193}
194
Reid Kleckner453e0562014-10-08 01:07:54 +0000195llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
196 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
197 // In general, we don't always emit static var decls once before we reference
198 // them. It is possible to reference them before emitting the function that
199 // contains them, and it is possible to emit the containing function multiple
200 // times.
201 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
202 return ExistingGV;
203
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000204 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000205 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000206
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000207 // Use the label if the variable is renamed with the asm-label extension.
208 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000209 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000210 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000211 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000212 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000213
Reid Kleckner453e0562014-10-08 01:07:54 +0000214 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000215 unsigned AddrSpace =
Reid Kleckner453e0562014-10-08 01:07:54 +0000216 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000217
218 // Local address space cannot have an initializer.
219 llvm::Constant *Init = nullptr;
220 if (Ty.getAddressSpace() != LangAS::opencl_local)
221 Init = EmitNullConstant(Ty);
222 else
223 Init = llvm::UndefValue::get(LTy);
224
Anders Carlssone33eed52009-09-26 18:16:06 +0000225 llvm::GlobalVariable *GV =
Reid Kleckner453e0562014-10-08 01:07:54 +0000226 new llvm::GlobalVariable(getModule(), LTy,
Anders Carlssone33eed52009-09-26 18:16:06 +0000227 Ty.isConstant(getContext()), Linkage,
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000228 Init, Name, nullptr,
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000229 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000230 AddrSpace);
Ken Dyck160146e2010-01-27 17:10:57 +0000231 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Reid Kleckner453e0562014-10-08 01:07:54 +0000232 setGlobalVisibility(GV, &D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000233
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000234 if (supportsCOMDAT() && GV->isWeakForLinker())
235 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000236
Richard Smithfd3834f2013-04-13 02:43:54 +0000237 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000238 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000239
Hans Wennborgef2272c2014-06-18 15:55:13 +0000240 if (D.isExternallyVisible()) {
241 if (D.hasAttr<DLLImportAttr>())
242 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
243 else if (D.hasAttr<DLLExportAttr>())
244 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
245 }
246
Eli Benderskycb399432014-03-24 22:05:38 +0000247 // Make sure the result is of the correct type.
Reid Kleckner453e0562014-10-08 01:07:54 +0000248 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
249 llvm::Constant *Addr = GV;
Eli Benderskycb399432014-03-24 22:05:38 +0000250 if (AddrSpace != ExpectedAddrSpace) {
251 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
Reid Kleckner453e0562014-10-08 01:07:54 +0000252 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
Eli Benderskycb399432014-03-24 22:05:38 +0000253 }
254
Reid Kleckner453e0562014-10-08 01:07:54 +0000255 setStaticLocalDeclAddress(&D, Addr);
256
257 // Ensure that the static local gets initialized by making sure the parent
258 // function gets emitted eventually.
259 const Decl *DC = cast<Decl>(D.getDeclContext());
260
261 // We can't name blocks or captured statements directly, so try to emit their
262 // parents.
263 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
264 DC = DC->getNonClosureContext();
265 // FIXME: Ensure that global blocks get emitted.
266 if (!DC)
267 return Addr;
268 }
269
270 GlobalDecl GD;
271 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
272 GD = GlobalDecl(CD, Ctor_Base);
273 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
274 GD = GlobalDecl(DD, Dtor_Base);
275 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
276 GD = GlobalDecl(FD);
277 else {
278 // Don't do anything for Obj-C method decls or global closures. We should
279 // never defer them.
280 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
281 }
282 if (GD.getDecl())
283 (void)GetAddrOfGlobal(GD);
284
285 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000286}
287
Richard Smith6331c402012-02-13 22:16:19 +0000288/// hasNontrivialDestruction - Determine whether a type's destruction is
289/// non-trivial. If so, and the variable uses static initialization, we must
290/// register its destructor to run on exit.
291static bool hasNontrivialDestruction(QualType T) {
292 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
293 return RD && !RD->hasTrivialDestructor();
294}
295
Chandler Carruth84537952012-03-30 19:44:53 +0000296/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
297/// global variable that has already been created for it. If the initializer
298/// has a different type than GV does, this may free GV and return a different
299/// one. Otherwise it just returns GV.
300llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000301CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000302 llvm::GlobalVariable *GV) {
303 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCall70013b62010-07-15 23:40:35 +0000304
Chris Lattnere99c1102009-12-05 08:22:11 +0000305 // If constant emission failed, then this should be a C++ static
306 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000307 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000308 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000309 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall68ff0372010-09-08 01:44:27 +0000310 else if (Builder.GetInsertBlock()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000311 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000312 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000313 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000314
Chandler Carruth84537952012-03-30 19:44:53 +0000315 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000316 }
Chandler Carruth84537952012-03-30 19:44:53 +0000317 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000318 }
John McCall70013b62010-07-15 23:40:35 +0000319
Chris Lattnere99c1102009-12-05 08:22:11 +0000320 // The initializer may differ in type from the global. Rewrite
321 // the global to match the initializer. (We have to do this
322 // because some types, like unions, can't be completely represented
323 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000324 if (GV->getType()->getElementType() != Init->getType()) {
325 llvm::GlobalVariable *OldGV = GV;
326
327 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
328 OldGV->isConstant(),
329 OldGV->getLinkage(), Init, "",
330 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000331 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000332 CGM.getContext().getTargetAddressSpace(D.getType()));
333 GV->setVisibility(OldGV->getVisibility());
Reid Klecknereab97d32015-07-20 20:35:30 +0000334 GV->setComdat(OldGV->getComdat());
Eric Christopher31ab1302011-08-23 22:38:00 +0000335
Chris Lattnere99c1102009-12-05 08:22:11 +0000336 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000337 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000338
Chris Lattnere99c1102009-12-05 08:22:11 +0000339 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000340 llvm::Constant *NewPtrForOldDecl =
341 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
342 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000343
Chris Lattnere99c1102009-12-05 08:22:11 +0000344 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000345 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000346 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000347
Chandler Carruth84537952012-03-30 19:44:53 +0000348 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
349 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000350
351 if (hasNontrivialDestruction(D.getType())) {
352 // We have a constant initializer, but a nontrivial destructor. We still
353 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000354 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000355 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000356 }
357
Chandler Carruth84537952012-03-30 19:44:53 +0000358 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000359}
360
John McCall1c9c3fd2010-10-15 04:57:14 +0000361void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000362 llvm::GlobalValue::LinkageTypes Linkage) {
John McCallb88a5662012-03-30 21:00:39 +0000363 // Check to see if we already have a global variable for this
364 // declaration. This can happen when double-emitting function
365 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000366 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
John McCall7f416cc2015-09-08 08:05:57 +0000367 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara374e602009-02-25 19:45:19 +0000368
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000369 // Store into LocalDeclMap before generating initializer to handle
370 // circular references.
John McCall7f416cc2015-09-08 08:05:57 +0000371 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000372
John McCall4a39ab82010-05-04 20:45:42 +0000373 // We can't have a VLA here, but we can have a pointer to a VLA,
374 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000375 // Make sure to evaluate VLA bounds now so that we have them for later.
376 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000377 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000378
John McCallb88a5662012-03-30 21:00:39 +0000379 // Save the type in case adding the initializer forces a type change.
380 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000381
Eli Benderskycb399432014-03-24 22:05:38 +0000382 llvm::GlobalVariable *var =
383 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Artem Belevich4d430ba2016-05-09 22:09:56 +0000384
385 // CUDA's local and local static __shared__ variables should not
386 // have any non-empty initializers. This is ensured by Sema.
387 // Whatever initializer such variable may have when it gets here is
388 // a no-op and should not be emitted.
389 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
390 D.hasAttr<CUDASharedAttr>();
Chris Lattnere99c1102009-12-05 08:22:11 +0000391 // If this value has an initializer, emit it.
Artem Belevich4d430ba2016-05-09 22:09:56 +0000392 if (D.getInit() && !isCudaSharedVar)
John McCallb88a5662012-03-30 21:00:39 +0000393 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000394
John McCall7f416cc2015-09-08 08:05:57 +0000395 var->setAlignment(alignment.getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000396
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000397 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000398 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000399
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000400 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000401 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000402
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000403 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000404 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000405
Chandler Carruth84537952012-03-30 19:44:53 +0000406 // We may have to cast the constant because of the initializer
407 // mismatch above.
408 //
409 // FIXME: It is really dangerous to store this in the map; if anyone
410 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000411 llvm::Constant *castedAddr =
412 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCall7f416cc2015-09-08 08:05:57 +0000413 if (var != castedAddr)
414 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCallb88a5662012-03-30 21:00:39 +0000415 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000416
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000417 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000418
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000419 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000420 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000421 if (DI &&
Benjamin Kramer8c305922016-02-02 11:06:51 +0000422 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000423 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000424 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000425 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000426}
Mike Stump11289f42009-09-09 15:08:12 +0000427
John McCall2b7fc382010-07-13 20:32:21 +0000428namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000429 struct DestroyObject final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000430 DestroyObject(Address addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000431 CodeGenFunction::Destroyer *destroyer,
432 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000433 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000434 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000435
John McCall7f416cc2015-09-08 08:05:57 +0000436 Address addr;
John McCall82fe67b2011-07-09 01:37:26 +0000437 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000438 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000439 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000440
Craig Topper4f12f102014-03-12 06:41:41 +0000441 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000442 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000443 bool useEHCleanupForArray =
444 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000445
446 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000447 }
448 };
449
David Blaikie7e70d682015-08-18 22:40:54 +0000450 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000451 DestroyNRVOVariable(Address addr,
John McCall82fe67b2011-07-09 01:37:26 +0000452 const CXXDestructorDecl *Dtor,
453 llvm::Value *NRVOFlag)
454 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000455
456 const CXXDestructorDecl *Dtor;
457 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000458 Address Loc;
John McCall2b7fc382010-07-13 20:32:21 +0000459
Craig Topper4f12f102014-03-12 06:41:41 +0000460 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000461 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000462 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000463
Craig Topper8a13c412014-05-21 05:09:00 +0000464 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000465 if (NRVO) {
466 // If we exited via NRVO, we skip the destructor call.
467 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
468 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000469 llvm::Value *DidNRVO =
470 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000471 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
472 CGF.EmitBlock(RunDtorBB);
473 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000474
John McCall2b7fc382010-07-13 20:32:21 +0000475 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +0000476 /*ForVirtualBase=*/false,
477 /*Delegating=*/false,
478 Loc);
John McCall2b7fc382010-07-13 20:32:21 +0000479
480 if (NRVO) CGF.EmitBlock(SkipDtorBB);
481 }
482 };
John McCall2b7fc382010-07-13 20:32:21 +0000483
David Blaikie7e70d682015-08-18 22:40:54 +0000484 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000485 Address Stack;
486 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000487 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000488 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000489 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
490 CGF.Builder.CreateCall(F, V);
491 }
492 };
493
David Blaikie7e70d682015-08-18 22:40:54 +0000494 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000495 const VarDecl &Var;
496 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
497
Craig Topper4f12f102014-03-12 06:41:41 +0000498 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000499 // Compute the address of the local variable, in case it's a
500 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000501 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
502 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000503 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
504 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000505 CGF.EmitExtendGCLifetime(value);
506 }
507 };
508
David Blaikie7e70d682015-08-18 22:40:54 +0000509 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000510 llvm::Constant *CleanupFn;
511 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000512 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000513
John McCalla464ff92010-07-21 06:13:08 +0000514 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000515 const VarDecl *Var)
516 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000517
Craig Topper4f12f102014-03-12 06:41:41 +0000518 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000519 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
520 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000521 // Compute the address of the local variable, in case it's a byref
522 // or something.
John McCall7f416cc2015-09-08 08:05:57 +0000523 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCallc533cb72011-02-22 06:44:22 +0000524
John McCalla464ff92010-07-21 06:13:08 +0000525 // In some cases, the type of the function argument will be different from
526 // the type of the pointer. An example of this is
527 // void f(void* arg);
528 // __attribute__((cleanup(f))) void *g;
529 //
530 // To fix this we insert a bitcast here.
531 QualType ArgTy = FnInfo.arg_begin()->type;
532 llvm::Value *Arg =
533 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
534
535 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000536 Args.add(RValue::get(Arg),
537 CGF.getContext().getPointerType(Var.getType()));
John McCalla464ff92010-07-21 06:13:08 +0000538 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
539 }
540 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000541} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000542
John McCall31168b02011-06-15 23:02:42 +0000543/// EmitAutoVarWithLifetime - Does the setup required for an automatic
544/// variable with lifetime.
545static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000546 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000547 Qualifiers::ObjCLifetime lifetime) {
548 switch (lifetime) {
549 case Qualifiers::OCL_None:
550 llvm_unreachable("present but none");
551
552 case Qualifiers::OCL_ExplicitNone:
553 // nothing to do
554 break;
555
556 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000557 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000558 (var.hasAttr<ObjCPreciseLifetimeAttr>()
559 ? CodeGenFunction::destroyARCStrongPrecise
560 : CodeGenFunction::destroyARCStrongImprecise);
561
562 CleanupKind cleanupKind = CGF.getARCCleanupKind();
563 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
564 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000565 break;
566 }
567 case Qualifiers::OCL_Autoreleasing:
568 // nothing to do
569 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000570
John McCall31168b02011-06-15 23:02:42 +0000571 case Qualifiers::OCL_Weak:
572 // __weak objects always get EH cleanups; otherwise, exceptions
573 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000574 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
575 CodeGenFunction::destroyARCWeak,
576 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000577 break;
578 }
579}
580
581static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
582 if (const Expr *e = dyn_cast<Expr>(s)) {
583 // Skip the most common kinds of expressions that make
584 // hierarchy-walking expensive.
585 s = e = e->IgnoreParenCasts();
586
587 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
588 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000589 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
590 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000591 for (const auto &I : block->captures()) {
592 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000593 return true;
594 }
595 }
John McCall31168b02011-06-15 23:02:42 +0000596 }
597
Benjamin Kramer642f1732015-07-02 21:03:14 +0000598 for (const Stmt *SubStmt : s->children())
599 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
600 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000601 return true;
602
603 return false;
604}
605
606static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
607 if (!decl) return false;
608 if (!isa<VarDecl>(decl)) return false;
609 const VarDecl *var = cast<VarDecl>(decl);
610 return isAccessedBy(*var, e);
611}
612
John McCallf8a9b662015-10-21 18:06:31 +0000613static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
614 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000615 bool needsCast = false;
616
John McCallf8a9b662015-10-21 18:06:31 +0000617 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
618 switch (castExpr->getCastKind()) {
619 // Look through casts that don't require representation changes.
620 case CK_NoOp:
621 case CK_BitCast:
622 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000623 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000624 break;
625
626 // If we find an l-value to r-value cast from a __weak variable,
627 // emit this operation as a copy or move.
628 case CK_LValueToRValue: {
629 const Expr *srcExpr = castExpr->getSubExpr();
630 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
631 return false;
632
633 // Emit the source l-value.
634 LValue srcLV = CGF.EmitLValue(srcExpr);
635
John McCall0204e342015-11-16 22:11:41 +0000636 // Handle a formal type change to avoid asserting.
637 auto srcAddr = srcLV.getAddress();
638 if (needsCast) {
639 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
640 destLV.getAddress().getElementType());
641 }
642
John McCallf8a9b662015-10-21 18:06:31 +0000643 // If it was an l-value, use objc_copyWeak.
644 if (srcExpr->getValueKind() == VK_LValue) {
John McCall0204e342015-11-16 22:11:41 +0000645 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000646 } else {
647 assert(srcExpr->getValueKind() == VK_XValue);
John McCall0204e342015-11-16 22:11:41 +0000648 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000649 }
650 return true;
651 }
652
653 // Stop at anything else.
654 default:
655 return false;
656 }
657
658 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000659 }
660 return false;
661}
662
John McCall1553b192011-06-16 04:16:24 +0000663static void drillIntoBlockVariable(CodeGenFunction &CGF,
664 LValue &lvalue,
665 const VarDecl *var) {
John McCall7f416cc2015-09-08 08:05:57 +0000666 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCall1553b192011-06-16 04:16:24 +0000667}
668
David Blaikie73ca5692014-12-09 00:32:22 +0000669void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000670 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000671 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000672 if (!lifetime) {
673 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000674 if (capturedByInit)
675 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +0000676 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000677 return;
678 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000679
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000680 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
681 init = DIE->getExpr();
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000682
John McCall31168b02011-06-15 23:02:42 +0000683 // If we're emitting a value with lifetime, we have to do the
684 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000685 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
686 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000687 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000688 }
689 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000690
691 // We have to maintain the illusion that the variable is
692 // zero-initialized. If the variable might be accessed in its
693 // initializer, zero-initialize before running the initializer, then
694 // actually perform the initialization with an assign.
695 bool accessedByInit = false;
696 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000697 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000698 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000699 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000700 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000701 if (capturedByInit) {
702 // We can use a simple GEP for this because it can't have been
703 // moved yet.
John McCall7f416cc2015-09-08 08:05:57 +0000704 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
705 cast<VarDecl>(D),
706 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000707 }
708
John McCall7f416cc2015-09-08 08:05:57 +0000709 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
John McCall31168b02011-06-15 23:02:42 +0000710 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000711
John McCall31168b02011-06-15 23:02:42 +0000712 // If __weak, we want to use a barrier under certain conditions.
713 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000714 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000715
716 // Otherwise just do a simple store.
717 else
David Chisnallfa35df62012-01-16 17:27:18 +0000718 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000719 }
720
721 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000722 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000723
724 switch (lifetime) {
725 case Qualifiers::OCL_None:
726 llvm_unreachable("present but none");
727
728 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000729 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000730 break;
731
732 case Qualifiers::OCL_Strong: {
733 value = EmitARCRetainScalarExpr(init);
734 break;
735 }
736
737 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000738 // If it's not accessed by the initializer, try to emit the
739 // initialization with a copy or move.
740 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
741 return;
742 }
743
John McCall31168b02011-06-15 23:02:42 +0000744 // No way to optimize a producing initializer into this. It's not
745 // worth optimizing for, because the value will immediately
746 // disappear in the common case.
747 value = EmitScalarExpr(init);
748
John McCall1553b192011-06-16 04:16:24 +0000749 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000750 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000751 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000752 else
John McCall1553b192011-06-16 04:16:24 +0000753 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000754 return;
755 }
756
757 case Qualifiers::OCL_Autoreleasing:
758 value = EmitARCRetainAutoreleaseScalarExpr(init);
759 break;
760 }
761
John McCall1553b192011-06-16 04:16:24 +0000762 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000763
764 // If the variable might have been accessed by its initializer, we
765 // might have to initialize with a barrier. We have to do this for
766 // both __weak and __strong, but __weak got filtered out above.
767 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000768 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000769 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000770 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000771 return;
772 }
773
David Chisnallfa35df62012-01-16 17:27:18 +0000774 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000775}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000776
John McCalld4631322011-06-17 06:42:21 +0000777/// EmitScalarInit - Initialize the given lvalue with the given object.
778void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
779 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
780 if (!lifetime)
David Chisnallfa35df62012-01-16 17:27:18 +0000781 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCalld4631322011-06-17 06:42:21 +0000782
783 switch (lifetime) {
784 case Qualifiers::OCL_None:
785 llvm_unreachable("present but none");
786
787 case Qualifiers::OCL_ExplicitNone:
788 // nothing to do
789 break;
790
791 case Qualifiers::OCL_Strong:
792 init = EmitARCRetain(lvalue.getType(), init);
793 break;
794
795 case Qualifiers::OCL_Weak:
796 // Initialize and then skip the primitive store.
797 EmitARCInitWeak(lvalue.getAddress(), init);
798 return;
799
800 case Qualifiers::OCL_Autoreleasing:
801 init = EmitARCRetainAutorelease(lvalue.getType(), init);
802 break;
803 }
804
David Chisnallfa35df62012-01-16 17:27:18 +0000805 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCalld4631322011-06-17 06:42:21 +0000806}
807
Chris Lattnerb85025f2010-12-01 02:05:19 +0000808/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
809/// non-zero parts of the specified initializer with equal or fewer than
810/// NumStores scalar stores.
811static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
812 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000813 // Zero and Undef never requires any extra stores.
814 if (isa<llvm::ConstantAggregateZero>(Init) ||
815 isa<llvm::ConstantPointerNull>(Init) ||
816 isa<llvm::UndefValue>(Init))
817 return true;
818 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
819 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
820 isa<llvm::ConstantExpr>(Init))
821 return Init->isNullValue() || NumStores--;
822
823 // See if we can emit each element.
824 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
825 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
826 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
827 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
828 return false;
829 }
830 return true;
831 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000832
Chris Lattner236b3572012-01-31 04:36:19 +0000833 if (llvm::ConstantDataSequential *CDS =
834 dyn_cast<llvm::ConstantDataSequential>(Init)) {
835 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
836 llvm::Constant *Elt = CDS->getElementAsConstant(i);
837 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
838 return false;
839 }
840 return true;
841 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000842
Chris Lattnerb85025f2010-12-01 02:05:19 +0000843 // Anything else is hard and scary.
844 return false;
845}
846
847/// emitStoresForInitAfterMemset - For inits that
848/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
849/// stores that would be required.
850static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000851 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000852 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
853 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000854
Chris Lattnere6af8862010-12-02 01:58:41 +0000855 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
856 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
857 isa<llvm::ConstantExpr>(Init)) {
John McCall7f416cc2015-09-08 08:05:57 +0000858 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000859 return;
860 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000861
862 if (llvm::ConstantDataSequential *CDS =
863 dyn_cast<llvm::ConstantDataSequential>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000864 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
865 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000866
867 // If necessary, get a pointer to the element and emit it.
868 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000869 emitStoresForInitAfterMemset(
870 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
871 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000872 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000873 return;
874 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000875
Chris Lattnere6af8862010-12-02 01:58:41 +0000876 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
877 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000878
Chris Lattnere6af8862010-12-02 01:58:41 +0000879 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
880 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000881
882 // If necessary, get a pointer to the element and emit it.
883 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000884 emitStoresForInitAfterMemset(
885 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
886 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000887 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000888}
889
Chris Lattnerb85025f2010-12-01 02:05:19 +0000890/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
891/// plus some stores to initialize a local variable instead of using a memcpy
892/// from a constant global. It is beneficial to use memset if the global is all
893/// zeros, or mostly zeros and large.
894static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
895 uint64_t GlobalSize) {
896 // If a global is all zeros, always use a memset.
897 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
898
Chris Lattnerb85025f2010-12-01 02:05:19 +0000899 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
900 // do it if it will require 6 or fewer scalar stores.
901 // TODO: Should budget depends on the size? Avoiding a large global warrants
902 // plopping in more stores.
903 unsigned StoreBudget = 6;
904 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000905
906 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000907 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
908}
909
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000910/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000911/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000912/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000913void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
914 AutoVarEmission emission = EmitAutoVarAlloca(D);
915 EmitAutoVarInit(emission);
916 EmitAutoVarCleanups(emission);
917}
Chris Lattner03df1222007-06-02 04:53:11 +0000918
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000919/// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
920/// markers.
921static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
922 const LangOptions &LangOpts) {
923 // Asan uses markers for use-after-scope checks.
924 if (CGOpts.SanitizeAddressUseAfterScope)
925 return true;
926
927 // Disable lifetime markers in msan builds.
928 // FIXME: Remove this when msan works with lifetime markers.
929 if (LangOpts.Sanitize.has(SanitizerKind::Memory))
930 return false;
931
932 // For now, only in optimized builds.
933 return CGOpts.OptimizationLevel != 0;
934}
935
David Majnemerdc012fa2015-04-22 21:38:15 +0000936/// Emit a lifetime.begin marker if some criteria are satisfied.
937/// \return a pointer to the temporary size Value if a marker was emitted, null
938/// otherwise
939llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
940 llvm::Value *Addr) {
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000941 if (!shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), getLangOpts()))
Reid Kleckner1ef49212015-04-23 18:07:13 +0000942 return nullptr;
943
David Majnemerdc012fa2015-04-22 21:38:15 +0000944 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000945 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
946 llvm::CallInst *C =
947 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000948 C->setDoesNotThrow();
949 return SizeV;
950}
951
952void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000953 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
954 llvm::CallInst *C =
955 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000956 C->setDoesNotThrow();
957}
958
John McCallc533cb72011-02-22 06:44:22 +0000959/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000960/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +0000961CodeGenFunction::AutoVarEmission
962CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
963 QualType Ty = D.getType();
964
965 AutoVarEmission emission(D);
966
967 bool isByRef = D.hasAttr<BlocksAttr>();
968 emission.IsByRef = isByRef;
969
970 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +0000971
John McCall23c29fe2011-06-24 21:55:10 +0000972 // If the type is variably-modified, emit all the VLA sizes for it.
973 if (Ty->isVariablyModifiedType())
974 EmitVariablyModifiedType(Ty);
975
John McCall7f416cc2015-09-08 08:05:57 +0000976 Address address = Address::invalid();
Eli Friedmana682d392008-02-15 12:20:59 +0000977 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000978 bool NRVO = getLangOpts().ElideConstructors &&
979 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +0000980
Richard Smith2bcde3a2013-06-02 00:09:52 +0000981 // If this value is an array or struct with a statically determinable
982 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +0000983 //
984 // TODO: We should constant-evaluate the initializer of any variable,
985 // as long as it is initialized by a constant expression. Currently,
986 // isConstantInitializer produces wrong answers for structs with
987 // reference or bitfield members, and a few other cases, and checking
988 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +0000989 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
990 (D.isConstexpr() ||
991 ((Ty.isPODType(getContext()) ||
992 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
993 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +0000994
Rafael Espindola609f5d92013-03-26 18:41:47 +0000995 // If the variable's a const type, and it's neither an NRVO
996 // candidate nor a __block variable and has no mutable members,
997 // emit it as a global instead.
998 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
999 CGM.isTypeConstant(Ty, true)) {
1000 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +00001001
John McCall7f416cc2015-09-08 08:05:57 +00001002 // Signal this condition to later callbacks.
1003 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +00001004 assert(emission.wasEmittedAsGlobal());
1005 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +00001006 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001007
Rafael Espindola609f5d92013-03-26 18:41:47 +00001008 // Otherwise, tell the initialization code that we're in this case.
1009 emission.IsConstantAggregate = true;
1010 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001011
Rafael Espindola609f5d92013-03-26 18:41:47 +00001012 // A normal fixed sized variable becomes an alloca in the entry block,
1013 // unless it's an NRVO variable.
Eric Christopher31ab1302011-08-23 22:38:00 +00001014
Rafael Espindola609f5d92013-03-26 18:41:47 +00001015 if (NRVO) {
1016 // The named return value optimization: allocate this variable in the
1017 // return slot, so that we can elide the copy when returning this
1018 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +00001019 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +00001020
Rafael Espindola609f5d92013-03-26 18:41:47 +00001021 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1022 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
1023 // Create a flag that is used to indicate when the NRVO was applied
1024 // to this variable. Set it to zero to indicate that NRVO was not
1025 // applied.
1026 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +00001027 Address NRVOFlag =
1028 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +00001029 EnsureInsertPoint();
1030 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +00001031
Rafael Espindola609f5d92013-03-26 18:41:47 +00001032 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +00001033 NRVOFlags[&D] = NRVOFlag.getPointer();
1034 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +00001035 }
Douglas Gregor290c93e2010-05-15 06:46:45 +00001036 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001037 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001038 CharUnits allocaAlignment;
1039 llvm::Type *allocaTy;
1040 if (isByRef) {
1041 auto &byrefInfo = getBlockByrefInfo(&D);
1042 allocaTy = byrefInfo.Type;
1043 allocaAlignment = byrefInfo.ByrefAlignment;
1044 } else {
1045 allocaTy = ConvertTypeForMem(Ty);
1046 allocaAlignment = alignment;
1047 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001048
John McCall999110f2015-09-08 09:18:30 +00001049 // Create the alloca. Note that we set the name separately from
1050 // building the instruction so that it's there even in no-asserts
1051 // builds.
1052 address = CreateTempAlloca(allocaTy, allocaAlignment);
1053 address.getPointer()->setName(D.getName());
Rafael Espindola609f5d92013-03-26 18:41:47 +00001054
Reid Kleckner1f88e932015-10-07 21:03:41 +00001055 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1056 // the catch parameter starts in the catchpad instruction, and we can't
1057 // insert code in those basic blocks.
1058 bool IsMSCatchParam =
1059 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1060
Rafael Espindola609f5d92013-03-26 18:41:47 +00001061 // Emit a lifetime intrinsic if meaningful. There's no point
1062 // in doing this if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001063 if (HaveInsertPoint() && !IsMSCatchParam) {
John McCall7f416cc2015-09-08 08:05:57 +00001064 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1065 emission.SizeForLifetimeMarkers =
1066 EmitLifetimeStart(size, address.getPointer());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001067 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001068 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001069 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001070 }
Chris Lattner03df1222007-06-02 04:53:11 +00001071 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001072 EnsureInsertPoint();
1073
Anders Carlsson15949b32009-02-09 20:41:50 +00001074 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001075 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001076 Address Stack =
1077 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001078
Anders Carlsson30032882008-12-12 07:38:43 +00001079 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001080 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001081 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001082
1083 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001084
John McCalla464ff92010-07-21 06:13:08 +00001085 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001086 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001087 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001088 }
Mike Stump11289f42009-09-09 15:08:12 +00001089
John McCall23c29fe2011-06-24 21:55:10 +00001090 llvm::Value *elementCount;
1091 QualType elementType;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001092 std::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +00001093
Chris Lattner2192fe52011-07-18 04:24:23 +00001094 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +00001095
1096 // Allocate memory for the array.
John McCall23c29fe2011-06-24 21:55:10 +00001097 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1098 vla->setAlignment(alignment.getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +00001099
John McCall7f416cc2015-09-08 08:05:57 +00001100 address = Address(vla, alignment);
Chris Lattner03df1222007-06-02 04:53:11 +00001101 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001102
John McCall7f416cc2015-09-08 08:05:57 +00001103 setAddrOfLocalVar(&D, address);
1104 emission.Addr = address;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001105
1106 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +00001107 if (HaveInsertPoint())
1108 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001109 if (CGM.getCodeGenOpts().getDebugInfo() >=
1110 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001111 DI->setLocation(D.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001112 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001113 }
Devang Patel887e2152011-06-03 19:21:47 +00001114 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001115
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001116 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001117 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001118
John McCallc533cb72011-02-22 06:44:22 +00001119 return emission;
1120}
1121
1122/// Determines whether the given __block variable is potentially
1123/// captured by the given expression.
1124static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1125 // Skip the most common kinds of expressions that make
1126 // hierarchy-walking expensive.
1127 e = e->IgnoreParenCasts();
1128
1129 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1130 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +00001131 for (const auto &I : block->captures()) {
1132 if (I.getVariable() == &var)
John McCallc533cb72011-02-22 06:44:22 +00001133 return true;
1134 }
1135
1136 // No need to walk into the subexpressions.
1137 return false;
1138 }
1139
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001140 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1141 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001142 for (const auto *BI : CS->body())
1143 if (const auto *E = dyn_cast<Expr>(BI)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001144 if (isCapturedBy(var, E))
1145 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001146 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001147 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001148 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001149 for (const auto *I : DS->decls()) {
1150 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1151 const Expr *Init = VD->getInit();
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001152 if (Init && isCapturedBy(var, Init))
1153 return true;
1154 }
1155 }
1156 }
1157 else
1158 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1159 // Later, provide code to poke into statements for capture analysis.
1160 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001161 return false;
1162 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001163
Benjamin Kramer642f1732015-07-02 21:03:14 +00001164 for (const Stmt *SubStmt : e->children())
1165 if (isCapturedBy(var, cast<Expr>(SubStmt)))
John McCallc533cb72011-02-22 06:44:22 +00001166 return true;
1167
1168 return false;
1169}
1170
Douglas Gregor82e1af22011-07-01 21:08:19 +00001171/// \brief Determine whether the given initializer is trivial in the sense
1172/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001173bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001174 if (!Init)
1175 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001176
Douglas Gregor82e1af22011-07-01 21:08:19 +00001177 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1178 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1179 if (Constructor->isTrivial() &&
1180 Constructor->isDefaultConstructor() &&
1181 !Construct->requiresZeroInitialization())
1182 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001183
Douglas Gregor82e1af22011-07-01 21:08:19 +00001184 return false;
1185}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001186
John McCallc533cb72011-02-22 06:44:22 +00001187void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001188 assert(emission.Variable && "emission was not valid!");
1189
John McCallc533cb72011-02-22 06:44:22 +00001190 // If this was emitted as a global constant, we're done.
1191 if (emission.wasEmittedAsGlobal()) return;
1192
John McCall9e2e22f2011-02-22 07:16:58 +00001193 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001194 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001195 QualType type = D.getType();
1196
Chris Lattner07eb7332007-07-12 00:39:48 +00001197 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001198 const Expr *Init = D.getInit();
1199
1200 // If we are at an unreachable point, we don't need to emit the initializer
1201 // unless it contains a label.
1202 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001203 if (!Init || !ContainsLabel(Init)) return;
1204 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001205 }
1206
John McCall73064872011-03-31 01:59:53 +00001207 // Initialize the structure of a __block variable.
1208 if (emission.IsByRef)
1209 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001210
Douglas Gregor82e1af22011-07-01 21:08:19 +00001211 if (isTrivialInitializer(Init))
1212 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001213
John McCallc533cb72011-02-22 06:44:22 +00001214 // Check whether this is a byref variable that's potentially
1215 // captured and moved by its own initializer. If so, we'll need to
1216 // emit the initializer first, then copy into the variable.
1217 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1218
John McCall7f416cc2015-09-08 08:05:57 +00001219 Address Loc =
1220 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
John McCallc533cb72011-02-22 06:44:22 +00001221
Craig Topper8a13c412014-05-21 05:09:00 +00001222 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001223 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001224 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smithdafff942012-01-14 04:30:29 +00001225 constant = CGM.EmitConstantInit(D, this);
Richard Smithfddd3842011-12-30 21:15:51 +00001226 }
1227
1228 if (!constant) {
John McCall7f416cc2015-09-08 08:05:57 +00001229 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001230 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001231 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001232 }
John McCall91ca10f2011-03-08 09:11:50 +00001233
Richard Smith2bcde3a2013-06-02 00:09:52 +00001234 if (!emission.IsConstantAggregate) {
1235 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001236 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001237 lv.setNonGC(true);
1238 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1239 }
1240
John McCallc533cb72011-02-22 06:44:22 +00001241 // If this is a simple aggregate initialization, we can optimize it
1242 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001243 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001244
John McCall91ca10f2011-03-08 09:11:50 +00001245 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001246 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001247 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001248
Chris Lattner2192fe52011-07-18 04:24:23 +00001249 llvm::Type *BP = Int8PtrTy;
John McCall7f416cc2015-09-08 08:05:57 +00001250 if (Loc.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001251 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001252
John McCall91ca10f2011-03-08 09:11:50 +00001253 // If the initializer is all or mostly zeros, codegen with memset then do
1254 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001255 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001256 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall91ca10f2011-03-08 09:11:50 +00001257 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
John McCall7f416cc2015-09-08 08:05:57 +00001258 isVolatile);
Benjamin Kramer29f9a002012-08-27 22:07:02 +00001259 // Zero and undef don't require a stores.
1260 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall91ca10f2011-03-08 09:11:50 +00001261 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001262 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1263 isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001264 }
John McCall91ca10f2011-03-08 09:11:50 +00001265 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001266 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001267 // memcpy from the global to the alloca.
Reid Kleckner453e0562014-10-08 01:07:54 +00001268 std::string Name = getStaticDeclName(CGM, D);
John McCall91ca10f2011-03-08 09:11:50 +00001269 llvm::GlobalVariable *GV =
1270 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001271 llvm::GlobalValue::PrivateLinkage,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001272 constant, Name);
John McCall7f416cc2015-09-08 08:05:57 +00001273 GV->setAlignment(Loc.getAlignment().getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001274 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Eric Christopher31ab1302011-08-23 22:38:00 +00001275
John McCall7f416cc2015-09-08 08:05:57 +00001276 Address SrcPtr = Address(GV, Loc.getAlignment());
1277 if (SrcPtr.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001278 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001279
John McCall7f416cc2015-09-08 08:05:57 +00001280 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
John McCall91ca10f2011-03-08 09:11:50 +00001281 }
1282}
1283
1284/// Emit an expression as an initializer for a variable at the given
1285/// location. The expression is not necessarily the normal
1286/// initializer for the variable, and the address is not necessarily
1287/// its normal location.
1288///
1289/// \param init the initializing expression
1290/// \param var the variable to act as if we're initializing
1291/// \param loc the address to initialize; its type is a pointer
1292/// to the LLVM mapping of the variable's type
1293/// \param alignment the alignment of the address
1294/// \param capturedByInit true if the variable is a __block variable
1295/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001296void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001297 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001298 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001299
1300 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001301 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001302 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001303 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001304 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001305 return;
1306 }
1307 switch (getEvaluationKind(type)) {
1308 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001309 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001310 return;
1311 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001312 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001313 if (capturedByInit)
1314 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001315 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001316 return;
1317 }
1318 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001319 if (type->isAtomicType()) {
1320 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1321 } else {
1322 // TODO: how can we delay here if D is captured by its initializer?
1323 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001324 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001325 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001326 AggValueSlot::IsNotAliased));
John McCalla8ec7eb2013-03-07 21:37:17 +00001327 }
John McCall47fb9502013-03-07 21:37:08 +00001328 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001329 }
John McCall47fb9502013-03-07 21:37:08 +00001330 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001331}
John McCallbd309292010-07-06 01:34:17 +00001332
John McCall82fe67b2011-07-09 01:37:26 +00001333/// Enter a destroy cleanup for the given local variable.
1334void CodeGenFunction::emitAutoVarTypeCleanup(
1335 const CodeGenFunction::AutoVarEmission &emission,
1336 QualType::DestructionKind dtorKind) {
1337 assert(dtorKind != QualType::DK_none);
1338
1339 // Note that for __block variables, we want to destroy the
1340 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001341 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001342
1343 const VarDecl *var = emission.Variable;
1344 QualType type = var->getType();
1345
1346 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001347 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001348
1349 switch (dtorKind) {
1350 case QualType::DK_none:
1351 llvm_unreachable("no cleanup for trivially-destructible variable");
1352
1353 case QualType::DK_cxx_destructor:
1354 // If there's an NRVO flag on the emission, we need a different
1355 // cleanup.
1356 if (emission.NRVOFlag) {
1357 assert(!type->isArrayType());
1358 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +00001359 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1360 dtor, emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001361 return;
1362 }
1363 break;
1364
1365 case QualType::DK_objc_strong_lifetime:
1366 // Suppress cleanups for pseudo-strong variables.
1367 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001368
John McCall82fe67b2011-07-09 01:37:26 +00001369 // Otherwise, consider whether to use an EH cleanup or not.
1370 cleanupKind = getARCCleanupKind();
1371
1372 // Use the imprecise destroyer by default.
1373 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1374 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1375 break;
1376
1377 case QualType::DK_objc_weak_lifetime:
1378 break;
1379 }
1380
1381 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001382 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001383
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001384 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001385 // is being pushed as an EH cleanup.
1386 bool useEHCleanup = (cleanupKind & EHCleanup);
1387 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1388 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001389}
1390
John McCallc533cb72011-02-22 06:44:22 +00001391void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001392 assert(emission.Variable && "emission was not valid!");
1393
John McCallc533cb72011-02-22 06:44:22 +00001394 // If this was emitted as a global constant, we're done.
1395 if (emission.wasEmittedAsGlobal()) return;
1396
John McCall8c38d352012-04-13 18:44:05 +00001397 // If we don't have an insertion point, we're done. Sema prevents
1398 // us from jumping into any of these scopes anyway.
1399 if (!HaveInsertPoint()) return;
1400
John McCall9e2e22f2011-02-22 07:16:58 +00001401 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001402
Nadav Rotem1da30942013-03-23 06:43:35 +00001403 // Make sure we call @llvm.lifetime.end. This needs to happen
1404 // *last*, so the cleanup needs to be pushed *first*.
Tim Shen421119f2016-07-01 21:08:47 +00001405 if (emission.useLifetimeMarkers())
1406 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
Nadav Rotem1da30942013-03-23 06:43:35 +00001407 emission.getAllocatedAddress(),
1408 emission.getSizeForLifetimeMarkers());
Nadav Rotem1da30942013-03-23 06:43:35 +00001409
John McCall82fe67b2011-07-09 01:37:26 +00001410 // Check the type for a cleanup.
1411 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1412 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001413
John McCall1bd25562011-06-24 23:21:27 +00001414 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001415 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001416 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1417 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1418 }
1419
John McCallc533cb72011-02-22 06:44:22 +00001420 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001421 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001422 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001423
John McCallc533cb72011-02-22 06:44:22 +00001424 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001425 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001426
John McCalla729c622012-02-17 03:33:10 +00001427 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001428 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001429 }
Mike Stump626aecc2009-03-05 01:23:13 +00001430
John McCallc533cb72011-02-22 06:44:22 +00001431 // If this is a block variable, call _Block_object_destroy
1432 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001433 if (emission.IsByRef)
1434 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001435}
Chris Lattner53621a52007-06-13 20:44:40 +00001436
Peter Collingbourne1425b452012-01-26 03:33:36 +00001437CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001438CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1439 switch (kind) {
1440 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001441 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001442 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001443 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001444 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001445 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001446 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001447 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001448 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001449}
1450
John McCall12cc42a2013-02-01 05:11:40 +00001451/// pushEHDestroy - Push the standard destructor for the given type as
1452/// an EH-only cleanup.
1453void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001454 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00001455 assert(dtorKind && "cannot push destructor for trivial type");
1456 assert(needsEHCleanup(dtorKind));
1457
1458 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1459}
1460
1461/// pushDestroy - Push the standard destructor for the given type as
1462/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001463void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001464 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00001465 assert(dtorKind && "cannot push destructor for trivial type");
1466
1467 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1468 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1469 cleanupKind & EHCleanup);
1470}
1471
John McCall7f416cc2015-09-08 08:05:57 +00001472void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001473 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001474 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001475 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1476 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001477}
1478
John McCall7f416cc2015-09-08 08:05:57 +00001479void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001480 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1481}
1482
Richard Smith736a9472013-06-12 20:42:33 +00001483void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00001484 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00001485 Destroyer *destroyer, bool useEHCleanupForArray) {
1486 assert(!isInConditionalBranch() &&
1487 "performing lifetime extension from within conditional");
1488
1489 // Push an EH-only cleanup for the object now.
1490 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1491 // around in case a temporary's destructor throws an exception.
1492 if (cleanupKind & EHCleanup)
1493 EHStack.pushCleanup<DestroyObject>(
1494 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1495 destroyer, useEHCleanupForArray);
1496
1497 // Remember that we need to push a full cleanup for the object at the
1498 // end of the full-expression.
1499 pushCleanupAfterFullExpr<DestroyObject>(
1500 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1501}
1502
John McCall178360e2011-07-11 08:38:19 +00001503/// emitDestroy - Immediately perform the destruction of the given
1504/// object.
1505///
1506/// \param addr - the address of the object; a type*
1507/// \param type - the type of the object; if an array type, all
1508/// objects are destroyed in reverse order
1509/// \param destroyer - the function to call to destroy individual
1510/// elements
1511/// \param useEHCleanupForArray - whether an EH cleanup should be
1512/// used when destroying array elements, in case one of the
1513/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00001514void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001515 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001516 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001517 const ArrayType *arrayType = getContext().getAsArrayType(type);
1518 if (!arrayType)
1519 return destroyer(*this, addr, type);
1520
John McCall7f416cc2015-09-08 08:05:57 +00001521 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1522
1523 CharUnits elementAlign =
1524 addr.getAlignment()
1525 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00001526
1527 // Normally we have to check whether the array is zero-length.
1528 bool checkZeroLength = true;
1529
1530 // But if the array length is constant, we can suppress that.
1531 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1532 // ...and if it's constant zero, we can just skip the entire thing.
1533 if (constLength->isZero()) return;
1534 checkZeroLength = false;
1535 }
1536
John McCall7f416cc2015-09-08 08:05:57 +00001537 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00001538 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00001539 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001540 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001541}
1542
John McCall178360e2011-07-11 08:38:19 +00001543/// emitArrayDestroy - Destroys all the elements of the given array,
1544/// beginning from last to first. The array cannot be zero-length.
1545///
1546/// \param begin - a type* denoting the first element of the array
1547/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001548/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00001549/// \param destroyer - the function to call to destroy elements
1550/// \param useEHCleanup - whether to push an EH cleanup to destroy
1551/// the remaining elements in case the destruction of a single
1552/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001553void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1554 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001555 QualType elementType,
1556 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001557 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001558 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001559 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00001560 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00001561
1562 // The basic structure here is a do-while loop, because we don't
1563 // need to check for the zero-element case.
1564 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1565 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1566
John McCall97eab0a2011-07-13 08:09:46 +00001567 if (checkZeroLength) {
1568 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1569 "arraydestroy.isempty");
1570 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1571 }
1572
John McCall82fe67b2011-07-09 01:37:26 +00001573 // Enter the loop body, making that address the current address.
1574 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1575 EmitBlock(bodyBB);
1576 llvm::PHINode *elementPast =
1577 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1578 elementPast->addIncoming(end, entryBB);
1579
1580 // Shift the address back by one element.
1581 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1582 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1583 "arraydestroy.element");
1584
John McCall178360e2011-07-11 08:38:19 +00001585 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00001586 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1587 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001588
John McCall82fe67b2011-07-09 01:37:26 +00001589 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00001590 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00001591
John McCall178360e2011-07-11 08:38:19 +00001592 if (useEHCleanup)
1593 PopCleanupBlock();
1594
John McCall82fe67b2011-07-09 01:37:26 +00001595 // Check whether we've reached the end.
1596 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1597 Builder.CreateCondBr(done, doneBB, bodyBB);
1598 elementPast->addIncoming(element, Builder.GetInsertBlock());
1599
1600 // Done.
1601 EmitBlock(doneBB);
1602}
1603
John McCall178360e2011-07-11 08:38:19 +00001604/// Perform partial array destruction as if in an EH cleanup. Unlike
1605/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001606static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1607 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001608 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001609 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001610 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001611 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001612 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1613 // VLAs don't require a GEP index to walk into.
1614 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001615 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001616 type = arrayType->getElementType();
1617 }
John McCall97eab0a2011-07-13 08:09:46 +00001618
1619 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00001620 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00001621
John McCallf0f0b7a2015-09-14 18:57:08 +00001622 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001623 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1624 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001625 }
1626
John McCall97eab0a2011-07-13 08:09:46 +00001627 // Destroy the array. We don't ever need an EH cleanup because we
1628 // assume that we're in an EH cleanup ourselves, so a throwing
1629 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00001630 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001631 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001632}
1633
John McCall82fe67b2011-07-09 01:37:26 +00001634namespace {
John McCall178360e2011-07-11 08:38:19 +00001635 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1636 /// array destroy where the end pointer is regularly determined and
1637 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001638 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00001639 llvm::Value *ArrayBegin;
1640 llvm::Value *ArrayEnd;
1641 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001642 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001643 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00001644 public:
1645 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001646 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001647 CodeGenFunction::Destroyer *destroyer)
1648 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00001649 ElementType(elementType), Destroyer(destroyer),
1650 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00001651
Craig Topper4f12f102014-03-12 06:41:41 +00001652 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001653 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001654 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00001655 }
1656 };
1657
1658 /// IrregularPartialArrayDestroy - a cleanup which performs a
1659 /// partial array destroy where the end pointer is irregularly
1660 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001661 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001662 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00001663 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00001664 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001665 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001666 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00001667 public:
John McCall178360e2011-07-11 08:38:19 +00001668 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001669 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001670 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001671 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001672 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001673 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00001674 ElementType(elementType), Destroyer(destroyer),
1675 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00001676
Craig Topper4f12f102014-03-12 06:41:41 +00001677 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001678 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001679 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001680 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001681 }
1682 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001683} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00001684
John McCall178360e2011-07-11 08:38:19 +00001685/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001686/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001687/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001688///
John McCall82fe67b2011-07-09 01:37:26 +00001689/// \param elementType - the immediate element type of the array;
1690/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001691void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001692 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001693 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001694 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001695 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001696 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1697 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00001698 elementType, elementAlign,
1699 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001700}
1701
1702/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1703/// already-constructed elements of the given array. The cleanup
1704/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001705///
John McCall178360e2011-07-11 08:38:19 +00001706/// \param elementType - the immediate element type of the array;
1707/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001708void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1709 llvm::Value *arrayEnd,
1710 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001711 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001712 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001713 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001714 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001715 elementType, elementAlign,
1716 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001717}
1718
Nadav Rotem1da30942013-03-23 06:43:35 +00001719/// Lazily declare the @llvm.lifetime.start intrinsic.
1720llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1721 if (LifetimeStartFn) return LifetimeStartFn;
1722 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1723 llvm::Intrinsic::lifetime_start);
1724 return LifetimeStartFn;
1725}
1726
1727/// Lazily declare the @llvm.lifetime.end intrinsic.
1728llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1729 if (LifetimeEndFn) return LifetimeEndFn;
1730 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1731 llvm::Intrinsic::lifetime_end);
1732 return LifetimeEndFn;
1733}
1734
John McCall31168b02011-06-15 23:02:42 +00001735namespace {
1736 /// A cleanup to perform a release of an object at the end of a
1737 /// function. This is used to balance out the incoming +1 of a
1738 /// ns_consumed argument when we can't reasonably do that just by
1739 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00001740 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001741 ConsumeARCParameter(llvm::Value *param,
1742 ARCPreciseLifetime_t precise)
1743 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001744
1745 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001746 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001747
Craig Topper4f12f102014-03-12 06:41:41 +00001748 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001749 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001750 }
1751 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001752} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00001753
Mike Stump11289f42009-09-09 15:08:12 +00001754/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001755/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00001756void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1757 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001758 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001759 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001760 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001761
John McCall7f416cc2015-09-08 08:05:57 +00001762 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00001763
Adrian Prantl51936dd2013-03-14 17:53:33 +00001764 QualType Ty = D.getType();
1765
John McCall147d0212011-02-22 22:38:33 +00001766 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00001767 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00001768 // The only implicit argument a block has is its literal.
John McCall7f416cc2015-09-08 08:05:57 +00001769 // We assume this is always passed directly.
John McCall147d0212011-02-22 22:38:33 +00001770 if (BlockInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001771 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
John McCall147d0212011-02-22 22:38:33 +00001772 return;
1773 }
Reid Klecknere5a321b2016-09-07 18:21:30 +00001774
1775 // Apply any prologue 'this' adjustments required by the ABI. Be careful to
1776 // handle the case where 'this' is passed indirectly as part of an inalloca
1777 // struct.
1778 if (const CXXMethodDecl *MD =
1779 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
1780 if (MD->isVirtual() && IPD == CXXABIThisDecl) {
1781 llvm::Value *This = Arg.isIndirect()
1782 ? Builder.CreateLoad(Arg.getIndirectAddress())
1783 : Arg.getDirectValue();
1784 This = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue(
1785 *this, CurGD, This);
1786 if (Arg.isIndirect())
1787 Builder.CreateStore(This, Arg.getIndirectAddress());
1788 else
1789 Arg = ParamValue::forDirect(This);
1790 }
1791 }
John McCall147d0212011-02-22 22:38:33 +00001792 }
1793
John McCall7f416cc2015-09-08 08:05:57 +00001794 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001795 bool DoStore = false;
1796 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001797 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001798 if (Arg.isIndirect()) {
1799 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001800 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00001801 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001802 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00001803 if (DeclPtr.getType() != IRTy)
1804 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1805
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001806 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00001807 // Don't push a cleanup in a thunk for a method that will also emit a
1808 // cleanup.
1809 if (!IsScalar && !CurFuncIsThunk &&
Reid Kleckner739756c2013-12-04 19:23:12 +00001810 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001811 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1812 if (RD && RD->hasNonTrivialDestructor())
1813 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001814 }
Chris Lattner53621a52007-06-13 20:44:40 +00001815 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001816 // Otherwise, create a temporary to hold the value.
John McCall7f416cc2015-09-08 08:05:57 +00001817 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1818 D.getName() + ".addr");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001819 DoStore = true;
1820 }
Mike Stump11289f42009-09-09 15:08:12 +00001821
John McCall7f416cc2015-09-08 08:05:57 +00001822 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1823
1824 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001825 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00001826 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001827 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1828 // We honor __attribute__((ns_consumed)) for types with lifetime.
1829 // For __strong, it's handled by just skipping the initial retain;
1830 // otherwise we have to balance out the initial +1 with an extra
1831 // cleanup to do the release at the end of the function.
1832 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1833
1834 // 'self' is always formally __strong, but if this is not an
1835 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001836 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001837 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1838 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001839 assert(lt == Qualifiers::OCL_Strong);
1840 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001841 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001842 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001843 lt = Qualifiers::OCL_ExplicitNone;
1844 }
1845
1846 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001847 if (!isConsumed) {
1848 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1849 // use objc_storeStrong(&dest, value) for retaining the
1850 // object. But first, store a null into 'dest' because
1851 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001852 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001853 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
John McCall7f416cc2015-09-08 08:05:57 +00001854 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001855 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001856 }
1857 else
John McCall31168b02011-06-15 23:02:42 +00001858 // Don't use objc_retainBlock for block pointers, because we
1859 // don't want to Block_copy something just because we got it
1860 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00001861 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001862 }
John McCall31168b02011-06-15 23:02:42 +00001863 } else {
1864 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00001865 if (isConsumed) {
1866 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1867 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00001868 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00001869 precise);
1870 }
John McCall31168b02011-06-15 23:02:42 +00001871
1872 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00001873 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001874 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001875 }
1876 }
1877
1878 // Enter the cleanup scope.
1879 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1880 }
Chris Lattner53621a52007-06-13 20:44:40 +00001881 }
1882
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001883 // Store the initial value into the alloca.
1884 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00001885 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001886
John McCall7f416cc2015-09-08 08:05:57 +00001887 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001888
1889 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001890 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001891 if (CGM.getCodeGenOpts().getDebugInfo() >=
1892 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001893 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001894 }
1895 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001896
1897 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001898 EmitVarAnnotations(&D, DeclPtr.getPointer());
Chris Lattner53621a52007-06-13 20:44:40 +00001899}
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001900
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001901void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1902 CodeGenFunction *CGF) {
1903 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1904 return;
1905 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
1906}