blob: b6ab75f67ccfb9b2a9de558183679c6207036220 [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:
Douglas Gregor85f3f952015-07-07 03:57:15 +000088 case Decl::ObjCTypeParam:
David Blaikie83d382b2011-09-23 05:06:16 +000089 llvm_unreachable("Declaration should not be in declstmts!");
Amjad Abouddc4531e2016-04-30 01:44:38 +000090 case Decl::Function: // void X();
91 case Decl::Record: // struct/union/class X;
92 case Decl::Enum: // enum X;
93 case Decl::EnumConstant: // enum ? { X = ? }
94 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +000095 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +000096 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +000097 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +000098 case Decl::OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +000099 case Decl::OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +0000100 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +0000101 // None of these decls require codegen support.
102 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +0000103
David Blaikief121b932013-05-20 22:50:41 +0000104 case Decl::NamespaceAlias:
105 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000106 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
David Blaikief121b932013-05-20 22:50:41 +0000107 return;
David Blaikiebd483762013-05-20 04:58:53 +0000108 case Decl::Using: // using X; [C++]
109 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000110 DI->EmitUsingDecl(cast<UsingDecl>(D));
David Blaikiebd483762013-05-20 04:58:53 +0000111 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000112 case Decl::UsingDirective: // using namespace X; [C++]
113 if (CGDebugInfo *DI = getDebugInfo())
114 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
115 return;
Daniel Dunbara7998072008-08-29 17:28:43 +0000116 case Decl::Var: {
117 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000118 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000119 "Should not see file-scope variables inside a function!");
John McCall1c9c3fd2010-10-15 04:57:14 +0000120 return EmitVarDecl(VD);
Chris Lattner84915fa2007-06-02 04:16:21 +0000121 }
Mike Stump11289f42009-09-09 15:08:12 +0000122
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000123 case Decl::OMPDeclareReduction:
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000124 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000125
Richard Smithdda56e42011-04-15 14:24:37 +0000126 case Decl::Typedef: // typedef int X;
127 case Decl::TypeAlias: { // using X = int; [C++0x]
128 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000129 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000130
Anders Carlsson5d985f52008-12-20 21:51:53 +0000131 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000132 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000133 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000134 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000135}
Chris Lattner03df1222007-06-02 04:53:11 +0000136
John McCall1c9c3fd2010-10-15 04:57:14 +0000137/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000138/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000139void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000140 if (D.isStaticLocal()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000141 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000142 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000143
David Majnemer27d69db2014-04-28 22:17:59 +0000144 // FIXME: We need to force the emission/use of a guard variable for
145 // some variables even if we can constant-evaluate them because
146 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000147
John McCall1c9c3fd2010-10-15 04:57:14 +0000148 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000149 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000150
151 if (D.hasExternalStorage())
Lauro Ramos Venanciobada8d42008-02-16 22:30:38 +0000152 // Don't emit it now, allow it to be emitted lazily on its first use.
153 return;
Daniel Dunbar0ca16602009-04-14 02:25:56 +0000154
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000155 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000156 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
157
158 assert(D.hasLocalStorage());
159 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000160}
161
Reid Kleckner453e0562014-10-08 01:07:54 +0000162static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
163 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000164 return CGM.getMangledName(&D).str();
165
Reid Kleckner453e0562014-10-08 01:07:54 +0000166 // If this isn't C++, we don't need a mangled name, just a pretty one.
167 assert(!D.isExternallyVisible() && "name shouldn't matter");
168 std::string ContextName;
169 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000170 if (auto *CD = dyn_cast<CapturedDecl>(DC))
171 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000172 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000173 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000174 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
175 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
176 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
177 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000178 else
David Blaikie83d382b2011-09-23 05:06:16 +0000179 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000180
Reid Kleckner453e0562014-10-08 01:07:54 +0000181 ContextName += "." + D.getNameAsString();
182 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000183}
184
Reid Kleckner453e0562014-10-08 01:07:54 +0000185llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
186 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
187 // In general, we don't always emit static var decls once before we reference
188 // them. It is possible to reference them before emitting the function that
189 // contains them, and it is possible to emit the containing function multiple
190 // times.
191 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
192 return ExistingGV;
193
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000194 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000195 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000196
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000197 // Use the label if the variable is renamed with the asm-label extension.
198 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000199 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000200 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000201 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000202 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000203
Reid Kleckner453e0562014-10-08 01:07:54 +0000204 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000205 unsigned AddrSpace =
Reid Kleckner453e0562014-10-08 01:07:54 +0000206 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000207
208 // Local address space cannot have an initializer.
209 llvm::Constant *Init = nullptr;
210 if (Ty.getAddressSpace() != LangAS::opencl_local)
211 Init = EmitNullConstant(Ty);
212 else
213 Init = llvm::UndefValue::get(LTy);
214
Anders Carlssone33eed52009-09-26 18:16:06 +0000215 llvm::GlobalVariable *GV =
Reid Kleckner453e0562014-10-08 01:07:54 +0000216 new llvm::GlobalVariable(getModule(), LTy,
Anders Carlssone33eed52009-09-26 18:16:06 +0000217 Ty.isConstant(getContext()), Linkage,
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000218 Init, Name, nullptr,
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000219 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000220 AddrSpace);
Ken Dyck160146e2010-01-27 17:10:57 +0000221 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Reid Kleckner453e0562014-10-08 01:07:54 +0000222 setGlobalVisibility(GV, &D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000223
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000224 if (supportsCOMDAT() && GV->isWeakForLinker())
225 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000226
Richard Smithfd3834f2013-04-13 02:43:54 +0000227 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000228 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000229
Hans Wennborgef2272c2014-06-18 15:55:13 +0000230 if (D.isExternallyVisible()) {
231 if (D.hasAttr<DLLImportAttr>())
232 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
233 else if (D.hasAttr<DLLExportAttr>())
234 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
235 }
236
Eli Benderskycb399432014-03-24 22:05:38 +0000237 // Make sure the result is of the correct type.
Reid Kleckner453e0562014-10-08 01:07:54 +0000238 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
239 llvm::Constant *Addr = GV;
Eli Benderskycb399432014-03-24 22:05:38 +0000240 if (AddrSpace != ExpectedAddrSpace) {
241 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
Reid Kleckner453e0562014-10-08 01:07:54 +0000242 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
Eli Benderskycb399432014-03-24 22:05:38 +0000243 }
244
Reid Kleckner453e0562014-10-08 01:07:54 +0000245 setStaticLocalDeclAddress(&D, Addr);
246
247 // Ensure that the static local gets initialized by making sure the parent
248 // function gets emitted eventually.
249 const Decl *DC = cast<Decl>(D.getDeclContext());
250
251 // We can't name blocks or captured statements directly, so try to emit their
252 // parents.
253 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
254 DC = DC->getNonClosureContext();
255 // FIXME: Ensure that global blocks get emitted.
256 if (!DC)
257 return Addr;
258 }
259
260 GlobalDecl GD;
261 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
262 GD = GlobalDecl(CD, Ctor_Base);
263 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
264 GD = GlobalDecl(DD, Dtor_Base);
265 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
266 GD = GlobalDecl(FD);
267 else {
268 // Don't do anything for Obj-C method decls or global closures. We should
269 // never defer them.
270 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
271 }
272 if (GD.getDecl())
273 (void)GetAddrOfGlobal(GD);
274
275 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000276}
277
Richard Smith6331c402012-02-13 22:16:19 +0000278/// hasNontrivialDestruction - Determine whether a type's destruction is
279/// non-trivial. If so, and the variable uses static initialization, we must
280/// register its destructor to run on exit.
281static bool hasNontrivialDestruction(QualType T) {
282 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
283 return RD && !RD->hasTrivialDestructor();
284}
285
Chandler Carruth84537952012-03-30 19:44:53 +0000286/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
287/// global variable that has already been created for it. If the initializer
288/// has a different type than GV does, this may free GV and return a different
289/// one. Otherwise it just returns GV.
290llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000291CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000292 llvm::GlobalVariable *GV) {
293 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCall70013b62010-07-15 23:40:35 +0000294
Chris Lattnere99c1102009-12-05 08:22:11 +0000295 // If constant emission failed, then this should be a C++ static
296 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000297 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000298 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000299 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall68ff0372010-09-08 01:44:27 +0000300 else if (Builder.GetInsertBlock()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000301 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000302 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000303 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000304
Chandler Carruth84537952012-03-30 19:44:53 +0000305 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000306 }
Chandler Carruth84537952012-03-30 19:44:53 +0000307 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000308 }
John McCall70013b62010-07-15 23:40:35 +0000309
Chris Lattnere99c1102009-12-05 08:22:11 +0000310 // The initializer may differ in type from the global. Rewrite
311 // the global to match the initializer. (We have to do this
312 // because some types, like unions, can't be completely represented
313 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000314 if (GV->getType()->getElementType() != Init->getType()) {
315 llvm::GlobalVariable *OldGV = GV;
316
317 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
318 OldGV->isConstant(),
319 OldGV->getLinkage(), Init, "",
320 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000321 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000322 CGM.getContext().getTargetAddressSpace(D.getType()));
323 GV->setVisibility(OldGV->getVisibility());
Reid Klecknereab97d32015-07-20 20:35:30 +0000324 GV->setComdat(OldGV->getComdat());
Eric Christopher31ab1302011-08-23 22:38:00 +0000325
Chris Lattnere99c1102009-12-05 08:22:11 +0000326 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000327 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000328
Chris Lattnere99c1102009-12-05 08:22:11 +0000329 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000330 llvm::Constant *NewPtrForOldDecl =
331 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
332 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000333
Chris Lattnere99c1102009-12-05 08:22:11 +0000334 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000335 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000336 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000337
Chandler Carruth84537952012-03-30 19:44:53 +0000338 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
339 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000340
341 if (hasNontrivialDestruction(D.getType())) {
342 // We have a constant initializer, but a nontrivial destructor. We still
343 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000344 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000345 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000346 }
347
Chandler Carruth84537952012-03-30 19:44:53 +0000348 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000349}
350
John McCall1c9c3fd2010-10-15 04:57:14 +0000351void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000352 llvm::GlobalValue::LinkageTypes Linkage) {
John McCallb88a5662012-03-30 21:00:39 +0000353 // Check to see if we already have a global variable for this
354 // declaration. This can happen when double-emitting function
355 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000356 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
John McCall7f416cc2015-09-08 08:05:57 +0000357 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara374e602009-02-25 19:45:19 +0000358
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000359 // Store into LocalDeclMap before generating initializer to handle
360 // circular references.
John McCall7f416cc2015-09-08 08:05:57 +0000361 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000362
John McCall4a39ab82010-05-04 20:45:42 +0000363 // We can't have a VLA here, but we can have a pointer to a VLA,
364 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000365 // Make sure to evaluate VLA bounds now so that we have them for later.
366 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000367 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000368
John McCallb88a5662012-03-30 21:00:39 +0000369 // Save the type in case adding the initializer forces a type change.
370 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000371
Eli Benderskycb399432014-03-24 22:05:38 +0000372 llvm::GlobalVariable *var =
373 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Artem Belevich4d430ba2016-05-09 22:09:56 +0000374
375 // CUDA's local and local static __shared__ variables should not
376 // have any non-empty initializers. This is ensured by Sema.
377 // Whatever initializer such variable may have when it gets here is
378 // a no-op and should not be emitted.
379 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
380 D.hasAttr<CUDASharedAttr>();
Chris Lattnere99c1102009-12-05 08:22:11 +0000381 // If this value has an initializer, emit it.
Artem Belevich4d430ba2016-05-09 22:09:56 +0000382 if (D.getInit() && !isCudaSharedVar)
John McCallb88a5662012-03-30 21:00:39 +0000383 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000384
John McCall7f416cc2015-09-08 08:05:57 +0000385 var->setAlignment(alignment.getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000386
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000387 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000388 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000389
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000390 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000391 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000392
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000393 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000394 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000395
Chandler Carruth84537952012-03-30 19:44:53 +0000396 // We may have to cast the constant because of the initializer
397 // mismatch above.
398 //
399 // FIXME: It is really dangerous to store this in the map; if anyone
400 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000401 llvm::Constant *castedAddr =
402 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCall7f416cc2015-09-08 08:05:57 +0000403 if (var != castedAddr)
404 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCallb88a5662012-03-30 21:00:39 +0000405 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000406
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000407 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000408
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000409 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000410 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000411 if (DI &&
Benjamin Kramer8c305922016-02-02 11:06:51 +0000412 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000413 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000414 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000415 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000416}
Mike Stump11289f42009-09-09 15:08:12 +0000417
John McCall2b7fc382010-07-13 20:32:21 +0000418namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000419 struct DestroyObject final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000420 DestroyObject(Address addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000421 CodeGenFunction::Destroyer *destroyer,
422 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000423 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000424 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000425
John McCall7f416cc2015-09-08 08:05:57 +0000426 Address addr;
John McCall82fe67b2011-07-09 01:37:26 +0000427 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000428 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000429 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000430
Craig Topper4f12f102014-03-12 06:41:41 +0000431 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000432 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000433 bool useEHCleanupForArray =
434 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000435
436 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000437 }
438 };
439
David Blaikie7e70d682015-08-18 22:40:54 +0000440 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000441 DestroyNRVOVariable(Address addr,
John McCall82fe67b2011-07-09 01:37:26 +0000442 const CXXDestructorDecl *Dtor,
443 llvm::Value *NRVOFlag)
444 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000445
446 const CXXDestructorDecl *Dtor;
447 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000448 Address Loc;
John McCall2b7fc382010-07-13 20:32:21 +0000449
Craig Topper4f12f102014-03-12 06:41:41 +0000450 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000451 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000452 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000453
Craig Topper8a13c412014-05-21 05:09:00 +0000454 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000455 if (NRVO) {
456 // If we exited via NRVO, we skip the destructor call.
457 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
458 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000459 llvm::Value *DidNRVO =
460 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000461 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
462 CGF.EmitBlock(RunDtorBB);
463 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000464
John McCall2b7fc382010-07-13 20:32:21 +0000465 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +0000466 /*ForVirtualBase=*/false,
467 /*Delegating=*/false,
468 Loc);
John McCall2b7fc382010-07-13 20:32:21 +0000469
470 if (NRVO) CGF.EmitBlock(SkipDtorBB);
471 }
472 };
John McCall2b7fc382010-07-13 20:32:21 +0000473
David Blaikie7e70d682015-08-18 22:40:54 +0000474 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000475 Address Stack;
476 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000477 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000478 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000479 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
480 CGF.Builder.CreateCall(F, V);
481 }
482 };
483
David Blaikie7e70d682015-08-18 22:40:54 +0000484 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000485 const VarDecl &Var;
486 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
487
Craig Topper4f12f102014-03-12 06:41:41 +0000488 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000489 // Compute the address of the local variable, in case it's a
490 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000491 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
492 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000493 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
494 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000495 CGF.EmitExtendGCLifetime(value);
496 }
497 };
498
David Blaikie7e70d682015-08-18 22:40:54 +0000499 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000500 llvm::Constant *CleanupFn;
501 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000502 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000503
John McCalla464ff92010-07-21 06:13:08 +0000504 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000505 const VarDecl *Var)
506 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000507
Craig Topper4f12f102014-03-12 06:41:41 +0000508 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000509 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
510 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000511 // Compute the address of the local variable, in case it's a byref
512 // or something.
John McCall7f416cc2015-09-08 08:05:57 +0000513 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCallc533cb72011-02-22 06:44:22 +0000514
John McCalla464ff92010-07-21 06:13:08 +0000515 // In some cases, the type of the function argument will be different from
516 // the type of the pointer. An example of this is
517 // void f(void* arg);
518 // __attribute__((cleanup(f))) void *g;
519 //
520 // To fix this we insert a bitcast here.
521 QualType ArgTy = FnInfo.arg_begin()->type;
522 llvm::Value *Arg =
523 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
524
525 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000526 Args.add(RValue::get(Arg),
527 CGF.getContext().getPointerType(Var.getType()));
John McCalla464ff92010-07-21 06:13:08 +0000528 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
529 }
530 };
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000531
532 /// A cleanup to call @llvm.lifetime.end.
David Blaikie7e70d682015-08-18 22:40:54 +0000533 class CallLifetimeEnd final : public EHScopeStack::Cleanup {
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000534 llvm::Value *Addr;
535 llvm::Value *Size;
536 public:
John McCall7f416cc2015-09-08 08:05:57 +0000537 CallLifetimeEnd(Address addr, llvm::Value *size)
538 : Addr(addr.getPointer()), Size(size) {}
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000539
540 void Emit(CodeGenFunction &CGF, Flags flags) override {
David Majnemerdc012fa2015-04-22 21:38:15 +0000541 CGF.EmitLifetimeEnd(Size, Addr);
Arnaud A. de Grandmaison6e24a462014-07-21 19:47:02 +0000542 }
543 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000544} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000545
John McCall31168b02011-06-15 23:02:42 +0000546/// EmitAutoVarWithLifetime - Does the setup required for an automatic
547/// variable with lifetime.
548static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000549 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000550 Qualifiers::ObjCLifetime lifetime) {
551 switch (lifetime) {
552 case Qualifiers::OCL_None:
553 llvm_unreachable("present but none");
554
555 case Qualifiers::OCL_ExplicitNone:
556 // nothing to do
557 break;
558
559 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000560 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000561 (var.hasAttr<ObjCPreciseLifetimeAttr>()
562 ? CodeGenFunction::destroyARCStrongPrecise
563 : CodeGenFunction::destroyARCStrongImprecise);
564
565 CleanupKind cleanupKind = CGF.getARCCleanupKind();
566 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
567 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000568 break;
569 }
570 case Qualifiers::OCL_Autoreleasing:
571 // nothing to do
572 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000573
John McCall31168b02011-06-15 23:02:42 +0000574 case Qualifiers::OCL_Weak:
575 // __weak objects always get EH cleanups; otherwise, exceptions
576 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000577 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
578 CodeGenFunction::destroyARCWeak,
579 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000580 break;
581 }
582}
583
584static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
585 if (const Expr *e = dyn_cast<Expr>(s)) {
586 // Skip the most common kinds of expressions that make
587 // hierarchy-walking expensive.
588 s = e = e->IgnoreParenCasts();
589
590 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
591 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000592 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
593 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000594 for (const auto &I : block->captures()) {
595 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000596 return true;
597 }
598 }
John McCall31168b02011-06-15 23:02:42 +0000599 }
600
Benjamin Kramer642f1732015-07-02 21:03:14 +0000601 for (const Stmt *SubStmt : s->children())
602 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
603 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000604 return true;
605
606 return false;
607}
608
609static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
610 if (!decl) return false;
611 if (!isa<VarDecl>(decl)) return false;
612 const VarDecl *var = cast<VarDecl>(decl);
613 return isAccessedBy(*var, e);
614}
615
John McCallf8a9b662015-10-21 18:06:31 +0000616static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
617 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000618 bool needsCast = false;
619
John McCallf8a9b662015-10-21 18:06:31 +0000620 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
621 switch (castExpr->getCastKind()) {
622 // Look through casts that don't require representation changes.
623 case CK_NoOp:
624 case CK_BitCast:
625 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000626 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000627 break;
628
629 // If we find an l-value to r-value cast from a __weak variable,
630 // emit this operation as a copy or move.
631 case CK_LValueToRValue: {
632 const Expr *srcExpr = castExpr->getSubExpr();
633 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
634 return false;
635
636 // Emit the source l-value.
637 LValue srcLV = CGF.EmitLValue(srcExpr);
638
John McCall0204e342015-11-16 22:11:41 +0000639 // Handle a formal type change to avoid asserting.
640 auto srcAddr = srcLV.getAddress();
641 if (needsCast) {
642 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
643 destLV.getAddress().getElementType());
644 }
645
John McCallf8a9b662015-10-21 18:06:31 +0000646 // If it was an l-value, use objc_copyWeak.
647 if (srcExpr->getValueKind() == VK_LValue) {
John McCall0204e342015-11-16 22:11:41 +0000648 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000649 } else {
650 assert(srcExpr->getValueKind() == VK_XValue);
John McCall0204e342015-11-16 22:11:41 +0000651 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000652 }
653 return true;
654 }
655
656 // Stop at anything else.
657 default:
658 return false;
659 }
660
661 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000662 }
663 return false;
664}
665
John McCall1553b192011-06-16 04:16:24 +0000666static void drillIntoBlockVariable(CodeGenFunction &CGF,
667 LValue &lvalue,
668 const VarDecl *var) {
John McCall7f416cc2015-09-08 08:05:57 +0000669 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCall1553b192011-06-16 04:16:24 +0000670}
671
David Blaikie73ca5692014-12-09 00:32:22 +0000672void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000673 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000674 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000675 if (!lifetime) {
676 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000677 if (capturedByInit)
678 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +0000679 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000680 return;
681 }
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000682
683 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
684 init = DIE->getExpr();
685
John McCall31168b02011-06-15 23:02:42 +0000686 // If we're emitting a value with lifetime, we have to do the
687 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000688 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
689 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000690 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000691 }
692 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000693
694 // We have to maintain the illusion that the variable is
695 // zero-initialized. If the variable might be accessed in its
696 // initializer, zero-initialize before running the initializer, then
697 // actually perform the initialization with an assign.
698 bool accessedByInit = false;
699 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000700 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000701 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000702 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000703 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000704 if (capturedByInit) {
705 // We can use a simple GEP for this because it can't have been
706 // moved yet.
John McCall7f416cc2015-09-08 08:05:57 +0000707 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
708 cast<VarDecl>(D),
709 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000710 }
711
John McCall7f416cc2015-09-08 08:05:57 +0000712 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
John McCall31168b02011-06-15 23:02:42 +0000713 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000714
John McCall31168b02011-06-15 23:02:42 +0000715 // If __weak, we want to use a barrier under certain conditions.
716 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000717 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000718
719 // Otherwise just do a simple store.
720 else
David Chisnallfa35df62012-01-16 17:27:18 +0000721 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000722 }
723
724 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000725 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000726
727 switch (lifetime) {
728 case Qualifiers::OCL_None:
729 llvm_unreachable("present but none");
730
731 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000732 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000733 break;
734
735 case Qualifiers::OCL_Strong: {
736 value = EmitARCRetainScalarExpr(init);
737 break;
738 }
739
740 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000741 // If it's not accessed by the initializer, try to emit the
742 // initialization with a copy or move.
743 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
744 return;
745 }
746
John McCall31168b02011-06-15 23:02:42 +0000747 // No way to optimize a producing initializer into this. It's not
748 // worth optimizing for, because the value will immediately
749 // disappear in the common case.
750 value = EmitScalarExpr(init);
751
John McCall1553b192011-06-16 04:16:24 +0000752 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000753 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000754 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000755 else
John McCall1553b192011-06-16 04:16:24 +0000756 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000757 return;
758 }
759
760 case Qualifiers::OCL_Autoreleasing:
761 value = EmitARCRetainAutoreleaseScalarExpr(init);
762 break;
763 }
764
John McCall1553b192011-06-16 04:16:24 +0000765 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000766
767 // If the variable might have been accessed by its initializer, we
768 // might have to initialize with a barrier. We have to do this for
769 // both __weak and __strong, but __weak got filtered out above.
770 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000771 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000772 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000773 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000774 return;
775 }
776
David Chisnallfa35df62012-01-16 17:27:18 +0000777 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000778}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000779
John McCalld4631322011-06-17 06:42:21 +0000780/// EmitScalarInit - Initialize the given lvalue with the given object.
781void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
782 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
783 if (!lifetime)
David Chisnallfa35df62012-01-16 17:27:18 +0000784 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCalld4631322011-06-17 06:42:21 +0000785
786 switch (lifetime) {
787 case Qualifiers::OCL_None:
788 llvm_unreachable("present but none");
789
790 case Qualifiers::OCL_ExplicitNone:
791 // nothing to do
792 break;
793
794 case Qualifiers::OCL_Strong:
795 init = EmitARCRetain(lvalue.getType(), init);
796 break;
797
798 case Qualifiers::OCL_Weak:
799 // Initialize and then skip the primitive store.
800 EmitARCInitWeak(lvalue.getAddress(), init);
801 return;
802
803 case Qualifiers::OCL_Autoreleasing:
804 init = EmitARCRetainAutorelease(lvalue.getType(), init);
805 break;
806 }
807
David Chisnallfa35df62012-01-16 17:27:18 +0000808 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCalld4631322011-06-17 06:42:21 +0000809}
810
Chris Lattnerb85025f2010-12-01 02:05:19 +0000811/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
812/// non-zero parts of the specified initializer with equal or fewer than
813/// NumStores scalar stores.
814static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
815 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000816 // Zero and Undef never requires any extra stores.
817 if (isa<llvm::ConstantAggregateZero>(Init) ||
818 isa<llvm::ConstantPointerNull>(Init) ||
819 isa<llvm::UndefValue>(Init))
820 return true;
821 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
822 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
823 isa<llvm::ConstantExpr>(Init))
824 return Init->isNullValue() || NumStores--;
825
826 // See if we can emit each element.
827 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
828 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
829 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
830 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
831 return false;
832 }
833 return true;
834 }
Chris Lattner236b3572012-01-31 04:36:19 +0000835
836 if (llvm::ConstantDataSequential *CDS =
837 dyn_cast<llvm::ConstantDataSequential>(Init)) {
838 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
839 llvm::Constant *Elt = CDS->getElementAsConstant(i);
840 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
841 return false;
842 }
843 return true;
844 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000845
Chris Lattnerb85025f2010-12-01 02:05:19 +0000846 // Anything else is hard and scary.
847 return false;
848}
849
850/// emitStoresForInitAfterMemset - For inits that
851/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
852/// stores that would be required.
853static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000854 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000855 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
856 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000857
Chris Lattnere6af8862010-12-02 01:58:41 +0000858 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
859 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
860 isa<llvm::ConstantExpr>(Init)) {
John McCall7f416cc2015-09-08 08:05:57 +0000861 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000862 return;
863 }
864
865 if (llvm::ConstantDataSequential *CDS =
866 dyn_cast<llvm::ConstantDataSequential>(Init)) {
867 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
868 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000869
870 // If necessary, get a pointer to the element and emit it.
871 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000872 emitStoresForInitAfterMemset(
873 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
874 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000875 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000876 return;
877 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000878
Chris Lattnere6af8862010-12-02 01:58:41 +0000879 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
880 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000881
Chris Lattnere6af8862010-12-02 01:58:41 +0000882 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
883 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000884
885 // If necessary, get a pointer to the element and emit it.
886 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000887 emitStoresForInitAfterMemset(
888 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
889 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000890 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000891}
892
Chris Lattnerb85025f2010-12-01 02:05:19 +0000893/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
894/// plus some stores to initialize a local variable instead of using a memcpy
895/// from a constant global. It is beneficial to use memset if the global is all
896/// zeros, or mostly zeros and large.
897static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
898 uint64_t GlobalSize) {
899 // If a global is all zeros, always use a memset.
900 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
901
Chris Lattnerb85025f2010-12-01 02:05:19 +0000902 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
903 // do it if it will require 6 or fewer scalar stores.
904 // TODO: Should budget depends on the size? Avoiding a large global warrants
905 // plopping in more stores.
906 unsigned StoreBudget = 6;
907 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000908
909 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000910 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
911}
912
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000913/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000914/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000915/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000916void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
917 AutoVarEmission emission = EmitAutoVarAlloca(D);
918 EmitAutoVarInit(emission);
919 EmitAutoVarCleanups(emission);
920}
Chris Lattner03df1222007-06-02 04:53:11 +0000921
David Majnemerdc012fa2015-04-22 21:38:15 +0000922/// Emit a lifetime.begin marker if some criteria are satisfied.
923/// \return a pointer to the temporary size Value if a marker was emitted, null
924/// otherwise
925llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
926 llvm::Value *Addr) {
927 // For now, only in optimized builds.
928 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
929 return nullptr;
930
Reid Kleckner1ef49212015-04-23 18:07:13 +0000931 // Disable lifetime markers in msan builds.
932 // FIXME: Remove this when msan works with lifetime markers.
933 if (getLangOpts().Sanitize.has(SanitizerKind::Memory))
934 return nullptr;
935
David Majnemerdc012fa2015-04-22 21:38:15 +0000936 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000937 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
938 llvm::CallInst *C =
939 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000940 C->setDoesNotThrow();
941 return SizeV;
942}
943
944void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000945 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
946 llvm::CallInst *C =
947 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000948 C->setDoesNotThrow();
949}
950
John McCallc533cb72011-02-22 06:44:22 +0000951/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000952/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +0000953CodeGenFunction::AutoVarEmission
954CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
955 QualType Ty = D.getType();
956
957 AutoVarEmission emission(D);
958
959 bool isByRef = D.hasAttr<BlocksAttr>();
960 emission.IsByRef = isByRef;
961
962 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +0000963
John McCall23c29fe2011-06-24 21:55:10 +0000964 // If the type is variably-modified, emit all the VLA sizes for it.
965 if (Ty->isVariablyModifiedType())
966 EmitVariablyModifiedType(Ty);
967
John McCall7f416cc2015-09-08 08:05:57 +0000968 Address address = Address::invalid();
Eli Friedmana682d392008-02-15 12:20:59 +0000969 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000970 bool NRVO = getLangOpts().ElideConstructors &&
971 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +0000972
Richard Smith2bcde3a2013-06-02 00:09:52 +0000973 // If this value is an array or struct with a statically determinable
974 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +0000975 //
976 // TODO: We should constant-evaluate the initializer of any variable,
977 // as long as it is initialized by a constant expression. Currently,
978 // isConstantInitializer produces wrong answers for structs with
979 // reference or bitfield members, and a few other cases, and checking
980 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +0000981 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
982 (D.isConstexpr() ||
983 ((Ty.isPODType(getContext()) ||
984 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
985 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +0000986
Rafael Espindola609f5d92013-03-26 18:41:47 +0000987 // If the variable's a const type, and it's neither an NRVO
988 // candidate nor a __block variable and has no mutable members,
989 // emit it as a global instead.
990 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
991 CGM.isTypeConstant(Ty, true)) {
992 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +0000993
John McCall7f416cc2015-09-08 08:05:57 +0000994 // Signal this condition to later callbacks.
995 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +0000996 assert(emission.wasEmittedAsGlobal());
997 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +0000998 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000999
Rafael Espindola609f5d92013-03-26 18:41:47 +00001000 // Otherwise, tell the initialization code that we're in this case.
1001 emission.IsConstantAggregate = true;
1002 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001003
Rafael Espindola609f5d92013-03-26 18:41:47 +00001004 // A normal fixed sized variable becomes an alloca in the entry block,
1005 // unless it's an NRVO variable.
Eric Christopher31ab1302011-08-23 22:38:00 +00001006
Rafael Espindola609f5d92013-03-26 18:41:47 +00001007 if (NRVO) {
1008 // The named return value optimization: allocate this variable in the
1009 // return slot, so that we can elide the copy when returning this
1010 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +00001011 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +00001012
Rafael Espindola609f5d92013-03-26 18:41:47 +00001013 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1014 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
1015 // Create a flag that is used to indicate when the NRVO was applied
1016 // to this variable. Set it to zero to indicate that NRVO was not
1017 // applied.
1018 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +00001019 Address NRVOFlag =
1020 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +00001021 EnsureInsertPoint();
1022 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +00001023
Rafael Espindola609f5d92013-03-26 18:41:47 +00001024 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +00001025 NRVOFlags[&D] = NRVOFlag.getPointer();
1026 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +00001027 }
Douglas Gregor290c93e2010-05-15 06:46:45 +00001028 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001029 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001030 CharUnits allocaAlignment;
1031 llvm::Type *allocaTy;
1032 if (isByRef) {
1033 auto &byrefInfo = getBlockByrefInfo(&D);
1034 allocaTy = byrefInfo.Type;
1035 allocaAlignment = byrefInfo.ByrefAlignment;
1036 } else {
1037 allocaTy = ConvertTypeForMem(Ty);
1038 allocaAlignment = alignment;
1039 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001040
John McCall999110f2015-09-08 09:18:30 +00001041 // Create the alloca. Note that we set the name separately from
1042 // building the instruction so that it's there even in no-asserts
1043 // builds.
1044 address = CreateTempAlloca(allocaTy, allocaAlignment);
1045 address.getPointer()->setName(D.getName());
Rafael Espindola609f5d92013-03-26 18:41:47 +00001046
Reid Kleckner1f88e932015-10-07 21:03:41 +00001047 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1048 // the catch parameter starts in the catchpad instruction, and we can't
1049 // insert code in those basic blocks.
1050 bool IsMSCatchParam =
1051 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1052
Rafael Espindola609f5d92013-03-26 18:41:47 +00001053 // Emit a lifetime intrinsic if meaningful. There's no point
1054 // in doing this if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001055 if (HaveInsertPoint() && !IsMSCatchParam) {
John McCall7f416cc2015-09-08 08:05:57 +00001056 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1057 emission.SizeForLifetimeMarkers =
1058 EmitLifetimeStart(size, address.getPointer());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001059 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001060 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001061 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001062 }
Chris Lattner03df1222007-06-02 04:53:11 +00001063 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001064 EnsureInsertPoint();
1065
Anders Carlsson15949b32009-02-09 20:41:50 +00001066 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001067 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001068 Address Stack =
1069 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001070
Anders Carlsson30032882008-12-12 07:38:43 +00001071 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001072 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001073 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001074
1075 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001076
John McCalla464ff92010-07-21 06:13:08 +00001077 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001078 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001079 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001080 }
Mike Stump11289f42009-09-09 15:08:12 +00001081
John McCall23c29fe2011-06-24 21:55:10 +00001082 llvm::Value *elementCount;
1083 QualType elementType;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001084 std::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +00001085
Chris Lattner2192fe52011-07-18 04:24:23 +00001086 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +00001087
1088 // Allocate memory for the array.
John McCall23c29fe2011-06-24 21:55:10 +00001089 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1090 vla->setAlignment(alignment.getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +00001091
John McCall7f416cc2015-09-08 08:05:57 +00001092 address = Address(vla, alignment);
Chris Lattner03df1222007-06-02 04:53:11 +00001093 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001094
John McCall7f416cc2015-09-08 08:05:57 +00001095 setAddrOfLocalVar(&D, address);
1096 emission.Addr = address;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001097
1098 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +00001099 if (HaveInsertPoint())
1100 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001101 if (CGM.getCodeGenOpts().getDebugInfo() >=
1102 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001103 DI->setLocation(D.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001104 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001105 }
Devang Patel887e2152011-06-03 19:21:47 +00001106 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001107
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001108 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001109 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001110
John McCallc533cb72011-02-22 06:44:22 +00001111 return emission;
1112}
1113
1114/// Determines whether the given __block variable is potentially
1115/// captured by the given expression.
1116static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1117 // Skip the most common kinds of expressions that make
1118 // hierarchy-walking expensive.
1119 e = e->IgnoreParenCasts();
1120
1121 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1122 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +00001123 for (const auto &I : block->captures()) {
1124 if (I.getVariable() == &var)
John McCallc533cb72011-02-22 06:44:22 +00001125 return true;
1126 }
1127
1128 // No need to walk into the subexpressions.
1129 return false;
1130 }
1131
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001132 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1133 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001134 for (const auto *BI : CS->body())
1135 if (const auto *E = dyn_cast<Expr>(BI)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001136 if (isCapturedBy(var, E))
1137 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001138 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001139 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001140 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001141 for (const auto *I : DS->decls()) {
1142 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1143 const Expr *Init = VD->getInit();
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001144 if (Init && isCapturedBy(var, Init))
1145 return true;
1146 }
1147 }
1148 }
1149 else
1150 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1151 // Later, provide code to poke into statements for capture analysis.
1152 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001153 return false;
1154 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001155
Benjamin Kramer642f1732015-07-02 21:03:14 +00001156 for (const Stmt *SubStmt : e->children())
1157 if (isCapturedBy(var, cast<Expr>(SubStmt)))
John McCallc533cb72011-02-22 06:44:22 +00001158 return true;
1159
1160 return false;
1161}
1162
Douglas Gregor82e1af22011-07-01 21:08:19 +00001163/// \brief Determine whether the given initializer is trivial in the sense
1164/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001165bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001166 if (!Init)
1167 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001168
Douglas Gregor82e1af22011-07-01 21:08:19 +00001169 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1170 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1171 if (Constructor->isTrivial() &&
1172 Constructor->isDefaultConstructor() &&
1173 !Construct->requiresZeroInitialization())
1174 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001175
Douglas Gregor82e1af22011-07-01 21:08:19 +00001176 return false;
1177}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001178
John McCallc533cb72011-02-22 06:44:22 +00001179void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001180 assert(emission.Variable && "emission was not valid!");
1181
John McCallc533cb72011-02-22 06:44:22 +00001182 // If this was emitted as a global constant, we're done.
1183 if (emission.wasEmittedAsGlobal()) return;
1184
John McCall9e2e22f2011-02-22 07:16:58 +00001185 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001186 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001187 QualType type = D.getType();
1188
Chris Lattner07eb7332007-07-12 00:39:48 +00001189 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001190 const Expr *Init = D.getInit();
1191
1192 // If we are at an unreachable point, we don't need to emit the initializer
1193 // unless it contains a label.
1194 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001195 if (!Init || !ContainsLabel(Init)) return;
1196 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001197 }
1198
John McCall73064872011-03-31 01:59:53 +00001199 // Initialize the structure of a __block variable.
1200 if (emission.IsByRef)
1201 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001202
Douglas Gregor82e1af22011-07-01 21:08:19 +00001203 if (isTrivialInitializer(Init))
1204 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001205
John McCallc533cb72011-02-22 06:44:22 +00001206 // Check whether this is a byref variable that's potentially
1207 // captured and moved by its own initializer. If so, we'll need to
1208 // emit the initializer first, then copy into the variable.
1209 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1210
John McCall7f416cc2015-09-08 08:05:57 +00001211 Address Loc =
1212 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
John McCallc533cb72011-02-22 06:44:22 +00001213
Craig Topper8a13c412014-05-21 05:09:00 +00001214 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001215 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001216 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smithdafff942012-01-14 04:30:29 +00001217 constant = CGM.EmitConstantInit(D, this);
Richard Smithfddd3842011-12-30 21:15:51 +00001218 }
1219
1220 if (!constant) {
John McCall7f416cc2015-09-08 08:05:57 +00001221 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001222 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001223 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001224 }
John McCall91ca10f2011-03-08 09:11:50 +00001225
Richard Smith2bcde3a2013-06-02 00:09:52 +00001226 if (!emission.IsConstantAggregate) {
1227 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001228 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001229 lv.setNonGC(true);
1230 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1231 }
1232
John McCallc533cb72011-02-22 06:44:22 +00001233 // If this is a simple aggregate initialization, we can optimize it
1234 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001235 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001236
John McCall91ca10f2011-03-08 09:11:50 +00001237 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001238 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001239 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001240
Chris Lattner2192fe52011-07-18 04:24:23 +00001241 llvm::Type *BP = Int8PtrTy;
John McCall7f416cc2015-09-08 08:05:57 +00001242 if (Loc.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001243 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001244
John McCall91ca10f2011-03-08 09:11:50 +00001245 // If the initializer is all or mostly zeros, codegen with memset then do
1246 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001247 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001248 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall91ca10f2011-03-08 09:11:50 +00001249 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
John McCall7f416cc2015-09-08 08:05:57 +00001250 isVolatile);
Benjamin Kramer29f9a002012-08-27 22:07:02 +00001251 // Zero and undef don't require a stores.
1252 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall91ca10f2011-03-08 09:11:50 +00001253 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001254 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1255 isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001256 }
John McCall91ca10f2011-03-08 09:11:50 +00001257 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001258 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001259 // memcpy from the global to the alloca.
Reid Kleckner453e0562014-10-08 01:07:54 +00001260 std::string Name = getStaticDeclName(CGM, D);
John McCall91ca10f2011-03-08 09:11:50 +00001261 llvm::GlobalVariable *GV =
1262 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001263 llvm::GlobalValue::PrivateLinkage,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001264 constant, Name);
John McCall7f416cc2015-09-08 08:05:57 +00001265 GV->setAlignment(Loc.getAlignment().getQuantity());
Eli Friedmanb8578422011-05-27 22:32:55 +00001266 GV->setUnnamedAddr(true);
Eric Christopher31ab1302011-08-23 22:38:00 +00001267
John McCall7f416cc2015-09-08 08:05:57 +00001268 Address SrcPtr = Address(GV, Loc.getAlignment());
1269 if (SrcPtr.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001270 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001271
John McCall7f416cc2015-09-08 08:05:57 +00001272 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
John McCall91ca10f2011-03-08 09:11:50 +00001273 }
1274}
1275
1276/// Emit an expression as an initializer for a variable at the given
1277/// location. The expression is not necessarily the normal
1278/// initializer for the variable, and the address is not necessarily
1279/// its normal location.
1280///
1281/// \param init the initializing expression
1282/// \param var the variable to act as if we're initializing
1283/// \param loc the address to initialize; its type is a pointer
1284/// to the LLVM mapping of the variable's type
1285/// \param alignment the alignment of the address
1286/// \param capturedByInit true if the variable is a __block variable
1287/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001288void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001289 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001290 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001291
1292 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001293 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001294 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001295 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001296 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001297 return;
1298 }
1299 switch (getEvaluationKind(type)) {
1300 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001301 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001302 return;
1303 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001304 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001305 if (capturedByInit)
1306 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001307 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001308 return;
1309 }
1310 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001311 if (type->isAtomicType()) {
1312 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1313 } else {
1314 // TODO: how can we delay here if D is captured by its initializer?
1315 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001316 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001317 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001318 AggValueSlot::IsNotAliased));
John McCalla8ec7eb2013-03-07 21:37:17 +00001319 }
John McCall47fb9502013-03-07 21:37:08 +00001320 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001321 }
John McCall47fb9502013-03-07 21:37:08 +00001322 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001323}
John McCallbd309292010-07-06 01:34:17 +00001324
John McCall82fe67b2011-07-09 01:37:26 +00001325/// Enter a destroy cleanup for the given local variable.
1326void CodeGenFunction::emitAutoVarTypeCleanup(
1327 const CodeGenFunction::AutoVarEmission &emission,
1328 QualType::DestructionKind dtorKind) {
1329 assert(dtorKind != QualType::DK_none);
1330
1331 // Note that for __block variables, we want to destroy the
1332 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001333 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001334
1335 const VarDecl *var = emission.Variable;
1336 QualType type = var->getType();
1337
1338 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001339 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001340
1341 switch (dtorKind) {
1342 case QualType::DK_none:
1343 llvm_unreachable("no cleanup for trivially-destructible variable");
1344
1345 case QualType::DK_cxx_destructor:
1346 // If there's an NRVO flag on the emission, we need a different
1347 // cleanup.
1348 if (emission.NRVOFlag) {
1349 assert(!type->isArrayType());
1350 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +00001351 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1352 dtor, emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001353 return;
1354 }
1355 break;
1356
1357 case QualType::DK_objc_strong_lifetime:
1358 // Suppress cleanups for pseudo-strong variables.
1359 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001360
John McCall82fe67b2011-07-09 01:37:26 +00001361 // Otherwise, consider whether to use an EH cleanup or not.
1362 cleanupKind = getARCCleanupKind();
1363
1364 // Use the imprecise destroyer by default.
1365 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1366 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1367 break;
1368
1369 case QualType::DK_objc_weak_lifetime:
1370 break;
1371 }
1372
1373 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001374 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001375
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001376 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001377 // is being pushed as an EH cleanup.
1378 bool useEHCleanup = (cleanupKind & EHCleanup);
1379 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1380 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001381}
1382
John McCallc533cb72011-02-22 06:44:22 +00001383void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001384 assert(emission.Variable && "emission was not valid!");
1385
John McCallc533cb72011-02-22 06:44:22 +00001386 // If this was emitted as a global constant, we're done.
1387 if (emission.wasEmittedAsGlobal()) return;
1388
John McCall8c38d352012-04-13 18:44:05 +00001389 // If we don't have an insertion point, we're done. Sema prevents
1390 // us from jumping into any of these scopes anyway.
1391 if (!HaveInsertPoint()) return;
1392
John McCall9e2e22f2011-02-22 07:16:58 +00001393 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001394
Nadav Rotem1da30942013-03-23 06:43:35 +00001395 // Make sure we call @llvm.lifetime.end. This needs to happen
1396 // *last*, so the cleanup needs to be pushed *first*.
1397 if (emission.useLifetimeMarkers()) {
Akira Hatanaka8af7bb22016-04-01 22:58:55 +00001398 EHStack.pushCleanup<CallLifetimeEnd>(NormalAndEHCleanup,
Nadav Rotem1da30942013-03-23 06:43:35 +00001399 emission.getAllocatedAddress(),
1400 emission.getSizeForLifetimeMarkers());
David Majnemerdc012fa2015-04-22 21:38:15 +00001401 EHCleanupScope &cleanup = cast<EHCleanupScope>(*EHStack.begin());
1402 cleanup.setLifetimeMarker();
Nadav Rotem1da30942013-03-23 06:43:35 +00001403 }
1404
John McCall82fe67b2011-07-09 01:37:26 +00001405 // Check the type for a cleanup.
1406 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1407 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001408
John McCall1bd25562011-06-24 23:21:27 +00001409 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001410 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001411 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1412 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1413 }
1414
John McCallc533cb72011-02-22 06:44:22 +00001415 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001416 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001417 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001418
John McCallc533cb72011-02-22 06:44:22 +00001419 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001420 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001421
John McCalla729c622012-02-17 03:33:10 +00001422 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001423 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001424 }
Mike Stump626aecc2009-03-05 01:23:13 +00001425
John McCallc533cb72011-02-22 06:44:22 +00001426 // If this is a block variable, call _Block_object_destroy
1427 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001428 if (emission.IsByRef)
1429 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001430}
Chris Lattner53621a52007-06-13 20:44:40 +00001431
Peter Collingbourne1425b452012-01-26 03:33:36 +00001432CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001433CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1434 switch (kind) {
1435 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001436 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001437 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001438 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001439 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001440 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001441 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001442 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001443 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001444}
1445
John McCall12cc42a2013-02-01 05:11:40 +00001446/// pushEHDestroy - Push the standard destructor for the given type as
1447/// an EH-only cleanup.
1448void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001449 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00001450 assert(dtorKind && "cannot push destructor for trivial type");
1451 assert(needsEHCleanup(dtorKind));
1452
1453 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1454}
1455
1456/// pushDestroy - Push the standard destructor for the given type as
1457/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001458void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001459 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00001460 assert(dtorKind && "cannot push destructor for trivial type");
1461
1462 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1463 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1464 cleanupKind & EHCleanup);
1465}
1466
John McCall7f416cc2015-09-08 08:05:57 +00001467void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001468 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001469 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001470 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1471 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001472}
1473
John McCall7f416cc2015-09-08 08:05:57 +00001474void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001475 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1476}
1477
Richard Smith736a9472013-06-12 20:42:33 +00001478void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00001479 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00001480 Destroyer *destroyer, bool useEHCleanupForArray) {
1481 assert(!isInConditionalBranch() &&
1482 "performing lifetime extension from within conditional");
1483
1484 // Push an EH-only cleanup for the object now.
1485 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1486 // around in case a temporary's destructor throws an exception.
1487 if (cleanupKind & EHCleanup)
1488 EHStack.pushCleanup<DestroyObject>(
1489 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1490 destroyer, useEHCleanupForArray);
1491
1492 // Remember that we need to push a full cleanup for the object at the
1493 // end of the full-expression.
1494 pushCleanupAfterFullExpr<DestroyObject>(
1495 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1496}
1497
John McCall178360e2011-07-11 08:38:19 +00001498/// emitDestroy - Immediately perform the destruction of the given
1499/// object.
1500///
1501/// \param addr - the address of the object; a type*
1502/// \param type - the type of the object; if an array type, all
1503/// objects are destroyed in reverse order
1504/// \param destroyer - the function to call to destroy individual
1505/// elements
1506/// \param useEHCleanupForArray - whether an EH cleanup should be
1507/// used when destroying array elements, in case one of the
1508/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00001509void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001510 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001511 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001512 const ArrayType *arrayType = getContext().getAsArrayType(type);
1513 if (!arrayType)
1514 return destroyer(*this, addr, type);
1515
John McCall7f416cc2015-09-08 08:05:57 +00001516 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1517
1518 CharUnits elementAlign =
1519 addr.getAlignment()
1520 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00001521
1522 // Normally we have to check whether the array is zero-length.
1523 bool checkZeroLength = true;
1524
1525 // But if the array length is constant, we can suppress that.
1526 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1527 // ...and if it's constant zero, we can just skip the entire thing.
1528 if (constLength->isZero()) return;
1529 checkZeroLength = false;
1530 }
1531
John McCall7f416cc2015-09-08 08:05:57 +00001532 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00001533 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00001534 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001535 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001536}
1537
John McCall178360e2011-07-11 08:38:19 +00001538/// emitArrayDestroy - Destroys all the elements of the given array,
1539/// beginning from last to first. The array cannot be zero-length.
1540///
1541/// \param begin - a type* denoting the first element of the array
1542/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001543/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00001544/// \param destroyer - the function to call to destroy elements
1545/// \param useEHCleanup - whether to push an EH cleanup to destroy
1546/// the remaining elements in case the destruction of a single
1547/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001548void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1549 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001550 QualType elementType,
1551 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001552 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001553 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001554 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00001555 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00001556
1557 // The basic structure here is a do-while loop, because we don't
1558 // need to check for the zero-element case.
1559 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1560 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1561
John McCall97eab0a2011-07-13 08:09:46 +00001562 if (checkZeroLength) {
1563 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1564 "arraydestroy.isempty");
1565 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1566 }
1567
John McCall82fe67b2011-07-09 01:37:26 +00001568 // Enter the loop body, making that address the current address.
1569 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1570 EmitBlock(bodyBB);
1571 llvm::PHINode *elementPast =
1572 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1573 elementPast->addIncoming(end, entryBB);
1574
1575 // Shift the address back by one element.
1576 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1577 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1578 "arraydestroy.element");
1579
John McCall178360e2011-07-11 08:38:19 +00001580 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00001581 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1582 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001583
John McCall82fe67b2011-07-09 01:37:26 +00001584 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00001585 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00001586
John McCall178360e2011-07-11 08:38:19 +00001587 if (useEHCleanup)
1588 PopCleanupBlock();
1589
John McCall82fe67b2011-07-09 01:37:26 +00001590 // Check whether we've reached the end.
1591 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1592 Builder.CreateCondBr(done, doneBB, bodyBB);
1593 elementPast->addIncoming(element, Builder.GetInsertBlock());
1594
1595 // Done.
1596 EmitBlock(doneBB);
1597}
1598
John McCall178360e2011-07-11 08:38:19 +00001599/// Perform partial array destruction as if in an EH cleanup. Unlike
1600/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001601static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1602 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001603 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001604 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001605 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001606 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001607 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1608 // VLAs don't require a GEP index to walk into.
1609 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001610 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001611 type = arrayType->getElementType();
1612 }
John McCall97eab0a2011-07-13 08:09:46 +00001613
1614 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00001615 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00001616
John McCallf0f0b7a2015-09-14 18:57:08 +00001617 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001618 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1619 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001620 }
1621
John McCall97eab0a2011-07-13 08:09:46 +00001622 // Destroy the array. We don't ever need an EH cleanup because we
1623 // assume that we're in an EH cleanup ourselves, so a throwing
1624 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00001625 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001626 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001627}
1628
John McCall82fe67b2011-07-09 01:37:26 +00001629namespace {
John McCall178360e2011-07-11 08:38:19 +00001630 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1631 /// array destroy where the end pointer is regularly determined and
1632 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001633 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00001634 llvm::Value *ArrayBegin;
1635 llvm::Value *ArrayEnd;
1636 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001637 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001638 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00001639 public:
1640 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001641 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001642 CodeGenFunction::Destroyer *destroyer)
1643 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00001644 ElementType(elementType), Destroyer(destroyer),
1645 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00001646
Craig Topper4f12f102014-03-12 06:41:41 +00001647 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001648 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001649 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00001650 }
1651 };
1652
1653 /// IrregularPartialArrayDestroy - a cleanup which performs a
1654 /// partial array destroy where the end pointer is irregularly
1655 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001656 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001657 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00001658 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00001659 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001660 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001661 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00001662 public:
John McCall178360e2011-07-11 08:38:19 +00001663 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001664 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001665 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001666 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001667 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001668 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00001669 ElementType(elementType), Destroyer(destroyer),
1670 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00001671
Craig Topper4f12f102014-03-12 06:41:41 +00001672 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001673 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001674 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001675 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001676 }
1677 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001678} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00001679
John McCall178360e2011-07-11 08:38:19 +00001680/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001681/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001682/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001683///
John McCall82fe67b2011-07-09 01:37:26 +00001684/// \param elementType - the immediate element type of the array;
1685/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001686void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001687 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001688 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001689 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001690 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001691 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1692 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00001693 elementType, elementAlign,
1694 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001695}
1696
1697/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1698/// already-constructed elements of the given array. The cleanup
1699/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001700///
John McCall178360e2011-07-11 08:38:19 +00001701/// \param elementType - the immediate element type of the array;
1702/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001703void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1704 llvm::Value *arrayEnd,
1705 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001706 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001707 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001708 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001709 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001710 elementType, elementAlign,
1711 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001712}
1713
Nadav Rotem1da30942013-03-23 06:43:35 +00001714/// Lazily declare the @llvm.lifetime.start intrinsic.
1715llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1716 if (LifetimeStartFn) return LifetimeStartFn;
1717 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1718 llvm::Intrinsic::lifetime_start);
1719 return LifetimeStartFn;
1720}
1721
1722/// Lazily declare the @llvm.lifetime.end intrinsic.
1723llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1724 if (LifetimeEndFn) return LifetimeEndFn;
1725 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1726 llvm::Intrinsic::lifetime_end);
1727 return LifetimeEndFn;
1728}
1729
John McCall31168b02011-06-15 23:02:42 +00001730namespace {
1731 /// A cleanup to perform a release of an object at the end of a
1732 /// function. This is used to balance out the incoming +1 of a
1733 /// ns_consumed argument when we can't reasonably do that just by
1734 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00001735 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001736 ConsumeARCParameter(llvm::Value *param,
1737 ARCPreciseLifetime_t precise)
1738 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001739
1740 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001741 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001742
Craig Topper4f12f102014-03-12 06:41:41 +00001743 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001744 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001745 }
1746 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001747} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00001748
Mike Stump11289f42009-09-09 15:08:12 +00001749/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001750/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00001751void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1752 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001753 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001754 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001755 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001756
John McCall7f416cc2015-09-08 08:05:57 +00001757 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00001758
Adrian Prantl51936dd2013-03-14 17:53:33 +00001759 QualType Ty = D.getType();
1760
John McCall147d0212011-02-22 22:38:33 +00001761 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00001762 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00001763 // The only implicit argument a block has is its literal.
John McCall7f416cc2015-09-08 08:05:57 +00001764 // We assume this is always passed directly.
John McCall147d0212011-02-22 22:38:33 +00001765 if (BlockInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001766 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
John McCall147d0212011-02-22 22:38:33 +00001767 return;
1768 }
1769 }
1770
John McCall7f416cc2015-09-08 08:05:57 +00001771 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001772 bool DoStore = false;
1773 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001774 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001775 if (Arg.isIndirect()) {
1776 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001777 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00001778 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001779 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00001780 if (DeclPtr.getType() != IRTy)
1781 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1782
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001783 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00001784 // Don't push a cleanup in a thunk for a method that will also emit a
1785 // cleanup.
1786 if (!IsScalar && !CurFuncIsThunk &&
Reid Kleckner739756c2013-12-04 19:23:12 +00001787 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001788 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1789 if (RD && RD->hasNonTrivialDestructor())
1790 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001791 }
Chris Lattner53621a52007-06-13 20:44:40 +00001792 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001793 // Otherwise, create a temporary to hold the value.
John McCall7f416cc2015-09-08 08:05:57 +00001794 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1795 D.getName() + ".addr");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001796 DoStore = true;
1797 }
Mike Stump11289f42009-09-09 15:08:12 +00001798
John McCall7f416cc2015-09-08 08:05:57 +00001799 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1800
1801 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001802 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00001803 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001804 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1805 // We honor __attribute__((ns_consumed)) for types with lifetime.
1806 // For __strong, it's handled by just skipping the initial retain;
1807 // otherwise we have to balance out the initial +1 with an extra
1808 // cleanup to do the release at the end of the function.
1809 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1810
1811 // 'self' is always formally __strong, but if this is not an
1812 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001813 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001814 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1815 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001816 assert(lt == Qualifiers::OCL_Strong);
1817 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001818 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001819 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001820 lt = Qualifiers::OCL_ExplicitNone;
1821 }
1822
1823 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001824 if (!isConsumed) {
1825 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1826 // use objc_storeStrong(&dest, value) for retaining the
1827 // object. But first, store a null into 'dest' because
1828 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001829 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001830 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
John McCall7f416cc2015-09-08 08:05:57 +00001831 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001832 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001833 }
1834 else
John McCall31168b02011-06-15 23:02:42 +00001835 // Don't use objc_retainBlock for block pointers, because we
1836 // don't want to Block_copy something just because we got it
1837 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00001838 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001839 }
John McCall31168b02011-06-15 23:02:42 +00001840 } else {
1841 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00001842 if (isConsumed) {
1843 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1844 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00001845 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00001846 precise);
1847 }
John McCall31168b02011-06-15 23:02:42 +00001848
1849 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00001850 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001851 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001852 }
1853 }
1854
1855 // Enter the cleanup scope.
1856 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1857 }
Chris Lattner53621a52007-06-13 20:44:40 +00001858 }
1859
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001860 // Store the initial value into the alloca.
1861 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00001862 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001863
John McCall7f416cc2015-09-08 08:05:57 +00001864 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001865
1866 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001867 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001868 if (CGM.getCodeGenOpts().getDebugInfo() >=
1869 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001870 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001871 }
1872 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001873
1874 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001875 EmitVarAnnotations(&D, DeclPtr.getPointer());
Chris Lattner53621a52007-06-13 20:44:40 +00001876}
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001877
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001878void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1879 CodeGenFunction *CGF) {
1880 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1881 return;
1882 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
1883}