blob: 10a0b46d9028a9f6b1b766259753beca969342a0 [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:
Richard Smithbc491202017-02-17 20:05:37 +000053 case Decl::CXXDeductionGuide:
Douglas Gregor19043f02010-04-23 02:02:43 +000054 case Decl::CXXMethod:
55 case Decl::CXXConstructor:
56 case Decl::CXXDestructor:
57 case Decl::CXXConversion:
58 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000059 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000060 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000061 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000062 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000063 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000064 case Decl::ImplicitParam:
65 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000066 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000067 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000068 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000069 case Decl::TemplateTemplateParm:
70 case Decl::ObjCMethod:
71 case Decl::ObjCCategory:
72 case Decl::ObjCProtocol:
73 case Decl::ObjCInterface:
74 case Decl::ObjCCategoryImpl:
75 case Decl::ObjCImplementation:
76 case Decl::ObjCProperty:
77 case Decl::ObjCCompatibleAlias:
Nico Weber66220292016-03-02 17:28:48 +000078 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +000079 case Decl::PragmaDetectMismatch:
Abramo Bagnarad7340582010-06-05 05:09:32 +000080 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000081 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +000082 case Decl::Export:
Douglas Gregor19043f02010-04-23 02:02:43 +000083 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000084 case Decl::FileScopeAsm:
85 case Decl::Friend:
86 case Decl::FriendTemplate:
87 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000088 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000089 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000090 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +000091 case Decl::ConstructorUsingShadow:
Douglas Gregor85f3f952015-07-07 03:57:15 +000092 case Decl::ObjCTypeParam:
Richard Smithda383632016-08-15 01:33:41 +000093 case Decl::Binding:
David Blaikie83d382b2011-09-23 05:06:16 +000094 llvm_unreachable("Declaration should not be in declstmts!");
Amjad Abouddc4531e2016-04-30 01:44:38 +000095 case Decl::Function: // void X();
96 case Decl::Record: // struct/union/class X;
97 case Decl::Enum: // enum X;
98 case Decl::EnumConstant: // enum ? { X = ? }
99 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +0000100 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +0000101 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +0000102 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000103 case Decl::OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000104 case Decl::OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +0000105 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +0000106 // None of these decls require codegen support.
107 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +0000108
David Blaikief121b932013-05-20 22:50:41 +0000109 case Decl::NamespaceAlias:
110 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000111 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
David Blaikief121b932013-05-20 22:50:41 +0000112 return;
David Blaikiebd483762013-05-20 04:58:53 +0000113 case Decl::Using: // using X; [C++]
114 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000115 DI->EmitUsingDecl(cast<UsingDecl>(D));
David Blaikiebd483762013-05-20 04:58:53 +0000116 return;
Richard Smith151c4562016-12-20 21:35:28 +0000117 case Decl::UsingPack:
118 for (auto *Using : cast<UsingPackDecl>(D).expansions())
119 EmitDecl(*Using);
120 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000121 case Decl::UsingDirective: // using namespace X; [C++]
122 if (CGDebugInfo *DI = getDebugInfo())
123 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
124 return;
Richard Smithbdb84f32016-07-22 23:36:59 +0000125 case Decl::Var:
126 case Decl::Decomposition: {
Daniel Dunbara7998072008-08-29 17:28:43 +0000127 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000128 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000129 "Should not see file-scope variables inside a function!");
Richard Smithda383632016-08-15 01:33:41 +0000130 EmitVarDecl(VD);
131 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
132 for (auto *B : DD->bindings())
133 if (auto *HD = B->getHoldingVar())
134 EmitVarDecl(*HD);
135 return;
Chris Lattner84915fa2007-06-02 04:16:21 +0000136 }
Mike Stump11289f42009-09-09 15:08:12 +0000137
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000138 case Decl::OMPDeclareReduction:
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000139 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000140
Richard Smithdda56e42011-04-15 14:24:37 +0000141 case Decl::Typedef: // typedef int X;
142 case Decl::TypeAlias: { // using X = int; [C++0x]
143 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000144 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000145
Anders Carlsson5d985f52008-12-20 21:51:53 +0000146 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000147 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000148 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000149 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000150}
Chris Lattner03df1222007-06-02 04:53:11 +0000151
John McCall1c9c3fd2010-10-15 04:57:14 +0000152/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000153/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000154void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000155 if (D.isStaticLocal()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000156 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000157 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000158
David Majnemer27d69db2014-04-28 22:17:59 +0000159 // FIXME: We need to force the emission/use of a guard variable for
160 // some variables even if we can constant-evaluate them because
161 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000162
John McCall1c9c3fd2010-10-15 04:57:14 +0000163 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000164 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000165
166 if (D.hasExternalStorage())
Lauro Ramos Venanciobada8d42008-02-16 22:30:38 +0000167 // Don't emit it now, allow it to be emitted lazily on its first use.
168 return;
Daniel Dunbar0ca16602009-04-14 02:25:56 +0000169
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000170 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000171 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
172
173 assert(D.hasLocalStorage());
174 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000175}
176
Reid Kleckner453e0562014-10-08 01:07:54 +0000177static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
178 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000179 return CGM.getMangledName(&D).str();
180
Reid Kleckner453e0562014-10-08 01:07:54 +0000181 // If this isn't C++, we don't need a mangled name, just a pretty one.
182 assert(!D.isExternallyVisible() && "name shouldn't matter");
183 std::string ContextName;
184 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000185 if (auto *CD = dyn_cast<CapturedDecl>(DC))
186 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000187 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000188 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000189 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
190 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
191 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
192 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000193 else
David Blaikie83d382b2011-09-23 05:06:16 +0000194 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000195
Reid Kleckner453e0562014-10-08 01:07:54 +0000196 ContextName += "." + D.getNameAsString();
197 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000198}
199
Reid Kleckner453e0562014-10-08 01:07:54 +0000200llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
201 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
202 // In general, we don't always emit static var decls once before we reference
203 // them. It is possible to reference them before emitting the function that
204 // contains them, and it is possible to emit the containing function multiple
205 // times.
206 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
207 return ExistingGV;
208
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000209 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000210 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000211
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000212 // Use the label if the variable is renamed with the asm-label extension.
213 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000214 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000215 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000216 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000217 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000218
Reid Kleckner453e0562014-10-08 01:07:54 +0000219 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000220 unsigned AddrSpace =
Reid Kleckner453e0562014-10-08 01:07:54 +0000221 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000222
223 // Local address space cannot have an initializer.
224 llvm::Constant *Init = nullptr;
225 if (Ty.getAddressSpace() != LangAS::opencl_local)
226 Init = EmitNullConstant(Ty);
227 else
228 Init = llvm::UndefValue::get(LTy);
229
Anders Carlssone33eed52009-09-26 18:16:06 +0000230 llvm::GlobalVariable *GV =
Reid Kleckner453e0562014-10-08 01:07:54 +0000231 new llvm::GlobalVariable(getModule(), LTy,
Anders Carlssone33eed52009-09-26 18:16:06 +0000232 Ty.isConstant(getContext()), Linkage,
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000233 Init, Name, nullptr,
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000234 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000235 AddrSpace);
Ken Dyck160146e2010-01-27 17:10:57 +0000236 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Reid Kleckner453e0562014-10-08 01:07:54 +0000237 setGlobalVisibility(GV, &D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000238
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000239 if (supportsCOMDAT() && GV->isWeakForLinker())
240 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000241
Richard Smithfd3834f2013-04-13 02:43:54 +0000242 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000243 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000244
Hans Wennborgef2272c2014-06-18 15:55:13 +0000245 if (D.isExternallyVisible()) {
246 if (D.hasAttr<DLLImportAttr>())
247 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
248 else if (D.hasAttr<DLLExportAttr>())
249 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
250 }
251
Eli Benderskycb399432014-03-24 22:05:38 +0000252 // Make sure the result is of the correct type.
Reid Kleckner453e0562014-10-08 01:07:54 +0000253 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
254 llvm::Constant *Addr = GV;
Eli Benderskycb399432014-03-24 22:05:38 +0000255 if (AddrSpace != ExpectedAddrSpace) {
256 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
Reid Kleckner453e0562014-10-08 01:07:54 +0000257 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
Eli Benderskycb399432014-03-24 22:05:38 +0000258 }
259
Reid Kleckner453e0562014-10-08 01:07:54 +0000260 setStaticLocalDeclAddress(&D, Addr);
261
262 // Ensure that the static local gets initialized by making sure the parent
263 // function gets emitted eventually.
264 const Decl *DC = cast<Decl>(D.getDeclContext());
265
266 // We can't name blocks or captured statements directly, so try to emit their
267 // parents.
268 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
269 DC = DC->getNonClosureContext();
270 // FIXME: Ensure that global blocks get emitted.
271 if (!DC)
272 return Addr;
273 }
274
275 GlobalDecl GD;
276 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
277 GD = GlobalDecl(CD, Ctor_Base);
278 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
279 GD = GlobalDecl(DD, Dtor_Base);
280 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
281 GD = GlobalDecl(FD);
282 else {
283 // Don't do anything for Obj-C method decls or global closures. We should
284 // never defer them.
285 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
286 }
287 if (GD.getDecl())
288 (void)GetAddrOfGlobal(GD);
289
290 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000291}
292
Richard Smith6331c402012-02-13 22:16:19 +0000293/// hasNontrivialDestruction - Determine whether a type's destruction is
294/// non-trivial. If so, and the variable uses static initialization, we must
295/// register its destructor to run on exit.
296static bool hasNontrivialDestruction(QualType T) {
297 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
298 return RD && !RD->hasTrivialDestructor();
299}
300
Chandler Carruth84537952012-03-30 19:44:53 +0000301/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
302/// global variable that has already been created for it. If the initializer
303/// has a different type than GV does, this may free GV and return a different
304/// one. Otherwise it just returns GV.
305llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000306CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000307 llvm::GlobalVariable *GV) {
308 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCall70013b62010-07-15 23:40:35 +0000309
Chris Lattnere99c1102009-12-05 08:22:11 +0000310 // If constant emission failed, then this should be a C++ static
311 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000312 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000313 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000314 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
Matthias Braun44bfe032017-01-10 17:43:01 +0000315 else if (HaveInsertPoint()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000316 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000317 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000318 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000319
Chandler Carruth84537952012-03-30 19:44:53 +0000320 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000321 }
Chandler Carruth84537952012-03-30 19:44:53 +0000322 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000323 }
John McCall70013b62010-07-15 23:40:35 +0000324
Chris Lattnere99c1102009-12-05 08:22:11 +0000325 // The initializer may differ in type from the global. Rewrite
326 // the global to match the initializer. (We have to do this
327 // because some types, like unions, can't be completely represented
328 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000329 if (GV->getType()->getElementType() != Init->getType()) {
330 llvm::GlobalVariable *OldGV = GV;
331
332 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
333 OldGV->isConstant(),
334 OldGV->getLinkage(), Init, "",
335 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000336 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000337 CGM.getContext().getTargetAddressSpace(D.getType()));
338 GV->setVisibility(OldGV->getVisibility());
Reid Klecknereab97d32015-07-20 20:35:30 +0000339 GV->setComdat(OldGV->getComdat());
Eric Christopher31ab1302011-08-23 22:38:00 +0000340
Chris Lattnere99c1102009-12-05 08:22:11 +0000341 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000342 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000343
Chris Lattnere99c1102009-12-05 08:22:11 +0000344 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000345 llvm::Constant *NewPtrForOldDecl =
346 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
347 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000348
Chris Lattnere99c1102009-12-05 08:22:11 +0000349 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000350 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000351 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000352
Chandler Carruth84537952012-03-30 19:44:53 +0000353 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
354 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000355
Matthias Braun44bfe032017-01-10 17:43:01 +0000356 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
Richard Smith6331c402012-02-13 22:16:19 +0000357 // We have a constant initializer, but a nontrivial destructor. We still
358 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000359 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000360 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000361 }
362
Chandler Carruth84537952012-03-30 19:44:53 +0000363 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000364}
365
John McCall1c9c3fd2010-10-15 04:57:14 +0000366void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000367 llvm::GlobalValue::LinkageTypes Linkage) {
John McCallb88a5662012-03-30 21:00:39 +0000368 // Check to see if we already have a global variable for this
369 // declaration. This can happen when double-emitting function
370 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000371 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
John McCall7f416cc2015-09-08 08:05:57 +0000372 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara374e602009-02-25 19:45:19 +0000373
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000374 // Store into LocalDeclMap before generating initializer to handle
375 // circular references.
John McCall7f416cc2015-09-08 08:05:57 +0000376 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000377
John McCall4a39ab82010-05-04 20:45:42 +0000378 // We can't have a VLA here, but we can have a pointer to a VLA,
379 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000380 // Make sure to evaluate VLA bounds now so that we have them for later.
381 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000382 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000383
John McCallb88a5662012-03-30 21:00:39 +0000384 // Save the type in case adding the initializer forces a type change.
385 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000386
Eli Benderskycb399432014-03-24 22:05:38 +0000387 llvm::GlobalVariable *var =
388 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Artem Belevich4d430ba2016-05-09 22:09:56 +0000389
390 // CUDA's local and local static __shared__ variables should not
391 // have any non-empty initializers. This is ensured by Sema.
392 // Whatever initializer such variable may have when it gets here is
393 // a no-op and should not be emitted.
394 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
395 D.hasAttr<CUDASharedAttr>();
Chris Lattnere99c1102009-12-05 08:22:11 +0000396 // If this value has an initializer, emit it.
Artem Belevich4d430ba2016-05-09 22:09:56 +0000397 if (D.getInit() && !isCudaSharedVar)
John McCallb88a5662012-03-30 21:00:39 +0000398 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000399
John McCall7f416cc2015-09-08 08:05:57 +0000400 var->setAlignment(alignment.getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000401
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000402 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000403 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000404
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000405 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000406 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000407
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000408 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000409 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000410
Chandler Carruth84537952012-03-30 19:44:53 +0000411 // We may have to cast the constant because of the initializer
412 // mismatch above.
413 //
414 // FIXME: It is really dangerous to store this in the map; if anyone
415 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000416 llvm::Constant *castedAddr =
417 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCall7f416cc2015-09-08 08:05:57 +0000418 if (var != castedAddr)
419 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCallb88a5662012-03-30 21:00:39 +0000420 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000421
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000422 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000423
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000424 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000425 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000426 if (DI &&
Benjamin Kramer8c305922016-02-02 11:06:51 +0000427 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000428 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000429 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000430 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000431}
Mike Stump11289f42009-09-09 15:08:12 +0000432
John McCall2b7fc382010-07-13 20:32:21 +0000433namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000434 struct DestroyObject final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000435 DestroyObject(Address addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000436 CodeGenFunction::Destroyer *destroyer,
437 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000438 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000439 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000440
John McCall7f416cc2015-09-08 08:05:57 +0000441 Address addr;
John McCall82fe67b2011-07-09 01:37:26 +0000442 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000443 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000444 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000445
Craig Topper4f12f102014-03-12 06:41:41 +0000446 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000447 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000448 bool useEHCleanupForArray =
449 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000450
451 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000452 }
453 };
454
David Blaikie7e70d682015-08-18 22:40:54 +0000455 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000456 DestroyNRVOVariable(Address addr,
John McCall82fe67b2011-07-09 01:37:26 +0000457 const CXXDestructorDecl *Dtor,
458 llvm::Value *NRVOFlag)
459 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000460
461 const CXXDestructorDecl *Dtor;
462 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000463 Address Loc;
John McCall2b7fc382010-07-13 20:32:21 +0000464
Craig Topper4f12f102014-03-12 06:41:41 +0000465 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000466 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000467 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000468
Craig Topper8a13c412014-05-21 05:09:00 +0000469 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000470 if (NRVO) {
471 // If we exited via NRVO, we skip the destructor call.
472 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
473 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000474 llvm::Value *DidNRVO =
475 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000476 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
477 CGF.EmitBlock(RunDtorBB);
478 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000479
John McCall2b7fc382010-07-13 20:32:21 +0000480 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +0000481 /*ForVirtualBase=*/false,
482 /*Delegating=*/false,
483 Loc);
John McCall2b7fc382010-07-13 20:32:21 +0000484
485 if (NRVO) CGF.EmitBlock(SkipDtorBB);
486 }
487 };
John McCall2b7fc382010-07-13 20:32:21 +0000488
David Blaikie7e70d682015-08-18 22:40:54 +0000489 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000490 Address Stack;
491 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000492 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000493 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000494 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
495 CGF.Builder.CreateCall(F, V);
496 }
497 };
498
David Blaikie7e70d682015-08-18 22:40:54 +0000499 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000500 const VarDecl &Var;
501 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
502
Craig Topper4f12f102014-03-12 06:41:41 +0000503 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000504 // Compute the address of the local variable, in case it's a
505 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000506 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
507 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000508 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
509 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000510 CGF.EmitExtendGCLifetime(value);
511 }
512 };
513
David Blaikie7e70d682015-08-18 22:40:54 +0000514 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000515 llvm::Constant *CleanupFn;
516 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000517 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000518
John McCalla464ff92010-07-21 06:13:08 +0000519 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000520 const VarDecl *Var)
521 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000522
Craig Topper4f12f102014-03-12 06:41:41 +0000523 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000524 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
525 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000526 // Compute the address of the local variable, in case it's a byref
527 // or something.
John McCall7f416cc2015-09-08 08:05:57 +0000528 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCallc533cb72011-02-22 06:44:22 +0000529
John McCalla464ff92010-07-21 06:13:08 +0000530 // In some cases, the type of the function argument will be different from
531 // the type of the pointer. An example of this is
532 // void f(void* arg);
533 // __attribute__((cleanup(f))) void *g;
534 //
535 // To fix this we insert a bitcast here.
536 QualType ArgTy = FnInfo.arg_begin()->type;
537 llvm::Value *Arg =
538 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
539
540 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000541 Args.add(RValue::get(Arg),
542 CGF.getContext().getPointerType(Var.getType()));
John McCallb92ab1a2016-10-26 23:46:34 +0000543 auto Callee = CGCallee::forDirect(CleanupFn);
544 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
John McCalla464ff92010-07-21 06:13:08 +0000545 }
546 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000547} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000548
John McCall31168b02011-06-15 23:02:42 +0000549/// EmitAutoVarWithLifetime - Does the setup required for an automatic
550/// variable with lifetime.
551static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000552 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000553 Qualifiers::ObjCLifetime lifetime) {
554 switch (lifetime) {
555 case Qualifiers::OCL_None:
556 llvm_unreachable("present but none");
557
558 case Qualifiers::OCL_ExplicitNone:
559 // nothing to do
560 break;
561
562 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000563 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000564 (var.hasAttr<ObjCPreciseLifetimeAttr>()
565 ? CodeGenFunction::destroyARCStrongPrecise
566 : CodeGenFunction::destroyARCStrongImprecise);
567
568 CleanupKind cleanupKind = CGF.getARCCleanupKind();
569 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
570 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000571 break;
572 }
573 case Qualifiers::OCL_Autoreleasing:
574 // nothing to do
575 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000576
John McCall31168b02011-06-15 23:02:42 +0000577 case Qualifiers::OCL_Weak:
578 // __weak objects always get EH cleanups; otherwise, exceptions
579 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000580 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
581 CodeGenFunction::destroyARCWeak,
582 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000583 break;
584 }
585}
586
587static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
588 if (const Expr *e = dyn_cast<Expr>(s)) {
589 // Skip the most common kinds of expressions that make
590 // hierarchy-walking expensive.
591 s = e = e->IgnoreParenCasts();
592
593 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
594 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000595 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
596 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000597 for (const auto &I : block->captures()) {
598 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000599 return true;
600 }
601 }
John McCall31168b02011-06-15 23:02:42 +0000602 }
603
Benjamin Kramer642f1732015-07-02 21:03:14 +0000604 for (const Stmt *SubStmt : s->children())
605 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
606 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000607 return true;
608
609 return false;
610}
611
612static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
613 if (!decl) return false;
614 if (!isa<VarDecl>(decl)) return false;
615 const VarDecl *var = cast<VarDecl>(decl);
616 return isAccessedBy(*var, e);
617}
618
John McCallf8a9b662015-10-21 18:06:31 +0000619static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
620 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000621 bool needsCast = false;
622
John McCallf8a9b662015-10-21 18:06:31 +0000623 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
624 switch (castExpr->getCastKind()) {
625 // Look through casts that don't require representation changes.
626 case CK_NoOp:
627 case CK_BitCast:
628 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000629 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000630 break;
631
632 // If we find an l-value to r-value cast from a __weak variable,
633 // emit this operation as a copy or move.
634 case CK_LValueToRValue: {
635 const Expr *srcExpr = castExpr->getSubExpr();
636 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
637 return false;
638
639 // Emit the source l-value.
640 LValue srcLV = CGF.EmitLValue(srcExpr);
641
John McCall0204e342015-11-16 22:11:41 +0000642 // Handle a formal type change to avoid asserting.
643 auto srcAddr = srcLV.getAddress();
644 if (needsCast) {
645 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
646 destLV.getAddress().getElementType());
647 }
648
John McCallf8a9b662015-10-21 18:06:31 +0000649 // If it was an l-value, use objc_copyWeak.
650 if (srcExpr->getValueKind() == VK_LValue) {
John McCall0204e342015-11-16 22:11:41 +0000651 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000652 } else {
653 assert(srcExpr->getValueKind() == VK_XValue);
John McCall0204e342015-11-16 22:11:41 +0000654 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000655 }
656 return true;
657 }
658
659 // Stop at anything else.
660 default:
661 return false;
662 }
663
664 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000665 }
666 return false;
667}
668
John McCall1553b192011-06-16 04:16:24 +0000669static void drillIntoBlockVariable(CodeGenFunction &CGF,
670 LValue &lvalue,
671 const VarDecl *var) {
John McCall7f416cc2015-09-08 08:05:57 +0000672 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCall1553b192011-06-16 04:16:24 +0000673}
674
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000675void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
676 SourceLocation Loc) {
677 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
678 return;
679
680 auto Nullability = LHS.getType()->getNullability(getContext());
681 if (!Nullability || *Nullability != NullabilityKind::NonNull)
682 return;
683
684 // Check if the right hand side of the assignment is nonnull, if the left
685 // hand side must be nonnull.
686 SanitizerScope SanScope(this);
687 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000688 llvm::Constant *StaticData[] = {
689 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
Simon Pilgrim2df19982017-03-14 21:43:52 +0000690 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
Vedant Kumar2b9f48a2017-03-14 16:48:29 +0000691 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000692 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
693 SanitizerHandler::TypeMismatch, StaticData, RHS);
694}
695
David Blaikie73ca5692014-12-09 00:32:22 +0000696void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000697 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000698 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000699 if (!lifetime) {
700 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000701 if (capturedByInit)
702 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000703 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
David Blaikie66e41972015-01-14 07:38:27 +0000704 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000705 return;
706 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000707
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000708 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
709 init = DIE->getExpr();
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000710
John McCall31168b02011-06-15 23:02:42 +0000711 // If we're emitting a value with lifetime, we have to do the
712 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000713 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
714 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000715 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000716 }
717 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000718
719 // We have to maintain the illusion that the variable is
720 // zero-initialized. If the variable might be accessed in its
721 // initializer, zero-initialize before running the initializer, then
722 // actually perform the initialization with an assign.
723 bool accessedByInit = false;
724 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000725 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000726 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000727 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000728 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000729 if (capturedByInit) {
730 // We can use a simple GEP for this because it can't have been
731 // moved yet.
John McCall7f416cc2015-09-08 08:05:57 +0000732 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
733 cast<VarDecl>(D),
734 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000735 }
736
John McCall7f416cc2015-09-08 08:05:57 +0000737 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
Yaxun Liu402804b2016-12-15 08:09:08 +0000738 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000739
John McCall31168b02011-06-15 23:02:42 +0000740 // If __weak, we want to use a barrier under certain conditions.
741 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000742 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000743
744 // Otherwise just do a simple store.
745 else
David Chisnallfa35df62012-01-16 17:27:18 +0000746 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000747 }
748
749 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000750 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000751
752 switch (lifetime) {
753 case Qualifiers::OCL_None:
754 llvm_unreachable("present but none");
755
756 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000757 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000758 break;
759
760 case Qualifiers::OCL_Strong: {
761 value = EmitARCRetainScalarExpr(init);
762 break;
763 }
764
765 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000766 // If it's not accessed by the initializer, try to emit the
767 // initialization with a copy or move.
768 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
769 return;
770 }
771
John McCall31168b02011-06-15 23:02:42 +0000772 // No way to optimize a producing initializer into this. It's not
773 // worth optimizing for, because the value will immediately
774 // disappear in the common case.
775 value = EmitScalarExpr(init);
776
John McCall1553b192011-06-16 04:16:24 +0000777 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000778 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000779 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000780 else
John McCall1553b192011-06-16 04:16:24 +0000781 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000782 return;
783 }
784
785 case Qualifiers::OCL_Autoreleasing:
786 value = EmitARCRetainAutoreleaseScalarExpr(init);
787 break;
788 }
789
John McCall1553b192011-06-16 04:16:24 +0000790 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000791
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000792 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
793
John McCall31168b02011-06-15 23:02:42 +0000794 // If the variable might have been accessed by its initializer, we
795 // might have to initialize with a barrier. We have to do this for
796 // both __weak and __strong, but __weak got filtered out above.
797 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000798 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000799 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000800 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000801 return;
802 }
803
David Chisnallfa35df62012-01-16 17:27:18 +0000804 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000805}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000806
807/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
808/// non-zero parts of the specified initializer with equal or fewer than
809/// NumStores scalar stores.
810static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
811 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000812 // Zero and Undef never requires any extra stores.
813 if (isa<llvm::ConstantAggregateZero>(Init) ||
814 isa<llvm::ConstantPointerNull>(Init) ||
815 isa<llvm::UndefValue>(Init))
816 return true;
817 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
818 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
819 isa<llvm::ConstantExpr>(Init))
820 return Init->isNullValue() || NumStores--;
821
822 // See if we can emit each element.
823 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
824 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
825 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
826 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
827 return false;
828 }
829 return true;
830 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000831
Chris Lattner236b3572012-01-31 04:36:19 +0000832 if (llvm::ConstantDataSequential *CDS =
833 dyn_cast<llvm::ConstantDataSequential>(Init)) {
834 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
835 llvm::Constant *Elt = CDS->getElementAsConstant(i);
836 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
837 return false;
838 }
839 return true;
840 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000841
Chris Lattnerb85025f2010-12-01 02:05:19 +0000842 // Anything else is hard and scary.
843 return false;
844}
845
846/// emitStoresForInitAfterMemset - For inits that
847/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
848/// stores that would be required.
849static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000850 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000851 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
852 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000853
Chris Lattnere6af8862010-12-02 01:58:41 +0000854 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
855 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
856 isa<llvm::ConstantExpr>(Init)) {
John McCall7f416cc2015-09-08 08:05:57 +0000857 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000858 return;
859 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000860
861 if (llvm::ConstantDataSequential *CDS =
862 dyn_cast<llvm::ConstantDataSequential>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000863 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
864 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000865
866 // If necessary, get a pointer to the element and emit it.
867 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000868 emitStoresForInitAfterMemset(
869 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
870 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000871 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000872 return;
873 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000874
Chris Lattnere6af8862010-12-02 01:58:41 +0000875 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
876 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000877
Chris Lattnere6af8862010-12-02 01:58:41 +0000878 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
879 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000880
881 // If necessary, get a pointer to the element and emit it.
882 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000883 emitStoresForInitAfterMemset(
884 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
885 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000886 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000887}
888
Chris Lattnerb85025f2010-12-01 02:05:19 +0000889/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
890/// plus some stores to initialize a local variable instead of using a memcpy
891/// from a constant global. It is beneficial to use memset if the global is all
892/// zeros, or mostly zeros and large.
893static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
894 uint64_t GlobalSize) {
895 // If a global is all zeros, always use a memset.
896 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
897
Chris Lattnerb85025f2010-12-01 02:05:19 +0000898 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
899 // do it if it will require 6 or fewer scalar stores.
900 // TODO: Should budget depends on the size? Avoiding a large global warrants
901 // plopping in more stores.
902 unsigned StoreBudget = 6;
903 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000904
905 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000906 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
907}
908
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000909/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000910/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000911/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000912void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
913 AutoVarEmission emission = EmitAutoVarAlloca(D);
914 EmitAutoVarInit(emission);
915 EmitAutoVarCleanups(emission);
916}
Chris Lattner03df1222007-06-02 04:53:11 +0000917
David Majnemerdc012fa2015-04-22 21:38:15 +0000918/// Emit a lifetime.begin marker if some criteria are satisfied.
919/// \return a pointer to the temporary size Value if a marker was emitted, null
920/// otherwise
921llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
922 llvm::Value *Addr) {
Vitaly Buka1c943322016-10-26 01:59:57 +0000923 if (!ShouldEmitLifetimeMarkers)
Reid Kleckner1ef49212015-04-23 18:07:13 +0000924 return nullptr;
925
David Majnemerdc012fa2015-04-22 21:38:15 +0000926 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Yaxun Liu7f7f3232017-04-17 20:03:11 +0000927 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000928 llvm::CallInst *C =
929 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000930 C->setDoesNotThrow();
931 return SizeV;
932}
933
934void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Yaxun Liu7f7f3232017-04-17 20:03:11 +0000935 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000936 llvm::CallInst *C =
937 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000938 C->setDoesNotThrow();
939}
940
John McCallc533cb72011-02-22 06:44:22 +0000941/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000942/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +0000943CodeGenFunction::AutoVarEmission
944CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
945 QualType Ty = D.getType();
946
947 AutoVarEmission emission(D);
948
949 bool isByRef = D.hasAttr<BlocksAttr>();
950 emission.IsByRef = isByRef;
951
952 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +0000953
John McCall23c29fe2011-06-24 21:55:10 +0000954 // If the type is variably-modified, emit all the VLA sizes for it.
955 if (Ty->isVariablyModifiedType())
956 EmitVariablyModifiedType(Ty);
957
John McCall7f416cc2015-09-08 08:05:57 +0000958 Address address = Address::invalid();
Eli Friedmana682d392008-02-15 12:20:59 +0000959 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000960 bool NRVO = getLangOpts().ElideConstructors &&
961 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +0000962
Richard Smith2bcde3a2013-06-02 00:09:52 +0000963 // If this value is an array or struct with a statically determinable
964 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +0000965 //
966 // TODO: We should constant-evaluate the initializer of any variable,
967 // as long as it is initialized by a constant expression. Currently,
968 // isConstantInitializer produces wrong answers for structs with
969 // reference or bitfield members, and a few other cases, and checking
970 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +0000971 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
972 (D.isConstexpr() ||
973 ((Ty.isPODType(getContext()) ||
974 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
975 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +0000976
Rafael Espindola609f5d92013-03-26 18:41:47 +0000977 // If the variable's a const type, and it's neither an NRVO
978 // candidate nor a __block variable and has no mutable members,
979 // emit it as a global instead.
Anastasia Stulovae4a1c382016-11-29 17:01:19 +0000980 // Exception is if a variable is located in non-constant address space
981 // in OpenCL.
982 if ((!getLangOpts().OpenCL ||
983 Ty.getAddressSpace() == LangAS::opencl_constant) &&
984 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
985 CGM.isTypeConstant(Ty, true))) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000986 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +0000987
John McCall7f416cc2015-09-08 08:05:57 +0000988 // Signal this condition to later callbacks.
989 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +0000990 assert(emission.wasEmittedAsGlobal());
991 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +0000992 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000993
Rafael Espindola609f5d92013-03-26 18:41:47 +0000994 // Otherwise, tell the initialization code that we're in this case.
995 emission.IsConstantAggregate = true;
996 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000997
Rafael Espindola609f5d92013-03-26 18:41:47 +0000998 // A normal fixed sized variable becomes an alloca in the entry block,
999 // unless it's an NRVO variable.
Eric Christopher31ab1302011-08-23 22:38:00 +00001000
Rafael Espindola609f5d92013-03-26 18:41:47 +00001001 if (NRVO) {
1002 // The named return value optimization: allocate this variable in the
1003 // return slot, so that we can elide the copy when returning this
1004 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +00001005 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +00001006
Rafael Espindola609f5d92013-03-26 18:41:47 +00001007 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1008 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
1009 // Create a flag that is used to indicate when the NRVO was applied
1010 // to this variable. Set it to zero to indicate that NRVO was not
1011 // applied.
1012 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +00001013 Address NRVOFlag =
1014 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +00001015 EnsureInsertPoint();
1016 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +00001017
Rafael Espindola609f5d92013-03-26 18:41:47 +00001018 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +00001019 NRVOFlags[&D] = NRVOFlag.getPointer();
1020 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +00001021 }
Douglas Gregor290c93e2010-05-15 06:46:45 +00001022 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001023 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001024 CharUnits allocaAlignment;
1025 llvm::Type *allocaTy;
1026 if (isByRef) {
1027 auto &byrefInfo = getBlockByrefInfo(&D);
1028 allocaTy = byrefInfo.Type;
1029 allocaAlignment = byrefInfo.ByrefAlignment;
1030 } else {
1031 allocaTy = ConvertTypeForMem(Ty);
1032 allocaAlignment = alignment;
1033 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001034
John McCall999110f2015-09-08 09:18:30 +00001035 // Create the alloca. Note that we set the name separately from
1036 // building the instruction so that it's there even in no-asserts
1037 // builds.
1038 address = CreateTempAlloca(allocaTy, allocaAlignment);
1039 address.getPointer()->setName(D.getName());
Rafael Espindola609f5d92013-03-26 18:41:47 +00001040
Reid Kleckner1f88e932015-10-07 21:03:41 +00001041 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1042 // the catch parameter starts in the catchpad instruction, and we can't
1043 // insert code in those basic blocks.
1044 bool IsMSCatchParam =
1045 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1046
Vitaly Buka64c80b42016-10-26 05:42:30 +00001047 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1048 // if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001049 if (HaveInsertPoint() && !IsMSCatchParam) {
Akira Hatanakafdcd18b2017-01-25 22:55:13 +00001050 // If there's a jump into the lifetime of this variable, its lifetime
1051 // gets broken up into several regions in IR, which requires more work
1052 // to handle correctly. For now, just omit the intrinsics; this is a
1053 // rare case, and it's better to just be conservatively correct.
1054 // PR28267.
1055 //
1056 // We have to do this in all language modes if there's a jump past the
1057 // declaration. We also have to do it in C if there's a jump to an
1058 // earlier point in the current block because non-VLA lifetimes begin as
1059 // soon as the containing block is entered, not when its variables
1060 // actually come into scope; suppressing the lifetime annotations
1061 // completely in this case is unnecessarily pessimistic, but again, this
1062 // is rare.
1063 if (!Bypasses.IsBypassed(&D) &&
1064 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
Vitaly Buka64c80b42016-10-26 05:42:30 +00001065 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1066 emission.SizeForLifetimeMarkers =
1067 EmitLifetimeStart(size, address.getPointer());
1068 }
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001069 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001070 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001071 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001072 }
Chris Lattner03df1222007-06-02 04:53:11 +00001073 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001074 EnsureInsertPoint();
1075
Anders Carlsson15949b32009-02-09 20:41:50 +00001076 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001077 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001078 Address Stack =
1079 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001080
Anders Carlsson30032882008-12-12 07:38:43 +00001081 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001082 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001083 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001084
1085 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001086
John McCalla464ff92010-07-21 06:13:08 +00001087 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001088 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001089 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001090 }
Mike Stump11289f42009-09-09 15:08:12 +00001091
John McCall23c29fe2011-06-24 21:55:10 +00001092 llvm::Value *elementCount;
1093 QualType elementType;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001094 std::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +00001095
Chris Lattner2192fe52011-07-18 04:24:23 +00001096 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +00001097
1098 // Allocate memory for the array.
John McCall23c29fe2011-06-24 21:55:10 +00001099 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1100 vla->setAlignment(alignment.getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +00001101
John McCall7f416cc2015-09-08 08:05:57 +00001102 address = Address(vla, alignment);
Chris Lattner03df1222007-06-02 04:53:11 +00001103 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001104
John McCall7f416cc2015-09-08 08:05:57 +00001105 setAddrOfLocalVar(&D, address);
1106 emission.Addr = address;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001107
1108 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +00001109 if (HaveInsertPoint())
1110 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001111 if (CGM.getCodeGenOpts().getDebugInfo() >=
1112 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001113 DI->setLocation(D.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001114 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001115 }
Devang Patel887e2152011-06-03 19:21:47 +00001116 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001117
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001118 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001119 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001120
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001121 // Make sure we call @llvm.lifetime.end.
1122 if (emission.useLifetimeMarkers())
1123 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1124 emission.getAllocatedAddress(),
1125 emission.getSizeForLifetimeMarkers());
1126
John McCallc533cb72011-02-22 06:44:22 +00001127 return emission;
1128}
1129
1130/// Determines whether the given __block variable is potentially
1131/// captured by the given expression.
1132static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1133 // Skip the most common kinds of expressions that make
1134 // hierarchy-walking expensive.
1135 e = e->IgnoreParenCasts();
1136
1137 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1138 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +00001139 for (const auto &I : block->captures()) {
1140 if (I.getVariable() == &var)
John McCallc533cb72011-02-22 06:44:22 +00001141 return true;
1142 }
1143
1144 // No need to walk into the subexpressions.
1145 return false;
1146 }
1147
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001148 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1149 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001150 for (const auto *BI : CS->body())
1151 if (const auto *E = dyn_cast<Expr>(BI)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001152 if (isCapturedBy(var, E))
1153 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001154 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001155 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001156 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001157 for (const auto *I : DS->decls()) {
1158 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1159 const Expr *Init = VD->getInit();
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001160 if (Init && isCapturedBy(var, Init))
1161 return true;
1162 }
1163 }
1164 }
1165 else
1166 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1167 // Later, provide code to poke into statements for capture analysis.
1168 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001169 return false;
1170 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001171
Benjamin Kramer642f1732015-07-02 21:03:14 +00001172 for (const Stmt *SubStmt : e->children())
1173 if (isCapturedBy(var, cast<Expr>(SubStmt)))
John McCallc533cb72011-02-22 06:44:22 +00001174 return true;
1175
1176 return false;
1177}
1178
Douglas Gregor82e1af22011-07-01 21:08:19 +00001179/// \brief Determine whether the given initializer is trivial in the sense
1180/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001181bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001182 if (!Init)
1183 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001184
Douglas Gregor82e1af22011-07-01 21:08:19 +00001185 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1186 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1187 if (Constructor->isTrivial() &&
1188 Constructor->isDefaultConstructor() &&
1189 !Construct->requiresZeroInitialization())
1190 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001191
Douglas Gregor82e1af22011-07-01 21:08:19 +00001192 return false;
1193}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001194
John McCallc533cb72011-02-22 06:44:22 +00001195void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001196 assert(emission.Variable && "emission was not valid!");
1197
John McCallc533cb72011-02-22 06:44:22 +00001198 // If this was emitted as a global constant, we're done.
1199 if (emission.wasEmittedAsGlobal()) return;
1200
John McCall9e2e22f2011-02-22 07:16:58 +00001201 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001202 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001203 QualType type = D.getType();
1204
Chris Lattner07eb7332007-07-12 00:39:48 +00001205 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001206 const Expr *Init = D.getInit();
1207
1208 // If we are at an unreachable point, we don't need to emit the initializer
1209 // unless it contains a label.
1210 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001211 if (!Init || !ContainsLabel(Init)) return;
1212 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001213 }
1214
John McCall73064872011-03-31 01:59:53 +00001215 // Initialize the structure of a __block variable.
1216 if (emission.IsByRef)
1217 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001218
Douglas Gregor82e1af22011-07-01 21:08:19 +00001219 if (isTrivialInitializer(Init))
1220 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001221
John McCallc533cb72011-02-22 06:44:22 +00001222 // Check whether this is a byref variable that's potentially
1223 // captured and moved by its own initializer. If so, we'll need to
1224 // emit the initializer first, then copy into the variable.
1225 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1226
John McCall7f416cc2015-09-08 08:05:57 +00001227 Address Loc =
1228 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
John McCallc533cb72011-02-22 06:44:22 +00001229
Craig Topper8a13c412014-05-21 05:09:00 +00001230 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001231 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001232 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smithdafff942012-01-14 04:30:29 +00001233 constant = CGM.EmitConstantInit(D, this);
Richard Smithfddd3842011-12-30 21:15:51 +00001234 }
1235
1236 if (!constant) {
John McCall7f416cc2015-09-08 08:05:57 +00001237 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001238 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001239 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001240 }
John McCall91ca10f2011-03-08 09:11:50 +00001241
Richard Smith2bcde3a2013-06-02 00:09:52 +00001242 if (!emission.IsConstantAggregate) {
1243 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001244 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001245 lv.setNonGC(true);
1246 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1247 }
1248
John McCallc533cb72011-02-22 06:44:22 +00001249 // If this is a simple aggregate initialization, we can optimize it
1250 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001251 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001252
John McCall91ca10f2011-03-08 09:11:50 +00001253 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001254 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001255 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001256
Chris Lattner2192fe52011-07-18 04:24:23 +00001257 llvm::Type *BP = Int8PtrTy;
John McCall7f416cc2015-09-08 08:05:57 +00001258 if (Loc.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001259 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001260
John McCall91ca10f2011-03-08 09:11:50 +00001261 // If the initializer is all or mostly zeros, codegen with memset then do
1262 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001263 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001264 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall91ca10f2011-03-08 09:11:50 +00001265 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
John McCall7f416cc2015-09-08 08:05:57 +00001266 isVolatile);
Benjamin Kramer29f9a002012-08-27 22:07:02 +00001267 // Zero and undef don't require a stores.
1268 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall91ca10f2011-03-08 09:11:50 +00001269 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001270 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1271 isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001272 }
John McCall91ca10f2011-03-08 09:11:50 +00001273 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001274 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001275 // memcpy from the global to the alloca.
Reid Kleckner453e0562014-10-08 01:07:54 +00001276 std::string Name = getStaticDeclName(CGM, D);
Alexey Baderabdcfc12016-10-31 10:26:31 +00001277 unsigned AS = 0;
1278 if (getLangOpts().OpenCL) {
1279 AS = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
1280 BP = llvm::PointerType::getInt8PtrTy(getLLVMContext(), AS);
1281 }
John McCall91ca10f2011-03-08 09:11:50 +00001282 llvm::GlobalVariable *GV =
1283 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001284 llvm::GlobalValue::PrivateLinkage,
Alexey Baderabdcfc12016-10-31 10:26:31 +00001285 constant, Name, nullptr,
1286 llvm::GlobalValue::NotThreadLocal, AS);
John McCall7f416cc2015-09-08 08:05:57 +00001287 GV->setAlignment(Loc.getAlignment().getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001288 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Eric Christopher31ab1302011-08-23 22:38:00 +00001289
John McCall7f416cc2015-09-08 08:05:57 +00001290 Address SrcPtr = Address(GV, Loc.getAlignment());
1291 if (SrcPtr.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001292 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001293
John McCall7f416cc2015-09-08 08:05:57 +00001294 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
John McCall91ca10f2011-03-08 09:11:50 +00001295 }
1296}
1297
1298/// Emit an expression as an initializer for a variable at the given
1299/// location. The expression is not necessarily the normal
1300/// initializer for the variable, and the address is not necessarily
1301/// its normal location.
1302///
1303/// \param init the initializing expression
1304/// \param var the variable to act as if we're initializing
1305/// \param loc the address to initialize; its type is a pointer
1306/// to the LLVM mapping of the variable's type
1307/// \param alignment the alignment of the address
1308/// \param capturedByInit true if the variable is a __block variable
1309/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001310void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001311 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001312 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001313
1314 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001315 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001316 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001317 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001318 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001319 return;
1320 }
1321 switch (getEvaluationKind(type)) {
1322 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001323 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001324 return;
1325 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001326 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001327 if (capturedByInit)
1328 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001329 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001330 return;
1331 }
1332 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001333 if (type->isAtomicType()) {
1334 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1335 } else {
1336 // TODO: how can we delay here if D is captured by its initializer?
1337 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001338 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001339 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001340 AggValueSlot::IsNotAliased));
John McCalla8ec7eb2013-03-07 21:37:17 +00001341 }
John McCall47fb9502013-03-07 21:37:08 +00001342 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001343 }
John McCall47fb9502013-03-07 21:37:08 +00001344 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001345}
John McCallbd309292010-07-06 01:34:17 +00001346
John McCall82fe67b2011-07-09 01:37:26 +00001347/// Enter a destroy cleanup for the given local variable.
1348void CodeGenFunction::emitAutoVarTypeCleanup(
1349 const CodeGenFunction::AutoVarEmission &emission,
1350 QualType::DestructionKind dtorKind) {
1351 assert(dtorKind != QualType::DK_none);
1352
1353 // Note that for __block variables, we want to destroy the
1354 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001355 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001356
1357 const VarDecl *var = emission.Variable;
1358 QualType type = var->getType();
1359
1360 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001361 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001362
1363 switch (dtorKind) {
1364 case QualType::DK_none:
1365 llvm_unreachable("no cleanup for trivially-destructible variable");
1366
1367 case QualType::DK_cxx_destructor:
1368 // If there's an NRVO flag on the emission, we need a different
1369 // cleanup.
1370 if (emission.NRVOFlag) {
1371 assert(!type->isArrayType());
1372 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +00001373 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1374 dtor, emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001375 return;
1376 }
1377 break;
1378
1379 case QualType::DK_objc_strong_lifetime:
1380 // Suppress cleanups for pseudo-strong variables.
1381 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001382
John McCall82fe67b2011-07-09 01:37:26 +00001383 // Otherwise, consider whether to use an EH cleanup or not.
1384 cleanupKind = getARCCleanupKind();
1385
1386 // Use the imprecise destroyer by default.
1387 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1388 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1389 break;
1390
1391 case QualType::DK_objc_weak_lifetime:
1392 break;
1393 }
1394
1395 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001396 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001397
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001398 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001399 // is being pushed as an EH cleanup.
1400 bool useEHCleanup = (cleanupKind & EHCleanup);
1401 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1402 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001403}
1404
John McCallc533cb72011-02-22 06:44:22 +00001405void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001406 assert(emission.Variable && "emission was not valid!");
1407
John McCallc533cb72011-02-22 06:44:22 +00001408 // If this was emitted as a global constant, we're done.
1409 if (emission.wasEmittedAsGlobal()) return;
1410
John McCall8c38d352012-04-13 18:44:05 +00001411 // If we don't have an insertion point, we're done. Sema prevents
1412 // us from jumping into any of these scopes anyway.
1413 if (!HaveInsertPoint()) return;
1414
John McCall9e2e22f2011-02-22 07:16:58 +00001415 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001416
John McCall82fe67b2011-07-09 01:37:26 +00001417 // Check the type for a cleanup.
1418 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1419 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001420
John McCall1bd25562011-06-24 23:21:27 +00001421 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001422 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001423 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1424 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1425 }
1426
John McCallc533cb72011-02-22 06:44:22 +00001427 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001428 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001429 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001430
John McCallc533cb72011-02-22 06:44:22 +00001431 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001432 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001433
John McCalla729c622012-02-17 03:33:10 +00001434 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001435 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001436 }
Mike Stump626aecc2009-03-05 01:23:13 +00001437
John McCallc533cb72011-02-22 06:44:22 +00001438 // If this is a block variable, call _Block_object_destroy
1439 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001440 if (emission.IsByRef)
1441 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001442}
Chris Lattner53621a52007-06-13 20:44:40 +00001443
Peter Collingbourne1425b452012-01-26 03:33:36 +00001444CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001445CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1446 switch (kind) {
1447 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001448 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001449 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001450 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001451 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001452 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001453 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001454 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001455 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001456}
1457
John McCall12cc42a2013-02-01 05:11:40 +00001458/// pushEHDestroy - Push the standard destructor for the given type as
1459/// an EH-only cleanup.
1460void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001461 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00001462 assert(dtorKind && "cannot push destructor for trivial type");
1463 assert(needsEHCleanup(dtorKind));
1464
1465 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1466}
1467
1468/// pushDestroy - Push the standard destructor for the given type as
1469/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001470void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001471 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00001472 assert(dtorKind && "cannot push destructor for trivial type");
1473
1474 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1475 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1476 cleanupKind & EHCleanup);
1477}
1478
John McCall7f416cc2015-09-08 08:05:57 +00001479void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001480 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001481 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001482 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1483 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001484}
1485
John McCall7f416cc2015-09-08 08:05:57 +00001486void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001487 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1488}
1489
Richard Smith736a9472013-06-12 20:42:33 +00001490void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00001491 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00001492 Destroyer *destroyer, bool useEHCleanupForArray) {
1493 assert(!isInConditionalBranch() &&
1494 "performing lifetime extension from within conditional");
1495
1496 // Push an EH-only cleanup for the object now.
1497 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1498 // around in case a temporary's destructor throws an exception.
1499 if (cleanupKind & EHCleanup)
1500 EHStack.pushCleanup<DestroyObject>(
1501 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1502 destroyer, useEHCleanupForArray);
1503
1504 // Remember that we need to push a full cleanup for the object at the
1505 // end of the full-expression.
1506 pushCleanupAfterFullExpr<DestroyObject>(
1507 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1508}
1509
John McCall178360e2011-07-11 08:38:19 +00001510/// emitDestroy - Immediately perform the destruction of the given
1511/// object.
1512///
1513/// \param addr - the address of the object; a type*
1514/// \param type - the type of the object; if an array type, all
1515/// objects are destroyed in reverse order
1516/// \param destroyer - the function to call to destroy individual
1517/// elements
1518/// \param useEHCleanupForArray - whether an EH cleanup should be
1519/// used when destroying array elements, in case one of the
1520/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00001521void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001522 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001523 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001524 const ArrayType *arrayType = getContext().getAsArrayType(type);
1525 if (!arrayType)
1526 return destroyer(*this, addr, type);
1527
John McCall7f416cc2015-09-08 08:05:57 +00001528 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1529
1530 CharUnits elementAlign =
1531 addr.getAlignment()
1532 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00001533
1534 // Normally we have to check whether the array is zero-length.
1535 bool checkZeroLength = true;
1536
1537 // But if the array length is constant, we can suppress that.
1538 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1539 // ...and if it's constant zero, we can just skip the entire thing.
1540 if (constLength->isZero()) return;
1541 checkZeroLength = false;
1542 }
1543
John McCall7f416cc2015-09-08 08:05:57 +00001544 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00001545 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00001546 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001547 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001548}
1549
John McCall178360e2011-07-11 08:38:19 +00001550/// emitArrayDestroy - Destroys all the elements of the given array,
1551/// beginning from last to first. The array cannot be zero-length.
1552///
1553/// \param begin - a type* denoting the first element of the array
1554/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001555/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00001556/// \param destroyer - the function to call to destroy elements
1557/// \param useEHCleanup - whether to push an EH cleanup to destroy
1558/// the remaining elements in case the destruction of a single
1559/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001560void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1561 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001562 QualType elementType,
1563 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001564 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001565 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001566 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00001567 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00001568
1569 // The basic structure here is a do-while loop, because we don't
1570 // need to check for the zero-element case.
1571 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1572 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1573
John McCall97eab0a2011-07-13 08:09:46 +00001574 if (checkZeroLength) {
1575 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1576 "arraydestroy.isempty");
1577 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1578 }
1579
John McCall82fe67b2011-07-09 01:37:26 +00001580 // Enter the loop body, making that address the current address.
1581 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1582 EmitBlock(bodyBB);
1583 llvm::PHINode *elementPast =
1584 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1585 elementPast->addIncoming(end, entryBB);
1586
1587 // Shift the address back by one element.
1588 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1589 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1590 "arraydestroy.element");
1591
John McCall178360e2011-07-11 08:38:19 +00001592 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00001593 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1594 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001595
John McCall82fe67b2011-07-09 01:37:26 +00001596 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00001597 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00001598
John McCall178360e2011-07-11 08:38:19 +00001599 if (useEHCleanup)
1600 PopCleanupBlock();
1601
John McCall82fe67b2011-07-09 01:37:26 +00001602 // Check whether we've reached the end.
1603 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1604 Builder.CreateCondBr(done, doneBB, bodyBB);
1605 elementPast->addIncoming(element, Builder.GetInsertBlock());
1606
1607 // Done.
1608 EmitBlock(doneBB);
1609}
1610
John McCall178360e2011-07-11 08:38:19 +00001611/// Perform partial array destruction as if in an EH cleanup. Unlike
1612/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001613static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1614 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001615 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001616 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001617 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001618 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001619 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1620 // VLAs don't require a GEP index to walk into.
1621 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001622 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001623 type = arrayType->getElementType();
1624 }
John McCall97eab0a2011-07-13 08:09:46 +00001625
1626 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00001627 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00001628
John McCallf0f0b7a2015-09-14 18:57:08 +00001629 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001630 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1631 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001632 }
1633
John McCall97eab0a2011-07-13 08:09:46 +00001634 // Destroy the array. We don't ever need an EH cleanup because we
1635 // assume that we're in an EH cleanup ourselves, so a throwing
1636 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00001637 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001638 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001639}
1640
John McCall82fe67b2011-07-09 01:37:26 +00001641namespace {
John McCall178360e2011-07-11 08:38:19 +00001642 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1643 /// array destroy where the end pointer is regularly determined and
1644 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001645 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00001646 llvm::Value *ArrayBegin;
1647 llvm::Value *ArrayEnd;
1648 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001649 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001650 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00001651 public:
1652 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001653 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001654 CodeGenFunction::Destroyer *destroyer)
1655 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00001656 ElementType(elementType), Destroyer(destroyer),
1657 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00001658
Craig Topper4f12f102014-03-12 06:41:41 +00001659 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001660 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001661 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00001662 }
1663 };
1664
1665 /// IrregularPartialArrayDestroy - a cleanup which performs a
1666 /// partial array destroy where the end pointer is irregularly
1667 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001668 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001669 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00001670 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00001671 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001672 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001673 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00001674 public:
John McCall178360e2011-07-11 08:38:19 +00001675 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001676 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001677 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001678 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001679 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001680 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00001681 ElementType(elementType), Destroyer(destroyer),
1682 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00001683
Craig Topper4f12f102014-03-12 06:41:41 +00001684 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001685 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001686 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001687 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001688 }
1689 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001690} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00001691
John McCall178360e2011-07-11 08:38:19 +00001692/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001693/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001694/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001695///
John McCall82fe67b2011-07-09 01:37:26 +00001696/// \param elementType - the immediate element type of the array;
1697/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001698void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001699 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001700 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001701 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001702 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001703 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1704 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00001705 elementType, elementAlign,
1706 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001707}
1708
1709/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1710/// already-constructed elements of the given array. The cleanup
1711/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001712///
John McCall178360e2011-07-11 08:38:19 +00001713/// \param elementType - the immediate element type of the array;
1714/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001715void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1716 llvm::Value *arrayEnd,
1717 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001718 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001719 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001720 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001721 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001722 elementType, elementAlign,
1723 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001724}
1725
Nadav Rotem1da30942013-03-23 06:43:35 +00001726/// Lazily declare the @llvm.lifetime.start intrinsic.
1727llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00001728 if (LifetimeStartFn)
1729 return LifetimeStartFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00001730 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001731 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00001732 return LifetimeStartFn;
1733}
1734
1735/// Lazily declare the @llvm.lifetime.end intrinsic.
1736llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00001737 if (LifetimeEndFn)
1738 return LifetimeEndFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00001739 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001740 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00001741 return LifetimeEndFn;
1742}
1743
John McCall31168b02011-06-15 23:02:42 +00001744namespace {
1745 /// A cleanup to perform a release of an object at the end of a
1746 /// function. This is used to balance out the incoming +1 of a
1747 /// ns_consumed argument when we can't reasonably do that just by
1748 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00001749 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001750 ConsumeARCParameter(llvm::Value *param,
1751 ARCPreciseLifetime_t precise)
1752 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001753
1754 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001755 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001756
Craig Topper4f12f102014-03-12 06:41:41 +00001757 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001758 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001759 }
1760 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001761} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00001762
Mike Stump11289f42009-09-09 15:08:12 +00001763/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001764/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00001765void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1766 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001767 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001768 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001769 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001770
John McCall7f416cc2015-09-08 08:05:57 +00001771 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00001772
Adrian Prantl51936dd2013-03-14 17:53:33 +00001773 QualType Ty = D.getType();
1774
John McCall147d0212011-02-22 22:38:33 +00001775 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00001776 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00001777 // The only implicit argument a block has is its literal.
John McCall7f416cc2015-09-08 08:05:57 +00001778 // We assume this is always passed directly.
John McCall147d0212011-02-22 22:38:33 +00001779 if (BlockInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001780 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
John McCall147d0212011-02-22 22:38:33 +00001781 return;
1782 }
Reid Klecknere5a321b2016-09-07 18:21:30 +00001783
1784 // Apply any prologue 'this' adjustments required by the ABI. Be careful to
1785 // handle the case where 'this' is passed indirectly as part of an inalloca
1786 // struct.
1787 if (const CXXMethodDecl *MD =
1788 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
1789 if (MD->isVirtual() && IPD == CXXABIThisDecl) {
1790 llvm::Value *This = Arg.isIndirect()
1791 ? Builder.CreateLoad(Arg.getIndirectAddress())
1792 : Arg.getDirectValue();
1793 This = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue(
1794 *this, CurGD, This);
1795 if (Arg.isIndirect())
1796 Builder.CreateStore(This, Arg.getIndirectAddress());
1797 else
1798 Arg = ParamValue::forDirect(This);
1799 }
1800 }
John McCall147d0212011-02-22 22:38:33 +00001801 }
1802
John McCall7f416cc2015-09-08 08:05:57 +00001803 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001804 bool DoStore = false;
1805 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001806 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001807 if (Arg.isIndirect()) {
1808 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001809 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00001810 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001811 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00001812 if (DeclPtr.getType() != IRTy)
1813 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1814
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001815 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00001816 // Don't push a cleanup in a thunk for a method that will also emit a
1817 // cleanup.
1818 if (!IsScalar && !CurFuncIsThunk &&
Reid Kleckner739756c2013-12-04 19:23:12 +00001819 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001820 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1821 if (RD && RD->hasNonTrivialDestructor())
1822 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001823 }
Chris Lattner53621a52007-06-13 20:44:40 +00001824 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001825 // Otherwise, create a temporary to hold the value.
John McCall7f416cc2015-09-08 08:05:57 +00001826 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1827 D.getName() + ".addr");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001828 DoStore = true;
1829 }
Mike Stump11289f42009-09-09 15:08:12 +00001830
John McCall7f416cc2015-09-08 08:05:57 +00001831 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1832
1833 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001834 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00001835 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001836 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1837 // We honor __attribute__((ns_consumed)) for types with lifetime.
1838 // For __strong, it's handled by just skipping the initial retain;
1839 // otherwise we have to balance out the initial +1 with an extra
1840 // cleanup to do the release at the end of the function.
1841 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1842
1843 // 'self' is always formally __strong, but if this is not an
1844 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001845 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001846 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1847 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001848 assert(lt == Qualifiers::OCL_Strong);
1849 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001850 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001851 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001852 lt = Qualifiers::OCL_ExplicitNone;
1853 }
1854
1855 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001856 if (!isConsumed) {
1857 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1858 // use objc_storeStrong(&dest, value) for retaining the
1859 // object. But first, store a null into 'dest' because
1860 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001861 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001862 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
John McCall7f416cc2015-09-08 08:05:57 +00001863 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001864 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001865 }
1866 else
John McCall31168b02011-06-15 23:02:42 +00001867 // Don't use objc_retainBlock for block pointers, because we
1868 // don't want to Block_copy something just because we got it
1869 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00001870 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001871 }
John McCall31168b02011-06-15 23:02:42 +00001872 } else {
1873 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00001874 if (isConsumed) {
1875 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1876 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00001877 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00001878 precise);
1879 }
John McCall31168b02011-06-15 23:02:42 +00001880
1881 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00001882 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001883 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001884 }
1885 }
1886
1887 // Enter the cleanup scope.
1888 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1889 }
Chris Lattner53621a52007-06-13 20:44:40 +00001890 }
1891
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001892 // Store the initial value into the alloca.
1893 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00001894 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001895
John McCall7f416cc2015-09-08 08:05:57 +00001896 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001897
1898 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001899 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001900 if (CGM.getCodeGenOpts().getDebugInfo() >=
1901 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001902 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001903 }
1904 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001905
1906 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001907 EmitVarAnnotations(&D, DeclPtr.getPointer());
Vedant Kumar42c17ec2017-03-14 01:56:34 +00001908
1909 // We can only check return value nullability if all arguments to the
1910 // function satisfy their nullability preconditions. This makes it necessary
1911 // to emit null checks for args in the function body itself.
1912 if (requiresReturnValueNullabilityCheck()) {
1913 auto Nullability = Ty->getNullability(getContext());
1914 if (Nullability && *Nullability == NullabilityKind::NonNull) {
1915 SanitizerScope SanScope(this);
1916 RetValNullabilityPrecondition =
1917 Builder.CreateAnd(RetValNullabilityPrecondition,
1918 Builder.CreateIsNotNull(Arg.getAnyValue()));
1919 }
1920 }
Chris Lattner53621a52007-06-13 20:44:40 +00001921}
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001922
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001923void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1924 CodeGenFunction *CGF) {
1925 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1926 return;
1927 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
1928}