blob: e0cb07b98dd015475bfa43165a3205aaec594d74 [file] [log] [blame]
Chris Lattner84915fa2007-06-02 04:16:21 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner84915fa2007-06-02 04:16:21 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Decl nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
John McCall7f416cc2015-09-08 08:05:57 +000015#include "CGBlocks.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000016#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGDebugInfo.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000018#include "CGOpenCLRuntime.h"
Alexey Bataevc5b1d322016-03-04 09:22:22 +000019#include "CGOpenMPRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "CodeGenModule.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000021#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000022#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000023#include "clang/AST/Decl.h"
Anders Carlsson4c03d982008-08-25 01:38:19 +000024#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000025#include "clang/AST/DeclOpenMP.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000026#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000027#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000028#include "clang/CodeGen/CGFunctionInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000029#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/GlobalVariable.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/Type.h"
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +000034
Chris Lattner84915fa2007-06-02 04:16:21 +000035using namespace clang;
36using namespace CodeGen;
37
Chris Lattner1ad38f82007-06-09 01:20:56 +000038void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000039 switch (D.getKind()) {
David Majnemerd9b1a4f2015-11-04 03:40:30 +000040 case Decl::BuiltinTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000041 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +000042 case Decl::ExternCContext:
Douglas Gregor19043f02010-04-23 02:02:43 +000043 case Decl::Namespace:
44 case Decl::UnresolvedUsingTypename:
45 case Decl::ClassTemplateSpecialization:
46 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000047 case Decl::VarTemplateSpecialization:
48 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000049 case Decl::TemplateTypeParm:
50 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000051 case Decl::NonTypeTemplateParm:
Douglas Gregor19043f02010-04-23 02:02:43 +000052 case Decl::CXXMethod:
53 case Decl::CXXConstructor:
54 case Decl::CXXDestructor:
55 case Decl::CXXConversion:
56 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000057 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000058 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000059 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000060 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000061 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000062 case Decl::ImplicitParam:
63 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000064 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000065 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000066 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000067 case Decl::TemplateTemplateParm:
68 case Decl::ObjCMethod:
69 case Decl::ObjCCategory:
70 case Decl::ObjCProtocol:
71 case Decl::ObjCInterface:
72 case Decl::ObjCCategoryImpl:
73 case Decl::ObjCImplementation:
74 case Decl::ObjCProperty:
75 case Decl::ObjCCompatibleAlias:
Nico Weber66220292016-03-02 17:28:48 +000076 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +000077 case Decl::PragmaDetectMismatch:
Abramo Bagnarad7340582010-06-05 05:09:32 +000078 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000079 case Decl::LinkageSpec:
80 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000081 case Decl::FileScopeAsm:
82 case Decl::Friend:
83 case Decl::FriendTemplate:
84 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000085 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000086 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000087 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +000088 case Decl::ConstructorUsingShadow:
Douglas Gregor85f3f952015-07-07 03:57:15 +000089 case Decl::ObjCTypeParam:
David Blaikie83d382b2011-09-23 05:06:16 +000090 llvm_unreachable("Declaration should not be in declstmts!");
Amjad Abouddc4531e2016-04-30 01:44:38 +000091 case Decl::Function: // void X();
92 case Decl::Record: // struct/union/class X;
93 case Decl::Enum: // enum X;
94 case Decl::EnumConstant: // enum ? { X = ? }
95 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +000096 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +000097 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +000098 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +000099 case Decl::OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000100 case Decl::OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +0000101 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +0000102 // None of these decls require codegen support.
103 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +0000104
David Blaikief121b932013-05-20 22:50:41 +0000105 case Decl::NamespaceAlias:
106 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000107 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
David Blaikief121b932013-05-20 22:50:41 +0000108 return;
David Blaikiebd483762013-05-20 04:58:53 +0000109 case Decl::Using: // using X; [C++]
110 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000111 DI->EmitUsingDecl(cast<UsingDecl>(D));
David Blaikiebd483762013-05-20 04:58:53 +0000112 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000113 case Decl::UsingDirective: // using namespace X; [C++]
114 if (CGDebugInfo *DI = getDebugInfo())
115 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
116 return;
Richard Smithbdb84f32016-07-22 23:36:59 +0000117 case Decl::Var:
118 case Decl::Decomposition: {
Daniel Dunbara7998072008-08-29 17:28:43 +0000119 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000120 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000121 "Should not see file-scope variables inside a function!");
John McCall1c9c3fd2010-10-15 04:57:14 +0000122 return EmitVarDecl(VD);
Chris Lattner84915fa2007-06-02 04:16:21 +0000123 }
Richard Smithbdb84f32016-07-22 23:36:59 +0000124 case Decl::Binding:
125 return CGM.ErrorUnsupported(&D, "structured binding");
Mike Stump11289f42009-09-09 15:08:12 +0000126
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000127 case Decl::OMPDeclareReduction:
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000128 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000129
Richard Smithdda56e42011-04-15 14:24:37 +0000130 case Decl::Typedef: // typedef int X;
131 case Decl::TypeAlias: { // using X = int; [C++0x]
132 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000133 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000134
Anders Carlsson5d985f52008-12-20 21:51:53 +0000135 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000136 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000137 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000138 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000139}
Chris Lattner03df1222007-06-02 04:53:11 +0000140
John McCall1c9c3fd2010-10-15 04:57:14 +0000141/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000142/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000143void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000144 if (D.isStaticLocal()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000145 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000146 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000147
David Majnemer27d69db2014-04-28 22:17:59 +0000148 // FIXME: We need to force the emission/use of a guard variable for
149 // some variables even if we can constant-evaluate them because
150 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000151
John McCall1c9c3fd2010-10-15 04:57:14 +0000152 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000153 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000154
155 if (D.hasExternalStorage())
Lauro Ramos Venanciobada8d42008-02-16 22:30:38 +0000156 // Don't emit it now, allow it to be emitted lazily on its first use.
157 return;
Daniel Dunbar0ca16602009-04-14 02:25:56 +0000158
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000159 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000160 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
161
162 assert(D.hasLocalStorage());
163 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000164}
165
Reid Kleckner453e0562014-10-08 01:07:54 +0000166static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
167 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000168 return CGM.getMangledName(&D).str();
169
Reid Kleckner453e0562014-10-08 01:07:54 +0000170 // If this isn't C++, we don't need a mangled name, just a pretty one.
171 assert(!D.isExternallyVisible() && "name shouldn't matter");
172 std::string ContextName;
173 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000174 if (auto *CD = dyn_cast<CapturedDecl>(DC))
175 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000176 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000177 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000178 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
179 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
180 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
181 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000182 else
David Blaikie83d382b2011-09-23 05:06:16 +0000183 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000184
Reid Kleckner453e0562014-10-08 01:07:54 +0000185 ContextName += "." + D.getNameAsString();
186 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000187}
188
Reid Kleckner453e0562014-10-08 01:07:54 +0000189llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
190 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
191 // In general, we don't always emit static var decls once before we reference
192 // them. It is possible to reference them before emitting the function that
193 // contains them, and it is possible to emit the containing function multiple
194 // times.
195 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
196 return ExistingGV;
197
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000198 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000199 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000200
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000201 // Use the label if the variable is renamed with the asm-label extension.
202 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000203 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000204 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000205 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000206 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000207
Reid Kleckner453e0562014-10-08 01:07:54 +0000208 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000209 unsigned AddrSpace =
Reid Kleckner453e0562014-10-08 01:07:54 +0000210 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000211
212 // Local address space cannot have an initializer.
213 llvm::Constant *Init = nullptr;
214 if (Ty.getAddressSpace() != LangAS::opencl_local)
215 Init = EmitNullConstant(Ty);
216 else
217 Init = llvm::UndefValue::get(LTy);
218
Anders Carlssone33eed52009-09-26 18:16:06 +0000219 llvm::GlobalVariable *GV =
Reid Kleckner453e0562014-10-08 01:07:54 +0000220 new llvm::GlobalVariable(getModule(), LTy,
Anders Carlssone33eed52009-09-26 18:16:06 +0000221 Ty.isConstant(getContext()), Linkage,
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000222 Init, Name, nullptr,
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000223 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000224 AddrSpace);
Ken Dyck160146e2010-01-27 17:10:57 +0000225 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Reid Kleckner453e0562014-10-08 01:07:54 +0000226 setGlobalVisibility(GV, &D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000227
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000228 if (supportsCOMDAT() && GV->isWeakForLinker())
229 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000230
Richard Smithfd3834f2013-04-13 02:43:54 +0000231 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000232 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000233
Hans Wennborgef2272c2014-06-18 15:55:13 +0000234 if (D.isExternallyVisible()) {
235 if (D.hasAttr<DLLImportAttr>())
236 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
237 else if (D.hasAttr<DLLExportAttr>())
238 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
239 }
240
Eli Benderskycb399432014-03-24 22:05:38 +0000241 // Make sure the result is of the correct type.
Reid Kleckner453e0562014-10-08 01:07:54 +0000242 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
243 llvm::Constant *Addr = GV;
Eli Benderskycb399432014-03-24 22:05:38 +0000244 if (AddrSpace != ExpectedAddrSpace) {
245 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
Reid Kleckner453e0562014-10-08 01:07:54 +0000246 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
Eli Benderskycb399432014-03-24 22:05:38 +0000247 }
248
Reid Kleckner453e0562014-10-08 01:07:54 +0000249 setStaticLocalDeclAddress(&D, Addr);
250
251 // Ensure that the static local gets initialized by making sure the parent
252 // function gets emitted eventually.
253 const Decl *DC = cast<Decl>(D.getDeclContext());
254
255 // We can't name blocks or captured statements directly, so try to emit their
256 // parents.
257 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
258 DC = DC->getNonClosureContext();
259 // FIXME: Ensure that global blocks get emitted.
260 if (!DC)
261 return Addr;
262 }
263
264 GlobalDecl GD;
265 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
266 GD = GlobalDecl(CD, Ctor_Base);
267 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
268 GD = GlobalDecl(DD, Dtor_Base);
269 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
270 GD = GlobalDecl(FD);
271 else {
272 // Don't do anything for Obj-C method decls or global closures. We should
273 // never defer them.
274 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
275 }
276 if (GD.getDecl())
277 (void)GetAddrOfGlobal(GD);
278
279 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000280}
281
Richard Smith6331c402012-02-13 22:16:19 +0000282/// hasNontrivialDestruction - Determine whether a type's destruction is
283/// non-trivial. If so, and the variable uses static initialization, we must
284/// register its destructor to run on exit.
285static bool hasNontrivialDestruction(QualType T) {
286 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
287 return RD && !RD->hasTrivialDestructor();
288}
289
Chandler Carruth84537952012-03-30 19:44:53 +0000290/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
291/// global variable that has already been created for it. If the initializer
292/// has a different type than GV does, this may free GV and return a different
293/// one. Otherwise it just returns GV.
294llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000295CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000296 llvm::GlobalVariable *GV) {
297 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCall70013b62010-07-15 23:40:35 +0000298
Chris Lattnere99c1102009-12-05 08:22:11 +0000299 // If constant emission failed, then this should be a C++ static
300 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000301 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000302 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000303 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall68ff0372010-09-08 01:44:27 +0000304 else if (Builder.GetInsertBlock()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000305 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000306 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000307 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000308
Chandler Carruth84537952012-03-30 19:44:53 +0000309 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000310 }
Chandler Carruth84537952012-03-30 19:44:53 +0000311 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000312 }
John McCall70013b62010-07-15 23:40:35 +0000313
Chris Lattnere99c1102009-12-05 08:22:11 +0000314 // The initializer may differ in type from the global. Rewrite
315 // the global to match the initializer. (We have to do this
316 // because some types, like unions, can't be completely represented
317 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000318 if (GV->getType()->getElementType() != Init->getType()) {
319 llvm::GlobalVariable *OldGV = GV;
320
321 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
322 OldGV->isConstant(),
323 OldGV->getLinkage(), Init, "",
324 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000325 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000326 CGM.getContext().getTargetAddressSpace(D.getType()));
327 GV->setVisibility(OldGV->getVisibility());
Reid Klecknereab97d32015-07-20 20:35:30 +0000328 GV->setComdat(OldGV->getComdat());
Eric Christopher31ab1302011-08-23 22:38:00 +0000329
Chris Lattnere99c1102009-12-05 08:22:11 +0000330 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000331 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000332
Chris Lattnere99c1102009-12-05 08:22:11 +0000333 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000334 llvm::Constant *NewPtrForOldDecl =
335 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
336 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000337
Chris Lattnere99c1102009-12-05 08:22:11 +0000338 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000339 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000340 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000341
Chandler Carruth84537952012-03-30 19:44:53 +0000342 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
343 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000344
345 if (hasNontrivialDestruction(D.getType())) {
346 // We have a constant initializer, but a nontrivial destructor. We still
347 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000348 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000349 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000350 }
351
Chandler Carruth84537952012-03-30 19:44:53 +0000352 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000353}
354
John McCall1c9c3fd2010-10-15 04:57:14 +0000355void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000356 llvm::GlobalValue::LinkageTypes Linkage) {
John McCallb88a5662012-03-30 21:00:39 +0000357 // Check to see if we already have a global variable for this
358 // declaration. This can happen when double-emitting function
359 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000360 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
John McCall7f416cc2015-09-08 08:05:57 +0000361 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara374e602009-02-25 19:45:19 +0000362
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000363 // Store into LocalDeclMap before generating initializer to handle
364 // circular references.
John McCall7f416cc2015-09-08 08:05:57 +0000365 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000366
John McCall4a39ab82010-05-04 20:45:42 +0000367 // We can't have a VLA here, but we can have a pointer to a VLA,
368 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000369 // Make sure to evaluate VLA bounds now so that we have them for later.
370 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000371 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000372
John McCallb88a5662012-03-30 21:00:39 +0000373 // Save the type in case adding the initializer forces a type change.
374 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000375
Eli Benderskycb399432014-03-24 22:05:38 +0000376 llvm::GlobalVariable *var =
377 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Artem Belevich4d430ba2016-05-09 22:09:56 +0000378
379 // CUDA's local and local static __shared__ variables should not
380 // have any non-empty initializers. This is ensured by Sema.
381 // Whatever initializer such variable may have when it gets here is
382 // a no-op and should not be emitted.
383 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
384 D.hasAttr<CUDASharedAttr>();
Chris Lattnere99c1102009-12-05 08:22:11 +0000385 // If this value has an initializer, emit it.
Artem Belevich4d430ba2016-05-09 22:09:56 +0000386 if (D.getInit() && !isCudaSharedVar)
John McCallb88a5662012-03-30 21:00:39 +0000387 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000388
John McCall7f416cc2015-09-08 08:05:57 +0000389 var->setAlignment(alignment.getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000390
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000391 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000392 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000393
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000394 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000395 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000396
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000397 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000398 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000399
Chandler Carruth84537952012-03-30 19:44:53 +0000400 // We may have to cast the constant because of the initializer
401 // mismatch above.
402 //
403 // FIXME: It is really dangerous to store this in the map; if anyone
404 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000405 llvm::Constant *castedAddr =
406 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCall7f416cc2015-09-08 08:05:57 +0000407 if (var != castedAddr)
408 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCallb88a5662012-03-30 21:00:39 +0000409 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000410
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000411 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000412
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000413 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000414 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000415 if (DI &&
Benjamin Kramer8c305922016-02-02 11:06:51 +0000416 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000417 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000418 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000419 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000420}
Mike Stump11289f42009-09-09 15:08:12 +0000421
John McCall2b7fc382010-07-13 20:32:21 +0000422namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000423 struct DestroyObject final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000424 DestroyObject(Address addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000425 CodeGenFunction::Destroyer *destroyer,
426 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000427 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000428 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000429
John McCall7f416cc2015-09-08 08:05:57 +0000430 Address addr;
John McCall82fe67b2011-07-09 01:37:26 +0000431 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000432 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000433 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000434
Craig Topper4f12f102014-03-12 06:41:41 +0000435 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000436 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000437 bool useEHCleanupForArray =
438 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000439
440 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000441 }
442 };
443
David Blaikie7e70d682015-08-18 22:40:54 +0000444 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000445 DestroyNRVOVariable(Address addr,
John McCall82fe67b2011-07-09 01:37:26 +0000446 const CXXDestructorDecl *Dtor,
447 llvm::Value *NRVOFlag)
448 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000449
450 const CXXDestructorDecl *Dtor;
451 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000452 Address Loc;
John McCall2b7fc382010-07-13 20:32:21 +0000453
Craig Topper4f12f102014-03-12 06:41:41 +0000454 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000455 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000456 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000457
Craig Topper8a13c412014-05-21 05:09:00 +0000458 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000459 if (NRVO) {
460 // If we exited via NRVO, we skip the destructor call.
461 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
462 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000463 llvm::Value *DidNRVO =
464 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000465 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
466 CGF.EmitBlock(RunDtorBB);
467 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000468
John McCall2b7fc382010-07-13 20:32:21 +0000469 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +0000470 /*ForVirtualBase=*/false,
471 /*Delegating=*/false,
472 Loc);
John McCall2b7fc382010-07-13 20:32:21 +0000473
474 if (NRVO) CGF.EmitBlock(SkipDtorBB);
475 }
476 };
John McCall2b7fc382010-07-13 20:32:21 +0000477
David Blaikie7e70d682015-08-18 22:40:54 +0000478 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000479 Address Stack;
480 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000481 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000482 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000483 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
484 CGF.Builder.CreateCall(F, V);
485 }
486 };
487
David Blaikie7e70d682015-08-18 22:40:54 +0000488 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000489 const VarDecl &Var;
490 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
491
Craig Topper4f12f102014-03-12 06:41:41 +0000492 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000493 // Compute the address of the local variable, in case it's a
494 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000495 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
496 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000497 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
498 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000499 CGF.EmitExtendGCLifetime(value);
500 }
501 };
502
David Blaikie7e70d682015-08-18 22:40:54 +0000503 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000504 llvm::Constant *CleanupFn;
505 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000506 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000507
John McCalla464ff92010-07-21 06:13:08 +0000508 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000509 const VarDecl *Var)
510 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000511
Craig Topper4f12f102014-03-12 06:41:41 +0000512 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000513 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
514 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000515 // Compute the address of the local variable, in case it's a byref
516 // or something.
John McCall7f416cc2015-09-08 08:05:57 +0000517 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCallc533cb72011-02-22 06:44:22 +0000518
John McCalla464ff92010-07-21 06:13:08 +0000519 // In some cases, the type of the function argument will be different from
520 // the type of the pointer. An example of this is
521 // void f(void* arg);
522 // __attribute__((cleanup(f))) void *g;
523 //
524 // To fix this we insert a bitcast here.
525 QualType ArgTy = FnInfo.arg_begin()->type;
526 llvm::Value *Arg =
527 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
528
529 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000530 Args.add(RValue::get(Arg),
531 CGF.getContext().getPointerType(Var.getType()));
John McCalla464ff92010-07-21 06:13:08 +0000532 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
533 }
534 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000535} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000536
John McCall31168b02011-06-15 23:02:42 +0000537/// EmitAutoVarWithLifetime - Does the setup required for an automatic
538/// variable with lifetime.
539static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000540 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000541 Qualifiers::ObjCLifetime lifetime) {
542 switch (lifetime) {
543 case Qualifiers::OCL_None:
544 llvm_unreachable("present but none");
545
546 case Qualifiers::OCL_ExplicitNone:
547 // nothing to do
548 break;
549
550 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000551 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000552 (var.hasAttr<ObjCPreciseLifetimeAttr>()
553 ? CodeGenFunction::destroyARCStrongPrecise
554 : CodeGenFunction::destroyARCStrongImprecise);
555
556 CleanupKind cleanupKind = CGF.getARCCleanupKind();
557 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
558 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000559 break;
560 }
561 case Qualifiers::OCL_Autoreleasing:
562 // nothing to do
563 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000564
John McCall31168b02011-06-15 23:02:42 +0000565 case Qualifiers::OCL_Weak:
566 // __weak objects always get EH cleanups; otherwise, exceptions
567 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000568 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
569 CodeGenFunction::destroyARCWeak,
570 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000571 break;
572 }
573}
574
575static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
576 if (const Expr *e = dyn_cast<Expr>(s)) {
577 // Skip the most common kinds of expressions that make
578 // hierarchy-walking expensive.
579 s = e = e->IgnoreParenCasts();
580
581 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
582 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000583 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
584 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000585 for (const auto &I : block->captures()) {
586 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000587 return true;
588 }
589 }
John McCall31168b02011-06-15 23:02:42 +0000590 }
591
Benjamin Kramer642f1732015-07-02 21:03:14 +0000592 for (const Stmt *SubStmt : s->children())
593 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
594 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000595 return true;
596
597 return false;
598}
599
600static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
601 if (!decl) return false;
602 if (!isa<VarDecl>(decl)) return false;
603 const VarDecl *var = cast<VarDecl>(decl);
604 return isAccessedBy(*var, e);
605}
606
John McCallf8a9b662015-10-21 18:06:31 +0000607static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
608 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000609 bool needsCast = false;
610
John McCallf8a9b662015-10-21 18:06:31 +0000611 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
612 switch (castExpr->getCastKind()) {
613 // Look through casts that don't require representation changes.
614 case CK_NoOp:
615 case CK_BitCast:
616 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000617 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000618 break;
619
620 // If we find an l-value to r-value cast from a __weak variable,
621 // emit this operation as a copy or move.
622 case CK_LValueToRValue: {
623 const Expr *srcExpr = castExpr->getSubExpr();
624 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
625 return false;
626
627 // Emit the source l-value.
628 LValue srcLV = CGF.EmitLValue(srcExpr);
629
John McCall0204e342015-11-16 22:11:41 +0000630 // Handle a formal type change to avoid asserting.
631 auto srcAddr = srcLV.getAddress();
632 if (needsCast) {
633 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
634 destLV.getAddress().getElementType());
635 }
636
John McCallf8a9b662015-10-21 18:06:31 +0000637 // If it was an l-value, use objc_copyWeak.
638 if (srcExpr->getValueKind() == VK_LValue) {
John McCall0204e342015-11-16 22:11:41 +0000639 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000640 } else {
641 assert(srcExpr->getValueKind() == VK_XValue);
John McCall0204e342015-11-16 22:11:41 +0000642 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000643 }
644 return true;
645 }
646
647 // Stop at anything else.
648 default:
649 return false;
650 }
651
652 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000653 }
654 return false;
655}
656
John McCall1553b192011-06-16 04:16:24 +0000657static void drillIntoBlockVariable(CodeGenFunction &CGF,
658 LValue &lvalue,
659 const VarDecl *var) {
John McCall7f416cc2015-09-08 08:05:57 +0000660 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCall1553b192011-06-16 04:16:24 +0000661}
662
David Blaikie73ca5692014-12-09 00:32:22 +0000663void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000664 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000665 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000666 if (!lifetime) {
667 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000668 if (capturedByInit)
669 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +0000670 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000671 return;
672 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000673
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000674 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
675 init = DIE->getExpr();
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000676
John McCall31168b02011-06-15 23:02:42 +0000677 // If we're emitting a value with lifetime, we have to do the
678 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000679 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
680 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000681 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000682 }
683 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000684
685 // We have to maintain the illusion that the variable is
686 // zero-initialized. If the variable might be accessed in its
687 // initializer, zero-initialize before running the initializer, then
688 // actually perform the initialization with an assign.
689 bool accessedByInit = false;
690 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000691 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000692 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000693 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000694 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000695 if (capturedByInit) {
696 // We can use a simple GEP for this because it can't have been
697 // moved yet.
John McCall7f416cc2015-09-08 08:05:57 +0000698 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
699 cast<VarDecl>(D),
700 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000701 }
702
John McCall7f416cc2015-09-08 08:05:57 +0000703 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
John McCall31168b02011-06-15 23:02:42 +0000704 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000705
John McCall31168b02011-06-15 23:02:42 +0000706 // If __weak, we want to use a barrier under certain conditions.
707 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000708 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000709
710 // Otherwise just do a simple store.
711 else
David Chisnallfa35df62012-01-16 17:27:18 +0000712 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000713 }
714
715 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000716 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000717
718 switch (lifetime) {
719 case Qualifiers::OCL_None:
720 llvm_unreachable("present but none");
721
722 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000723 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000724 break;
725
726 case Qualifiers::OCL_Strong: {
727 value = EmitARCRetainScalarExpr(init);
728 break;
729 }
730
731 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000732 // If it's not accessed by the initializer, try to emit the
733 // initialization with a copy or move.
734 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
735 return;
736 }
737
John McCall31168b02011-06-15 23:02:42 +0000738 // No way to optimize a producing initializer into this. It's not
739 // worth optimizing for, because the value will immediately
740 // disappear in the common case.
741 value = EmitScalarExpr(init);
742
John McCall1553b192011-06-16 04:16:24 +0000743 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000744 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000745 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000746 else
John McCall1553b192011-06-16 04:16:24 +0000747 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000748 return;
749 }
750
751 case Qualifiers::OCL_Autoreleasing:
752 value = EmitARCRetainAutoreleaseScalarExpr(init);
753 break;
754 }
755
John McCall1553b192011-06-16 04:16:24 +0000756 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000757
758 // If the variable might have been accessed by its initializer, we
759 // might have to initialize with a barrier. We have to do this for
760 // both __weak and __strong, but __weak got filtered out above.
761 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000762 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000763 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000764 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000765 return;
766 }
767
David Chisnallfa35df62012-01-16 17:27:18 +0000768 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000769}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000770
John McCalld4631322011-06-17 06:42:21 +0000771/// EmitScalarInit - Initialize the given lvalue with the given object.
772void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
773 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
774 if (!lifetime)
David Chisnallfa35df62012-01-16 17:27:18 +0000775 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCalld4631322011-06-17 06:42:21 +0000776
777 switch (lifetime) {
778 case Qualifiers::OCL_None:
779 llvm_unreachable("present but none");
780
781 case Qualifiers::OCL_ExplicitNone:
782 // nothing to do
783 break;
784
785 case Qualifiers::OCL_Strong:
786 init = EmitARCRetain(lvalue.getType(), init);
787 break;
788
789 case Qualifiers::OCL_Weak:
790 // Initialize and then skip the primitive store.
791 EmitARCInitWeak(lvalue.getAddress(), init);
792 return;
793
794 case Qualifiers::OCL_Autoreleasing:
795 init = EmitARCRetainAutorelease(lvalue.getType(), init);
796 break;
797 }
798
David Chisnallfa35df62012-01-16 17:27:18 +0000799 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCalld4631322011-06-17 06:42:21 +0000800}
801
Chris Lattnerb85025f2010-12-01 02:05:19 +0000802/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
803/// non-zero parts of the specified initializer with equal or fewer than
804/// NumStores scalar stores.
805static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
806 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000807 // Zero and Undef never requires any extra stores.
808 if (isa<llvm::ConstantAggregateZero>(Init) ||
809 isa<llvm::ConstantPointerNull>(Init) ||
810 isa<llvm::UndefValue>(Init))
811 return true;
812 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
813 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
814 isa<llvm::ConstantExpr>(Init))
815 return Init->isNullValue() || NumStores--;
816
817 // See if we can emit each element.
818 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
819 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
820 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
821 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
822 return false;
823 }
824 return true;
825 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000826
Chris Lattner236b3572012-01-31 04:36:19 +0000827 if (llvm::ConstantDataSequential *CDS =
828 dyn_cast<llvm::ConstantDataSequential>(Init)) {
829 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
830 llvm::Constant *Elt = CDS->getElementAsConstant(i);
831 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
832 return false;
833 }
834 return true;
835 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000836
Chris Lattnerb85025f2010-12-01 02:05:19 +0000837 // Anything else is hard and scary.
838 return false;
839}
840
841/// emitStoresForInitAfterMemset - For inits that
842/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
843/// stores that would be required.
844static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000845 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000846 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
847 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000848
Chris Lattnere6af8862010-12-02 01:58:41 +0000849 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
850 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
851 isa<llvm::ConstantExpr>(Init)) {
John McCall7f416cc2015-09-08 08:05:57 +0000852 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000853 return;
854 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000855
856 if (llvm::ConstantDataSequential *CDS =
857 dyn_cast<llvm::ConstantDataSequential>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000858 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
859 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000860
861 // If necessary, get a pointer to the element and emit it.
862 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000863 emitStoresForInitAfterMemset(
864 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
865 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000866 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000867 return;
868 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000869
Chris Lattnere6af8862010-12-02 01:58:41 +0000870 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
871 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000872
Chris Lattnere6af8862010-12-02 01:58:41 +0000873 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
874 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000875
876 // If necessary, get a pointer to the element and emit it.
877 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000878 emitStoresForInitAfterMemset(
879 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
880 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000881 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000882}
883
Chris Lattnerb85025f2010-12-01 02:05:19 +0000884/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
885/// plus some stores to initialize a local variable instead of using a memcpy
886/// from a constant global. It is beneficial to use memset if the global is all
887/// zeros, or mostly zeros and large.
888static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
889 uint64_t GlobalSize) {
890 // If a global is all zeros, always use a memset.
891 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
892
Chris Lattnerb85025f2010-12-01 02:05:19 +0000893 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
894 // do it if it will require 6 or fewer scalar stores.
895 // TODO: Should budget depends on the size? Avoiding a large global warrants
896 // plopping in more stores.
897 unsigned StoreBudget = 6;
898 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000899
900 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000901 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
902}
903
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000904/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000905/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000906/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000907void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
908 AutoVarEmission emission = EmitAutoVarAlloca(D);
909 EmitAutoVarInit(emission);
910 EmitAutoVarCleanups(emission);
911}
Chris Lattner03df1222007-06-02 04:53:11 +0000912
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000913/// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
914/// markers.
915static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
916 const LangOptions &LangOpts) {
917 // Asan uses markers for use-after-scope checks.
918 if (CGOpts.SanitizeAddressUseAfterScope)
919 return true;
920
921 // Disable lifetime markers in msan builds.
922 // FIXME: Remove this when msan works with lifetime markers.
923 if (LangOpts.Sanitize.has(SanitizerKind::Memory))
924 return false;
925
926 // For now, only in optimized builds.
927 return CGOpts.OptimizationLevel != 0;
928}
929
David Majnemerdc012fa2015-04-22 21:38:15 +0000930/// Emit a lifetime.begin marker if some criteria are satisfied.
931/// \return a pointer to the temporary size Value if a marker was emitted, null
932/// otherwise
933llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
934 llvm::Value *Addr) {
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000935 if (!shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), getLangOpts()))
Reid Kleckner1ef49212015-04-23 18:07:13 +0000936 return nullptr;
937
David Majnemerdc012fa2015-04-22 21:38:15 +0000938 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000939 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
940 llvm::CallInst *C =
941 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000942 C->setDoesNotThrow();
943 return SizeV;
944}
945
946void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000947 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
948 llvm::CallInst *C =
949 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000950 C->setDoesNotThrow();
951}
952
John McCallc533cb72011-02-22 06:44:22 +0000953/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000954/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +0000955CodeGenFunction::AutoVarEmission
956CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
957 QualType Ty = D.getType();
958
959 AutoVarEmission emission(D);
960
961 bool isByRef = D.hasAttr<BlocksAttr>();
962 emission.IsByRef = isByRef;
963
964 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +0000965
John McCall23c29fe2011-06-24 21:55:10 +0000966 // If the type is variably-modified, emit all the VLA sizes for it.
967 if (Ty->isVariablyModifiedType())
968 EmitVariablyModifiedType(Ty);
969
John McCall7f416cc2015-09-08 08:05:57 +0000970 Address address = Address::invalid();
Eli Friedmana682d392008-02-15 12:20:59 +0000971 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000972 bool NRVO = getLangOpts().ElideConstructors &&
973 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +0000974
Richard Smith2bcde3a2013-06-02 00:09:52 +0000975 // If this value is an array or struct with a statically determinable
976 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +0000977 //
978 // TODO: We should constant-evaluate the initializer of any variable,
979 // as long as it is initialized by a constant expression. Currently,
980 // isConstantInitializer produces wrong answers for structs with
981 // reference or bitfield members, and a few other cases, and checking
982 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +0000983 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
984 (D.isConstexpr() ||
985 ((Ty.isPODType(getContext()) ||
986 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
987 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +0000988
Rafael Espindola609f5d92013-03-26 18:41:47 +0000989 // If the variable's a const type, and it's neither an NRVO
990 // candidate nor a __block variable and has no mutable members,
991 // emit it as a global instead.
992 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
993 CGM.isTypeConstant(Ty, true)) {
994 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +0000995
John McCall7f416cc2015-09-08 08:05:57 +0000996 // Signal this condition to later callbacks.
997 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +0000998 assert(emission.wasEmittedAsGlobal());
999 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +00001000 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001001
Rafael Espindola609f5d92013-03-26 18:41:47 +00001002 // Otherwise, tell the initialization code that we're in this case.
1003 emission.IsConstantAggregate = true;
1004 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001005
Rafael Espindola609f5d92013-03-26 18:41:47 +00001006 // A normal fixed sized variable becomes an alloca in the entry block,
1007 // unless it's an NRVO variable.
Eric Christopher31ab1302011-08-23 22:38:00 +00001008
Rafael Espindola609f5d92013-03-26 18:41:47 +00001009 if (NRVO) {
1010 // The named return value optimization: allocate this variable in the
1011 // return slot, so that we can elide the copy when returning this
1012 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +00001013 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +00001014
Rafael Espindola609f5d92013-03-26 18:41:47 +00001015 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1016 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
1017 // Create a flag that is used to indicate when the NRVO was applied
1018 // to this variable. Set it to zero to indicate that NRVO was not
1019 // applied.
1020 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +00001021 Address NRVOFlag =
1022 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +00001023 EnsureInsertPoint();
1024 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +00001025
Rafael Espindola609f5d92013-03-26 18:41:47 +00001026 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +00001027 NRVOFlags[&D] = NRVOFlag.getPointer();
1028 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +00001029 }
Douglas Gregor290c93e2010-05-15 06:46:45 +00001030 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001031 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001032 CharUnits allocaAlignment;
1033 llvm::Type *allocaTy;
1034 if (isByRef) {
1035 auto &byrefInfo = getBlockByrefInfo(&D);
1036 allocaTy = byrefInfo.Type;
1037 allocaAlignment = byrefInfo.ByrefAlignment;
1038 } else {
1039 allocaTy = ConvertTypeForMem(Ty);
1040 allocaAlignment = alignment;
1041 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001042
John McCall999110f2015-09-08 09:18:30 +00001043 // Create the alloca. Note that we set the name separately from
1044 // building the instruction so that it's there even in no-asserts
1045 // builds.
1046 address = CreateTempAlloca(allocaTy, allocaAlignment);
1047 address.getPointer()->setName(D.getName());
Rafael Espindola609f5d92013-03-26 18:41:47 +00001048
Reid Kleckner1f88e932015-10-07 21:03:41 +00001049 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1050 // the catch parameter starts in the catchpad instruction, and we can't
1051 // insert code in those basic blocks.
1052 bool IsMSCatchParam =
1053 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1054
Rafael Espindola609f5d92013-03-26 18:41:47 +00001055 // Emit a lifetime intrinsic if meaningful. There's no point
1056 // in doing this if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001057 if (HaveInsertPoint() && !IsMSCatchParam) {
John McCall7f416cc2015-09-08 08:05:57 +00001058 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1059 emission.SizeForLifetimeMarkers =
1060 EmitLifetimeStart(size, address.getPointer());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001061 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001062 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001063 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001064 }
Chris Lattner03df1222007-06-02 04:53:11 +00001065 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001066 EnsureInsertPoint();
1067
Anders Carlsson15949b32009-02-09 20:41:50 +00001068 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001069 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001070 Address Stack =
1071 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001072
Anders Carlsson30032882008-12-12 07:38:43 +00001073 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001074 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001075 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001076
1077 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001078
John McCalla464ff92010-07-21 06:13:08 +00001079 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001080 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001081 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001082 }
Mike Stump11289f42009-09-09 15:08:12 +00001083
John McCall23c29fe2011-06-24 21:55:10 +00001084 llvm::Value *elementCount;
1085 QualType elementType;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001086 std::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +00001087
Chris Lattner2192fe52011-07-18 04:24:23 +00001088 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +00001089
1090 // Allocate memory for the array.
John McCall23c29fe2011-06-24 21:55:10 +00001091 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1092 vla->setAlignment(alignment.getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +00001093
John McCall7f416cc2015-09-08 08:05:57 +00001094 address = Address(vla, alignment);
Chris Lattner03df1222007-06-02 04:53:11 +00001095 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001096
John McCall7f416cc2015-09-08 08:05:57 +00001097 setAddrOfLocalVar(&D, address);
1098 emission.Addr = address;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001099
1100 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +00001101 if (HaveInsertPoint())
1102 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001103 if (CGM.getCodeGenOpts().getDebugInfo() >=
1104 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001105 DI->setLocation(D.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001106 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001107 }
Devang Patel887e2152011-06-03 19:21:47 +00001108 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001109
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001110 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001111 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001112
John McCallc533cb72011-02-22 06:44:22 +00001113 return emission;
1114}
1115
1116/// Determines whether the given __block variable is potentially
1117/// captured by the given expression.
1118static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1119 // Skip the most common kinds of expressions that make
1120 // hierarchy-walking expensive.
1121 e = e->IgnoreParenCasts();
1122
1123 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1124 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +00001125 for (const auto &I : block->captures()) {
1126 if (I.getVariable() == &var)
John McCallc533cb72011-02-22 06:44:22 +00001127 return true;
1128 }
1129
1130 // No need to walk into the subexpressions.
1131 return false;
1132 }
1133
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001134 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1135 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001136 for (const auto *BI : CS->body())
1137 if (const auto *E = dyn_cast<Expr>(BI)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001138 if (isCapturedBy(var, E))
1139 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001140 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001141 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001142 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001143 for (const auto *I : DS->decls()) {
1144 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1145 const Expr *Init = VD->getInit();
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001146 if (Init && isCapturedBy(var, Init))
1147 return true;
1148 }
1149 }
1150 }
1151 else
1152 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1153 // Later, provide code to poke into statements for capture analysis.
1154 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001155 return false;
1156 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001157
Benjamin Kramer642f1732015-07-02 21:03:14 +00001158 for (const Stmt *SubStmt : e->children())
1159 if (isCapturedBy(var, cast<Expr>(SubStmt)))
John McCallc533cb72011-02-22 06:44:22 +00001160 return true;
1161
1162 return false;
1163}
1164
Douglas Gregor82e1af22011-07-01 21:08:19 +00001165/// \brief Determine whether the given initializer is trivial in the sense
1166/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001167bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001168 if (!Init)
1169 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001170
Douglas Gregor82e1af22011-07-01 21:08:19 +00001171 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1172 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1173 if (Constructor->isTrivial() &&
1174 Constructor->isDefaultConstructor() &&
1175 !Construct->requiresZeroInitialization())
1176 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001177
Douglas Gregor82e1af22011-07-01 21:08:19 +00001178 return false;
1179}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001180
John McCallc533cb72011-02-22 06:44:22 +00001181void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001182 assert(emission.Variable && "emission was not valid!");
1183
John McCallc533cb72011-02-22 06:44:22 +00001184 // If this was emitted as a global constant, we're done.
1185 if (emission.wasEmittedAsGlobal()) return;
1186
John McCall9e2e22f2011-02-22 07:16:58 +00001187 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001188 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001189 QualType type = D.getType();
1190
Chris Lattner07eb7332007-07-12 00:39:48 +00001191 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001192 const Expr *Init = D.getInit();
1193
1194 // If we are at an unreachable point, we don't need to emit the initializer
1195 // unless it contains a label.
1196 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001197 if (!Init || !ContainsLabel(Init)) return;
1198 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001199 }
1200
John McCall73064872011-03-31 01:59:53 +00001201 // Initialize the structure of a __block variable.
1202 if (emission.IsByRef)
1203 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001204
Douglas Gregor82e1af22011-07-01 21:08:19 +00001205 if (isTrivialInitializer(Init))
1206 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001207
John McCallc533cb72011-02-22 06:44:22 +00001208 // Check whether this is a byref variable that's potentially
1209 // captured and moved by its own initializer. If so, we'll need to
1210 // emit the initializer first, then copy into the variable.
1211 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1212
John McCall7f416cc2015-09-08 08:05:57 +00001213 Address Loc =
1214 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
John McCallc533cb72011-02-22 06:44:22 +00001215
Craig Topper8a13c412014-05-21 05:09:00 +00001216 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001217 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001218 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smithdafff942012-01-14 04:30:29 +00001219 constant = CGM.EmitConstantInit(D, this);
Richard Smithfddd3842011-12-30 21:15:51 +00001220 }
1221
1222 if (!constant) {
John McCall7f416cc2015-09-08 08:05:57 +00001223 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001224 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001225 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001226 }
John McCall91ca10f2011-03-08 09:11:50 +00001227
Richard Smith2bcde3a2013-06-02 00:09:52 +00001228 if (!emission.IsConstantAggregate) {
1229 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001230 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001231 lv.setNonGC(true);
1232 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1233 }
1234
John McCallc533cb72011-02-22 06:44:22 +00001235 // If this is a simple aggregate initialization, we can optimize it
1236 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001237 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001238
John McCall91ca10f2011-03-08 09:11:50 +00001239 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001240 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001241 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001242
Chris Lattner2192fe52011-07-18 04:24:23 +00001243 llvm::Type *BP = Int8PtrTy;
John McCall7f416cc2015-09-08 08:05:57 +00001244 if (Loc.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001245 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001246
John McCall91ca10f2011-03-08 09:11:50 +00001247 // If the initializer is all or mostly zeros, codegen with memset then do
1248 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001249 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001250 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall91ca10f2011-03-08 09:11:50 +00001251 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
John McCall7f416cc2015-09-08 08:05:57 +00001252 isVolatile);
Benjamin Kramer29f9a002012-08-27 22:07:02 +00001253 // Zero and undef don't require a stores.
1254 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall91ca10f2011-03-08 09:11:50 +00001255 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001256 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1257 isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001258 }
John McCall91ca10f2011-03-08 09:11:50 +00001259 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001260 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001261 // memcpy from the global to the alloca.
Reid Kleckner453e0562014-10-08 01:07:54 +00001262 std::string Name = getStaticDeclName(CGM, D);
John McCall91ca10f2011-03-08 09:11:50 +00001263 llvm::GlobalVariable *GV =
1264 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001265 llvm::GlobalValue::PrivateLinkage,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001266 constant, Name);
John McCall7f416cc2015-09-08 08:05:57 +00001267 GV->setAlignment(Loc.getAlignment().getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001268 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Eric Christopher31ab1302011-08-23 22:38:00 +00001269
John McCall7f416cc2015-09-08 08:05:57 +00001270 Address SrcPtr = Address(GV, Loc.getAlignment());
1271 if (SrcPtr.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001272 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001273
John McCall7f416cc2015-09-08 08:05:57 +00001274 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
John McCall91ca10f2011-03-08 09:11:50 +00001275 }
1276}
1277
1278/// Emit an expression as an initializer for a variable at the given
1279/// location. The expression is not necessarily the normal
1280/// initializer for the variable, and the address is not necessarily
1281/// its normal location.
1282///
1283/// \param init the initializing expression
1284/// \param var the variable to act as if we're initializing
1285/// \param loc the address to initialize; its type is a pointer
1286/// to the LLVM mapping of the variable's type
1287/// \param alignment the alignment of the address
1288/// \param capturedByInit true if the variable is a __block variable
1289/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001290void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001291 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001292 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001293
1294 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001295 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001296 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001297 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001298 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001299 return;
1300 }
1301 switch (getEvaluationKind(type)) {
1302 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001303 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001304 return;
1305 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001306 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001307 if (capturedByInit)
1308 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001309 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001310 return;
1311 }
1312 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001313 if (type->isAtomicType()) {
1314 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1315 } else {
1316 // TODO: how can we delay here if D is captured by its initializer?
1317 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001318 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001319 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001320 AggValueSlot::IsNotAliased));
John McCalla8ec7eb2013-03-07 21:37:17 +00001321 }
John McCall47fb9502013-03-07 21:37:08 +00001322 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001323 }
John McCall47fb9502013-03-07 21:37:08 +00001324 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001325}
John McCallbd309292010-07-06 01:34:17 +00001326
John McCall82fe67b2011-07-09 01:37:26 +00001327/// Enter a destroy cleanup for the given local variable.
1328void CodeGenFunction::emitAutoVarTypeCleanup(
1329 const CodeGenFunction::AutoVarEmission &emission,
1330 QualType::DestructionKind dtorKind) {
1331 assert(dtorKind != QualType::DK_none);
1332
1333 // Note that for __block variables, we want to destroy the
1334 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001335 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001336
1337 const VarDecl *var = emission.Variable;
1338 QualType type = var->getType();
1339
1340 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001341 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001342
1343 switch (dtorKind) {
1344 case QualType::DK_none:
1345 llvm_unreachable("no cleanup for trivially-destructible variable");
1346
1347 case QualType::DK_cxx_destructor:
1348 // If there's an NRVO flag on the emission, we need a different
1349 // cleanup.
1350 if (emission.NRVOFlag) {
1351 assert(!type->isArrayType());
1352 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +00001353 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1354 dtor, emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001355 return;
1356 }
1357 break;
1358
1359 case QualType::DK_objc_strong_lifetime:
1360 // Suppress cleanups for pseudo-strong variables.
1361 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001362
John McCall82fe67b2011-07-09 01:37:26 +00001363 // Otherwise, consider whether to use an EH cleanup or not.
1364 cleanupKind = getARCCleanupKind();
1365
1366 // Use the imprecise destroyer by default.
1367 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1368 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1369 break;
1370
1371 case QualType::DK_objc_weak_lifetime:
1372 break;
1373 }
1374
1375 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001376 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001377
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001378 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001379 // is being pushed as an EH cleanup.
1380 bool useEHCleanup = (cleanupKind & EHCleanup);
1381 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1382 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001383}
1384
John McCallc533cb72011-02-22 06:44:22 +00001385void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001386 assert(emission.Variable && "emission was not valid!");
1387
John McCallc533cb72011-02-22 06:44:22 +00001388 // If this was emitted as a global constant, we're done.
1389 if (emission.wasEmittedAsGlobal()) return;
1390
John McCall8c38d352012-04-13 18:44:05 +00001391 // If we don't have an insertion point, we're done. Sema prevents
1392 // us from jumping into any of these scopes anyway.
1393 if (!HaveInsertPoint()) return;
1394
John McCall9e2e22f2011-02-22 07:16:58 +00001395 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001396
Nadav Rotem1da30942013-03-23 06:43:35 +00001397 // Make sure we call @llvm.lifetime.end. This needs to happen
1398 // *last*, so the cleanup needs to be pushed *first*.
Tim Shen421119f2016-07-01 21:08:47 +00001399 if (emission.useLifetimeMarkers())
1400 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
Nadav Rotem1da30942013-03-23 06:43:35 +00001401 emission.getAllocatedAddress(),
1402 emission.getSizeForLifetimeMarkers());
Nadav Rotem1da30942013-03-23 06:43:35 +00001403
John McCall82fe67b2011-07-09 01:37:26 +00001404 // Check the type for a cleanup.
1405 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1406 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001407
John McCall1bd25562011-06-24 23:21:27 +00001408 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001409 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001410 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1411 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1412 }
1413
John McCallc533cb72011-02-22 06:44:22 +00001414 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001415 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001416 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001417
John McCallc533cb72011-02-22 06:44:22 +00001418 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001419 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001420
John McCalla729c622012-02-17 03:33:10 +00001421 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001422 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001423 }
Mike Stump626aecc2009-03-05 01:23:13 +00001424
John McCallc533cb72011-02-22 06:44:22 +00001425 // If this is a block variable, call _Block_object_destroy
1426 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001427 if (emission.IsByRef)
1428 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001429}
Chris Lattner53621a52007-06-13 20:44:40 +00001430
Peter Collingbourne1425b452012-01-26 03:33:36 +00001431CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001432CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1433 switch (kind) {
1434 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001435 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001436 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001437 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001438 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001439 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001440 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001441 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001442 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001443}
1444
John McCall12cc42a2013-02-01 05:11:40 +00001445/// pushEHDestroy - Push the standard destructor for the given type as
1446/// an EH-only cleanup.
1447void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001448 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00001449 assert(dtorKind && "cannot push destructor for trivial type");
1450 assert(needsEHCleanup(dtorKind));
1451
1452 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1453}
1454
1455/// pushDestroy - Push the standard destructor for the given type as
1456/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001457void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001458 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00001459 assert(dtorKind && "cannot push destructor for trivial type");
1460
1461 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1462 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1463 cleanupKind & EHCleanup);
1464}
1465
John McCall7f416cc2015-09-08 08:05:57 +00001466void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001467 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001468 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001469 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1470 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001471}
1472
John McCall7f416cc2015-09-08 08:05:57 +00001473void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001474 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1475}
1476
Richard Smith736a9472013-06-12 20:42:33 +00001477void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00001478 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00001479 Destroyer *destroyer, bool useEHCleanupForArray) {
1480 assert(!isInConditionalBranch() &&
1481 "performing lifetime extension from within conditional");
1482
1483 // Push an EH-only cleanup for the object now.
1484 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1485 // around in case a temporary's destructor throws an exception.
1486 if (cleanupKind & EHCleanup)
1487 EHStack.pushCleanup<DestroyObject>(
1488 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1489 destroyer, useEHCleanupForArray);
1490
1491 // Remember that we need to push a full cleanup for the object at the
1492 // end of the full-expression.
1493 pushCleanupAfterFullExpr<DestroyObject>(
1494 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1495}
1496
John McCall178360e2011-07-11 08:38:19 +00001497/// emitDestroy - Immediately perform the destruction of the given
1498/// object.
1499///
1500/// \param addr - the address of the object; a type*
1501/// \param type - the type of the object; if an array type, all
1502/// objects are destroyed in reverse order
1503/// \param destroyer - the function to call to destroy individual
1504/// elements
1505/// \param useEHCleanupForArray - whether an EH cleanup should be
1506/// used when destroying array elements, in case one of the
1507/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00001508void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001509 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001510 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001511 const ArrayType *arrayType = getContext().getAsArrayType(type);
1512 if (!arrayType)
1513 return destroyer(*this, addr, type);
1514
John McCall7f416cc2015-09-08 08:05:57 +00001515 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1516
1517 CharUnits elementAlign =
1518 addr.getAlignment()
1519 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00001520
1521 // Normally we have to check whether the array is zero-length.
1522 bool checkZeroLength = true;
1523
1524 // But if the array length is constant, we can suppress that.
1525 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1526 // ...and if it's constant zero, we can just skip the entire thing.
1527 if (constLength->isZero()) return;
1528 checkZeroLength = false;
1529 }
1530
John McCall7f416cc2015-09-08 08:05:57 +00001531 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00001532 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00001533 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001534 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001535}
1536
John McCall178360e2011-07-11 08:38:19 +00001537/// emitArrayDestroy - Destroys all the elements of the given array,
1538/// beginning from last to first. The array cannot be zero-length.
1539///
1540/// \param begin - a type* denoting the first element of the array
1541/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001542/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00001543/// \param destroyer - the function to call to destroy elements
1544/// \param useEHCleanup - whether to push an EH cleanup to destroy
1545/// the remaining elements in case the destruction of a single
1546/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001547void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1548 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001549 QualType elementType,
1550 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001551 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001552 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001553 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00001554 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00001555
1556 // The basic structure here is a do-while loop, because we don't
1557 // need to check for the zero-element case.
1558 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1559 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1560
John McCall97eab0a2011-07-13 08:09:46 +00001561 if (checkZeroLength) {
1562 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1563 "arraydestroy.isempty");
1564 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1565 }
1566
John McCall82fe67b2011-07-09 01:37:26 +00001567 // Enter the loop body, making that address the current address.
1568 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1569 EmitBlock(bodyBB);
1570 llvm::PHINode *elementPast =
1571 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1572 elementPast->addIncoming(end, entryBB);
1573
1574 // Shift the address back by one element.
1575 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1576 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1577 "arraydestroy.element");
1578
John McCall178360e2011-07-11 08:38:19 +00001579 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00001580 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1581 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001582
John McCall82fe67b2011-07-09 01:37:26 +00001583 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00001584 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00001585
John McCall178360e2011-07-11 08:38:19 +00001586 if (useEHCleanup)
1587 PopCleanupBlock();
1588
John McCall82fe67b2011-07-09 01:37:26 +00001589 // Check whether we've reached the end.
1590 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1591 Builder.CreateCondBr(done, doneBB, bodyBB);
1592 elementPast->addIncoming(element, Builder.GetInsertBlock());
1593
1594 // Done.
1595 EmitBlock(doneBB);
1596}
1597
John McCall178360e2011-07-11 08:38:19 +00001598/// Perform partial array destruction as if in an EH cleanup. Unlike
1599/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001600static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1601 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001602 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001603 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001604 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001605 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001606 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1607 // VLAs don't require a GEP index to walk into.
1608 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001609 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001610 type = arrayType->getElementType();
1611 }
John McCall97eab0a2011-07-13 08:09:46 +00001612
1613 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00001614 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00001615
John McCallf0f0b7a2015-09-14 18:57:08 +00001616 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001617 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1618 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001619 }
1620
John McCall97eab0a2011-07-13 08:09:46 +00001621 // Destroy the array. We don't ever need an EH cleanup because we
1622 // assume that we're in an EH cleanup ourselves, so a throwing
1623 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00001624 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001625 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001626}
1627
John McCall82fe67b2011-07-09 01:37:26 +00001628namespace {
John McCall178360e2011-07-11 08:38:19 +00001629 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1630 /// array destroy where the end pointer is regularly determined and
1631 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001632 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00001633 llvm::Value *ArrayBegin;
1634 llvm::Value *ArrayEnd;
1635 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001636 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001637 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00001638 public:
1639 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001640 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001641 CodeGenFunction::Destroyer *destroyer)
1642 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00001643 ElementType(elementType), Destroyer(destroyer),
1644 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00001645
Craig Topper4f12f102014-03-12 06:41:41 +00001646 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001647 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001648 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00001649 }
1650 };
1651
1652 /// IrregularPartialArrayDestroy - a cleanup which performs a
1653 /// partial array destroy where the end pointer is irregularly
1654 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001655 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001656 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00001657 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00001658 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001659 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001660 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00001661 public:
John McCall178360e2011-07-11 08:38:19 +00001662 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001663 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001664 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001665 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001666 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001667 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00001668 ElementType(elementType), Destroyer(destroyer),
1669 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00001670
Craig Topper4f12f102014-03-12 06:41:41 +00001671 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001672 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001673 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001674 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001675 }
1676 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001677} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00001678
John McCall178360e2011-07-11 08:38:19 +00001679/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001680/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001681/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001682///
John McCall82fe67b2011-07-09 01:37:26 +00001683/// \param elementType - the immediate element type of the array;
1684/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001685void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001686 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001687 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001688 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001689 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001690 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1691 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00001692 elementType, elementAlign,
1693 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001694}
1695
1696/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1697/// already-constructed elements of the given array. The cleanup
1698/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001699///
John McCall178360e2011-07-11 08:38:19 +00001700/// \param elementType - the immediate element type of the array;
1701/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001702void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1703 llvm::Value *arrayEnd,
1704 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001705 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001706 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001707 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001708 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001709 elementType, elementAlign,
1710 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001711}
1712
Nadav Rotem1da30942013-03-23 06:43:35 +00001713/// Lazily declare the @llvm.lifetime.start intrinsic.
1714llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1715 if (LifetimeStartFn) return LifetimeStartFn;
1716 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1717 llvm::Intrinsic::lifetime_start);
1718 return LifetimeStartFn;
1719}
1720
1721/// Lazily declare the @llvm.lifetime.end intrinsic.
1722llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1723 if (LifetimeEndFn) return LifetimeEndFn;
1724 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1725 llvm::Intrinsic::lifetime_end);
1726 return LifetimeEndFn;
1727}
1728
John McCall31168b02011-06-15 23:02:42 +00001729namespace {
1730 /// A cleanup to perform a release of an object at the end of a
1731 /// function. This is used to balance out the incoming +1 of a
1732 /// ns_consumed argument when we can't reasonably do that just by
1733 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00001734 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001735 ConsumeARCParameter(llvm::Value *param,
1736 ARCPreciseLifetime_t precise)
1737 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001738
1739 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001740 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001741
Craig Topper4f12f102014-03-12 06:41:41 +00001742 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001743 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001744 }
1745 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001746} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00001747
Mike Stump11289f42009-09-09 15:08:12 +00001748/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001749/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00001750void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1751 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001752 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001753 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001754 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001755
John McCall7f416cc2015-09-08 08:05:57 +00001756 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00001757
Adrian Prantl51936dd2013-03-14 17:53:33 +00001758 QualType Ty = D.getType();
1759
John McCall147d0212011-02-22 22:38:33 +00001760 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00001761 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00001762 // The only implicit argument a block has is its literal.
John McCall7f416cc2015-09-08 08:05:57 +00001763 // We assume this is always passed directly.
John McCall147d0212011-02-22 22:38:33 +00001764 if (BlockInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001765 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
John McCall147d0212011-02-22 22:38:33 +00001766 return;
1767 }
1768 }
1769
John McCall7f416cc2015-09-08 08:05:57 +00001770 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001771 bool DoStore = false;
1772 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001773 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001774 if (Arg.isIndirect()) {
1775 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001776 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00001777 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001778 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00001779 if (DeclPtr.getType() != IRTy)
1780 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1781
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001782 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00001783 // Don't push a cleanup in a thunk for a method that will also emit a
1784 // cleanup.
1785 if (!IsScalar && !CurFuncIsThunk &&
Reid Kleckner739756c2013-12-04 19:23:12 +00001786 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001787 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1788 if (RD && RD->hasNonTrivialDestructor())
1789 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001790 }
Chris Lattner53621a52007-06-13 20:44:40 +00001791 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001792 // Otherwise, create a temporary to hold the value.
John McCall7f416cc2015-09-08 08:05:57 +00001793 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1794 D.getName() + ".addr");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001795 DoStore = true;
1796 }
Mike Stump11289f42009-09-09 15:08:12 +00001797
John McCall7f416cc2015-09-08 08:05:57 +00001798 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1799
1800 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001801 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00001802 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001803 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1804 // We honor __attribute__((ns_consumed)) for types with lifetime.
1805 // For __strong, it's handled by just skipping the initial retain;
1806 // otherwise we have to balance out the initial +1 with an extra
1807 // cleanup to do the release at the end of the function.
1808 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1809
1810 // 'self' is always formally __strong, but if this is not an
1811 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001812 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001813 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1814 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001815 assert(lt == Qualifiers::OCL_Strong);
1816 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001817 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001818 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001819 lt = Qualifiers::OCL_ExplicitNone;
1820 }
1821
1822 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001823 if (!isConsumed) {
1824 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1825 // use objc_storeStrong(&dest, value) for retaining the
1826 // object. But first, store a null into 'dest' because
1827 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001828 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001829 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
John McCall7f416cc2015-09-08 08:05:57 +00001830 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001831 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001832 }
1833 else
John McCall31168b02011-06-15 23:02:42 +00001834 // Don't use objc_retainBlock for block pointers, because we
1835 // don't want to Block_copy something just because we got it
1836 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00001837 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001838 }
John McCall31168b02011-06-15 23:02:42 +00001839 } else {
1840 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00001841 if (isConsumed) {
1842 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1843 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00001844 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00001845 precise);
1846 }
John McCall31168b02011-06-15 23:02:42 +00001847
1848 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00001849 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001850 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001851 }
1852 }
1853
1854 // Enter the cleanup scope.
1855 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1856 }
Chris Lattner53621a52007-06-13 20:44:40 +00001857 }
1858
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001859 // Store the initial value into the alloca.
1860 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00001861 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001862
John McCall7f416cc2015-09-08 08:05:57 +00001863 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001864
1865 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001866 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001867 if (CGM.getCodeGenOpts().getDebugInfo() >=
1868 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001869 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001870 }
1871 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001872
1873 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001874 EmitVarAnnotations(&D, DeclPtr.getPointer());
Chris Lattner53621a52007-06-13 20:44:40 +00001875}
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001876
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001877void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1878 CodeGenFunction *CGF) {
1879 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1880 return;
1881 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
1882}