blob: 037b1351c0f5562f202effb8657ffc91be18d087 [file] [log] [blame]
Chris Lattner84915fa2007-06-02 04:16:21 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner84915fa2007-06-02 04:16:21 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Decl nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
John McCall7f416cc2015-09-08 08:05:57 +000015#include "CGBlocks.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000016#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGDebugInfo.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000018#include "CGOpenCLRuntime.h"
Alexey Bataevc5b1d322016-03-04 09:22:22 +000019#include "CGOpenMPRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "CodeGenModule.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000021#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000022#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000023#include "clang/AST/Decl.h"
Anders Carlsson4c03d982008-08-25 01:38:19 +000024#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000025#include "clang/AST/DeclOpenMP.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000026#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000027#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000028#include "clang/CodeGen/CGFunctionInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000029#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/GlobalVariable.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/Type.h"
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +000034
Chris Lattner84915fa2007-06-02 04:16:21 +000035using namespace clang;
36using namespace CodeGen;
37
Chris Lattner1ad38f82007-06-09 01:20:56 +000038void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000039 switch (D.getKind()) {
David Majnemerd9b1a4f2015-11-04 03:40:30 +000040 case Decl::BuiltinTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000041 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +000042 case Decl::ExternCContext:
Douglas Gregor19043f02010-04-23 02:02:43 +000043 case Decl::Namespace:
44 case Decl::UnresolvedUsingTypename:
45 case Decl::ClassTemplateSpecialization:
46 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000047 case Decl::VarTemplateSpecialization:
48 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000049 case Decl::TemplateTypeParm:
50 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000051 case Decl::NonTypeTemplateParm:
Douglas Gregor19043f02010-04-23 02:02:43 +000052 case Decl::CXXMethod:
53 case Decl::CXXConstructor:
54 case Decl::CXXDestructor:
55 case Decl::CXXConversion:
56 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000057 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000058 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000059 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000060 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000061 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000062 case Decl::ImplicitParam:
63 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000064 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000065 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000066 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000067 case Decl::TemplateTemplateParm:
68 case Decl::ObjCMethod:
69 case Decl::ObjCCategory:
70 case Decl::ObjCProtocol:
71 case Decl::ObjCInterface:
72 case Decl::ObjCCategoryImpl:
73 case Decl::ObjCImplementation:
74 case Decl::ObjCProperty:
75 case Decl::ObjCCompatibleAlias:
Nico Weber66220292016-03-02 17:28:48 +000076 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +000077 case Decl::PragmaDetectMismatch:
Abramo Bagnarad7340582010-06-05 05:09:32 +000078 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000079 case Decl::LinkageSpec:
80 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000081 case Decl::FileScopeAsm:
82 case Decl::Friend:
83 case Decl::FriendTemplate:
84 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000085 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000086 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000087 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +000088 case Decl::ConstructorUsingShadow:
Douglas Gregor85f3f952015-07-07 03:57:15 +000089 case Decl::ObjCTypeParam:
Richard Smithda383632016-08-15 01:33:41 +000090 case Decl::Binding:
David Blaikie83d382b2011-09-23 05:06:16 +000091 llvm_unreachable("Declaration should not be in declstmts!");
Amjad Abouddc4531e2016-04-30 01:44:38 +000092 case Decl::Function: // void X();
93 case Decl::Record: // struct/union/class X;
94 case Decl::Enum: // enum X;
95 case Decl::EnumConstant: // enum ? { X = ? }
96 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +000097 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +000098 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +000099 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000100 case Decl::OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000101 case Decl::OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +0000102 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +0000103 // None of these decls require codegen support.
104 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +0000105
David Blaikief121b932013-05-20 22:50:41 +0000106 case Decl::NamespaceAlias:
107 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000108 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
David Blaikief121b932013-05-20 22:50:41 +0000109 return;
David Blaikiebd483762013-05-20 04:58:53 +0000110 case Decl::Using: // using X; [C++]
111 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000112 DI->EmitUsingDecl(cast<UsingDecl>(D));
David Blaikiebd483762013-05-20 04:58:53 +0000113 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000114 case Decl::UsingDirective: // using namespace X; [C++]
115 if (CGDebugInfo *DI = getDebugInfo())
116 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
117 return;
Richard Smithbdb84f32016-07-22 23:36:59 +0000118 case Decl::Var:
119 case Decl::Decomposition: {
Daniel Dunbara7998072008-08-29 17:28:43 +0000120 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000121 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000122 "Should not see file-scope variables inside a function!");
Richard Smithda383632016-08-15 01:33:41 +0000123 EmitVarDecl(VD);
124 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
125 for (auto *B : DD->bindings())
126 if (auto *HD = B->getHoldingVar())
127 EmitVarDecl(*HD);
128 return;
Chris Lattner84915fa2007-06-02 04:16:21 +0000129 }
Mike Stump11289f42009-09-09 15:08:12 +0000130
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000131 case Decl::OMPDeclareReduction:
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000132 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000133
Richard Smithdda56e42011-04-15 14:24:37 +0000134 case Decl::Typedef: // typedef int X;
135 case Decl::TypeAlias: { // using X = int; [C++0x]
136 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000137 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000138
Anders Carlsson5d985f52008-12-20 21:51:53 +0000139 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000140 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000141 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000142 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000143}
Chris Lattner03df1222007-06-02 04:53:11 +0000144
John McCall1c9c3fd2010-10-15 04:57:14 +0000145/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000146/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000147void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000148 if (D.isStaticLocal()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000149 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000150 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000151
David Majnemer27d69db2014-04-28 22:17:59 +0000152 // FIXME: We need to force the emission/use of a guard variable for
153 // some variables even if we can constant-evaluate them because
154 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000155
John McCall1c9c3fd2010-10-15 04:57:14 +0000156 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000157 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000158
159 if (D.hasExternalStorage())
Lauro Ramos Venanciobada8d42008-02-16 22:30:38 +0000160 // Don't emit it now, allow it to be emitted lazily on its first use.
161 return;
Daniel Dunbar0ca16602009-04-14 02:25:56 +0000162
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000163 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000164 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
165
166 assert(D.hasLocalStorage());
167 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000168}
169
Reid Kleckner453e0562014-10-08 01:07:54 +0000170static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
171 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000172 return CGM.getMangledName(&D).str();
173
Reid Kleckner453e0562014-10-08 01:07:54 +0000174 // If this isn't C++, we don't need a mangled name, just a pretty one.
175 assert(!D.isExternallyVisible() && "name shouldn't matter");
176 std::string ContextName;
177 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000178 if (auto *CD = dyn_cast<CapturedDecl>(DC))
179 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000180 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000181 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000182 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
183 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
184 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
185 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000186 else
David Blaikie83d382b2011-09-23 05:06:16 +0000187 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000188
Reid Kleckner453e0562014-10-08 01:07:54 +0000189 ContextName += "." + D.getNameAsString();
190 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000191}
192
Reid Kleckner453e0562014-10-08 01:07:54 +0000193llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
194 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
195 // In general, we don't always emit static var decls once before we reference
196 // them. It is possible to reference them before emitting the function that
197 // contains them, and it is possible to emit the containing function multiple
198 // times.
199 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
200 return ExistingGV;
201
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000202 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000203 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000204
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000205 // Use the label if the variable is renamed with the asm-label extension.
206 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000207 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000208 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000209 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000210 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000211
Reid Kleckner453e0562014-10-08 01:07:54 +0000212 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000213 unsigned AddrSpace =
Reid Kleckner453e0562014-10-08 01:07:54 +0000214 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000215
216 // Local address space cannot have an initializer.
217 llvm::Constant *Init = nullptr;
218 if (Ty.getAddressSpace() != LangAS::opencl_local)
219 Init = EmitNullConstant(Ty);
220 else
221 Init = llvm::UndefValue::get(LTy);
222
Anders Carlssone33eed52009-09-26 18:16:06 +0000223 llvm::GlobalVariable *GV =
Reid Kleckner453e0562014-10-08 01:07:54 +0000224 new llvm::GlobalVariable(getModule(), LTy,
Anders Carlssone33eed52009-09-26 18:16:06 +0000225 Ty.isConstant(getContext()), Linkage,
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000226 Init, Name, nullptr,
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000227 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000228 AddrSpace);
Ken Dyck160146e2010-01-27 17:10:57 +0000229 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Reid Kleckner453e0562014-10-08 01:07:54 +0000230 setGlobalVisibility(GV, &D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000231
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000232 if (supportsCOMDAT() && GV->isWeakForLinker())
233 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000234
Richard Smithfd3834f2013-04-13 02:43:54 +0000235 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000236 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000237
Hans Wennborgef2272c2014-06-18 15:55:13 +0000238 if (D.isExternallyVisible()) {
239 if (D.hasAttr<DLLImportAttr>())
240 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
241 else if (D.hasAttr<DLLExportAttr>())
242 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
243 }
244
Eli Benderskycb399432014-03-24 22:05:38 +0000245 // Make sure the result is of the correct type.
Reid Kleckner453e0562014-10-08 01:07:54 +0000246 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
247 llvm::Constant *Addr = GV;
Eli Benderskycb399432014-03-24 22:05:38 +0000248 if (AddrSpace != ExpectedAddrSpace) {
249 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
Reid Kleckner453e0562014-10-08 01:07:54 +0000250 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
Eli Benderskycb399432014-03-24 22:05:38 +0000251 }
252
Reid Kleckner453e0562014-10-08 01:07:54 +0000253 setStaticLocalDeclAddress(&D, Addr);
254
255 // Ensure that the static local gets initialized by making sure the parent
256 // function gets emitted eventually.
257 const Decl *DC = cast<Decl>(D.getDeclContext());
258
259 // We can't name blocks or captured statements directly, so try to emit their
260 // parents.
261 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
262 DC = DC->getNonClosureContext();
263 // FIXME: Ensure that global blocks get emitted.
264 if (!DC)
265 return Addr;
266 }
267
268 GlobalDecl GD;
269 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
270 GD = GlobalDecl(CD, Ctor_Base);
271 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
272 GD = GlobalDecl(DD, Dtor_Base);
273 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
274 GD = GlobalDecl(FD);
275 else {
276 // Don't do anything for Obj-C method decls or global closures. We should
277 // never defer them.
278 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
279 }
280 if (GD.getDecl())
281 (void)GetAddrOfGlobal(GD);
282
283 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000284}
285
Richard Smith6331c402012-02-13 22:16:19 +0000286/// hasNontrivialDestruction - Determine whether a type's destruction is
287/// non-trivial. If so, and the variable uses static initialization, we must
288/// register its destructor to run on exit.
289static bool hasNontrivialDestruction(QualType T) {
290 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
291 return RD && !RD->hasTrivialDestructor();
292}
293
Chandler Carruth84537952012-03-30 19:44:53 +0000294/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
295/// global variable that has already been created for it. If the initializer
296/// has a different type than GV does, this may free GV and return a different
297/// one. Otherwise it just returns GV.
298llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000299CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000300 llvm::GlobalVariable *GV) {
301 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCall70013b62010-07-15 23:40:35 +0000302
Chris Lattnere99c1102009-12-05 08:22:11 +0000303 // If constant emission failed, then this should be a C++ static
304 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000305 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000306 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000307 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
John McCall68ff0372010-09-08 01:44:27 +0000308 else if (Builder.GetInsertBlock()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000309 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000310 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000311 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000312
Chandler Carruth84537952012-03-30 19:44:53 +0000313 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000314 }
Chandler Carruth84537952012-03-30 19:44:53 +0000315 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000316 }
John McCall70013b62010-07-15 23:40:35 +0000317
Chris Lattnere99c1102009-12-05 08:22:11 +0000318 // The initializer may differ in type from the global. Rewrite
319 // the global to match the initializer. (We have to do this
320 // because some types, like unions, can't be completely represented
321 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000322 if (GV->getType()->getElementType() != Init->getType()) {
323 llvm::GlobalVariable *OldGV = GV;
324
325 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
326 OldGV->isConstant(),
327 OldGV->getLinkage(), Init, "",
328 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000329 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000330 CGM.getContext().getTargetAddressSpace(D.getType()));
331 GV->setVisibility(OldGV->getVisibility());
Reid Klecknereab97d32015-07-20 20:35:30 +0000332 GV->setComdat(OldGV->getComdat());
Eric Christopher31ab1302011-08-23 22:38:00 +0000333
Chris Lattnere99c1102009-12-05 08:22:11 +0000334 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000335 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000336
Chris Lattnere99c1102009-12-05 08:22:11 +0000337 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000338 llvm::Constant *NewPtrForOldDecl =
339 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
340 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000341
Chris Lattnere99c1102009-12-05 08:22:11 +0000342 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000343 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000344 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000345
Chandler Carruth84537952012-03-30 19:44:53 +0000346 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
347 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000348
349 if (hasNontrivialDestruction(D.getType())) {
350 // We have a constant initializer, but a nontrivial destructor. We still
351 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000352 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000353 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000354 }
355
Chandler Carruth84537952012-03-30 19:44:53 +0000356 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000357}
358
John McCall1c9c3fd2010-10-15 04:57:14 +0000359void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000360 llvm::GlobalValue::LinkageTypes Linkage) {
John McCallb88a5662012-03-30 21:00:39 +0000361 // Check to see if we already have a global variable for this
362 // declaration. This can happen when double-emitting function
363 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000364 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
John McCall7f416cc2015-09-08 08:05:57 +0000365 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara374e602009-02-25 19:45:19 +0000366
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000367 // Store into LocalDeclMap before generating initializer to handle
368 // circular references.
John McCall7f416cc2015-09-08 08:05:57 +0000369 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000370
John McCall4a39ab82010-05-04 20:45:42 +0000371 // We can't have a VLA here, but we can have a pointer to a VLA,
372 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000373 // Make sure to evaluate VLA bounds now so that we have them for later.
374 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000375 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000376
John McCallb88a5662012-03-30 21:00:39 +0000377 // Save the type in case adding the initializer forces a type change.
378 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000379
Eli Benderskycb399432014-03-24 22:05:38 +0000380 llvm::GlobalVariable *var =
381 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Artem Belevich4d430ba2016-05-09 22:09:56 +0000382
383 // CUDA's local and local static __shared__ variables should not
384 // have any non-empty initializers. This is ensured by Sema.
385 // Whatever initializer such variable may have when it gets here is
386 // a no-op and should not be emitted.
387 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
388 D.hasAttr<CUDASharedAttr>();
Chris Lattnere99c1102009-12-05 08:22:11 +0000389 // If this value has an initializer, emit it.
Artem Belevich4d430ba2016-05-09 22:09:56 +0000390 if (D.getInit() && !isCudaSharedVar)
John McCallb88a5662012-03-30 21:00:39 +0000391 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000392
John McCall7f416cc2015-09-08 08:05:57 +0000393 var->setAlignment(alignment.getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000394
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000395 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000396 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000397
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000398 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000399 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000400
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000401 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000402 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000403
Chandler Carruth84537952012-03-30 19:44:53 +0000404 // We may have to cast the constant because of the initializer
405 // mismatch above.
406 //
407 // FIXME: It is really dangerous to store this in the map; if anyone
408 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000409 llvm::Constant *castedAddr =
410 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCall7f416cc2015-09-08 08:05:57 +0000411 if (var != castedAddr)
412 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCallb88a5662012-03-30 21:00:39 +0000413 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000414
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000415 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000416
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000417 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000418 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000419 if (DI &&
Benjamin Kramer8c305922016-02-02 11:06:51 +0000420 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000421 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000422 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000423 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000424}
Mike Stump11289f42009-09-09 15:08:12 +0000425
John McCall2b7fc382010-07-13 20:32:21 +0000426namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000427 struct DestroyObject final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000428 DestroyObject(Address addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000429 CodeGenFunction::Destroyer *destroyer,
430 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000431 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000432 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000433
John McCall7f416cc2015-09-08 08:05:57 +0000434 Address addr;
John McCall82fe67b2011-07-09 01:37:26 +0000435 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000436 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000437 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000438
Craig Topper4f12f102014-03-12 06:41:41 +0000439 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000440 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000441 bool useEHCleanupForArray =
442 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000443
444 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000445 }
446 };
447
David Blaikie7e70d682015-08-18 22:40:54 +0000448 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000449 DestroyNRVOVariable(Address addr,
John McCall82fe67b2011-07-09 01:37:26 +0000450 const CXXDestructorDecl *Dtor,
451 llvm::Value *NRVOFlag)
452 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000453
454 const CXXDestructorDecl *Dtor;
455 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000456 Address Loc;
John McCall2b7fc382010-07-13 20:32:21 +0000457
Craig Topper4f12f102014-03-12 06:41:41 +0000458 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000459 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000460 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000461
Craig Topper8a13c412014-05-21 05:09:00 +0000462 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000463 if (NRVO) {
464 // If we exited via NRVO, we skip the destructor call.
465 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
466 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000467 llvm::Value *DidNRVO =
468 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000469 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
470 CGF.EmitBlock(RunDtorBB);
471 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000472
John McCall2b7fc382010-07-13 20:32:21 +0000473 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +0000474 /*ForVirtualBase=*/false,
475 /*Delegating=*/false,
476 Loc);
John McCall2b7fc382010-07-13 20:32:21 +0000477
478 if (NRVO) CGF.EmitBlock(SkipDtorBB);
479 }
480 };
John McCall2b7fc382010-07-13 20:32:21 +0000481
David Blaikie7e70d682015-08-18 22:40:54 +0000482 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000483 Address Stack;
484 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000485 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000486 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000487 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
488 CGF.Builder.CreateCall(F, V);
489 }
490 };
491
David Blaikie7e70d682015-08-18 22:40:54 +0000492 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000493 const VarDecl &Var;
494 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
495
Craig Topper4f12f102014-03-12 06:41:41 +0000496 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000497 // Compute the address of the local variable, in case it's a
498 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000499 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
500 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000501 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
502 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000503 CGF.EmitExtendGCLifetime(value);
504 }
505 };
506
David Blaikie7e70d682015-08-18 22:40:54 +0000507 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000508 llvm::Constant *CleanupFn;
509 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000510 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000511
John McCalla464ff92010-07-21 06:13:08 +0000512 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000513 const VarDecl *Var)
514 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000515
Craig Topper4f12f102014-03-12 06:41:41 +0000516 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000517 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
518 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000519 // Compute the address of the local variable, in case it's a byref
520 // or something.
John McCall7f416cc2015-09-08 08:05:57 +0000521 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCallc533cb72011-02-22 06:44:22 +0000522
John McCalla464ff92010-07-21 06:13:08 +0000523 // In some cases, the type of the function argument will be different from
524 // the type of the pointer. An example of this is
525 // void f(void* arg);
526 // __attribute__((cleanup(f))) void *g;
527 //
528 // To fix this we insert a bitcast here.
529 QualType ArgTy = FnInfo.arg_begin()->type;
530 llvm::Value *Arg =
531 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
532
533 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000534 Args.add(RValue::get(Arg),
535 CGF.getContext().getPointerType(Var.getType()));
John McCalla464ff92010-07-21 06:13:08 +0000536 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
537 }
538 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000539} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000540
John McCall31168b02011-06-15 23:02:42 +0000541/// EmitAutoVarWithLifetime - Does the setup required for an automatic
542/// variable with lifetime.
543static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000544 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000545 Qualifiers::ObjCLifetime lifetime) {
546 switch (lifetime) {
547 case Qualifiers::OCL_None:
548 llvm_unreachable("present but none");
549
550 case Qualifiers::OCL_ExplicitNone:
551 // nothing to do
552 break;
553
554 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000555 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000556 (var.hasAttr<ObjCPreciseLifetimeAttr>()
557 ? CodeGenFunction::destroyARCStrongPrecise
558 : CodeGenFunction::destroyARCStrongImprecise);
559
560 CleanupKind cleanupKind = CGF.getARCCleanupKind();
561 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
562 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000563 break;
564 }
565 case Qualifiers::OCL_Autoreleasing:
566 // nothing to do
567 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000568
John McCall31168b02011-06-15 23:02:42 +0000569 case Qualifiers::OCL_Weak:
570 // __weak objects always get EH cleanups; otherwise, exceptions
571 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000572 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
573 CodeGenFunction::destroyARCWeak,
574 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000575 break;
576 }
577}
578
579static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
580 if (const Expr *e = dyn_cast<Expr>(s)) {
581 // Skip the most common kinds of expressions that make
582 // hierarchy-walking expensive.
583 s = e = e->IgnoreParenCasts();
584
585 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
586 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000587 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
588 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000589 for (const auto &I : block->captures()) {
590 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000591 return true;
592 }
593 }
John McCall31168b02011-06-15 23:02:42 +0000594 }
595
Benjamin Kramer642f1732015-07-02 21:03:14 +0000596 for (const Stmt *SubStmt : s->children())
597 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
598 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000599 return true;
600
601 return false;
602}
603
604static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
605 if (!decl) return false;
606 if (!isa<VarDecl>(decl)) return false;
607 const VarDecl *var = cast<VarDecl>(decl);
608 return isAccessedBy(*var, e);
609}
610
John McCallf8a9b662015-10-21 18:06:31 +0000611static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
612 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000613 bool needsCast = false;
614
John McCallf8a9b662015-10-21 18:06:31 +0000615 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
616 switch (castExpr->getCastKind()) {
617 // Look through casts that don't require representation changes.
618 case CK_NoOp:
619 case CK_BitCast:
620 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000621 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000622 break;
623
624 // If we find an l-value to r-value cast from a __weak variable,
625 // emit this operation as a copy or move.
626 case CK_LValueToRValue: {
627 const Expr *srcExpr = castExpr->getSubExpr();
628 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
629 return false;
630
631 // Emit the source l-value.
632 LValue srcLV = CGF.EmitLValue(srcExpr);
633
John McCall0204e342015-11-16 22:11:41 +0000634 // Handle a formal type change to avoid asserting.
635 auto srcAddr = srcLV.getAddress();
636 if (needsCast) {
637 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
638 destLV.getAddress().getElementType());
639 }
640
John McCallf8a9b662015-10-21 18:06:31 +0000641 // If it was an l-value, use objc_copyWeak.
642 if (srcExpr->getValueKind() == VK_LValue) {
John McCall0204e342015-11-16 22:11:41 +0000643 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000644 } else {
645 assert(srcExpr->getValueKind() == VK_XValue);
John McCall0204e342015-11-16 22:11:41 +0000646 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000647 }
648 return true;
649 }
650
651 // Stop at anything else.
652 default:
653 return false;
654 }
655
656 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000657 }
658 return false;
659}
660
John McCall1553b192011-06-16 04:16:24 +0000661static void drillIntoBlockVariable(CodeGenFunction &CGF,
662 LValue &lvalue,
663 const VarDecl *var) {
John McCall7f416cc2015-09-08 08:05:57 +0000664 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCall1553b192011-06-16 04:16:24 +0000665}
666
David Blaikie73ca5692014-12-09 00:32:22 +0000667void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000668 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000669 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000670 if (!lifetime) {
671 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000672 if (capturedByInit)
673 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +0000674 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000675 return;
676 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000677
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000678 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
679 init = DIE->getExpr();
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000680
John McCall31168b02011-06-15 23:02:42 +0000681 // If we're emitting a value with lifetime, we have to do the
682 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000683 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
684 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000685 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000686 }
687 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000688
689 // We have to maintain the illusion that the variable is
690 // zero-initialized. If the variable might be accessed in its
691 // initializer, zero-initialize before running the initializer, then
692 // actually perform the initialization with an assign.
693 bool accessedByInit = false;
694 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000695 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000696 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000697 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000698 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000699 if (capturedByInit) {
700 // We can use a simple GEP for this because it can't have been
701 // moved yet.
John McCall7f416cc2015-09-08 08:05:57 +0000702 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
703 cast<VarDecl>(D),
704 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000705 }
706
John McCall7f416cc2015-09-08 08:05:57 +0000707 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
John McCall31168b02011-06-15 23:02:42 +0000708 llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
Eric Christopher31ab1302011-08-23 22:38:00 +0000709
John McCall31168b02011-06-15 23:02:42 +0000710 // If __weak, we want to use a barrier under certain conditions.
711 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000712 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000713
714 // Otherwise just do a simple store.
715 else
David Chisnallfa35df62012-01-16 17:27:18 +0000716 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000717 }
718
719 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000720 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000721
722 switch (lifetime) {
723 case Qualifiers::OCL_None:
724 llvm_unreachable("present but none");
725
726 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000727 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000728 break;
729
730 case Qualifiers::OCL_Strong: {
731 value = EmitARCRetainScalarExpr(init);
732 break;
733 }
734
735 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000736 // If it's not accessed by the initializer, try to emit the
737 // initialization with a copy or move.
738 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
739 return;
740 }
741
John McCall31168b02011-06-15 23:02:42 +0000742 // No way to optimize a producing initializer into this. It's not
743 // worth optimizing for, because the value will immediately
744 // disappear in the common case.
745 value = EmitScalarExpr(init);
746
John McCall1553b192011-06-16 04:16:24 +0000747 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000748 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000749 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000750 else
John McCall1553b192011-06-16 04:16:24 +0000751 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000752 return;
753 }
754
755 case Qualifiers::OCL_Autoreleasing:
756 value = EmitARCRetainAutoreleaseScalarExpr(init);
757 break;
758 }
759
John McCall1553b192011-06-16 04:16:24 +0000760 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000761
762 // If the variable might have been accessed by its initializer, we
763 // might have to initialize with a barrier. We have to do this for
764 // both __weak and __strong, but __weak got filtered out above.
765 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000766 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000767 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000768 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000769 return;
770 }
771
David Chisnallfa35df62012-01-16 17:27:18 +0000772 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000773}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000774
John McCalld4631322011-06-17 06:42:21 +0000775/// EmitScalarInit - Initialize the given lvalue with the given object.
776void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
777 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
778 if (!lifetime)
David Chisnallfa35df62012-01-16 17:27:18 +0000779 return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
John McCalld4631322011-06-17 06:42:21 +0000780
781 switch (lifetime) {
782 case Qualifiers::OCL_None:
783 llvm_unreachable("present but none");
784
785 case Qualifiers::OCL_ExplicitNone:
786 // nothing to do
787 break;
788
789 case Qualifiers::OCL_Strong:
790 init = EmitARCRetain(lvalue.getType(), init);
791 break;
792
793 case Qualifiers::OCL_Weak:
794 // Initialize and then skip the primitive store.
795 EmitARCInitWeak(lvalue.getAddress(), init);
796 return;
797
798 case Qualifiers::OCL_Autoreleasing:
799 init = EmitARCRetainAutorelease(lvalue.getType(), init);
800 break;
801 }
802
David Chisnallfa35df62012-01-16 17:27:18 +0000803 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
John McCalld4631322011-06-17 06:42:21 +0000804}
805
Chris Lattnerb85025f2010-12-01 02:05:19 +0000806/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
807/// non-zero parts of the specified initializer with equal or fewer than
808/// NumStores scalar stores.
809static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
810 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000811 // Zero and Undef never requires any extra stores.
812 if (isa<llvm::ConstantAggregateZero>(Init) ||
813 isa<llvm::ConstantPointerNull>(Init) ||
814 isa<llvm::UndefValue>(Init))
815 return true;
816 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
817 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
818 isa<llvm::ConstantExpr>(Init))
819 return Init->isNullValue() || NumStores--;
820
821 // See if we can emit each element.
822 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
823 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
824 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
825 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
826 return false;
827 }
828 return true;
829 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000830
Chris Lattner236b3572012-01-31 04:36:19 +0000831 if (llvm::ConstantDataSequential *CDS =
832 dyn_cast<llvm::ConstantDataSequential>(Init)) {
833 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
834 llvm::Constant *Elt = CDS->getElementAsConstant(i);
835 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
836 return false;
837 }
838 return true;
839 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000840
Chris Lattnerb85025f2010-12-01 02:05:19 +0000841 // Anything else is hard and scary.
842 return false;
843}
844
845/// emitStoresForInitAfterMemset - For inits that
846/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
847/// stores that would be required.
848static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000849 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000850 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
851 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000852
Chris Lattnere6af8862010-12-02 01:58:41 +0000853 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
854 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
855 isa<llvm::ConstantExpr>(Init)) {
John McCall7f416cc2015-09-08 08:05:57 +0000856 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000857 return;
858 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000859
860 if (llvm::ConstantDataSequential *CDS =
861 dyn_cast<llvm::ConstantDataSequential>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000862 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
863 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000864
865 // If necessary, get a pointer to the element and emit it.
866 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000867 emitStoresForInitAfterMemset(
868 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
869 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000870 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000871 return;
872 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000873
Chris Lattnere6af8862010-12-02 01:58:41 +0000874 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
875 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000876
Chris Lattnere6af8862010-12-02 01:58:41 +0000877 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
878 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000879
880 // If necessary, get a pointer to the element and emit it.
881 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000882 emitStoresForInitAfterMemset(
883 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
884 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000885 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000886}
887
Chris Lattnerb85025f2010-12-01 02:05:19 +0000888/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
889/// plus some stores to initialize a local variable instead of using a memcpy
890/// from a constant global. It is beneficial to use memset if the global is all
891/// zeros, or mostly zeros and large.
892static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
893 uint64_t GlobalSize) {
894 // If a global is all zeros, always use a memset.
895 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
896
Chris Lattnerb85025f2010-12-01 02:05:19 +0000897 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
898 // do it if it will require 6 or fewer scalar stores.
899 // TODO: Should budget depends on the size? Avoiding a large global warrants
900 // plopping in more stores.
901 unsigned StoreBudget = 6;
902 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000903
904 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000905 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
906}
907
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000908/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000909/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000910/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000911void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
912 AutoVarEmission emission = EmitAutoVarAlloca(D);
913 EmitAutoVarInit(emission);
914 EmitAutoVarCleanups(emission);
915}
Chris Lattner03df1222007-06-02 04:53:11 +0000916
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000917/// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time
918/// markers.
919static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts,
920 const LangOptions &LangOpts) {
921 // Asan uses markers for use-after-scope checks.
922 if (CGOpts.SanitizeAddressUseAfterScope)
923 return true;
924
925 // Disable lifetime markers in msan builds.
926 // FIXME: Remove this when msan works with lifetime markers.
927 if (LangOpts.Sanitize.has(SanitizerKind::Memory))
928 return false;
929
930 // For now, only in optimized builds.
931 return CGOpts.OptimizationLevel != 0;
932}
933
David Majnemerdc012fa2015-04-22 21:38:15 +0000934/// Emit a lifetime.begin marker if some criteria are satisfied.
935/// \return a pointer to the temporary size Value if a marker was emitted, null
936/// otherwise
937llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
938 llvm::Value *Addr) {
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000939 if (!shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), getLangOpts()))
Reid Kleckner1ef49212015-04-23 18:07:13 +0000940 return nullptr;
941
David Majnemerdc012fa2015-04-22 21:38:15 +0000942 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000943 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
944 llvm::CallInst *C =
945 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000946 C->setDoesNotThrow();
947 return SizeV;
948}
949
950void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000951 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
952 llvm::CallInst *C =
953 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000954 C->setDoesNotThrow();
955}
956
John McCallc533cb72011-02-22 06:44:22 +0000957/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000958/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +0000959CodeGenFunction::AutoVarEmission
960CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
961 QualType Ty = D.getType();
962
963 AutoVarEmission emission(D);
964
965 bool isByRef = D.hasAttr<BlocksAttr>();
966 emission.IsByRef = isByRef;
967
968 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +0000969
John McCall23c29fe2011-06-24 21:55:10 +0000970 // If the type is variably-modified, emit all the VLA sizes for it.
971 if (Ty->isVariablyModifiedType())
972 EmitVariablyModifiedType(Ty);
973
John McCall7f416cc2015-09-08 08:05:57 +0000974 Address address = Address::invalid();
Eli Friedmana682d392008-02-15 12:20:59 +0000975 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000976 bool NRVO = getLangOpts().ElideConstructors &&
977 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +0000978
Richard Smith2bcde3a2013-06-02 00:09:52 +0000979 // If this value is an array or struct with a statically determinable
980 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +0000981 //
982 // TODO: We should constant-evaluate the initializer of any variable,
983 // as long as it is initialized by a constant expression. Currently,
984 // isConstantInitializer produces wrong answers for structs with
985 // reference or bitfield members, and a few other cases, and checking
986 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +0000987 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
988 (D.isConstexpr() ||
989 ((Ty.isPODType(getContext()) ||
990 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
991 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +0000992
Rafael Espindola609f5d92013-03-26 18:41:47 +0000993 // If the variable's a const type, and it's neither an NRVO
994 // candidate nor a __block variable and has no mutable members,
995 // emit it as a global instead.
996 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
997 CGM.isTypeConstant(Ty, true)) {
998 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +0000999
John McCall7f416cc2015-09-08 08:05:57 +00001000 // Signal this condition to later callbacks.
1001 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +00001002 assert(emission.wasEmittedAsGlobal());
1003 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +00001004 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001005
Rafael Espindola609f5d92013-03-26 18:41:47 +00001006 // Otherwise, tell the initialization code that we're in this case.
1007 emission.IsConstantAggregate = true;
1008 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001009
Rafael Espindola609f5d92013-03-26 18:41:47 +00001010 // A normal fixed sized variable becomes an alloca in the entry block,
1011 // unless it's an NRVO variable.
Eric Christopher31ab1302011-08-23 22:38:00 +00001012
Rafael Espindola609f5d92013-03-26 18:41:47 +00001013 if (NRVO) {
1014 // The named return value optimization: allocate this variable in the
1015 // return slot, so that we can elide the copy when returning this
1016 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +00001017 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +00001018
Rafael Espindola609f5d92013-03-26 18:41:47 +00001019 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1020 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
1021 // Create a flag that is used to indicate when the NRVO was applied
1022 // to this variable. Set it to zero to indicate that NRVO was not
1023 // applied.
1024 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +00001025 Address NRVOFlag =
1026 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +00001027 EnsureInsertPoint();
1028 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +00001029
Rafael Espindola609f5d92013-03-26 18:41:47 +00001030 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +00001031 NRVOFlags[&D] = NRVOFlag.getPointer();
1032 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +00001033 }
Douglas Gregor290c93e2010-05-15 06:46:45 +00001034 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001035 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001036 CharUnits allocaAlignment;
1037 llvm::Type *allocaTy;
1038 if (isByRef) {
1039 auto &byrefInfo = getBlockByrefInfo(&D);
1040 allocaTy = byrefInfo.Type;
1041 allocaAlignment = byrefInfo.ByrefAlignment;
1042 } else {
1043 allocaTy = ConvertTypeForMem(Ty);
1044 allocaAlignment = alignment;
1045 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001046
John McCall999110f2015-09-08 09:18:30 +00001047 // Create the alloca. Note that we set the name separately from
1048 // building the instruction so that it's there even in no-asserts
1049 // builds.
1050 address = CreateTempAlloca(allocaTy, allocaAlignment);
1051 address.getPointer()->setName(D.getName());
Rafael Espindola609f5d92013-03-26 18:41:47 +00001052
Reid Kleckner1f88e932015-10-07 21:03:41 +00001053 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1054 // the catch parameter starts in the catchpad instruction, and we can't
1055 // insert code in those basic blocks.
1056 bool IsMSCatchParam =
1057 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1058
Rafael Espindola609f5d92013-03-26 18:41:47 +00001059 // Emit a lifetime intrinsic if meaningful. There's no point
1060 // in doing this if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001061 if (HaveInsertPoint() && !IsMSCatchParam) {
John McCall7f416cc2015-09-08 08:05:57 +00001062 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1063 emission.SizeForLifetimeMarkers =
1064 EmitLifetimeStart(size, address.getPointer());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001065 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001066 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001067 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001068 }
Chris Lattner03df1222007-06-02 04:53:11 +00001069 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001070 EnsureInsertPoint();
1071
Anders Carlsson15949b32009-02-09 20:41:50 +00001072 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001073 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001074 Address Stack =
1075 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001076
Anders Carlsson30032882008-12-12 07:38:43 +00001077 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001078 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001079 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001080
1081 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001082
John McCalla464ff92010-07-21 06:13:08 +00001083 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001084 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001085 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001086 }
Mike Stump11289f42009-09-09 15:08:12 +00001087
John McCall23c29fe2011-06-24 21:55:10 +00001088 llvm::Value *elementCount;
1089 QualType elementType;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001090 std::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +00001091
Chris Lattner2192fe52011-07-18 04:24:23 +00001092 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +00001093
1094 // Allocate memory for the array.
John McCall23c29fe2011-06-24 21:55:10 +00001095 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1096 vla->setAlignment(alignment.getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +00001097
John McCall7f416cc2015-09-08 08:05:57 +00001098 address = Address(vla, alignment);
Chris Lattner03df1222007-06-02 04:53:11 +00001099 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001100
John McCall7f416cc2015-09-08 08:05:57 +00001101 setAddrOfLocalVar(&D, address);
1102 emission.Addr = address;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001103
1104 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +00001105 if (HaveInsertPoint())
1106 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001107 if (CGM.getCodeGenOpts().getDebugInfo() >=
1108 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001109 DI->setLocation(D.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001110 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001111 }
Devang Patel887e2152011-06-03 19:21:47 +00001112 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001113
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001114 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001115 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001116
John McCallc533cb72011-02-22 06:44:22 +00001117 return emission;
1118}
1119
1120/// Determines whether the given __block variable is potentially
1121/// captured by the given expression.
1122static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1123 // Skip the most common kinds of expressions that make
1124 // hierarchy-walking expensive.
1125 e = e->IgnoreParenCasts();
1126
1127 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1128 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +00001129 for (const auto &I : block->captures()) {
1130 if (I.getVariable() == &var)
John McCallc533cb72011-02-22 06:44:22 +00001131 return true;
1132 }
1133
1134 // No need to walk into the subexpressions.
1135 return false;
1136 }
1137
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001138 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1139 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001140 for (const auto *BI : CS->body())
1141 if (const auto *E = dyn_cast<Expr>(BI)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001142 if (isCapturedBy(var, E))
1143 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001144 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001145 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001146 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001147 for (const auto *I : DS->decls()) {
1148 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1149 const Expr *Init = VD->getInit();
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001150 if (Init && isCapturedBy(var, Init))
1151 return true;
1152 }
1153 }
1154 }
1155 else
1156 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1157 // Later, provide code to poke into statements for capture analysis.
1158 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001159 return false;
1160 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001161
Benjamin Kramer642f1732015-07-02 21:03:14 +00001162 for (const Stmt *SubStmt : e->children())
1163 if (isCapturedBy(var, cast<Expr>(SubStmt)))
John McCallc533cb72011-02-22 06:44:22 +00001164 return true;
1165
1166 return false;
1167}
1168
Douglas Gregor82e1af22011-07-01 21:08:19 +00001169/// \brief Determine whether the given initializer is trivial in the sense
1170/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001171bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001172 if (!Init)
1173 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001174
Douglas Gregor82e1af22011-07-01 21:08:19 +00001175 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1176 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1177 if (Constructor->isTrivial() &&
1178 Constructor->isDefaultConstructor() &&
1179 !Construct->requiresZeroInitialization())
1180 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001181
Douglas Gregor82e1af22011-07-01 21:08:19 +00001182 return false;
1183}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001184
John McCallc533cb72011-02-22 06:44:22 +00001185void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001186 assert(emission.Variable && "emission was not valid!");
1187
John McCallc533cb72011-02-22 06:44:22 +00001188 // If this was emitted as a global constant, we're done.
1189 if (emission.wasEmittedAsGlobal()) return;
1190
John McCall9e2e22f2011-02-22 07:16:58 +00001191 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001192 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001193 QualType type = D.getType();
1194
Chris Lattner07eb7332007-07-12 00:39:48 +00001195 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001196 const Expr *Init = D.getInit();
1197
1198 // If we are at an unreachable point, we don't need to emit the initializer
1199 // unless it contains a label.
1200 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001201 if (!Init || !ContainsLabel(Init)) return;
1202 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001203 }
1204
John McCall73064872011-03-31 01:59:53 +00001205 // Initialize the structure of a __block variable.
1206 if (emission.IsByRef)
1207 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001208
Douglas Gregor82e1af22011-07-01 21:08:19 +00001209 if (isTrivialInitializer(Init))
1210 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001211
John McCallc533cb72011-02-22 06:44:22 +00001212 // Check whether this is a byref variable that's potentially
1213 // captured and moved by its own initializer. If so, we'll need to
1214 // emit the initializer first, then copy into the variable.
1215 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1216
John McCall7f416cc2015-09-08 08:05:57 +00001217 Address Loc =
1218 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
John McCallc533cb72011-02-22 06:44:22 +00001219
Craig Topper8a13c412014-05-21 05:09:00 +00001220 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001221 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001222 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smithdafff942012-01-14 04:30:29 +00001223 constant = CGM.EmitConstantInit(D, this);
Richard Smithfddd3842011-12-30 21:15:51 +00001224 }
1225
1226 if (!constant) {
John McCall7f416cc2015-09-08 08:05:57 +00001227 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001228 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001229 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001230 }
John McCall91ca10f2011-03-08 09:11:50 +00001231
Richard Smith2bcde3a2013-06-02 00:09:52 +00001232 if (!emission.IsConstantAggregate) {
1233 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001234 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001235 lv.setNonGC(true);
1236 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1237 }
1238
John McCallc533cb72011-02-22 06:44:22 +00001239 // If this is a simple aggregate initialization, we can optimize it
1240 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001241 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001242
John McCall91ca10f2011-03-08 09:11:50 +00001243 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001244 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001245 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001246
Chris Lattner2192fe52011-07-18 04:24:23 +00001247 llvm::Type *BP = Int8PtrTy;
John McCall7f416cc2015-09-08 08:05:57 +00001248 if (Loc.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001249 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001250
John McCall91ca10f2011-03-08 09:11:50 +00001251 // If the initializer is all or mostly zeros, codegen with memset then do
1252 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001253 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001254 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall91ca10f2011-03-08 09:11:50 +00001255 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
John McCall7f416cc2015-09-08 08:05:57 +00001256 isVolatile);
Benjamin Kramer29f9a002012-08-27 22:07:02 +00001257 // Zero and undef don't require a stores.
1258 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall91ca10f2011-03-08 09:11:50 +00001259 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001260 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1261 isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001262 }
John McCall91ca10f2011-03-08 09:11:50 +00001263 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001264 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001265 // memcpy from the global to the alloca.
Reid Kleckner453e0562014-10-08 01:07:54 +00001266 std::string Name = getStaticDeclName(CGM, D);
John McCall91ca10f2011-03-08 09:11:50 +00001267 llvm::GlobalVariable *GV =
1268 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001269 llvm::GlobalValue::PrivateLinkage,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +00001270 constant, Name);
John McCall7f416cc2015-09-08 08:05:57 +00001271 GV->setAlignment(Loc.getAlignment().getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001272 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Eric Christopher31ab1302011-08-23 22:38:00 +00001273
John McCall7f416cc2015-09-08 08:05:57 +00001274 Address SrcPtr = Address(GV, Loc.getAlignment());
1275 if (SrcPtr.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001276 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001277
John McCall7f416cc2015-09-08 08:05:57 +00001278 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
John McCall91ca10f2011-03-08 09:11:50 +00001279 }
1280}
1281
1282/// Emit an expression as an initializer for a variable at the given
1283/// location. The expression is not necessarily the normal
1284/// initializer for the variable, and the address is not necessarily
1285/// its normal location.
1286///
1287/// \param init the initializing expression
1288/// \param var the variable to act as if we're initializing
1289/// \param loc the address to initialize; its type is a pointer
1290/// to the LLVM mapping of the variable's type
1291/// \param alignment the alignment of the address
1292/// \param capturedByInit true if the variable is a __block variable
1293/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001294void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001295 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001296 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001297
1298 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001299 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001300 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001301 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001302 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001303 return;
1304 }
1305 switch (getEvaluationKind(type)) {
1306 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001307 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001308 return;
1309 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001310 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001311 if (capturedByInit)
1312 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001313 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001314 return;
1315 }
1316 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001317 if (type->isAtomicType()) {
1318 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1319 } else {
1320 // TODO: how can we delay here if D is captured by its initializer?
1321 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001322 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001323 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001324 AggValueSlot::IsNotAliased));
John McCalla8ec7eb2013-03-07 21:37:17 +00001325 }
John McCall47fb9502013-03-07 21:37:08 +00001326 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001327 }
John McCall47fb9502013-03-07 21:37:08 +00001328 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001329}
John McCallbd309292010-07-06 01:34:17 +00001330
John McCall82fe67b2011-07-09 01:37:26 +00001331/// Enter a destroy cleanup for the given local variable.
1332void CodeGenFunction::emitAutoVarTypeCleanup(
1333 const CodeGenFunction::AutoVarEmission &emission,
1334 QualType::DestructionKind dtorKind) {
1335 assert(dtorKind != QualType::DK_none);
1336
1337 // Note that for __block variables, we want to destroy the
1338 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001339 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001340
1341 const VarDecl *var = emission.Variable;
1342 QualType type = var->getType();
1343
1344 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001345 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001346
1347 switch (dtorKind) {
1348 case QualType::DK_none:
1349 llvm_unreachable("no cleanup for trivially-destructible variable");
1350
1351 case QualType::DK_cxx_destructor:
1352 // If there's an NRVO flag on the emission, we need a different
1353 // cleanup.
1354 if (emission.NRVOFlag) {
1355 assert(!type->isArrayType());
1356 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +00001357 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1358 dtor, emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001359 return;
1360 }
1361 break;
1362
1363 case QualType::DK_objc_strong_lifetime:
1364 // Suppress cleanups for pseudo-strong variables.
1365 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001366
John McCall82fe67b2011-07-09 01:37:26 +00001367 // Otherwise, consider whether to use an EH cleanup or not.
1368 cleanupKind = getARCCleanupKind();
1369
1370 // Use the imprecise destroyer by default.
1371 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1372 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1373 break;
1374
1375 case QualType::DK_objc_weak_lifetime:
1376 break;
1377 }
1378
1379 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001380 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001381
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001382 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001383 // is being pushed as an EH cleanup.
1384 bool useEHCleanup = (cleanupKind & EHCleanup);
1385 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1386 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001387}
1388
John McCallc533cb72011-02-22 06:44:22 +00001389void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001390 assert(emission.Variable && "emission was not valid!");
1391
John McCallc533cb72011-02-22 06:44:22 +00001392 // If this was emitted as a global constant, we're done.
1393 if (emission.wasEmittedAsGlobal()) return;
1394
John McCall8c38d352012-04-13 18:44:05 +00001395 // If we don't have an insertion point, we're done. Sema prevents
1396 // us from jumping into any of these scopes anyway.
1397 if (!HaveInsertPoint()) return;
1398
John McCall9e2e22f2011-02-22 07:16:58 +00001399 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001400
Nadav Rotem1da30942013-03-23 06:43:35 +00001401 // Make sure we call @llvm.lifetime.end. This needs to happen
1402 // *last*, so the cleanup needs to be pushed *first*.
Tim Shen421119f2016-07-01 21:08:47 +00001403 if (emission.useLifetimeMarkers())
1404 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
Nadav Rotem1da30942013-03-23 06:43:35 +00001405 emission.getAllocatedAddress(),
1406 emission.getSizeForLifetimeMarkers());
Nadav Rotem1da30942013-03-23 06:43:35 +00001407
John McCall82fe67b2011-07-09 01:37:26 +00001408 // Check the type for a cleanup.
1409 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1410 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001411
John McCall1bd25562011-06-24 23:21:27 +00001412 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001413 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001414 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1415 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1416 }
1417
John McCallc533cb72011-02-22 06:44:22 +00001418 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001419 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001420 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001421
John McCallc533cb72011-02-22 06:44:22 +00001422 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001423 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001424
John McCalla729c622012-02-17 03:33:10 +00001425 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001426 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001427 }
Mike Stump626aecc2009-03-05 01:23:13 +00001428
John McCallc533cb72011-02-22 06:44:22 +00001429 // If this is a block variable, call _Block_object_destroy
1430 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001431 if (emission.IsByRef)
1432 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001433}
Chris Lattner53621a52007-06-13 20:44:40 +00001434
Peter Collingbourne1425b452012-01-26 03:33:36 +00001435CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001436CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1437 switch (kind) {
1438 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001439 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001440 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001441 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001442 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001443 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001444 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001445 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001446 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001447}
1448
John McCall12cc42a2013-02-01 05:11:40 +00001449/// pushEHDestroy - Push the standard destructor for the given type as
1450/// an EH-only cleanup.
1451void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001452 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00001453 assert(dtorKind && "cannot push destructor for trivial type");
1454 assert(needsEHCleanup(dtorKind));
1455
1456 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1457}
1458
1459/// pushDestroy - Push the standard destructor for the given type as
1460/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001461void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001462 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00001463 assert(dtorKind && "cannot push destructor for trivial type");
1464
1465 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1466 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1467 cleanupKind & EHCleanup);
1468}
1469
John McCall7f416cc2015-09-08 08:05:57 +00001470void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001471 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001472 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001473 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1474 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001475}
1476
John McCall7f416cc2015-09-08 08:05:57 +00001477void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001478 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1479}
1480
Richard Smith736a9472013-06-12 20:42:33 +00001481void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00001482 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00001483 Destroyer *destroyer, bool useEHCleanupForArray) {
1484 assert(!isInConditionalBranch() &&
1485 "performing lifetime extension from within conditional");
1486
1487 // Push an EH-only cleanup for the object now.
1488 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1489 // around in case a temporary's destructor throws an exception.
1490 if (cleanupKind & EHCleanup)
1491 EHStack.pushCleanup<DestroyObject>(
1492 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1493 destroyer, useEHCleanupForArray);
1494
1495 // Remember that we need to push a full cleanup for the object at the
1496 // end of the full-expression.
1497 pushCleanupAfterFullExpr<DestroyObject>(
1498 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1499}
1500
John McCall178360e2011-07-11 08:38:19 +00001501/// emitDestroy - Immediately perform the destruction of the given
1502/// object.
1503///
1504/// \param addr - the address of the object; a type*
1505/// \param type - the type of the object; if an array type, all
1506/// objects are destroyed in reverse order
1507/// \param destroyer - the function to call to destroy individual
1508/// elements
1509/// \param useEHCleanupForArray - whether an EH cleanup should be
1510/// used when destroying array elements, in case one of the
1511/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00001512void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001513 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001514 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001515 const ArrayType *arrayType = getContext().getAsArrayType(type);
1516 if (!arrayType)
1517 return destroyer(*this, addr, type);
1518
John McCall7f416cc2015-09-08 08:05:57 +00001519 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1520
1521 CharUnits elementAlign =
1522 addr.getAlignment()
1523 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00001524
1525 // Normally we have to check whether the array is zero-length.
1526 bool checkZeroLength = true;
1527
1528 // But if the array length is constant, we can suppress that.
1529 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1530 // ...and if it's constant zero, we can just skip the entire thing.
1531 if (constLength->isZero()) return;
1532 checkZeroLength = false;
1533 }
1534
John McCall7f416cc2015-09-08 08:05:57 +00001535 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00001536 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00001537 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001538 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001539}
1540
John McCall178360e2011-07-11 08:38:19 +00001541/// emitArrayDestroy - Destroys all the elements of the given array,
1542/// beginning from last to first. The array cannot be zero-length.
1543///
1544/// \param begin - a type* denoting the first element of the array
1545/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001546/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00001547/// \param destroyer - the function to call to destroy elements
1548/// \param useEHCleanup - whether to push an EH cleanup to destroy
1549/// the remaining elements in case the destruction of a single
1550/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001551void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1552 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001553 QualType elementType,
1554 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001555 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001556 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001557 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00001558 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00001559
1560 // The basic structure here is a do-while loop, because we don't
1561 // need to check for the zero-element case.
1562 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1563 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1564
John McCall97eab0a2011-07-13 08:09:46 +00001565 if (checkZeroLength) {
1566 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1567 "arraydestroy.isempty");
1568 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1569 }
1570
John McCall82fe67b2011-07-09 01:37:26 +00001571 // Enter the loop body, making that address the current address.
1572 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1573 EmitBlock(bodyBB);
1574 llvm::PHINode *elementPast =
1575 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1576 elementPast->addIncoming(end, entryBB);
1577
1578 // Shift the address back by one element.
1579 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1580 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1581 "arraydestroy.element");
1582
John McCall178360e2011-07-11 08:38:19 +00001583 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00001584 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1585 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001586
John McCall82fe67b2011-07-09 01:37:26 +00001587 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00001588 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00001589
John McCall178360e2011-07-11 08:38:19 +00001590 if (useEHCleanup)
1591 PopCleanupBlock();
1592
John McCall82fe67b2011-07-09 01:37:26 +00001593 // Check whether we've reached the end.
1594 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1595 Builder.CreateCondBr(done, doneBB, bodyBB);
1596 elementPast->addIncoming(element, Builder.GetInsertBlock());
1597
1598 // Done.
1599 EmitBlock(doneBB);
1600}
1601
John McCall178360e2011-07-11 08:38:19 +00001602/// Perform partial array destruction as if in an EH cleanup. Unlike
1603/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001604static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1605 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001606 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001607 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001608 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001609 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001610 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1611 // VLAs don't require a GEP index to walk into.
1612 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001613 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001614 type = arrayType->getElementType();
1615 }
John McCall97eab0a2011-07-13 08:09:46 +00001616
1617 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00001618 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00001619
John McCallf0f0b7a2015-09-14 18:57:08 +00001620 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001621 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1622 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001623 }
1624
John McCall97eab0a2011-07-13 08:09:46 +00001625 // Destroy the array. We don't ever need an EH cleanup because we
1626 // assume that we're in an EH cleanup ourselves, so a throwing
1627 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00001628 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001629 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001630}
1631
John McCall82fe67b2011-07-09 01:37:26 +00001632namespace {
John McCall178360e2011-07-11 08:38:19 +00001633 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1634 /// array destroy where the end pointer is regularly determined and
1635 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001636 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00001637 llvm::Value *ArrayBegin;
1638 llvm::Value *ArrayEnd;
1639 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001640 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001641 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00001642 public:
1643 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001644 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001645 CodeGenFunction::Destroyer *destroyer)
1646 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00001647 ElementType(elementType), Destroyer(destroyer),
1648 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00001649
Craig Topper4f12f102014-03-12 06:41:41 +00001650 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001651 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001652 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00001653 }
1654 };
1655
1656 /// IrregularPartialArrayDestroy - a cleanup which performs a
1657 /// partial array destroy where the end pointer is irregularly
1658 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001659 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001660 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00001661 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00001662 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001663 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001664 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00001665 public:
John McCall178360e2011-07-11 08:38:19 +00001666 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001667 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001668 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001669 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001670 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001671 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00001672 ElementType(elementType), Destroyer(destroyer),
1673 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00001674
Craig Topper4f12f102014-03-12 06:41:41 +00001675 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001676 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001677 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001678 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001679 }
1680 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001681} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00001682
John McCall178360e2011-07-11 08:38:19 +00001683/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001684/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001685/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001686///
John McCall82fe67b2011-07-09 01:37:26 +00001687/// \param elementType - the immediate element type of the array;
1688/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001689void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001690 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001691 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001692 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001693 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001694 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1695 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00001696 elementType, elementAlign,
1697 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001698}
1699
1700/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1701/// already-constructed elements of the given array. The cleanup
1702/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001703///
John McCall178360e2011-07-11 08:38:19 +00001704/// \param elementType - the immediate element type of the array;
1705/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001706void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1707 llvm::Value *arrayEnd,
1708 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001709 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001710 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001711 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001712 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001713 elementType, elementAlign,
1714 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001715}
1716
Nadav Rotem1da30942013-03-23 06:43:35 +00001717/// Lazily declare the @llvm.lifetime.start intrinsic.
1718llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1719 if (LifetimeStartFn) return LifetimeStartFn;
1720 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1721 llvm::Intrinsic::lifetime_start);
1722 return LifetimeStartFn;
1723}
1724
1725/// Lazily declare the @llvm.lifetime.end intrinsic.
1726llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1727 if (LifetimeEndFn) return LifetimeEndFn;
1728 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1729 llvm::Intrinsic::lifetime_end);
1730 return LifetimeEndFn;
1731}
1732
John McCall31168b02011-06-15 23:02:42 +00001733namespace {
1734 /// A cleanup to perform a release of an object at the end of a
1735 /// function. This is used to balance out the incoming +1 of a
1736 /// ns_consumed argument when we can't reasonably do that just by
1737 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00001738 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001739 ConsumeARCParameter(llvm::Value *param,
1740 ARCPreciseLifetime_t precise)
1741 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001742
1743 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001744 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001745
Craig Topper4f12f102014-03-12 06:41:41 +00001746 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001747 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001748 }
1749 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001750} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00001751
Mike Stump11289f42009-09-09 15:08:12 +00001752/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001753/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00001754void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1755 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001756 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001757 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001758 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001759
John McCall7f416cc2015-09-08 08:05:57 +00001760 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00001761
Adrian Prantl51936dd2013-03-14 17:53:33 +00001762 QualType Ty = D.getType();
1763
John McCall147d0212011-02-22 22:38:33 +00001764 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00001765 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00001766 // The only implicit argument a block has is its literal.
John McCall7f416cc2015-09-08 08:05:57 +00001767 // We assume this is always passed directly.
John McCall147d0212011-02-22 22:38:33 +00001768 if (BlockInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001769 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
John McCall147d0212011-02-22 22:38:33 +00001770 return;
1771 }
1772 }
1773
John McCall7f416cc2015-09-08 08:05:57 +00001774 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001775 bool DoStore = false;
1776 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001777 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001778 if (Arg.isIndirect()) {
1779 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001780 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00001781 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001782 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00001783 if (DeclPtr.getType() != IRTy)
1784 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1785
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001786 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00001787 // Don't push a cleanup in a thunk for a method that will also emit a
1788 // cleanup.
1789 if (!IsScalar && !CurFuncIsThunk &&
Reid Kleckner739756c2013-12-04 19:23:12 +00001790 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001791 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1792 if (RD && RD->hasNonTrivialDestructor())
1793 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001794 }
Chris Lattner53621a52007-06-13 20:44:40 +00001795 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001796 // Otherwise, create a temporary to hold the value.
John McCall7f416cc2015-09-08 08:05:57 +00001797 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1798 D.getName() + ".addr");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001799 DoStore = true;
1800 }
Mike Stump11289f42009-09-09 15:08:12 +00001801
John McCall7f416cc2015-09-08 08:05:57 +00001802 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1803
1804 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001805 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00001806 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001807 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1808 // We honor __attribute__((ns_consumed)) for types with lifetime.
1809 // For __strong, it's handled by just skipping the initial retain;
1810 // otherwise we have to balance out the initial +1 with an extra
1811 // cleanup to do the release at the end of the function.
1812 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1813
1814 // 'self' is always formally __strong, but if this is not an
1815 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001816 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001817 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1818 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001819 assert(lt == Qualifiers::OCL_Strong);
1820 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001821 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001822 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001823 lt = Qualifiers::OCL_ExplicitNone;
1824 }
1825
1826 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001827 if (!isConsumed) {
1828 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1829 // use objc_storeStrong(&dest, value) for retaining the
1830 // object. But first, store a null into 'dest' because
1831 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001832 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001833 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
John McCall7f416cc2015-09-08 08:05:57 +00001834 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001835 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001836 }
1837 else
John McCall31168b02011-06-15 23:02:42 +00001838 // Don't use objc_retainBlock for block pointers, because we
1839 // don't want to Block_copy something just because we got it
1840 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00001841 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001842 }
John McCall31168b02011-06-15 23:02:42 +00001843 } else {
1844 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00001845 if (isConsumed) {
1846 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1847 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00001848 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00001849 precise);
1850 }
John McCall31168b02011-06-15 23:02:42 +00001851
1852 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00001853 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001854 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001855 }
1856 }
1857
1858 // Enter the cleanup scope.
1859 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1860 }
Chris Lattner53621a52007-06-13 20:44:40 +00001861 }
1862
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001863 // Store the initial value into the alloca.
1864 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00001865 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001866
John McCall7f416cc2015-09-08 08:05:57 +00001867 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001868
1869 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001870 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001871 if (CGM.getCodeGenOpts().getDebugInfo() >=
1872 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001873 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001874 }
1875 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001876
1877 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001878 EmitVarAnnotations(&D, DeclPtr.getPointer());
Chris Lattner53621a52007-06-13 20:44:40 +00001879}
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001880
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001881void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1882 CodeGenFunction *CGF) {
1883 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1884 return;
1885 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
1886}