blob: b7c1743f62eb0236c343b57229fd9ac32c89b212 [file] [log] [blame]
Chris Lattner84915fa2007-06-02 04:16:21 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner84915fa2007-06-02 04:16:21 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Decl nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
John McCall7f416cc2015-09-08 08:05:57 +000015#include "CGBlocks.h"
Reid Klecknere5a321b2016-09-07 18:21:30 +000016#include "CGCXXABI.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000017#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGDebugInfo.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000019#include "CGOpenCLRuntime.h"
Alexey Bataevc5b1d322016-03-04 09:22:22 +000020#include "CGOpenMPRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "CodeGenModule.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000022#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000023#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000024#include "clang/AST/Decl.h"
Anders Carlsson4c03d982008-08-25 01:38:19 +000025#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000026#include "clang/AST/DeclOpenMP.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000027#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000028#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000029#include "clang/CodeGen/CGFunctionInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000030#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/Type.h"
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +000035
Chris Lattner84915fa2007-06-02 04:16:21 +000036using namespace clang;
37using namespace CodeGen;
38
Chris Lattner1ad38f82007-06-09 01:20:56 +000039void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000040 switch (D.getKind()) {
David Majnemerd9b1a4f2015-11-04 03:40:30 +000041 case Decl::BuiltinTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000042 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +000043 case Decl::ExternCContext:
Douglas Gregor19043f02010-04-23 02:02:43 +000044 case Decl::Namespace:
45 case Decl::UnresolvedUsingTypename:
46 case Decl::ClassTemplateSpecialization:
47 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000048 case Decl::VarTemplateSpecialization:
49 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000050 case Decl::TemplateTypeParm:
51 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000052 case Decl::NonTypeTemplateParm:
Douglas Gregor19043f02010-04-23 02:02:43 +000053 case Decl::CXXMethod:
54 case Decl::CXXConstructor:
55 case Decl::CXXDestructor:
56 case Decl::CXXConversion:
57 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000058 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000059 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000060 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000061 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000062 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000063 case Decl::ImplicitParam:
64 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000065 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000066 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000067 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000068 case Decl::TemplateTemplateParm:
69 case Decl::ObjCMethod:
70 case Decl::ObjCCategory:
71 case Decl::ObjCProtocol:
72 case Decl::ObjCInterface:
73 case Decl::ObjCCategoryImpl:
74 case Decl::ObjCImplementation:
75 case Decl::ObjCProperty:
76 case Decl::ObjCCompatibleAlias:
Nico Weber66220292016-03-02 17:28:48 +000077 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +000078 case Decl::PragmaDetectMismatch:
Abramo Bagnarad7340582010-06-05 05:09:32 +000079 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000080 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +000081 case Decl::Export:
Douglas Gregor19043f02010-04-23 02:02:43 +000082 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000083 case Decl::FileScopeAsm:
84 case Decl::Friend:
85 case Decl::FriendTemplate:
86 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000087 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000088 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000089 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +000090 case Decl::ConstructorUsingShadow:
Douglas Gregor85f3f952015-07-07 03:57:15 +000091 case Decl::ObjCTypeParam:
Richard Smithda383632016-08-15 01:33:41 +000092 case Decl::Binding:
David Blaikie83d382b2011-09-23 05:06:16 +000093 llvm_unreachable("Declaration should not be in declstmts!");
Amjad Abouddc4531e2016-04-30 01:44:38 +000094 case Decl::Function: // void X();
95 case Decl::Record: // struct/union/class X;
96 case Decl::Enum: // enum X;
97 case Decl::EnumConstant: // enum ? { X = ? }
98 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +000099 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +0000100 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +0000101 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000102 case Decl::OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000103 case Decl::OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +0000104 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +0000105 // None of these decls require codegen support.
106 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +0000107
David Blaikief121b932013-05-20 22:50:41 +0000108 case Decl::NamespaceAlias:
109 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000110 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
David Blaikief121b932013-05-20 22:50:41 +0000111 return;
David Blaikiebd483762013-05-20 04:58:53 +0000112 case Decl::Using: // using X; [C++]
113 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000114 DI->EmitUsingDecl(cast<UsingDecl>(D));
David Blaikiebd483762013-05-20 04:58:53 +0000115 return;
Richard Smith151c4562016-12-20 21:35:28 +0000116 case Decl::UsingPack:
117 for (auto *Using : cast<UsingPackDecl>(D).expansions())
118 EmitDecl(*Using);
119 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000120 case Decl::UsingDirective: // using namespace X; [C++]
121 if (CGDebugInfo *DI = getDebugInfo())
122 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
123 return;
Richard Smithbdb84f32016-07-22 23:36:59 +0000124 case Decl::Var:
125 case Decl::Decomposition: {
Daniel Dunbara7998072008-08-29 17:28:43 +0000126 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000127 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000128 "Should not see file-scope variables inside a function!");
Richard Smithda383632016-08-15 01:33:41 +0000129 EmitVarDecl(VD);
130 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
131 for (auto *B : DD->bindings())
132 if (auto *HD = B->getHoldingVar())
133 EmitVarDecl(*HD);
134 return;
Chris Lattner84915fa2007-06-02 04:16:21 +0000135 }
Mike Stump11289f42009-09-09 15:08:12 +0000136
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000137 case Decl::OMPDeclareReduction:
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000138 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000139
Richard Smithdda56e42011-04-15 14:24:37 +0000140 case Decl::Typedef: // typedef int X;
141 case Decl::TypeAlias: { // using X = int; [C++0x]
142 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000143 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000144
Anders Carlsson5d985f52008-12-20 21:51:53 +0000145 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000146 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000147 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000148 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000149}
Chris Lattner03df1222007-06-02 04:53:11 +0000150
John McCall1c9c3fd2010-10-15 04:57:14 +0000151/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000152/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000153void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000154 if (D.isStaticLocal()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000155 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000156 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000157
David Majnemer27d69db2014-04-28 22:17:59 +0000158 // FIXME: We need to force the emission/use of a guard variable for
159 // some variables even if we can constant-evaluate them because
160 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000161
John McCall1c9c3fd2010-10-15 04:57:14 +0000162 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000163 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000164
165 if (D.hasExternalStorage())
Lauro Ramos Venanciobada8d42008-02-16 22:30:38 +0000166 // Don't emit it now, allow it to be emitted lazily on its first use.
167 return;
Daniel Dunbar0ca16602009-04-14 02:25:56 +0000168
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000169 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000170 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
171
172 assert(D.hasLocalStorage());
173 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000174}
175
Reid Kleckner453e0562014-10-08 01:07:54 +0000176static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
177 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000178 return CGM.getMangledName(&D).str();
179
Reid Kleckner453e0562014-10-08 01:07:54 +0000180 // If this isn't C++, we don't need a mangled name, just a pretty one.
181 assert(!D.isExternallyVisible() && "name shouldn't matter");
182 std::string ContextName;
183 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000184 if (auto *CD = dyn_cast<CapturedDecl>(DC))
185 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000186 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000187 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000188 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
189 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
190 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
191 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000192 else
David Blaikie83d382b2011-09-23 05:06:16 +0000193 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000194
Reid Kleckner453e0562014-10-08 01:07:54 +0000195 ContextName += "." + D.getNameAsString();
196 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000197}
198
Reid Kleckner453e0562014-10-08 01:07:54 +0000199llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
200 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
201 // In general, we don't always emit static var decls once before we reference
202 // them. It is possible to reference them before emitting the function that
203 // contains them, and it is possible to emit the containing function multiple
204 // times.
205 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
206 return ExistingGV;
207
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000208 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000209 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000210
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000211 // Use the label if the variable is renamed with the asm-label extension.
212 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000213 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000214 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000215 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000216 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000217
Reid Kleckner453e0562014-10-08 01:07:54 +0000218 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000219 unsigned AddrSpace =
Reid Kleckner453e0562014-10-08 01:07:54 +0000220 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000221
222 // Local address space cannot have an initializer.
223 llvm::Constant *Init = nullptr;
224 if (Ty.getAddressSpace() != LangAS::opencl_local)
225 Init = EmitNullConstant(Ty);
226 else
227 Init = llvm::UndefValue::get(LTy);
228
Anders Carlssone33eed52009-09-26 18:16:06 +0000229 llvm::GlobalVariable *GV =
Reid Kleckner453e0562014-10-08 01:07:54 +0000230 new llvm::GlobalVariable(getModule(), LTy,
Anders Carlssone33eed52009-09-26 18:16:06 +0000231 Ty.isConstant(getContext()), Linkage,
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000232 Init, Name, nullptr,
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000233 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000234 AddrSpace);
Ken Dyck160146e2010-01-27 17:10:57 +0000235 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Reid Kleckner453e0562014-10-08 01:07:54 +0000236 setGlobalVisibility(GV, &D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000237
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000238 if (supportsCOMDAT() && GV->isWeakForLinker())
239 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000240
Richard Smithfd3834f2013-04-13 02:43:54 +0000241 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000242 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000243
Hans Wennborgef2272c2014-06-18 15:55:13 +0000244 if (D.isExternallyVisible()) {
245 if (D.hasAttr<DLLImportAttr>())
246 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
247 else if (D.hasAttr<DLLExportAttr>())
248 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
249 }
250
Eli Benderskycb399432014-03-24 22:05:38 +0000251 // Make sure the result is of the correct type.
Reid Kleckner453e0562014-10-08 01:07:54 +0000252 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
253 llvm::Constant *Addr = GV;
Eli Benderskycb399432014-03-24 22:05:38 +0000254 if (AddrSpace != ExpectedAddrSpace) {
255 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
Reid Kleckner453e0562014-10-08 01:07:54 +0000256 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
Eli Benderskycb399432014-03-24 22:05:38 +0000257 }
258
Reid Kleckner453e0562014-10-08 01:07:54 +0000259 setStaticLocalDeclAddress(&D, Addr);
260
261 // Ensure that the static local gets initialized by making sure the parent
262 // function gets emitted eventually.
263 const Decl *DC = cast<Decl>(D.getDeclContext());
264
265 // We can't name blocks or captured statements directly, so try to emit their
266 // parents.
267 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
268 DC = DC->getNonClosureContext();
269 // FIXME: Ensure that global blocks get emitted.
270 if (!DC)
271 return Addr;
272 }
273
274 GlobalDecl GD;
275 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
276 GD = GlobalDecl(CD, Ctor_Base);
277 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
278 GD = GlobalDecl(DD, Dtor_Base);
279 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
280 GD = GlobalDecl(FD);
281 else {
282 // Don't do anything for Obj-C method decls or global closures. We should
283 // never defer them.
284 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
285 }
286 if (GD.getDecl())
287 (void)GetAddrOfGlobal(GD);
288
289 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000290}
291
Richard Smith6331c402012-02-13 22:16:19 +0000292/// hasNontrivialDestruction - Determine whether a type's destruction is
293/// non-trivial. If so, and the variable uses static initialization, we must
294/// register its destructor to run on exit.
295static bool hasNontrivialDestruction(QualType T) {
296 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
297 return RD && !RD->hasTrivialDestructor();
298}
299
Chandler Carruth84537952012-03-30 19:44:53 +0000300/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
301/// global variable that has already been created for it. If the initializer
302/// has a different type than GV does, this may free GV and return a different
303/// one. Otherwise it just returns GV.
304llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000305CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000306 llvm::GlobalVariable *GV) {
307 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCall70013b62010-07-15 23:40:35 +0000308
Chris Lattnere99c1102009-12-05 08:22:11 +0000309 // If constant emission failed, then this should be a C++ static
310 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000311 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000312 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000313 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
Matthias Braun44bfe032017-01-10 17:43:01 +0000314 else if (HaveInsertPoint()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000315 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000316 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000317 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000318
Chandler Carruth84537952012-03-30 19:44:53 +0000319 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000320 }
Chandler Carruth84537952012-03-30 19:44:53 +0000321 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000322 }
John McCall70013b62010-07-15 23:40:35 +0000323
Chris Lattnere99c1102009-12-05 08:22:11 +0000324 // The initializer may differ in type from the global. Rewrite
325 // the global to match the initializer. (We have to do this
326 // because some types, like unions, can't be completely represented
327 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000328 if (GV->getType()->getElementType() != Init->getType()) {
329 llvm::GlobalVariable *OldGV = GV;
330
331 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
332 OldGV->isConstant(),
333 OldGV->getLinkage(), Init, "",
334 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000335 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000336 CGM.getContext().getTargetAddressSpace(D.getType()));
337 GV->setVisibility(OldGV->getVisibility());
Reid Klecknereab97d32015-07-20 20:35:30 +0000338 GV->setComdat(OldGV->getComdat());
Eric Christopher31ab1302011-08-23 22:38:00 +0000339
Chris Lattnere99c1102009-12-05 08:22:11 +0000340 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000341 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000342
Chris Lattnere99c1102009-12-05 08:22:11 +0000343 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000344 llvm::Constant *NewPtrForOldDecl =
345 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
346 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000347
Chris Lattnere99c1102009-12-05 08:22:11 +0000348 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000349 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000350 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000351
Chandler Carruth84537952012-03-30 19:44:53 +0000352 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
353 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000354
Matthias Braun44bfe032017-01-10 17:43:01 +0000355 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
Richard Smith6331c402012-02-13 22:16:19 +0000356 // We have a constant initializer, but a nontrivial destructor. We still
357 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000358 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000359 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000360 }
361
Chandler Carruth84537952012-03-30 19:44:53 +0000362 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000363}
364
John McCall1c9c3fd2010-10-15 04:57:14 +0000365void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000366 llvm::GlobalValue::LinkageTypes Linkage) {
John McCallb88a5662012-03-30 21:00:39 +0000367 // Check to see if we already have a global variable for this
368 // declaration. This can happen when double-emitting function
369 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000370 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
John McCall7f416cc2015-09-08 08:05:57 +0000371 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara374e602009-02-25 19:45:19 +0000372
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000373 // Store into LocalDeclMap before generating initializer to handle
374 // circular references.
John McCall7f416cc2015-09-08 08:05:57 +0000375 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000376
John McCall4a39ab82010-05-04 20:45:42 +0000377 // We can't have a VLA here, but we can have a pointer to a VLA,
378 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000379 // Make sure to evaluate VLA bounds now so that we have them for later.
380 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000381 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000382
John McCallb88a5662012-03-30 21:00:39 +0000383 // Save the type in case adding the initializer forces a type change.
384 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000385
Eli Benderskycb399432014-03-24 22:05:38 +0000386 llvm::GlobalVariable *var =
387 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Artem Belevich4d430ba2016-05-09 22:09:56 +0000388
389 // CUDA's local and local static __shared__ variables should not
390 // have any non-empty initializers. This is ensured by Sema.
391 // Whatever initializer such variable may have when it gets here is
392 // a no-op and should not be emitted.
393 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
394 D.hasAttr<CUDASharedAttr>();
Chris Lattnere99c1102009-12-05 08:22:11 +0000395 // If this value has an initializer, emit it.
Artem Belevich4d430ba2016-05-09 22:09:56 +0000396 if (D.getInit() && !isCudaSharedVar)
John McCallb88a5662012-03-30 21:00:39 +0000397 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000398
John McCall7f416cc2015-09-08 08:05:57 +0000399 var->setAlignment(alignment.getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000400
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000401 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000402 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000403
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000404 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000405 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000406
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000407 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000408 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000409
Chandler Carruth84537952012-03-30 19:44:53 +0000410 // We may have to cast the constant because of the initializer
411 // mismatch above.
412 //
413 // FIXME: It is really dangerous to store this in the map; if anyone
414 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000415 llvm::Constant *castedAddr =
416 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCall7f416cc2015-09-08 08:05:57 +0000417 if (var != castedAddr)
418 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCallb88a5662012-03-30 21:00:39 +0000419 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000420
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000421 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000422
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000423 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000424 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000425 if (DI &&
Benjamin Kramer8c305922016-02-02 11:06:51 +0000426 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000427 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000428 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000429 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000430}
Mike Stump11289f42009-09-09 15:08:12 +0000431
John McCall2b7fc382010-07-13 20:32:21 +0000432namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000433 struct DestroyObject final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000434 DestroyObject(Address addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000435 CodeGenFunction::Destroyer *destroyer,
436 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000437 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000438 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000439
John McCall7f416cc2015-09-08 08:05:57 +0000440 Address addr;
John McCall82fe67b2011-07-09 01:37:26 +0000441 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000442 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000443 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000444
Craig Topper4f12f102014-03-12 06:41:41 +0000445 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000446 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000447 bool useEHCleanupForArray =
448 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000449
450 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000451 }
452 };
453
David Blaikie7e70d682015-08-18 22:40:54 +0000454 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000455 DestroyNRVOVariable(Address addr,
John McCall82fe67b2011-07-09 01:37:26 +0000456 const CXXDestructorDecl *Dtor,
457 llvm::Value *NRVOFlag)
458 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000459
460 const CXXDestructorDecl *Dtor;
461 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000462 Address Loc;
John McCall2b7fc382010-07-13 20:32:21 +0000463
Craig Topper4f12f102014-03-12 06:41:41 +0000464 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000465 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000466 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000467
Craig Topper8a13c412014-05-21 05:09:00 +0000468 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000469 if (NRVO) {
470 // If we exited via NRVO, we skip the destructor call.
471 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
472 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000473 llvm::Value *DidNRVO =
474 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000475 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
476 CGF.EmitBlock(RunDtorBB);
477 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000478
John McCall2b7fc382010-07-13 20:32:21 +0000479 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +0000480 /*ForVirtualBase=*/false,
481 /*Delegating=*/false,
482 Loc);
John McCall2b7fc382010-07-13 20:32:21 +0000483
484 if (NRVO) CGF.EmitBlock(SkipDtorBB);
485 }
486 };
John McCall2b7fc382010-07-13 20:32:21 +0000487
David Blaikie7e70d682015-08-18 22:40:54 +0000488 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000489 Address Stack;
490 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000491 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000492 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000493 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
494 CGF.Builder.CreateCall(F, V);
495 }
496 };
497
David Blaikie7e70d682015-08-18 22:40:54 +0000498 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000499 const VarDecl &Var;
500 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
501
Craig Topper4f12f102014-03-12 06:41:41 +0000502 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000503 // Compute the address of the local variable, in case it's a
504 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000505 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
506 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000507 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
508 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000509 CGF.EmitExtendGCLifetime(value);
510 }
511 };
512
David Blaikie7e70d682015-08-18 22:40:54 +0000513 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000514 llvm::Constant *CleanupFn;
515 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000516 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000517
John McCalla464ff92010-07-21 06:13:08 +0000518 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000519 const VarDecl *Var)
520 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000521
Craig Topper4f12f102014-03-12 06:41:41 +0000522 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000523 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
524 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000525 // Compute the address of the local variable, in case it's a byref
526 // or something.
John McCall7f416cc2015-09-08 08:05:57 +0000527 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCallc533cb72011-02-22 06:44:22 +0000528
John McCalla464ff92010-07-21 06:13:08 +0000529 // In some cases, the type of the function argument will be different from
530 // the type of the pointer. An example of this is
531 // void f(void* arg);
532 // __attribute__((cleanup(f))) void *g;
533 //
534 // To fix this we insert a bitcast here.
535 QualType ArgTy = FnInfo.arg_begin()->type;
536 llvm::Value *Arg =
537 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
538
539 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000540 Args.add(RValue::get(Arg),
541 CGF.getContext().getPointerType(Var.getType()));
John McCallb92ab1a2016-10-26 23:46:34 +0000542 auto Callee = CGCallee::forDirect(CleanupFn);
543 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
John McCalla464ff92010-07-21 06:13:08 +0000544 }
545 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000546} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000547
John McCall31168b02011-06-15 23:02:42 +0000548/// EmitAutoVarWithLifetime - Does the setup required for an automatic
549/// variable with lifetime.
550static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000551 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000552 Qualifiers::ObjCLifetime lifetime) {
553 switch (lifetime) {
554 case Qualifiers::OCL_None:
555 llvm_unreachable("present but none");
556
557 case Qualifiers::OCL_ExplicitNone:
558 // nothing to do
559 break;
560
561 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000562 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000563 (var.hasAttr<ObjCPreciseLifetimeAttr>()
564 ? CodeGenFunction::destroyARCStrongPrecise
565 : CodeGenFunction::destroyARCStrongImprecise);
566
567 CleanupKind cleanupKind = CGF.getARCCleanupKind();
568 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
569 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000570 break;
571 }
572 case Qualifiers::OCL_Autoreleasing:
573 // nothing to do
574 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000575
John McCall31168b02011-06-15 23:02:42 +0000576 case Qualifiers::OCL_Weak:
577 // __weak objects always get EH cleanups; otherwise, exceptions
578 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000579 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
580 CodeGenFunction::destroyARCWeak,
581 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000582 break;
583 }
584}
585
586static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
587 if (const Expr *e = dyn_cast<Expr>(s)) {
588 // Skip the most common kinds of expressions that make
589 // hierarchy-walking expensive.
590 s = e = e->IgnoreParenCasts();
591
592 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
593 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000594 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
595 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000596 for (const auto &I : block->captures()) {
597 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000598 return true;
599 }
600 }
John McCall31168b02011-06-15 23:02:42 +0000601 }
602
Benjamin Kramer642f1732015-07-02 21:03:14 +0000603 for (const Stmt *SubStmt : s->children())
604 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
605 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000606 return true;
607
608 return false;
609}
610
611static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
612 if (!decl) return false;
613 if (!isa<VarDecl>(decl)) return false;
614 const VarDecl *var = cast<VarDecl>(decl);
615 return isAccessedBy(*var, e);
616}
617
John McCallf8a9b662015-10-21 18:06:31 +0000618static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
619 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000620 bool needsCast = false;
621
John McCallf8a9b662015-10-21 18:06:31 +0000622 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
623 switch (castExpr->getCastKind()) {
624 // Look through casts that don't require representation changes.
625 case CK_NoOp:
626 case CK_BitCast:
627 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000628 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000629 break;
630
631 // If we find an l-value to r-value cast from a __weak variable,
632 // emit this operation as a copy or move.
633 case CK_LValueToRValue: {
634 const Expr *srcExpr = castExpr->getSubExpr();
635 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
636 return false;
637
638 // Emit the source l-value.
639 LValue srcLV = CGF.EmitLValue(srcExpr);
640
John McCall0204e342015-11-16 22:11:41 +0000641 // Handle a formal type change to avoid asserting.
642 auto srcAddr = srcLV.getAddress();
643 if (needsCast) {
644 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
645 destLV.getAddress().getElementType());
646 }
647
John McCallf8a9b662015-10-21 18:06:31 +0000648 // If it was an l-value, use objc_copyWeak.
649 if (srcExpr->getValueKind() == VK_LValue) {
John McCall0204e342015-11-16 22:11:41 +0000650 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000651 } else {
652 assert(srcExpr->getValueKind() == VK_XValue);
John McCall0204e342015-11-16 22:11:41 +0000653 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000654 }
655 return true;
656 }
657
658 // Stop at anything else.
659 default:
660 return false;
661 }
662
663 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000664 }
665 return false;
666}
667
John McCall1553b192011-06-16 04:16:24 +0000668static void drillIntoBlockVariable(CodeGenFunction &CGF,
669 LValue &lvalue,
670 const VarDecl *var) {
John McCall7f416cc2015-09-08 08:05:57 +0000671 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCall1553b192011-06-16 04:16:24 +0000672}
673
David Blaikie73ca5692014-12-09 00:32:22 +0000674void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000675 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000676 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000677 if (!lifetime) {
678 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000679 if (capturedByInit)
680 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +0000681 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000682 return;
683 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000684
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000685 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
686 init = DIE->getExpr();
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000687
John McCall31168b02011-06-15 23:02:42 +0000688 // If we're emitting a value with lifetime, we have to do the
689 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000690 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
691 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000692 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000693 }
694 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000695
696 // We have to maintain the illusion that the variable is
697 // zero-initialized. If the variable might be accessed in its
698 // initializer, zero-initialize before running the initializer, then
699 // actually perform the initialization with an assign.
700 bool accessedByInit = false;
701 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000702 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000703 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000704 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000705 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000706 if (capturedByInit) {
707 // We can use a simple GEP for this because it can't have been
708 // moved yet.
John McCall7f416cc2015-09-08 08:05:57 +0000709 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
710 cast<VarDecl>(D),
711 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000712 }
713
John McCall7f416cc2015-09-08 08:05:57 +0000714 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
Yaxun Liu402804b2016-12-15 08:09:08 +0000715 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000716
John McCall31168b02011-06-15 23:02:42 +0000717 // If __weak, we want to use a barrier under certain conditions.
718 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000719 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000720
721 // Otherwise just do a simple store.
722 else
David Chisnallfa35df62012-01-16 17:27:18 +0000723 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000724 }
725
726 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000727 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000728
729 switch (lifetime) {
730 case Qualifiers::OCL_None:
731 llvm_unreachable("present but none");
732
733 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000734 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000735 break;
736
737 case Qualifiers::OCL_Strong: {
738 value = EmitARCRetainScalarExpr(init);
739 break;
740 }
741
742 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000743 // If it's not accessed by the initializer, try to emit the
744 // initialization with a copy or move.
745 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
746 return;
747 }
748
John McCall31168b02011-06-15 23:02:42 +0000749 // No way to optimize a producing initializer into this. It's not
750 // worth optimizing for, because the value will immediately
751 // disappear in the common case.
752 value = EmitScalarExpr(init);
753
John McCall1553b192011-06-16 04:16:24 +0000754 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000755 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000756 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000757 else
John McCall1553b192011-06-16 04:16:24 +0000758 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000759 return;
760 }
761
762 case Qualifiers::OCL_Autoreleasing:
763 value = EmitARCRetainAutoreleaseScalarExpr(init);
764 break;
765 }
766
John McCall1553b192011-06-16 04:16:24 +0000767 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000768
769 // If the variable might have been accessed by its initializer, we
770 // might have to initialize with a barrier. We have to do this for
771 // both __weak and __strong, but __weak got filtered out above.
772 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000773 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000774 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000775 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000776 return;
777 }
778
David Chisnallfa35df62012-01-16 17:27:18 +0000779 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000780}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000781
782/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
783/// non-zero parts of the specified initializer with equal or fewer than
784/// NumStores scalar stores.
785static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
786 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000787 // Zero and Undef never requires any extra stores.
788 if (isa<llvm::ConstantAggregateZero>(Init) ||
789 isa<llvm::ConstantPointerNull>(Init) ||
790 isa<llvm::UndefValue>(Init))
791 return true;
792 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
793 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
794 isa<llvm::ConstantExpr>(Init))
795 return Init->isNullValue() || NumStores--;
796
797 // See if we can emit each element.
798 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
799 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
800 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
801 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
802 return false;
803 }
804 return true;
805 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000806
Chris Lattner236b3572012-01-31 04:36:19 +0000807 if (llvm::ConstantDataSequential *CDS =
808 dyn_cast<llvm::ConstantDataSequential>(Init)) {
809 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
810 llvm::Constant *Elt = CDS->getElementAsConstant(i);
811 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
812 return false;
813 }
814 return true;
815 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000816
Chris Lattnerb85025f2010-12-01 02:05:19 +0000817 // Anything else is hard and scary.
818 return false;
819}
820
821/// emitStoresForInitAfterMemset - For inits that
822/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
823/// stores that would be required.
824static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000825 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000826 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
827 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000828
Chris Lattnere6af8862010-12-02 01:58:41 +0000829 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
830 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
831 isa<llvm::ConstantExpr>(Init)) {
John McCall7f416cc2015-09-08 08:05:57 +0000832 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000833 return;
834 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000835
836 if (llvm::ConstantDataSequential *CDS =
837 dyn_cast<llvm::ConstantDataSequential>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000838 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
839 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000840
841 // If necessary, get a pointer to the element and emit it.
842 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000843 emitStoresForInitAfterMemset(
844 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
845 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000846 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000847 return;
848 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000849
Chris Lattnere6af8862010-12-02 01:58:41 +0000850 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
851 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000852
Chris Lattnere6af8862010-12-02 01:58:41 +0000853 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
854 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000855
856 // If necessary, get a pointer to the element and emit it.
857 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000858 emitStoresForInitAfterMemset(
859 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
860 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000861 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000862}
863
Chris Lattnerb85025f2010-12-01 02:05:19 +0000864/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
865/// plus some stores to initialize a local variable instead of using a memcpy
866/// from a constant global. It is beneficial to use memset if the global is all
867/// zeros, or mostly zeros and large.
868static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
869 uint64_t GlobalSize) {
870 // If a global is all zeros, always use a memset.
871 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
872
Chris Lattnerb85025f2010-12-01 02:05:19 +0000873 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
874 // do it if it will require 6 or fewer scalar stores.
875 // TODO: Should budget depends on the size? Avoiding a large global warrants
876 // plopping in more stores.
877 unsigned StoreBudget = 6;
878 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000879
880 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000881 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
882}
883
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000884/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000885/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000886/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000887void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
888 AutoVarEmission emission = EmitAutoVarAlloca(D);
889 EmitAutoVarInit(emission);
890 EmitAutoVarCleanups(emission);
891}
Chris Lattner03df1222007-06-02 04:53:11 +0000892
David Majnemerdc012fa2015-04-22 21:38:15 +0000893/// Emit a lifetime.begin marker if some criteria are satisfied.
894/// \return a pointer to the temporary size Value if a marker was emitted, null
895/// otherwise
896llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
897 llvm::Value *Addr) {
Vitaly Buka1c943322016-10-26 01:59:57 +0000898 if (!ShouldEmitLifetimeMarkers)
Reid Kleckner1ef49212015-04-23 18:07:13 +0000899 return nullptr;
900
David Majnemerdc012fa2015-04-22 21:38:15 +0000901 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000902 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
903 llvm::CallInst *C =
904 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000905 C->setDoesNotThrow();
906 return SizeV;
907}
908
909void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000910 Addr = Builder.CreateBitCast(Addr, Int8PtrTy);
911 llvm::CallInst *C =
912 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000913 C->setDoesNotThrow();
914}
915
John McCallc533cb72011-02-22 06:44:22 +0000916/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000917/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +0000918CodeGenFunction::AutoVarEmission
919CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
920 QualType Ty = D.getType();
921
922 AutoVarEmission emission(D);
923
924 bool isByRef = D.hasAttr<BlocksAttr>();
925 emission.IsByRef = isByRef;
926
927 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +0000928
John McCall23c29fe2011-06-24 21:55:10 +0000929 // If the type is variably-modified, emit all the VLA sizes for it.
930 if (Ty->isVariablyModifiedType())
931 EmitVariablyModifiedType(Ty);
932
John McCall7f416cc2015-09-08 08:05:57 +0000933 Address address = Address::invalid();
Eli Friedmana682d392008-02-15 12:20:59 +0000934 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000935 bool NRVO = getLangOpts().ElideConstructors &&
936 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +0000937
Richard Smith2bcde3a2013-06-02 00:09:52 +0000938 // If this value is an array or struct with a statically determinable
939 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +0000940 //
941 // TODO: We should constant-evaluate the initializer of any variable,
942 // as long as it is initialized by a constant expression. Currently,
943 // isConstantInitializer produces wrong answers for structs with
944 // reference or bitfield members, and a few other cases, and checking
945 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +0000946 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
947 (D.isConstexpr() ||
948 ((Ty.isPODType(getContext()) ||
949 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
950 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +0000951
Rafael Espindola609f5d92013-03-26 18:41:47 +0000952 // If the variable's a const type, and it's neither an NRVO
953 // candidate nor a __block variable and has no mutable members,
954 // emit it as a global instead.
Anastasia Stulovae4a1c382016-11-29 17:01:19 +0000955 // Exception is if a variable is located in non-constant address space
956 // in OpenCL.
957 if ((!getLangOpts().OpenCL ||
958 Ty.getAddressSpace() == LangAS::opencl_constant) &&
959 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
960 CGM.isTypeConstant(Ty, true))) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000961 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +0000962
John McCall7f416cc2015-09-08 08:05:57 +0000963 // Signal this condition to later callbacks.
964 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +0000965 assert(emission.wasEmittedAsGlobal());
966 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +0000967 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000968
Rafael Espindola609f5d92013-03-26 18:41:47 +0000969 // Otherwise, tell the initialization code that we're in this case.
970 emission.IsConstantAggregate = true;
971 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000972
Rafael Espindola609f5d92013-03-26 18:41:47 +0000973 // A normal fixed sized variable becomes an alloca in the entry block,
974 // unless it's an NRVO variable.
Eric Christopher31ab1302011-08-23 22:38:00 +0000975
Rafael Espindola609f5d92013-03-26 18:41:47 +0000976 if (NRVO) {
977 // The named return value optimization: allocate this variable in the
978 // return slot, so that we can elide the copy when returning this
979 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +0000980 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +0000981
Rafael Espindola609f5d92013-03-26 18:41:47 +0000982 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
983 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
984 // Create a flag that is used to indicate when the NRVO was applied
985 // to this variable. Set it to zero to indicate that NRVO was not
986 // applied.
987 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000988 Address NRVOFlag =
989 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +0000990 EnsureInsertPoint();
991 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +0000992
Rafael Espindola609f5d92013-03-26 18:41:47 +0000993 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +0000994 NRVOFlags[&D] = NRVOFlag.getPointer();
995 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +0000996 }
Douglas Gregor290c93e2010-05-15 06:46:45 +0000997 }
Chris Lattnerb781dc792008-05-08 05:58:21 +0000998 } else {
John McCall7f416cc2015-09-08 08:05:57 +0000999 CharUnits allocaAlignment;
1000 llvm::Type *allocaTy;
1001 if (isByRef) {
1002 auto &byrefInfo = getBlockByrefInfo(&D);
1003 allocaTy = byrefInfo.Type;
1004 allocaAlignment = byrefInfo.ByrefAlignment;
1005 } else {
1006 allocaTy = ConvertTypeForMem(Ty);
1007 allocaAlignment = alignment;
1008 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001009
John McCall999110f2015-09-08 09:18:30 +00001010 // Create the alloca. Note that we set the name separately from
1011 // building the instruction so that it's there even in no-asserts
1012 // builds.
1013 address = CreateTempAlloca(allocaTy, allocaAlignment);
1014 address.getPointer()->setName(D.getName());
Rafael Espindola609f5d92013-03-26 18:41:47 +00001015
Reid Kleckner1f88e932015-10-07 21:03:41 +00001016 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1017 // the catch parameter starts in the catchpad instruction, and we can't
1018 // insert code in those basic blocks.
1019 bool IsMSCatchParam =
1020 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1021
Vitaly Buka64c80b42016-10-26 05:42:30 +00001022 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1023 // if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001024 if (HaveInsertPoint() && !IsMSCatchParam) {
Akira Hatanakafdcd18b2017-01-25 22:55:13 +00001025 // If there's a jump into the lifetime of this variable, its lifetime
1026 // gets broken up into several regions in IR, which requires more work
1027 // to handle correctly. For now, just omit the intrinsics; this is a
1028 // rare case, and it's better to just be conservatively correct.
1029 // PR28267.
1030 //
1031 // We have to do this in all language modes if there's a jump past the
1032 // declaration. We also have to do it in C if there's a jump to an
1033 // earlier point in the current block because non-VLA lifetimes begin as
1034 // soon as the containing block is entered, not when its variables
1035 // actually come into scope; suppressing the lifetime annotations
1036 // completely in this case is unnecessarily pessimistic, but again, this
1037 // is rare.
1038 if (!Bypasses.IsBypassed(&D) &&
1039 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
Vitaly Buka64c80b42016-10-26 05:42:30 +00001040 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1041 emission.SizeForLifetimeMarkers =
1042 EmitLifetimeStart(size, address.getPointer());
1043 }
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001044 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001045 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001046 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001047 }
Chris Lattner03df1222007-06-02 04:53:11 +00001048 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001049 EnsureInsertPoint();
1050
Anders Carlsson15949b32009-02-09 20:41:50 +00001051 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001052 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001053 Address Stack =
1054 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001055
Anders Carlsson30032882008-12-12 07:38:43 +00001056 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001057 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001058 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001059
1060 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001061
John McCalla464ff92010-07-21 06:13:08 +00001062 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001063 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001064 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001065 }
Mike Stump11289f42009-09-09 15:08:12 +00001066
John McCall23c29fe2011-06-24 21:55:10 +00001067 llvm::Value *elementCount;
1068 QualType elementType;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001069 std::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +00001070
Chris Lattner2192fe52011-07-18 04:24:23 +00001071 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +00001072
1073 // Allocate memory for the array.
John McCall23c29fe2011-06-24 21:55:10 +00001074 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1075 vla->setAlignment(alignment.getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +00001076
John McCall7f416cc2015-09-08 08:05:57 +00001077 address = Address(vla, alignment);
Chris Lattner03df1222007-06-02 04:53:11 +00001078 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001079
John McCall7f416cc2015-09-08 08:05:57 +00001080 setAddrOfLocalVar(&D, address);
1081 emission.Addr = address;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001082
1083 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +00001084 if (HaveInsertPoint())
1085 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001086 if (CGM.getCodeGenOpts().getDebugInfo() >=
1087 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001088 DI->setLocation(D.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001089 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001090 }
Devang Patel887e2152011-06-03 19:21:47 +00001091 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001092
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001093 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001094 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001095
John McCallc533cb72011-02-22 06:44:22 +00001096 return emission;
1097}
1098
1099/// Determines whether the given __block variable is potentially
1100/// captured by the given expression.
1101static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1102 // Skip the most common kinds of expressions that make
1103 // hierarchy-walking expensive.
1104 e = e->IgnoreParenCasts();
1105
1106 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1107 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +00001108 for (const auto &I : block->captures()) {
1109 if (I.getVariable() == &var)
John McCallc533cb72011-02-22 06:44:22 +00001110 return true;
1111 }
1112
1113 // No need to walk into the subexpressions.
1114 return false;
1115 }
1116
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001117 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1118 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001119 for (const auto *BI : CS->body())
1120 if (const auto *E = dyn_cast<Expr>(BI)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001121 if (isCapturedBy(var, E))
1122 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001123 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001124 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001125 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001126 for (const auto *I : DS->decls()) {
1127 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1128 const Expr *Init = VD->getInit();
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001129 if (Init && isCapturedBy(var, Init))
1130 return true;
1131 }
1132 }
1133 }
1134 else
1135 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1136 // Later, provide code to poke into statements for capture analysis.
1137 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001138 return false;
1139 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001140
Benjamin Kramer642f1732015-07-02 21:03:14 +00001141 for (const Stmt *SubStmt : e->children())
1142 if (isCapturedBy(var, cast<Expr>(SubStmt)))
John McCallc533cb72011-02-22 06:44:22 +00001143 return true;
1144
1145 return false;
1146}
1147
Douglas Gregor82e1af22011-07-01 21:08:19 +00001148/// \brief Determine whether the given initializer is trivial in the sense
1149/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001150bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001151 if (!Init)
1152 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001153
Douglas Gregor82e1af22011-07-01 21:08:19 +00001154 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1155 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1156 if (Constructor->isTrivial() &&
1157 Constructor->isDefaultConstructor() &&
1158 !Construct->requiresZeroInitialization())
1159 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001160
Douglas Gregor82e1af22011-07-01 21:08:19 +00001161 return false;
1162}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001163
John McCallc533cb72011-02-22 06:44:22 +00001164void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001165 assert(emission.Variable && "emission was not valid!");
1166
John McCallc533cb72011-02-22 06:44:22 +00001167 // If this was emitted as a global constant, we're done.
1168 if (emission.wasEmittedAsGlobal()) return;
1169
John McCall9e2e22f2011-02-22 07:16:58 +00001170 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001171 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001172 QualType type = D.getType();
1173
Chris Lattner07eb7332007-07-12 00:39:48 +00001174 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001175 const Expr *Init = D.getInit();
1176
1177 // If we are at an unreachable point, we don't need to emit the initializer
1178 // unless it contains a label.
1179 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001180 if (!Init || !ContainsLabel(Init)) return;
1181 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001182 }
1183
John McCall73064872011-03-31 01:59:53 +00001184 // Initialize the structure of a __block variable.
1185 if (emission.IsByRef)
1186 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001187
Douglas Gregor82e1af22011-07-01 21:08:19 +00001188 if (isTrivialInitializer(Init))
1189 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001190
John McCallc533cb72011-02-22 06:44:22 +00001191 // Check whether this is a byref variable that's potentially
1192 // captured and moved by its own initializer. If so, we'll need to
1193 // emit the initializer first, then copy into the variable.
1194 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1195
John McCall7f416cc2015-09-08 08:05:57 +00001196 Address Loc =
1197 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
John McCallc533cb72011-02-22 06:44:22 +00001198
Craig Topper8a13c412014-05-21 05:09:00 +00001199 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001200 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001201 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smithdafff942012-01-14 04:30:29 +00001202 constant = CGM.EmitConstantInit(D, this);
Richard Smithfddd3842011-12-30 21:15:51 +00001203 }
1204
1205 if (!constant) {
John McCall7f416cc2015-09-08 08:05:57 +00001206 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001207 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001208 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001209 }
John McCall91ca10f2011-03-08 09:11:50 +00001210
Richard Smith2bcde3a2013-06-02 00:09:52 +00001211 if (!emission.IsConstantAggregate) {
1212 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001213 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001214 lv.setNonGC(true);
1215 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1216 }
1217
John McCallc533cb72011-02-22 06:44:22 +00001218 // If this is a simple aggregate initialization, we can optimize it
1219 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001220 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001221
John McCall91ca10f2011-03-08 09:11:50 +00001222 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001223 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001224 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001225
Chris Lattner2192fe52011-07-18 04:24:23 +00001226 llvm::Type *BP = Int8PtrTy;
John McCall7f416cc2015-09-08 08:05:57 +00001227 if (Loc.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001228 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001229
John McCall91ca10f2011-03-08 09:11:50 +00001230 // If the initializer is all or mostly zeros, codegen with memset then do
1231 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001232 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001233 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall91ca10f2011-03-08 09:11:50 +00001234 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
John McCall7f416cc2015-09-08 08:05:57 +00001235 isVolatile);
Benjamin Kramer29f9a002012-08-27 22:07:02 +00001236 // Zero and undef don't require a stores.
1237 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall91ca10f2011-03-08 09:11:50 +00001238 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001239 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1240 isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001241 }
John McCall91ca10f2011-03-08 09:11:50 +00001242 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001243 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001244 // memcpy from the global to the alloca.
Reid Kleckner453e0562014-10-08 01:07:54 +00001245 std::string Name = getStaticDeclName(CGM, D);
Alexey Baderabdcfc12016-10-31 10:26:31 +00001246 unsigned AS = 0;
1247 if (getLangOpts().OpenCL) {
1248 AS = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
1249 BP = llvm::PointerType::getInt8PtrTy(getLLVMContext(), AS);
1250 }
John McCall91ca10f2011-03-08 09:11:50 +00001251 llvm::GlobalVariable *GV =
1252 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001253 llvm::GlobalValue::PrivateLinkage,
Alexey Baderabdcfc12016-10-31 10:26:31 +00001254 constant, Name, nullptr,
1255 llvm::GlobalValue::NotThreadLocal, AS);
John McCall7f416cc2015-09-08 08:05:57 +00001256 GV->setAlignment(Loc.getAlignment().getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001257 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Eric Christopher31ab1302011-08-23 22:38:00 +00001258
John McCall7f416cc2015-09-08 08:05:57 +00001259 Address SrcPtr = Address(GV, Loc.getAlignment());
1260 if (SrcPtr.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001261 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001262
John McCall7f416cc2015-09-08 08:05:57 +00001263 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
John McCall91ca10f2011-03-08 09:11:50 +00001264 }
1265}
1266
1267/// Emit an expression as an initializer for a variable at the given
1268/// location. The expression is not necessarily the normal
1269/// initializer for the variable, and the address is not necessarily
1270/// its normal location.
1271///
1272/// \param init the initializing expression
1273/// \param var the variable to act as if we're initializing
1274/// \param loc the address to initialize; its type is a pointer
1275/// to the LLVM mapping of the variable's type
1276/// \param alignment the alignment of the address
1277/// \param capturedByInit true if the variable is a __block variable
1278/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001279void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001280 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001281 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001282
1283 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001284 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001285 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001286 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001287 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001288 return;
1289 }
1290 switch (getEvaluationKind(type)) {
1291 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001292 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001293 return;
1294 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001295 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001296 if (capturedByInit)
1297 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001298 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001299 return;
1300 }
1301 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001302 if (type->isAtomicType()) {
1303 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1304 } else {
1305 // TODO: how can we delay here if D is captured by its initializer?
1306 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001307 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001308 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001309 AggValueSlot::IsNotAliased));
John McCalla8ec7eb2013-03-07 21:37:17 +00001310 }
John McCall47fb9502013-03-07 21:37:08 +00001311 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001312 }
John McCall47fb9502013-03-07 21:37:08 +00001313 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001314}
John McCallbd309292010-07-06 01:34:17 +00001315
John McCall82fe67b2011-07-09 01:37:26 +00001316/// Enter a destroy cleanup for the given local variable.
1317void CodeGenFunction::emitAutoVarTypeCleanup(
1318 const CodeGenFunction::AutoVarEmission &emission,
1319 QualType::DestructionKind dtorKind) {
1320 assert(dtorKind != QualType::DK_none);
1321
1322 // Note that for __block variables, we want to destroy the
1323 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001324 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001325
1326 const VarDecl *var = emission.Variable;
1327 QualType type = var->getType();
1328
1329 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001330 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001331
1332 switch (dtorKind) {
1333 case QualType::DK_none:
1334 llvm_unreachable("no cleanup for trivially-destructible variable");
1335
1336 case QualType::DK_cxx_destructor:
1337 // If there's an NRVO flag on the emission, we need a different
1338 // cleanup.
1339 if (emission.NRVOFlag) {
1340 assert(!type->isArrayType());
1341 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +00001342 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1343 dtor, emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001344 return;
1345 }
1346 break;
1347
1348 case QualType::DK_objc_strong_lifetime:
1349 // Suppress cleanups for pseudo-strong variables.
1350 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001351
John McCall82fe67b2011-07-09 01:37:26 +00001352 // Otherwise, consider whether to use an EH cleanup or not.
1353 cleanupKind = getARCCleanupKind();
1354
1355 // Use the imprecise destroyer by default.
1356 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1357 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1358 break;
1359
1360 case QualType::DK_objc_weak_lifetime:
1361 break;
1362 }
1363
1364 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001365 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001366
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001367 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001368 // is being pushed as an EH cleanup.
1369 bool useEHCleanup = (cleanupKind & EHCleanup);
1370 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1371 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001372}
1373
John McCallc533cb72011-02-22 06:44:22 +00001374void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001375 assert(emission.Variable && "emission was not valid!");
1376
John McCallc533cb72011-02-22 06:44:22 +00001377 // If this was emitted as a global constant, we're done.
1378 if (emission.wasEmittedAsGlobal()) return;
1379
John McCall8c38d352012-04-13 18:44:05 +00001380 // If we don't have an insertion point, we're done. Sema prevents
1381 // us from jumping into any of these scopes anyway.
1382 if (!HaveInsertPoint()) return;
1383
John McCall9e2e22f2011-02-22 07:16:58 +00001384 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001385
Nadav Rotem1da30942013-03-23 06:43:35 +00001386 // Make sure we call @llvm.lifetime.end. This needs to happen
1387 // *last*, so the cleanup needs to be pushed *first*.
Tim Shen421119f2016-07-01 21:08:47 +00001388 if (emission.useLifetimeMarkers())
1389 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
Nadav Rotem1da30942013-03-23 06:43:35 +00001390 emission.getAllocatedAddress(),
1391 emission.getSizeForLifetimeMarkers());
Nadav Rotem1da30942013-03-23 06:43:35 +00001392
John McCall82fe67b2011-07-09 01:37:26 +00001393 // Check the type for a cleanup.
1394 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1395 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001396
John McCall1bd25562011-06-24 23:21:27 +00001397 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001398 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001399 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1400 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1401 }
1402
John McCallc533cb72011-02-22 06:44:22 +00001403 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001404 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001405 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001406
John McCallc533cb72011-02-22 06:44:22 +00001407 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001408 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001409
John McCalla729c622012-02-17 03:33:10 +00001410 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001411 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001412 }
Mike Stump626aecc2009-03-05 01:23:13 +00001413
John McCallc533cb72011-02-22 06:44:22 +00001414 // If this is a block variable, call _Block_object_destroy
1415 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001416 if (emission.IsByRef)
1417 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001418}
Chris Lattner53621a52007-06-13 20:44:40 +00001419
Peter Collingbourne1425b452012-01-26 03:33:36 +00001420CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001421CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1422 switch (kind) {
1423 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001424 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001425 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001426 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001427 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001428 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001429 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001430 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001431 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001432}
1433
John McCall12cc42a2013-02-01 05:11:40 +00001434/// pushEHDestroy - Push the standard destructor for the given type as
1435/// an EH-only cleanup.
1436void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001437 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00001438 assert(dtorKind && "cannot push destructor for trivial type");
1439 assert(needsEHCleanup(dtorKind));
1440
1441 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1442}
1443
1444/// pushDestroy - Push the standard destructor for the given type as
1445/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001446void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001447 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00001448 assert(dtorKind && "cannot push destructor for trivial type");
1449
1450 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1451 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1452 cleanupKind & EHCleanup);
1453}
1454
John McCall7f416cc2015-09-08 08:05:57 +00001455void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001456 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001457 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001458 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1459 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001460}
1461
John McCall7f416cc2015-09-08 08:05:57 +00001462void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001463 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1464}
1465
Richard Smith736a9472013-06-12 20:42:33 +00001466void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00001467 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00001468 Destroyer *destroyer, bool useEHCleanupForArray) {
1469 assert(!isInConditionalBranch() &&
1470 "performing lifetime extension from within conditional");
1471
1472 // Push an EH-only cleanup for the object now.
1473 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1474 // around in case a temporary's destructor throws an exception.
1475 if (cleanupKind & EHCleanup)
1476 EHStack.pushCleanup<DestroyObject>(
1477 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1478 destroyer, useEHCleanupForArray);
1479
1480 // Remember that we need to push a full cleanup for the object at the
1481 // end of the full-expression.
1482 pushCleanupAfterFullExpr<DestroyObject>(
1483 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1484}
1485
John McCall178360e2011-07-11 08:38:19 +00001486/// emitDestroy - Immediately perform the destruction of the given
1487/// object.
1488///
1489/// \param addr - the address of the object; a type*
1490/// \param type - the type of the object; if an array type, all
1491/// objects are destroyed in reverse order
1492/// \param destroyer - the function to call to destroy individual
1493/// elements
1494/// \param useEHCleanupForArray - whether an EH cleanup should be
1495/// used when destroying array elements, in case one of the
1496/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00001497void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001498 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001499 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001500 const ArrayType *arrayType = getContext().getAsArrayType(type);
1501 if (!arrayType)
1502 return destroyer(*this, addr, type);
1503
John McCall7f416cc2015-09-08 08:05:57 +00001504 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1505
1506 CharUnits elementAlign =
1507 addr.getAlignment()
1508 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00001509
1510 // Normally we have to check whether the array is zero-length.
1511 bool checkZeroLength = true;
1512
1513 // But if the array length is constant, we can suppress that.
1514 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1515 // ...and if it's constant zero, we can just skip the entire thing.
1516 if (constLength->isZero()) return;
1517 checkZeroLength = false;
1518 }
1519
John McCall7f416cc2015-09-08 08:05:57 +00001520 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00001521 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00001522 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001523 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001524}
1525
John McCall178360e2011-07-11 08:38:19 +00001526/// emitArrayDestroy - Destroys all the elements of the given array,
1527/// beginning from last to first. The array cannot be zero-length.
1528///
1529/// \param begin - a type* denoting the first element of the array
1530/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001531/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00001532/// \param destroyer - the function to call to destroy elements
1533/// \param useEHCleanup - whether to push an EH cleanup to destroy
1534/// the remaining elements in case the destruction of a single
1535/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001536void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1537 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001538 QualType elementType,
1539 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001540 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001541 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001542 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00001543 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00001544
1545 // The basic structure here is a do-while loop, because we don't
1546 // need to check for the zero-element case.
1547 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1548 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1549
John McCall97eab0a2011-07-13 08:09:46 +00001550 if (checkZeroLength) {
1551 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1552 "arraydestroy.isempty");
1553 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1554 }
1555
John McCall82fe67b2011-07-09 01:37:26 +00001556 // Enter the loop body, making that address the current address.
1557 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1558 EmitBlock(bodyBB);
1559 llvm::PHINode *elementPast =
1560 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1561 elementPast->addIncoming(end, entryBB);
1562
1563 // Shift the address back by one element.
1564 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1565 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1566 "arraydestroy.element");
1567
John McCall178360e2011-07-11 08:38:19 +00001568 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00001569 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1570 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001571
John McCall82fe67b2011-07-09 01:37:26 +00001572 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00001573 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00001574
John McCall178360e2011-07-11 08:38:19 +00001575 if (useEHCleanup)
1576 PopCleanupBlock();
1577
John McCall82fe67b2011-07-09 01:37:26 +00001578 // Check whether we've reached the end.
1579 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1580 Builder.CreateCondBr(done, doneBB, bodyBB);
1581 elementPast->addIncoming(element, Builder.GetInsertBlock());
1582
1583 // Done.
1584 EmitBlock(doneBB);
1585}
1586
John McCall178360e2011-07-11 08:38:19 +00001587/// Perform partial array destruction as if in an EH cleanup. Unlike
1588/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001589static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1590 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001591 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001592 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001593 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001594 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001595 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1596 // VLAs don't require a GEP index to walk into.
1597 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001598 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001599 type = arrayType->getElementType();
1600 }
John McCall97eab0a2011-07-13 08:09:46 +00001601
1602 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00001603 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00001604
John McCallf0f0b7a2015-09-14 18:57:08 +00001605 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001606 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1607 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001608 }
1609
John McCall97eab0a2011-07-13 08:09:46 +00001610 // Destroy the array. We don't ever need an EH cleanup because we
1611 // assume that we're in an EH cleanup ourselves, so a throwing
1612 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00001613 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001614 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001615}
1616
John McCall82fe67b2011-07-09 01:37:26 +00001617namespace {
John McCall178360e2011-07-11 08:38:19 +00001618 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1619 /// array destroy where the end pointer is regularly determined and
1620 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001621 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00001622 llvm::Value *ArrayBegin;
1623 llvm::Value *ArrayEnd;
1624 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001625 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001626 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00001627 public:
1628 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001629 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001630 CodeGenFunction::Destroyer *destroyer)
1631 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00001632 ElementType(elementType), Destroyer(destroyer),
1633 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00001634
Craig Topper4f12f102014-03-12 06:41:41 +00001635 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001636 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001637 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00001638 }
1639 };
1640
1641 /// IrregularPartialArrayDestroy - a cleanup which performs a
1642 /// partial array destroy where the end pointer is irregularly
1643 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001644 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001645 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00001646 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00001647 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001648 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001649 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00001650 public:
John McCall178360e2011-07-11 08:38:19 +00001651 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001652 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001653 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001654 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001655 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001656 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00001657 ElementType(elementType), Destroyer(destroyer),
1658 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00001659
Craig Topper4f12f102014-03-12 06:41:41 +00001660 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001661 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001662 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001663 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001664 }
1665 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001666} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00001667
John McCall178360e2011-07-11 08:38:19 +00001668/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001669/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001670/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001671///
John McCall82fe67b2011-07-09 01:37:26 +00001672/// \param elementType - the immediate element type of the array;
1673/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001674void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001675 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001676 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001677 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001678 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001679 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1680 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00001681 elementType, elementAlign,
1682 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001683}
1684
1685/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1686/// already-constructed elements of the given array. The cleanup
1687/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001688///
John McCall178360e2011-07-11 08:38:19 +00001689/// \param elementType - the immediate element type of the array;
1690/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001691void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1692 llvm::Value *arrayEnd,
1693 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001694 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001695 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001696 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001697 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001698 elementType, elementAlign,
1699 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001700}
1701
Nadav Rotem1da30942013-03-23 06:43:35 +00001702/// Lazily declare the @llvm.lifetime.start intrinsic.
1703llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1704 if (LifetimeStartFn) return LifetimeStartFn;
1705 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1706 llvm::Intrinsic::lifetime_start);
1707 return LifetimeStartFn;
1708}
1709
1710/// Lazily declare the @llvm.lifetime.end intrinsic.
1711llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1712 if (LifetimeEndFn) return LifetimeEndFn;
1713 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1714 llvm::Intrinsic::lifetime_end);
1715 return LifetimeEndFn;
1716}
1717
John McCall31168b02011-06-15 23:02:42 +00001718namespace {
1719 /// A cleanup to perform a release of an object at the end of a
1720 /// function. This is used to balance out the incoming +1 of a
1721 /// ns_consumed argument when we can't reasonably do that just by
1722 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00001723 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001724 ConsumeARCParameter(llvm::Value *param,
1725 ARCPreciseLifetime_t precise)
1726 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001727
1728 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001729 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001730
Craig Topper4f12f102014-03-12 06:41:41 +00001731 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001732 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001733 }
1734 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001735} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00001736
Mike Stump11289f42009-09-09 15:08:12 +00001737/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001738/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00001739void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1740 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001741 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001742 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001743 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001744
John McCall7f416cc2015-09-08 08:05:57 +00001745 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00001746
Adrian Prantl51936dd2013-03-14 17:53:33 +00001747 QualType Ty = D.getType();
1748
John McCall147d0212011-02-22 22:38:33 +00001749 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00001750 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00001751 // The only implicit argument a block has is its literal.
John McCall7f416cc2015-09-08 08:05:57 +00001752 // We assume this is always passed directly.
John McCall147d0212011-02-22 22:38:33 +00001753 if (BlockInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001754 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
John McCall147d0212011-02-22 22:38:33 +00001755 return;
1756 }
Reid Klecknere5a321b2016-09-07 18:21:30 +00001757
1758 // Apply any prologue 'this' adjustments required by the ABI. Be careful to
1759 // handle the case where 'this' is passed indirectly as part of an inalloca
1760 // struct.
1761 if (const CXXMethodDecl *MD =
1762 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
1763 if (MD->isVirtual() && IPD == CXXABIThisDecl) {
1764 llvm::Value *This = Arg.isIndirect()
1765 ? Builder.CreateLoad(Arg.getIndirectAddress())
1766 : Arg.getDirectValue();
1767 This = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue(
1768 *this, CurGD, This);
1769 if (Arg.isIndirect())
1770 Builder.CreateStore(This, Arg.getIndirectAddress());
1771 else
1772 Arg = ParamValue::forDirect(This);
1773 }
1774 }
John McCall147d0212011-02-22 22:38:33 +00001775 }
1776
John McCall7f416cc2015-09-08 08:05:57 +00001777 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001778 bool DoStore = false;
1779 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001780 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001781 if (Arg.isIndirect()) {
1782 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001783 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00001784 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001785 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00001786 if (DeclPtr.getType() != IRTy)
1787 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1788
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001789 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00001790 // Don't push a cleanup in a thunk for a method that will also emit a
1791 // cleanup.
1792 if (!IsScalar && !CurFuncIsThunk &&
Reid Kleckner739756c2013-12-04 19:23:12 +00001793 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001794 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1795 if (RD && RD->hasNonTrivialDestructor())
1796 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001797 }
Chris Lattner53621a52007-06-13 20:44:40 +00001798 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001799 // Otherwise, create a temporary to hold the value.
John McCall7f416cc2015-09-08 08:05:57 +00001800 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1801 D.getName() + ".addr");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001802 DoStore = true;
1803 }
Mike Stump11289f42009-09-09 15:08:12 +00001804
John McCall7f416cc2015-09-08 08:05:57 +00001805 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1806
1807 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001808 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00001809 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001810 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1811 // We honor __attribute__((ns_consumed)) for types with lifetime.
1812 // For __strong, it's handled by just skipping the initial retain;
1813 // otherwise we have to balance out the initial +1 with an extra
1814 // cleanup to do the release at the end of the function.
1815 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1816
1817 // 'self' is always formally __strong, but if this is not an
1818 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001819 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001820 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1821 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001822 assert(lt == Qualifiers::OCL_Strong);
1823 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001824 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001825 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001826 lt = Qualifiers::OCL_ExplicitNone;
1827 }
1828
1829 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001830 if (!isConsumed) {
1831 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1832 // use objc_storeStrong(&dest, value) for retaining the
1833 // object. But first, store a null into 'dest' because
1834 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001835 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001836 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
John McCall7f416cc2015-09-08 08:05:57 +00001837 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001838 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001839 }
1840 else
John McCall31168b02011-06-15 23:02:42 +00001841 // Don't use objc_retainBlock for block pointers, because we
1842 // don't want to Block_copy something just because we got it
1843 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00001844 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001845 }
John McCall31168b02011-06-15 23:02:42 +00001846 } else {
1847 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00001848 if (isConsumed) {
1849 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1850 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00001851 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00001852 precise);
1853 }
John McCall31168b02011-06-15 23:02:42 +00001854
1855 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00001856 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001857 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001858 }
1859 }
1860
1861 // Enter the cleanup scope.
1862 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1863 }
Chris Lattner53621a52007-06-13 20:44:40 +00001864 }
1865
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001866 // Store the initial value into the alloca.
1867 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00001868 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001869
John McCall7f416cc2015-09-08 08:05:57 +00001870 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001871
1872 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001873 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001874 if (CGM.getCodeGenOpts().getDebugInfo() >=
1875 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001876 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001877 }
1878 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001879
1880 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001881 EmitVarAnnotations(&D, DeclPtr.getPointer());
Chris Lattner53621a52007-06-13 20:44:40 +00001882}
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001883
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001884void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1885 CodeGenFunction *CGF) {
1886 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1887 return;
1888 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
1889}