blob: 87bfa507a8c0de3561ac439be0dd1efe2d23a4f5 [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
John McCall7f416cc2015-09-08 08:05:57 +000014#include "CGBlocks.h"
Reid Klecknere5a321b2016-09-07 18:21:30 +000015#include "CGCXXABI.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000016#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGDebugInfo.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000018#include "CGOpenCLRuntime.h"
Alexey Bataevc5b1d322016-03-04 09:22:22 +000019#include "CGOpenMPRuntime.h"
Yaxun Liu6d96f1632017-05-18 18:51:09 +000020#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "CodeGenModule.h"
Yaxun Liu6d96f1632017-05-18 18:51:09 +000022#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000023#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000024#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000025#include "clang/AST/Decl.h"
Anders Carlsson4c03d982008-08-25 01:38:19 +000026#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000027#include "clang/AST/DeclOpenMP.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000028#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000029#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000030#include "clang/CodeGen/CGFunctionInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000031#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/GlobalVariable.h"
34#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/Type.h"
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +000036
Chris Lattner84915fa2007-06-02 04:16:21 +000037using namespace clang;
38using namespace CodeGen;
39
Chris Lattner1ad38f82007-06-09 01:20:56 +000040void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000041 switch (D.getKind()) {
David Majnemerd9b1a4f2015-11-04 03:40:30 +000042 case Decl::BuiltinTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000043 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +000044 case Decl::ExternCContext:
Douglas Gregor19043f02010-04-23 02:02:43 +000045 case Decl::Namespace:
46 case Decl::UnresolvedUsingTypename:
47 case Decl::ClassTemplateSpecialization:
48 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000049 case Decl::VarTemplateSpecialization:
50 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000051 case Decl::TemplateTypeParm:
52 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000053 case Decl::NonTypeTemplateParm:
Richard Smithbc491202017-02-17 20:05:37 +000054 case Decl::CXXDeductionGuide:
Douglas Gregor19043f02010-04-23 02:02:43 +000055 case Decl::CXXMethod:
56 case Decl::CXXConstructor:
57 case Decl::CXXDestructor:
58 case Decl::CXXConversion:
59 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000060 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000061 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000062 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000063 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000064 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000065 case Decl::ImplicitParam:
66 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000067 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000068 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000069 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000070 case Decl::TemplateTemplateParm:
71 case Decl::ObjCMethod:
72 case Decl::ObjCCategory:
73 case Decl::ObjCProtocol:
74 case Decl::ObjCInterface:
75 case Decl::ObjCCategoryImpl:
76 case Decl::ObjCImplementation:
77 case Decl::ObjCProperty:
78 case Decl::ObjCCompatibleAlias:
Nico Weber66220292016-03-02 17:28:48 +000079 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +000080 case Decl::PragmaDetectMismatch:
Abramo Bagnarad7340582010-06-05 05:09:32 +000081 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000082 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +000083 case Decl::Export:
Douglas Gregor19043f02010-04-23 02:02:43 +000084 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000085 case Decl::FileScopeAsm:
86 case Decl::Friend:
87 case Decl::FriendTemplate:
88 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000089 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000090 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000091 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +000092 case Decl::ConstructorUsingShadow:
Douglas Gregor85f3f952015-07-07 03:57:15 +000093 case Decl::ObjCTypeParam:
Richard Smithda383632016-08-15 01:33:41 +000094 case Decl::Binding:
David Blaikie83d382b2011-09-23 05:06:16 +000095 llvm_unreachable("Declaration should not be in declstmts!");
Amjad Abouddc4531e2016-04-30 01:44:38 +000096 case Decl::Function: // void X();
97 case Decl::Record: // struct/union/class X;
98 case Decl::Enum: // enum X;
99 case Decl::EnumConstant: // enum ? { X = ? }
100 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +0000101 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +0000102 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +0000103 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000104 case Decl::OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000105 case Decl::OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +0000106 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +0000107 // None of these decls require codegen support.
108 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +0000109
David Blaikief121b932013-05-20 22:50:41 +0000110 case Decl::NamespaceAlias:
111 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000112 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
David Blaikief121b932013-05-20 22:50:41 +0000113 return;
David Blaikiebd483762013-05-20 04:58:53 +0000114 case Decl::Using: // using X; [C++]
115 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000116 DI->EmitUsingDecl(cast<UsingDecl>(D));
David Blaikiebd483762013-05-20 04:58:53 +0000117 return;
Richard Smith151c4562016-12-20 21:35:28 +0000118 case Decl::UsingPack:
119 for (auto *Using : cast<UsingPackDecl>(D).expansions())
120 EmitDecl(*Using);
121 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000122 case Decl::UsingDirective: // using namespace X; [C++]
123 if (CGDebugInfo *DI = getDebugInfo())
124 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
125 return;
Richard Smithbdb84f32016-07-22 23:36:59 +0000126 case Decl::Var:
127 case Decl::Decomposition: {
Daniel Dunbara7998072008-08-29 17:28:43 +0000128 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000129 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000130 "Should not see file-scope variables inside a function!");
Richard Smithda383632016-08-15 01:33:41 +0000131 EmitVarDecl(VD);
132 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
133 for (auto *B : DD->bindings())
134 if (auto *HD = B->getHoldingVar())
135 EmitVarDecl(*HD);
136 return;
Chris Lattner84915fa2007-06-02 04:16:21 +0000137 }
Mike Stump11289f42009-09-09 15:08:12 +0000138
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000139 case Decl::OMPDeclareReduction:
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000140 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000141
Richard Smithdda56e42011-04-15 14:24:37 +0000142 case Decl::Typedef: // typedef int X;
143 case Decl::TypeAlias: { // using X = int; [C++0x]
144 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000145 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000146
Anders Carlsson5d985f52008-12-20 21:51:53 +0000147 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000148 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000149 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000150 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000151}
Chris Lattner03df1222007-06-02 04:53:11 +0000152
John McCall1c9c3fd2010-10-15 04:57:14 +0000153/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000154/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000155void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Yaxun Liu4f33b3d2017-05-15 14:47:47 +0000156 if (D.hasExternalStorage())
157 // Don't emit it now, allow it to be emitted lazily on its first use.
158 return;
159
160 // Some function-scope variable does not have static storage but still
161 // needs to be emitted like a static variable, e.g. a function-scope
162 // variable in constant address space in OpenCL.
163 if (D.getStorageDuration() != SD_Automatic) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000164 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000165 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000166
David Majnemer27d69db2014-04-28 22:17:59 +0000167 // FIXME: We need to force the emission/use of a guard variable for
168 // some variables even if we can constant-evaluate them because
169 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000170
John McCall1c9c3fd2010-10-15 04:57:14 +0000171 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000172 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000173
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000174 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000175 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
176
177 assert(D.hasLocalStorage());
178 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000179}
180
Reid Kleckner453e0562014-10-08 01:07:54 +0000181static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
182 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000183 return CGM.getMangledName(&D).str();
184
Reid Kleckner453e0562014-10-08 01:07:54 +0000185 // If this isn't C++, we don't need a mangled name, just a pretty one.
186 assert(!D.isExternallyVisible() && "name shouldn't matter");
187 std::string ContextName;
188 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000189 if (auto *CD = dyn_cast<CapturedDecl>(DC))
190 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000191 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000192 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000193 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
194 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
195 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
196 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000197 else
David Blaikie83d382b2011-09-23 05:06:16 +0000198 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000199
Reid Kleckner453e0562014-10-08 01:07:54 +0000200 ContextName += "." + D.getNameAsString();
201 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000202}
203
Reid Kleckner453e0562014-10-08 01:07:54 +0000204llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
205 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
206 // In general, we don't always emit static var decls once before we reference
207 // them. It is possible to reference them before emitting the function that
208 // contains them, and it is possible to emit the containing function multiple
209 // times.
210 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
211 return ExistingGV;
212
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000213 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000214 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000215
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000216 // Use the label if the variable is renamed with the asm-label extension.
217 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000218 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000219 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000220 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000221 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000222
Reid Kleckner453e0562014-10-08 01:07:54 +0000223 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000224 unsigned AddrSpace =
Reid Kleckner453e0562014-10-08 01:07:54 +0000225 GetGlobalVarAddressSpace(&D, getContext().getTargetAddressSpace(Ty));
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000226
227 // Local address space cannot have an initializer.
228 llvm::Constant *Init = nullptr;
229 if (Ty.getAddressSpace() != LangAS::opencl_local)
230 Init = EmitNullConstant(Ty);
231 else
232 Init = llvm::UndefValue::get(LTy);
233
Anders Carlssone33eed52009-09-26 18:16:06 +0000234 llvm::GlobalVariable *GV =
Reid Kleckner453e0562014-10-08 01:07:54 +0000235 new llvm::GlobalVariable(getModule(), LTy,
Anders Carlssone33eed52009-09-26 18:16:06 +0000236 Ty.isConstant(getContext()), Linkage,
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000237 Init, Name, nullptr,
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000238 llvm::GlobalVariable::NotThreadLocal,
Peter Collingbourneee0502d2012-08-28 20:37:10 +0000239 AddrSpace);
Ken Dyck160146e2010-01-27 17:10:57 +0000240 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Reid Kleckner453e0562014-10-08 01:07:54 +0000241 setGlobalVisibility(GV, &D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000242
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000243 if (supportsCOMDAT() && GV->isWeakForLinker())
244 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000245
Richard Smithfd3834f2013-04-13 02:43:54 +0000246 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000247 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000248
Hans Wennborgef2272c2014-06-18 15:55:13 +0000249 if (D.isExternallyVisible()) {
250 if (D.hasAttr<DLLImportAttr>())
251 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
252 else if (D.hasAttr<DLLExportAttr>())
253 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
254 }
255
Eli Benderskycb399432014-03-24 22:05:38 +0000256 // Make sure the result is of the correct type.
Reid Kleckner453e0562014-10-08 01:07:54 +0000257 unsigned ExpectedAddrSpace = getContext().getTargetAddressSpace(Ty);
258 llvm::Constant *Addr = GV;
Eli Benderskycb399432014-03-24 22:05:38 +0000259 if (AddrSpace != ExpectedAddrSpace) {
260 llvm::PointerType *PTy = llvm::PointerType::get(LTy, ExpectedAddrSpace);
Reid Kleckner453e0562014-10-08 01:07:54 +0000261 Addr = llvm::ConstantExpr::getAddrSpaceCast(GV, PTy);
Eli Benderskycb399432014-03-24 22:05:38 +0000262 }
263
Reid Kleckner453e0562014-10-08 01:07:54 +0000264 setStaticLocalDeclAddress(&D, Addr);
265
266 // Ensure that the static local gets initialized by making sure the parent
267 // function gets emitted eventually.
268 const Decl *DC = cast<Decl>(D.getDeclContext());
269
270 // We can't name blocks or captured statements directly, so try to emit their
271 // parents.
272 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
273 DC = DC->getNonClosureContext();
274 // FIXME: Ensure that global blocks get emitted.
275 if (!DC)
276 return Addr;
277 }
278
279 GlobalDecl GD;
280 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
281 GD = GlobalDecl(CD, Ctor_Base);
282 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
283 GD = GlobalDecl(DD, Dtor_Base);
284 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
285 GD = GlobalDecl(FD);
286 else {
287 // Don't do anything for Obj-C method decls or global closures. We should
288 // never defer them.
289 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
290 }
291 if (GD.getDecl())
292 (void)GetAddrOfGlobal(GD);
293
294 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000295}
296
Richard Smith6331c402012-02-13 22:16:19 +0000297/// hasNontrivialDestruction - Determine whether a type's destruction is
298/// non-trivial. If so, and the variable uses static initialization, we must
299/// register its destructor to run on exit.
300static bool hasNontrivialDestruction(QualType T) {
301 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
302 return RD && !RD->hasTrivialDestructor();
303}
304
Chandler Carruth84537952012-03-30 19:44:53 +0000305/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
306/// global variable that has already been created for it. If the initializer
307/// has a different type than GV does, this may free GV and return a different
308/// one. Otherwise it just returns GV.
309llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000310CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000311 llvm::GlobalVariable *GV) {
312 llvm::Constant *Init = CGM.EmitConstantInit(D, this);
John McCall70013b62010-07-15 23:40:35 +0000313
Chris Lattnere99c1102009-12-05 08:22:11 +0000314 // If constant emission failed, then this should be a C++ static
315 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000316 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000317 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000318 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
Matthias Braun44bfe032017-01-10 17:43:01 +0000319 else if (HaveInsertPoint()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000320 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000321 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000322 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000323
Chandler Carruth84537952012-03-30 19:44:53 +0000324 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000325 }
Chandler Carruth84537952012-03-30 19:44:53 +0000326 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000327 }
John McCall70013b62010-07-15 23:40:35 +0000328
Chris Lattnere99c1102009-12-05 08:22:11 +0000329 // The initializer may differ in type from the global. Rewrite
330 // the global to match the initializer. (We have to do this
331 // because some types, like unions, can't be completely represented
332 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000333 if (GV->getType()->getElementType() != Init->getType()) {
334 llvm::GlobalVariable *OldGV = GV;
335
336 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
337 OldGV->isConstant(),
338 OldGV->getLinkage(), Init, "",
339 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000340 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000341 CGM.getContext().getTargetAddressSpace(D.getType()));
342 GV->setVisibility(OldGV->getVisibility());
Reid Klecknereab97d32015-07-20 20:35:30 +0000343 GV->setComdat(OldGV->getComdat());
Eric Christopher31ab1302011-08-23 22:38:00 +0000344
Chris Lattnere99c1102009-12-05 08:22:11 +0000345 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000346 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000347
Chris Lattnere99c1102009-12-05 08:22:11 +0000348 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000349 llvm::Constant *NewPtrForOldDecl =
350 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
351 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000352
Chris Lattnere99c1102009-12-05 08:22:11 +0000353 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000354 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000355 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000356
Chandler Carruth84537952012-03-30 19:44:53 +0000357 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
358 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000359
Matthias Braun44bfe032017-01-10 17:43:01 +0000360 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
Richard Smith6331c402012-02-13 22:16:19 +0000361 // We have a constant initializer, but a nontrivial destructor. We still
362 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000363 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000364 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000365 }
366
Chandler Carruth84537952012-03-30 19:44:53 +0000367 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000368}
369
John McCall1c9c3fd2010-10-15 04:57:14 +0000370void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000371 llvm::GlobalValue::LinkageTypes Linkage) {
John McCallb88a5662012-03-30 21:00:39 +0000372 // Check to see if we already have a global variable for this
373 // declaration. This can happen when double-emitting function
374 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000375 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
John McCall7f416cc2015-09-08 08:05:57 +0000376 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara374e602009-02-25 19:45:19 +0000377
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000378 // Store into LocalDeclMap before generating initializer to handle
379 // circular references.
John McCall7f416cc2015-09-08 08:05:57 +0000380 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000381
John McCall4a39ab82010-05-04 20:45:42 +0000382 // We can't have a VLA here, but we can have a pointer to a VLA,
383 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000384 // Make sure to evaluate VLA bounds now so that we have them for later.
385 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000386 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000387
John McCallb88a5662012-03-30 21:00:39 +0000388 // Save the type in case adding the initializer forces a type change.
389 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000390
Eli Benderskycb399432014-03-24 22:05:38 +0000391 llvm::GlobalVariable *var =
392 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Artem Belevich4d430ba2016-05-09 22:09:56 +0000393
394 // CUDA's local and local static __shared__ variables should not
395 // have any non-empty initializers. This is ensured by Sema.
396 // Whatever initializer such variable may have when it gets here is
397 // a no-op and should not be emitted.
398 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
399 D.hasAttr<CUDASharedAttr>();
Chris Lattnere99c1102009-12-05 08:22:11 +0000400 // If this value has an initializer, emit it.
Artem Belevich4d430ba2016-05-09 22:09:56 +0000401 if (D.getInit() && !isCudaSharedVar)
John McCallb88a5662012-03-30 21:00:39 +0000402 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000403
John McCall7f416cc2015-09-08 08:05:57 +0000404 var->setAlignment(alignment.getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000405
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000406 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000407 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000408
Javed Absar2a67c9e2017-06-05 10:11:57 +0000409 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
410 var->addAttribute("bss-section", SA->getName());
411 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
412 var->addAttribute("data-section", SA->getName());
413 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
414 var->addAttribute("rodata-section", SA->getName());
415
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000416 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000417 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000418
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000419 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000420 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000421
Chandler Carruth84537952012-03-30 19:44:53 +0000422 // We may have to cast the constant because of the initializer
423 // mismatch above.
424 //
425 // FIXME: It is really dangerous to store this in the map; if anyone
426 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000427 llvm::Constant *castedAddr =
428 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCall7f416cc2015-09-08 08:05:57 +0000429 if (var != castedAddr)
430 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCallb88a5662012-03-30 21:00:39 +0000431 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000432
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000433 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000434
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000435 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000436 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000437 if (DI &&
Benjamin Kramer8c305922016-02-02 11:06:51 +0000438 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000439 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000440 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000441 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000442}
Mike Stump11289f42009-09-09 15:08:12 +0000443
John McCall2b7fc382010-07-13 20:32:21 +0000444namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000445 struct DestroyObject final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000446 DestroyObject(Address addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000447 CodeGenFunction::Destroyer *destroyer,
448 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000449 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000450 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000451
John McCall7f416cc2015-09-08 08:05:57 +0000452 Address addr;
John McCall82fe67b2011-07-09 01:37:26 +0000453 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000454 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000455 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000456
Craig Topper4f12f102014-03-12 06:41:41 +0000457 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000458 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000459 bool useEHCleanupForArray =
460 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000461
462 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000463 }
464 };
465
David Blaikie7e70d682015-08-18 22:40:54 +0000466 struct DestroyNRVOVariable final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000467 DestroyNRVOVariable(Address addr,
John McCall82fe67b2011-07-09 01:37:26 +0000468 const CXXDestructorDecl *Dtor,
469 llvm::Value *NRVOFlag)
470 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000471
472 const CXXDestructorDecl *Dtor;
473 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000474 Address Loc;
John McCall2b7fc382010-07-13 20:32:21 +0000475
Craig Topper4f12f102014-03-12 06:41:41 +0000476 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000477 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000478 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000479
Craig Topper8a13c412014-05-21 05:09:00 +0000480 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000481 if (NRVO) {
482 // If we exited via NRVO, we skip the destructor call.
483 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
484 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000485 llvm::Value *DidNRVO =
486 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000487 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
488 CGF.EmitBlock(RunDtorBB);
489 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000490
John McCall2b7fc382010-07-13 20:32:21 +0000491 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +0000492 /*ForVirtualBase=*/false,
493 /*Delegating=*/false,
494 Loc);
John McCall2b7fc382010-07-13 20:32:21 +0000495
496 if (NRVO) CGF.EmitBlock(SkipDtorBB);
497 }
498 };
John McCall2b7fc382010-07-13 20:32:21 +0000499
David Blaikie7e70d682015-08-18 22:40:54 +0000500 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000501 Address Stack;
502 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000503 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000504 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000505 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
506 CGF.Builder.CreateCall(F, V);
507 }
508 };
509
David Blaikie7e70d682015-08-18 22:40:54 +0000510 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000511 const VarDecl &Var;
512 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
513
Craig Topper4f12f102014-03-12 06:41:41 +0000514 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000515 // Compute the address of the local variable, in case it's a
516 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000517 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
518 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000519 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
520 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000521 CGF.EmitExtendGCLifetime(value);
522 }
523 };
524
David Blaikie7e70d682015-08-18 22:40:54 +0000525 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000526 llvm::Constant *CleanupFn;
527 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000528 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000529
John McCalla464ff92010-07-21 06:13:08 +0000530 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000531 const VarDecl *Var)
532 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000533
Craig Topper4f12f102014-03-12 06:41:41 +0000534 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000535 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
536 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000537 // Compute the address of the local variable, in case it's a byref
538 // or something.
John McCall7f416cc2015-09-08 08:05:57 +0000539 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCallc533cb72011-02-22 06:44:22 +0000540
John McCalla464ff92010-07-21 06:13:08 +0000541 // In some cases, the type of the function argument will be different from
542 // the type of the pointer. An example of this is
543 // void f(void* arg);
544 // __attribute__((cleanup(f))) void *g;
545 //
546 // To fix this we insert a bitcast here.
547 QualType ArgTy = FnInfo.arg_begin()->type;
548 llvm::Value *Arg =
549 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
550
551 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000552 Args.add(RValue::get(Arg),
553 CGF.getContext().getPointerType(Var.getType()));
John McCallb92ab1a2016-10-26 23:46:34 +0000554 auto Callee = CGCallee::forDirect(CleanupFn);
555 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
John McCalla464ff92010-07-21 06:13:08 +0000556 }
557 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000558} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000559
John McCall31168b02011-06-15 23:02:42 +0000560/// EmitAutoVarWithLifetime - Does the setup required for an automatic
561/// variable with lifetime.
562static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000563 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000564 Qualifiers::ObjCLifetime lifetime) {
565 switch (lifetime) {
566 case Qualifiers::OCL_None:
567 llvm_unreachable("present but none");
568
569 case Qualifiers::OCL_ExplicitNone:
570 // nothing to do
571 break;
572
573 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000574 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000575 (var.hasAttr<ObjCPreciseLifetimeAttr>()
576 ? CodeGenFunction::destroyARCStrongPrecise
577 : CodeGenFunction::destroyARCStrongImprecise);
578
579 CleanupKind cleanupKind = CGF.getARCCleanupKind();
580 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
581 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000582 break;
583 }
584 case Qualifiers::OCL_Autoreleasing:
585 // nothing to do
586 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000587
John McCall31168b02011-06-15 23:02:42 +0000588 case Qualifiers::OCL_Weak:
589 // __weak objects always get EH cleanups; otherwise, exceptions
590 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000591 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
592 CodeGenFunction::destroyARCWeak,
593 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000594 break;
595 }
596}
597
598static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
599 if (const Expr *e = dyn_cast<Expr>(s)) {
600 // Skip the most common kinds of expressions that make
601 // hierarchy-walking expensive.
602 s = e = e->IgnoreParenCasts();
603
604 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
605 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000606 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
607 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000608 for (const auto &I : block->captures()) {
609 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000610 return true;
611 }
612 }
John McCall31168b02011-06-15 23:02:42 +0000613 }
614
Benjamin Kramer642f1732015-07-02 21:03:14 +0000615 for (const Stmt *SubStmt : s->children())
616 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
617 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000618 return true;
619
620 return false;
621}
622
623static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
624 if (!decl) return false;
625 if (!isa<VarDecl>(decl)) return false;
626 const VarDecl *var = cast<VarDecl>(decl);
627 return isAccessedBy(*var, e);
628}
629
John McCallf8a9b662015-10-21 18:06:31 +0000630static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
631 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000632 bool needsCast = false;
633
John McCallf8a9b662015-10-21 18:06:31 +0000634 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
635 switch (castExpr->getCastKind()) {
636 // Look through casts that don't require representation changes.
637 case CK_NoOp:
638 case CK_BitCast:
639 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000640 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000641 break;
642
643 // If we find an l-value to r-value cast from a __weak variable,
644 // emit this operation as a copy or move.
645 case CK_LValueToRValue: {
646 const Expr *srcExpr = castExpr->getSubExpr();
647 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
648 return false;
649
650 // Emit the source l-value.
651 LValue srcLV = CGF.EmitLValue(srcExpr);
652
John McCall0204e342015-11-16 22:11:41 +0000653 // Handle a formal type change to avoid asserting.
654 auto srcAddr = srcLV.getAddress();
655 if (needsCast) {
656 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
657 destLV.getAddress().getElementType());
658 }
659
John McCallf8a9b662015-10-21 18:06:31 +0000660 // If it was an l-value, use objc_copyWeak.
661 if (srcExpr->getValueKind() == VK_LValue) {
John McCall0204e342015-11-16 22:11:41 +0000662 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000663 } else {
664 assert(srcExpr->getValueKind() == VK_XValue);
John McCall0204e342015-11-16 22:11:41 +0000665 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000666 }
667 return true;
668 }
669
670 // Stop at anything else.
671 default:
672 return false;
673 }
674
675 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000676 }
677 return false;
678}
679
John McCall1553b192011-06-16 04:16:24 +0000680static void drillIntoBlockVariable(CodeGenFunction &CGF,
681 LValue &lvalue,
682 const VarDecl *var) {
John McCall7f416cc2015-09-08 08:05:57 +0000683 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCall1553b192011-06-16 04:16:24 +0000684}
685
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000686void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
687 SourceLocation Loc) {
688 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
689 return;
690
691 auto Nullability = LHS.getType()->getNullability(getContext());
692 if (!Nullability || *Nullability != NullabilityKind::NonNull)
693 return;
694
695 // Check if the right hand side of the assignment is nonnull, if the left
696 // hand side must be nonnull.
697 SanitizerScope SanScope(this);
698 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000699 llvm::Constant *StaticData[] = {
700 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
Simon Pilgrim2df19982017-03-14 21:43:52 +0000701 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
Vedant Kumar2b9f48a2017-03-14 16:48:29 +0000702 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000703 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
704 SanitizerHandler::TypeMismatch, StaticData, RHS);
705}
706
David Blaikie73ca5692014-12-09 00:32:22 +0000707void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000708 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000709 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000710 if (!lifetime) {
711 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000712 if (capturedByInit)
713 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000714 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
David Blaikie66e41972015-01-14 07:38:27 +0000715 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000716 return;
717 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000718
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000719 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
720 init = DIE->getExpr();
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000721
John McCall31168b02011-06-15 23:02:42 +0000722 // If we're emitting a value with lifetime, we have to do the
723 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000724 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
725 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000726 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000727 }
728 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000729
730 // We have to maintain the illusion that the variable is
731 // zero-initialized. If the variable might be accessed in its
732 // initializer, zero-initialize before running the initializer, then
733 // actually perform the initialization with an assign.
734 bool accessedByInit = false;
735 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000736 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000737 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000738 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000739 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000740 if (capturedByInit) {
741 // We can use a simple GEP for this because it can't have been
742 // moved yet.
John McCall7f416cc2015-09-08 08:05:57 +0000743 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
744 cast<VarDecl>(D),
745 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000746 }
747
John McCall7f416cc2015-09-08 08:05:57 +0000748 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
Yaxun Liu402804b2016-12-15 08:09:08 +0000749 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000750
John McCall31168b02011-06-15 23:02:42 +0000751 // If __weak, we want to use a barrier under certain conditions.
752 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000753 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000754
755 // Otherwise just do a simple store.
756 else
David Chisnallfa35df62012-01-16 17:27:18 +0000757 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000758 }
759
760 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000761 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000762
763 switch (lifetime) {
764 case Qualifiers::OCL_None:
765 llvm_unreachable("present but none");
766
767 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000768 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000769 break;
770
771 case Qualifiers::OCL_Strong: {
772 value = EmitARCRetainScalarExpr(init);
773 break;
774 }
775
776 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000777 // If it's not accessed by the initializer, try to emit the
778 // initialization with a copy or move.
779 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
780 return;
781 }
782
John McCall31168b02011-06-15 23:02:42 +0000783 // No way to optimize a producing initializer into this. It's not
784 // worth optimizing for, because the value will immediately
785 // disappear in the common case.
786 value = EmitScalarExpr(init);
787
John McCall1553b192011-06-16 04:16:24 +0000788 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000789 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000790 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000791 else
John McCall1553b192011-06-16 04:16:24 +0000792 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000793 return;
794 }
795
796 case Qualifiers::OCL_Autoreleasing:
797 value = EmitARCRetainAutoreleaseScalarExpr(init);
798 break;
799 }
800
John McCall1553b192011-06-16 04:16:24 +0000801 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000802
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000803 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
804
John McCall31168b02011-06-15 23:02:42 +0000805 // If the variable might have been accessed by its initializer, we
806 // might have to initialize with a barrier. We have to do this for
807 // both __weak and __strong, but __weak got filtered out above.
808 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000809 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000810 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000811 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000812 return;
813 }
814
David Chisnallfa35df62012-01-16 17:27:18 +0000815 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000816}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000817
818/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
819/// non-zero parts of the specified initializer with equal or fewer than
820/// NumStores scalar stores.
821static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
822 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000823 // Zero and Undef never requires any extra stores.
824 if (isa<llvm::ConstantAggregateZero>(Init) ||
825 isa<llvm::ConstantPointerNull>(Init) ||
826 isa<llvm::UndefValue>(Init))
827 return true;
828 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
829 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
830 isa<llvm::ConstantExpr>(Init))
831 return Init->isNullValue() || NumStores--;
832
833 // See if we can emit each element.
834 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
835 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
836 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
837 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
838 return false;
839 }
840 return true;
841 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000842
Chris Lattner236b3572012-01-31 04:36:19 +0000843 if (llvm::ConstantDataSequential *CDS =
844 dyn_cast<llvm::ConstantDataSequential>(Init)) {
845 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
846 llvm::Constant *Elt = CDS->getElementAsConstant(i);
847 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
848 return false;
849 }
850 return true;
851 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000852
Chris Lattnerb85025f2010-12-01 02:05:19 +0000853 // Anything else is hard and scary.
854 return false;
855}
856
857/// emitStoresForInitAfterMemset - For inits that
858/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
859/// stores that would be required.
860static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
John McCallc533cb72011-02-22 06:44:22 +0000861 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000862 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
863 "called emitStoresForInitAfterMemset for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000864
Chris Lattnere6af8862010-12-02 01:58:41 +0000865 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
866 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
867 isa<llvm::ConstantExpr>(Init)) {
John McCall7f416cc2015-09-08 08:05:57 +0000868 Builder.CreateDefaultAlignedStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000869 return;
870 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000871
872 if (llvm::ConstantDataSequential *CDS =
873 dyn_cast<llvm::ConstantDataSequential>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000874 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
875 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000876
877 // If necessary, get a pointer to the element and emit it.
878 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000879 emitStoresForInitAfterMemset(
880 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
881 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000882 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000883 return;
884 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000885
Chris Lattnere6af8862010-12-02 01:58:41 +0000886 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
887 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000888
Chris Lattnere6af8862010-12-02 01:58:41 +0000889 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
890 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000891
892 // If necessary, get a pointer to the element and emit it.
893 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
David Blaikie17ea2662015-04-04 21:07:17 +0000894 emitStoresForInitAfterMemset(
895 Elt, Builder.CreateConstGEP2_32(Init->getType(), Loc, 0, i),
896 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000897 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000898}
899
Chris Lattnerb85025f2010-12-01 02:05:19 +0000900/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
901/// plus some stores to initialize a local variable instead of using a memcpy
902/// from a constant global. It is beneficial to use memset if the global is all
903/// zeros, or mostly zeros and large.
904static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
905 uint64_t GlobalSize) {
906 // If a global is all zeros, always use a memset.
907 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
908
Chris Lattnerb85025f2010-12-01 02:05:19 +0000909 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
910 // do it if it will require 6 or fewer scalar stores.
911 // TODO: Should budget depends on the size? Avoiding a large global warrants
912 // plopping in more stores.
913 unsigned StoreBudget = 6;
914 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000915
916 return GlobalSize > SizeLimit &&
Chris Lattnerb85025f2010-12-01 02:05:19 +0000917 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
918}
919
Nick Lewycky8a7d90b2010-12-30 20:21:55 +0000920/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +0000921/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +0000922/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +0000923void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
924 AutoVarEmission emission = EmitAutoVarAlloca(D);
925 EmitAutoVarInit(emission);
926 EmitAutoVarCleanups(emission);
927}
Chris Lattner03df1222007-06-02 04:53:11 +0000928
David Majnemerdc012fa2015-04-22 21:38:15 +0000929/// Emit a lifetime.begin marker if some criteria are satisfied.
930/// \return a pointer to the temporary size Value if a marker was emitted, null
931/// otherwise
932llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
933 llvm::Value *Addr) {
Vitaly Buka1c943322016-10-26 01:59:57 +0000934 if (!ShouldEmitLifetimeMarkers)
Reid Kleckner1ef49212015-04-23 18:07:13 +0000935 return nullptr;
936
David Majnemerdc012fa2015-04-22 21:38:15 +0000937 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Yaxun Liu7f7f3232017-04-17 20:03:11 +0000938 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000939 llvm::CallInst *C =
940 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000941 C->setDoesNotThrow();
942 return SizeV;
943}
944
945void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Yaxun Liu7f7f3232017-04-17 20:03:11 +0000946 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +0000947 llvm::CallInst *C =
948 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +0000949 C->setDoesNotThrow();
950}
951
John McCallc533cb72011-02-22 06:44:22 +0000952/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000953/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +0000954CodeGenFunction::AutoVarEmission
955CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
956 QualType Ty = D.getType();
957
958 AutoVarEmission emission(D);
959
960 bool isByRef = D.hasAttr<BlocksAttr>();
961 emission.IsByRef = isByRef;
962
963 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +0000964
John McCall23c29fe2011-06-24 21:55:10 +0000965 // If the type is variably-modified, emit all the VLA sizes for it.
966 if (Ty->isVariablyModifiedType())
967 EmitVariablyModifiedType(Ty);
968
John McCall7f416cc2015-09-08 08:05:57 +0000969 Address address = Address::invalid();
Eli Friedmana682d392008-02-15 12:20:59 +0000970 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000971 bool NRVO = getLangOpts().ElideConstructors &&
972 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +0000973
Richard Smith2bcde3a2013-06-02 00:09:52 +0000974 // If this value is an array or struct with a statically determinable
975 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +0000976 //
977 // TODO: We should constant-evaluate the initializer of any variable,
978 // as long as it is initialized by a constant expression. Currently,
979 // isConstantInitializer produces wrong answers for structs with
980 // reference or bitfield members, and a few other cases, and checking
981 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +0000982 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
983 (D.isConstexpr() ||
984 ((Ty.isPODType(getContext()) ||
985 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
986 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +0000987
Rafael Espindola609f5d92013-03-26 18:41:47 +0000988 // If the variable's a const type, and it's neither an NRVO
989 // candidate nor a __block variable and has no mutable members,
990 // emit it as a global instead.
Anastasia Stulovae4a1c382016-11-29 17:01:19 +0000991 // Exception is if a variable is located in non-constant address space
992 // in OpenCL.
993 if ((!getLangOpts().OpenCL ||
994 Ty.getAddressSpace() == LangAS::opencl_constant) &&
995 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
996 CGM.isTypeConstant(Ty, true))) {
Rafael Espindola609f5d92013-03-26 18:41:47 +0000997 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +0000998
John McCall7f416cc2015-09-08 08:05:57 +0000999 // Signal this condition to later callbacks.
1000 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +00001001 assert(emission.wasEmittedAsGlobal());
1002 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +00001003 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001004
Rafael Espindola609f5d92013-03-26 18:41:47 +00001005 // Otherwise, tell the initialization code that we're in this case.
1006 emission.IsConstantAggregate = true;
1007 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001008
Rafael Espindola609f5d92013-03-26 18:41:47 +00001009 // A normal fixed sized variable becomes an alloca in the entry block,
1010 // unless it's an NRVO variable.
Eric Christopher31ab1302011-08-23 22:38:00 +00001011
Rafael Espindola609f5d92013-03-26 18:41:47 +00001012 if (NRVO) {
1013 // The named return value optimization: allocate this variable in the
1014 // return slot, so that we can elide the copy when returning this
1015 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +00001016 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +00001017
Rafael Espindola609f5d92013-03-26 18:41:47 +00001018 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1019 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
1020 // Create a flag that is used to indicate when the NRVO was applied
1021 // to this variable. Set it to zero to indicate that NRVO was not
1022 // applied.
1023 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +00001024 Address NRVOFlag =
1025 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +00001026 EnsureInsertPoint();
1027 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +00001028
Rafael Espindola609f5d92013-03-26 18:41:47 +00001029 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +00001030 NRVOFlags[&D] = NRVOFlag.getPointer();
1031 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +00001032 }
Douglas Gregor290c93e2010-05-15 06:46:45 +00001033 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001034 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001035 CharUnits allocaAlignment;
1036 llvm::Type *allocaTy;
1037 if (isByRef) {
1038 auto &byrefInfo = getBlockByrefInfo(&D);
1039 allocaTy = byrefInfo.Type;
1040 allocaAlignment = byrefInfo.ByrefAlignment;
1041 } else {
1042 allocaTy = ConvertTypeForMem(Ty);
1043 allocaAlignment = alignment;
1044 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001045
John McCall999110f2015-09-08 09:18:30 +00001046 // Create the alloca. Note that we set the name separately from
1047 // building the instruction so that it's there even in no-asserts
1048 // builds.
1049 address = CreateTempAlloca(allocaTy, allocaAlignment);
1050 address.getPointer()->setName(D.getName());
Rafael Espindola609f5d92013-03-26 18:41:47 +00001051
Reid Kleckner1f88e932015-10-07 21:03:41 +00001052 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1053 // the catch parameter starts in the catchpad instruction, and we can't
1054 // insert code in those basic blocks.
1055 bool IsMSCatchParam =
1056 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1057
Vitaly Buka64c80b42016-10-26 05:42:30 +00001058 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1059 // if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001060 if (HaveInsertPoint() && !IsMSCatchParam) {
Akira Hatanakafdcd18b2017-01-25 22:55:13 +00001061 // If there's a jump into the lifetime of this variable, its lifetime
1062 // gets broken up into several regions in IR, which requires more work
1063 // to handle correctly. For now, just omit the intrinsics; this is a
1064 // rare case, and it's better to just be conservatively correct.
1065 // PR28267.
1066 //
1067 // We have to do this in all language modes if there's a jump past the
1068 // declaration. We also have to do it in C if there's a jump to an
1069 // earlier point in the current block because non-VLA lifetimes begin as
1070 // soon as the containing block is entered, not when its variables
1071 // actually come into scope; suppressing the lifetime annotations
1072 // completely in this case is unnecessarily pessimistic, but again, this
1073 // is rare.
1074 if (!Bypasses.IsBypassed(&D) &&
1075 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
Vitaly Buka64c80b42016-10-26 05:42:30 +00001076 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1077 emission.SizeForLifetimeMarkers =
1078 EmitLifetimeStart(size, address.getPointer());
1079 }
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001080 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001081 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001082 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001083 }
Chris Lattner03df1222007-06-02 04:53:11 +00001084 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001085 EnsureInsertPoint();
1086
Anders Carlsson15949b32009-02-09 20:41:50 +00001087 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001088 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001089 Address Stack =
1090 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001091
Anders Carlsson30032882008-12-12 07:38:43 +00001092 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001093 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001094 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001095
1096 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001097
John McCalla464ff92010-07-21 06:13:08 +00001098 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001099 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001100 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001101 }
Mike Stump11289f42009-09-09 15:08:12 +00001102
John McCall23c29fe2011-06-24 21:55:10 +00001103 llvm::Value *elementCount;
1104 QualType elementType;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001105 std::tie(elementCount, elementType) = getVLASize(Ty);
Anders Carlsson30032882008-12-12 07:38:43 +00001106
Chris Lattner2192fe52011-07-18 04:24:23 +00001107 llvm::Type *llvmTy = ConvertTypeForMem(elementType);
Anders Carlsson30032882008-12-12 07:38:43 +00001108
1109 // Allocate memory for the array.
John McCall23c29fe2011-06-24 21:55:10 +00001110 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1111 vla->setAlignment(alignment.getQuantity());
Anders Carlssone33eed52009-09-26 18:16:06 +00001112
John McCall7f416cc2015-09-08 08:05:57 +00001113 address = Address(vla, alignment);
Chris Lattner03df1222007-06-02 04:53:11 +00001114 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001115
Yaxun Liu6d96f1632017-05-18 18:51:09 +00001116 // Alloca always returns a pointer in alloca address space, which may
1117 // be different from the type defined by the language. For example,
1118 // in C++ the auto variables are in the default address space. Therefore
1119 // cast alloca to the expected address space when necessary.
1120 auto T = D.getType();
1121 assert(T.getAddressSpace() == LangAS::Default);
1122 if (getASTAllocaAddressSpace() != LangAS::Default) {
1123 auto *Addr = getTargetHooks().performAddrSpaceCast(
1124 *this, address.getPointer(), getASTAllocaAddressSpace(),
1125 T.getAddressSpace(),
1126 address.getElementType()->getPointerTo(
1127 getContext().getTargetAddressSpace(T.getAddressSpace())),
1128 /*non-null*/ true);
1129 address = Address(Addr, address.getAlignment());
1130 }
John McCall7f416cc2015-09-08 08:05:57 +00001131 setAddrOfLocalVar(&D, address);
1132 emission.Addr = address;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001133
1134 // Emit debug info for local var declaration.
Devang Patel887e2152011-06-03 19:21:47 +00001135 if (HaveInsertPoint())
1136 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001137 if (CGM.getCodeGenOpts().getDebugInfo() >=
1138 codegenoptions::LimitedDebugInfo) {
Alexey Samsonov74a38682012-05-04 07:39:27 +00001139 DI->setLocation(D.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001140 DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001141 }
Devang Patel887e2152011-06-03 19:21:47 +00001142 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001143
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001144 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001145 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001146
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001147 // Make sure we call @llvm.lifetime.end.
1148 if (emission.useLifetimeMarkers())
1149 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1150 emission.getAllocatedAddress(),
1151 emission.getSizeForLifetimeMarkers());
1152
John McCallc533cb72011-02-22 06:44:22 +00001153 return emission;
1154}
1155
1156/// Determines whether the given __block variable is potentially
1157/// captured by the given expression.
1158static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1159 // Skip the most common kinds of expressions that make
1160 // hierarchy-walking expensive.
1161 e = e->IgnoreParenCasts();
1162
1163 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1164 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +00001165 for (const auto &I : block->captures()) {
1166 if (I.getVariable() == &var)
John McCallc533cb72011-02-22 06:44:22 +00001167 return true;
1168 }
1169
1170 // No need to walk into the subexpressions.
1171 return false;
1172 }
1173
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001174 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1175 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001176 for (const auto *BI : CS->body())
1177 if (const auto *E = dyn_cast<Expr>(BI)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001178 if (isCapturedBy(var, E))
1179 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001180 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001181 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001182 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001183 for (const auto *I : DS->decls()) {
1184 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1185 const Expr *Init = VD->getInit();
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001186 if (Init && isCapturedBy(var, Init))
1187 return true;
1188 }
1189 }
1190 }
1191 else
1192 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1193 // Later, provide code to poke into statements for capture analysis.
1194 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001195 return false;
1196 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001197
Benjamin Kramer642f1732015-07-02 21:03:14 +00001198 for (const Stmt *SubStmt : e->children())
1199 if (isCapturedBy(var, cast<Expr>(SubStmt)))
John McCallc533cb72011-02-22 06:44:22 +00001200 return true;
1201
1202 return false;
1203}
1204
Douglas Gregor82e1af22011-07-01 21:08:19 +00001205/// \brief Determine whether the given initializer is trivial in the sense
1206/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001207bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001208 if (!Init)
1209 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001210
Douglas Gregor82e1af22011-07-01 21:08:19 +00001211 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1212 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1213 if (Constructor->isTrivial() &&
1214 Constructor->isDefaultConstructor() &&
1215 !Construct->requiresZeroInitialization())
1216 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001217
Douglas Gregor82e1af22011-07-01 21:08:19 +00001218 return false;
1219}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001220
John McCallc533cb72011-02-22 06:44:22 +00001221void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001222 assert(emission.Variable && "emission was not valid!");
1223
John McCallc533cb72011-02-22 06:44:22 +00001224 // If this was emitted as a global constant, we're done.
1225 if (emission.wasEmittedAsGlobal()) return;
1226
John McCall9e2e22f2011-02-22 07:16:58 +00001227 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001228 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001229 QualType type = D.getType();
1230
Chris Lattner07eb7332007-07-12 00:39:48 +00001231 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001232 const Expr *Init = D.getInit();
1233
1234 // If we are at an unreachable point, we don't need to emit the initializer
1235 // unless it contains a label.
1236 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001237 if (!Init || !ContainsLabel(Init)) return;
1238 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001239 }
1240
John McCall73064872011-03-31 01:59:53 +00001241 // Initialize the structure of a __block variable.
1242 if (emission.IsByRef)
1243 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001244
Douglas Gregor82e1af22011-07-01 21:08:19 +00001245 if (isTrivialInitializer(Init))
1246 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001247
John McCallc533cb72011-02-22 06:44:22 +00001248 // Check whether this is a byref variable that's potentially
1249 // captured and moved by its own initializer. If so, we'll need to
1250 // emit the initializer first, then copy into the variable.
1251 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1252
John McCall7f416cc2015-09-08 08:05:57 +00001253 Address Loc =
1254 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
John McCallc533cb72011-02-22 06:44:22 +00001255
Craig Topper8a13c412014-05-21 05:09:00 +00001256 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001257 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001258 assert(!capturedByInit && "constant init contains a capturing block?");
Richard Smithdafff942012-01-14 04:30:29 +00001259 constant = CGM.EmitConstantInit(D, this);
Richard Smithfddd3842011-12-30 21:15:51 +00001260 }
1261
1262 if (!constant) {
John McCall7f416cc2015-09-08 08:05:57 +00001263 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001264 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001265 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001266 }
John McCall91ca10f2011-03-08 09:11:50 +00001267
Richard Smith2bcde3a2013-06-02 00:09:52 +00001268 if (!emission.IsConstantAggregate) {
1269 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001270 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001271 lv.setNonGC(true);
1272 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1273 }
1274
John McCallc533cb72011-02-22 06:44:22 +00001275 // If this is a simple aggregate initialization, we can optimize it
1276 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001277 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001278
John McCall91ca10f2011-03-08 09:11:50 +00001279 llvm::Value *SizeVal =
Eric Christopher31ab1302011-08-23 22:38:00 +00001280 llvm::ConstantInt::get(IntPtrTy,
John McCall91ca10f2011-03-08 09:11:50 +00001281 getContext().getTypeSizeInChars(type).getQuantity());
John McCallc533cb72011-02-22 06:44:22 +00001282
Chris Lattner2192fe52011-07-18 04:24:23 +00001283 llvm::Type *BP = Int8PtrTy;
John McCall7f416cc2015-09-08 08:05:57 +00001284 if (Loc.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001285 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001286
John McCall91ca10f2011-03-08 09:11:50 +00001287 // If the initializer is all or mostly zeros, codegen with memset then do
1288 // a few stores afterward.
Eric Christopher31ab1302011-08-23 22:38:00 +00001289 if (shouldUseMemSetPlusStoresToInitialize(constant,
Micah Villmowdd31ca12012-10-08 16:25:52 +00001290 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
John McCall91ca10f2011-03-08 09:11:50 +00001291 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
John McCall7f416cc2015-09-08 08:05:57 +00001292 isVolatile);
Benjamin Kramer29f9a002012-08-27 22:07:02 +00001293 // Zero and undef don't require a stores.
1294 if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
John McCall91ca10f2011-03-08 09:11:50 +00001295 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
John McCall7f416cc2015-09-08 08:05:57 +00001296 emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1297 isVolatile, Builder);
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001298 }
John McCall91ca10f2011-03-08 09:11:50 +00001299 } else {
Eric Christopher31ab1302011-08-23 22:38:00 +00001300 // Otherwise, create a temporary global with the initializer then
John McCall91ca10f2011-03-08 09:11:50 +00001301 // memcpy from the global to the alloca.
Reid Kleckner453e0562014-10-08 01:07:54 +00001302 std::string Name = getStaticDeclName(CGM, D);
Alexey Baderabdcfc12016-10-31 10:26:31 +00001303 unsigned AS = 0;
1304 if (getLangOpts().OpenCL) {
1305 AS = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
1306 BP = llvm::PointerType::getInt8PtrTy(getLLVMContext(), AS);
1307 }
John McCall91ca10f2011-03-08 09:11:50 +00001308 llvm::GlobalVariable *GV =
1309 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
Eric Christopherb58b3e82011-08-24 00:33:55 +00001310 llvm::GlobalValue::PrivateLinkage,
Alexey Baderabdcfc12016-10-31 10:26:31 +00001311 constant, Name, nullptr,
1312 llvm::GlobalValue::NotThreadLocal, AS);
John McCall7f416cc2015-09-08 08:05:57 +00001313 GV->setAlignment(Loc.getAlignment().getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001314 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Eric Christopher31ab1302011-08-23 22:38:00 +00001315
John McCall7f416cc2015-09-08 08:05:57 +00001316 Address SrcPtr = Address(GV, Loc.getAlignment());
1317 if (SrcPtr.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001318 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
John McCall91ca10f2011-03-08 09:11:50 +00001319
John McCall7f416cc2015-09-08 08:05:57 +00001320 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
John McCall91ca10f2011-03-08 09:11:50 +00001321 }
1322}
1323
1324/// Emit an expression as an initializer for a variable at the given
1325/// location. The expression is not necessarily the normal
1326/// initializer for the variable, and the address is not necessarily
1327/// its normal location.
1328///
1329/// \param init the initializing expression
1330/// \param var the variable to act as if we're initializing
1331/// \param loc the address to initialize; its type is a pointer
1332/// to the LLVM mapping of the variable's type
1333/// \param alignment the alignment of the address
1334/// \param capturedByInit true if the variable is a __block variable
1335/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001336void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001337 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001338 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001339
1340 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001341 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001342 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001343 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001344 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001345 return;
1346 }
1347 switch (getEvaluationKind(type)) {
1348 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001349 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001350 return;
1351 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001352 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001353 if (capturedByInit)
1354 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001355 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001356 return;
1357 }
1358 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001359 if (type->isAtomicType()) {
1360 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1361 } else {
1362 // TODO: how can we delay here if D is captured by its initializer?
1363 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001364 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001365 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001366 AggValueSlot::IsNotAliased));
John McCalla8ec7eb2013-03-07 21:37:17 +00001367 }
John McCall47fb9502013-03-07 21:37:08 +00001368 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001369 }
John McCall47fb9502013-03-07 21:37:08 +00001370 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001371}
John McCallbd309292010-07-06 01:34:17 +00001372
John McCall82fe67b2011-07-09 01:37:26 +00001373/// Enter a destroy cleanup for the given local variable.
1374void CodeGenFunction::emitAutoVarTypeCleanup(
1375 const CodeGenFunction::AutoVarEmission &emission,
1376 QualType::DestructionKind dtorKind) {
1377 assert(dtorKind != QualType::DK_none);
1378
1379 // Note that for __block variables, we want to destroy the
1380 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001381 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001382
1383 const VarDecl *var = emission.Variable;
1384 QualType type = var->getType();
1385
1386 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001387 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001388
1389 switch (dtorKind) {
1390 case QualType::DK_none:
1391 llvm_unreachable("no cleanup for trivially-destructible variable");
1392
1393 case QualType::DK_cxx_destructor:
1394 // If there's an NRVO flag on the emission, we need a different
1395 // cleanup.
1396 if (emission.NRVOFlag) {
1397 assert(!type->isArrayType());
1398 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
John McCall7f416cc2015-09-08 08:05:57 +00001399 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1400 dtor, emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001401 return;
1402 }
1403 break;
1404
1405 case QualType::DK_objc_strong_lifetime:
1406 // Suppress cleanups for pseudo-strong variables.
1407 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001408
John McCall82fe67b2011-07-09 01:37:26 +00001409 // Otherwise, consider whether to use an EH cleanup or not.
1410 cleanupKind = getARCCleanupKind();
1411
1412 // Use the imprecise destroyer by default.
1413 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1414 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1415 break;
1416
1417 case QualType::DK_objc_weak_lifetime:
1418 break;
1419 }
1420
1421 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001422 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001423
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001424 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001425 // is being pushed as an EH cleanup.
1426 bool useEHCleanup = (cleanupKind & EHCleanup);
1427 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1428 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001429}
1430
John McCallc533cb72011-02-22 06:44:22 +00001431void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001432 assert(emission.Variable && "emission was not valid!");
1433
John McCallc533cb72011-02-22 06:44:22 +00001434 // If this was emitted as a global constant, we're done.
1435 if (emission.wasEmittedAsGlobal()) return;
1436
John McCall8c38d352012-04-13 18:44:05 +00001437 // If we don't have an insertion point, we're done. Sema prevents
1438 // us from jumping into any of these scopes anyway.
1439 if (!HaveInsertPoint()) return;
1440
John McCall9e2e22f2011-02-22 07:16:58 +00001441 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001442
John McCall82fe67b2011-07-09 01:37:26 +00001443 // Check the type for a cleanup.
1444 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1445 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001446
John McCall1bd25562011-06-24 23:21:27 +00001447 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001448 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001449 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1450 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1451 }
1452
John McCallc533cb72011-02-22 06:44:22 +00001453 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001454 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001455 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001456
John McCallc533cb72011-02-22 06:44:22 +00001457 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001458 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001459
John McCalla729c622012-02-17 03:33:10 +00001460 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001461 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001462 }
Mike Stump626aecc2009-03-05 01:23:13 +00001463
John McCallc533cb72011-02-22 06:44:22 +00001464 // If this is a block variable, call _Block_object_destroy
1465 // (on the unforwarded address).
John McCall73064872011-03-31 01:59:53 +00001466 if (emission.IsByRef)
1467 enterByrefCleanup(emission);
Chris Lattner03df1222007-06-02 04:53:11 +00001468}
Chris Lattner53621a52007-06-13 20:44:40 +00001469
Peter Collingbourne1425b452012-01-26 03:33:36 +00001470CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001471CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1472 switch (kind) {
1473 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001474 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001475 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001476 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001477 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001478 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001479 return destroyARCWeak;
John McCall82fe67b2011-07-09 01:37:26 +00001480 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001481 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001482}
1483
John McCall12cc42a2013-02-01 05:11:40 +00001484/// pushEHDestroy - Push the standard destructor for the given type as
1485/// an EH-only cleanup.
1486void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001487 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00001488 assert(dtorKind && "cannot push destructor for trivial type");
1489 assert(needsEHCleanup(dtorKind));
1490
1491 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1492}
1493
1494/// pushDestroy - Push the standard destructor for the given type as
1495/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001496void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001497 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00001498 assert(dtorKind && "cannot push destructor for trivial type");
1499
1500 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1501 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1502 cleanupKind & EHCleanup);
1503}
1504
John McCall7f416cc2015-09-08 08:05:57 +00001505void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001506 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001507 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001508 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1509 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001510}
1511
John McCall7f416cc2015-09-08 08:05:57 +00001512void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001513 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1514}
1515
Richard Smith736a9472013-06-12 20:42:33 +00001516void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00001517 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00001518 Destroyer *destroyer, bool useEHCleanupForArray) {
1519 assert(!isInConditionalBranch() &&
1520 "performing lifetime extension from within conditional");
1521
1522 // Push an EH-only cleanup for the object now.
1523 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1524 // around in case a temporary's destructor throws an exception.
1525 if (cleanupKind & EHCleanup)
1526 EHStack.pushCleanup<DestroyObject>(
1527 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1528 destroyer, useEHCleanupForArray);
1529
1530 // Remember that we need to push a full cleanup for the object at the
1531 // end of the full-expression.
1532 pushCleanupAfterFullExpr<DestroyObject>(
1533 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1534}
1535
John McCall178360e2011-07-11 08:38:19 +00001536/// emitDestroy - Immediately perform the destruction of the given
1537/// object.
1538///
1539/// \param addr - the address of the object; a type*
1540/// \param type - the type of the object; if an array type, all
1541/// objects are destroyed in reverse order
1542/// \param destroyer - the function to call to destroy individual
1543/// elements
1544/// \param useEHCleanupForArray - whether an EH cleanup should be
1545/// used when destroying array elements, in case one of the
1546/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00001547void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001548 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001549 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001550 const ArrayType *arrayType = getContext().getAsArrayType(type);
1551 if (!arrayType)
1552 return destroyer(*this, addr, type);
1553
John McCall7f416cc2015-09-08 08:05:57 +00001554 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1555
1556 CharUnits elementAlign =
1557 addr.getAlignment()
1558 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00001559
1560 // Normally we have to check whether the array is zero-length.
1561 bool checkZeroLength = true;
1562
1563 // But if the array length is constant, we can suppress that.
1564 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1565 // ...and if it's constant zero, we can just skip the entire thing.
1566 if (constLength->isZero()) return;
1567 checkZeroLength = false;
1568 }
1569
John McCall7f416cc2015-09-08 08:05:57 +00001570 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00001571 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00001572 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001573 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001574}
1575
John McCall178360e2011-07-11 08:38:19 +00001576/// emitArrayDestroy - Destroys all the elements of the given array,
1577/// beginning from last to first. The array cannot be zero-length.
1578///
1579/// \param begin - a type* denoting the first element of the array
1580/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001581/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00001582/// \param destroyer - the function to call to destroy elements
1583/// \param useEHCleanup - whether to push an EH cleanup to destroy
1584/// the remaining elements in case the destruction of a single
1585/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001586void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1587 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001588 QualType elementType,
1589 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001590 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001591 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001592 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00001593 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00001594
1595 // The basic structure here is a do-while loop, because we don't
1596 // need to check for the zero-element case.
1597 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1598 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1599
John McCall97eab0a2011-07-13 08:09:46 +00001600 if (checkZeroLength) {
1601 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1602 "arraydestroy.isempty");
1603 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1604 }
1605
John McCall82fe67b2011-07-09 01:37:26 +00001606 // Enter the loop body, making that address the current address.
1607 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1608 EmitBlock(bodyBB);
1609 llvm::PHINode *elementPast =
1610 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1611 elementPast->addIncoming(end, entryBB);
1612
1613 // Shift the address back by one element.
1614 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1615 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1616 "arraydestroy.element");
1617
John McCall178360e2011-07-11 08:38:19 +00001618 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00001619 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1620 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001621
John McCall82fe67b2011-07-09 01:37:26 +00001622 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00001623 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00001624
John McCall178360e2011-07-11 08:38:19 +00001625 if (useEHCleanup)
1626 PopCleanupBlock();
1627
John McCall82fe67b2011-07-09 01:37:26 +00001628 // Check whether we've reached the end.
1629 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1630 Builder.CreateCondBr(done, doneBB, bodyBB);
1631 elementPast->addIncoming(element, Builder.GetInsertBlock());
1632
1633 // Done.
1634 EmitBlock(doneBB);
1635}
1636
John McCall178360e2011-07-11 08:38:19 +00001637/// Perform partial array destruction as if in an EH cleanup. Unlike
1638/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001639static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1640 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001641 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001642 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001643 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001644 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001645 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1646 // VLAs don't require a GEP index to walk into.
1647 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001648 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001649 type = arrayType->getElementType();
1650 }
John McCall97eab0a2011-07-13 08:09:46 +00001651
1652 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00001653 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00001654
John McCallf0f0b7a2015-09-14 18:57:08 +00001655 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001656 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1657 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001658 }
1659
John McCall97eab0a2011-07-13 08:09:46 +00001660 // Destroy the array. We don't ever need an EH cleanup because we
1661 // assume that we're in an EH cleanup ourselves, so a throwing
1662 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00001663 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001664 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001665}
1666
John McCall82fe67b2011-07-09 01:37:26 +00001667namespace {
John McCall178360e2011-07-11 08:38:19 +00001668 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1669 /// array destroy where the end pointer is regularly determined and
1670 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001671 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00001672 llvm::Value *ArrayBegin;
1673 llvm::Value *ArrayEnd;
1674 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001675 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001676 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00001677 public:
1678 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001679 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001680 CodeGenFunction::Destroyer *destroyer)
1681 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00001682 ElementType(elementType), Destroyer(destroyer),
1683 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00001684
Craig Topper4f12f102014-03-12 06:41:41 +00001685 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001686 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001687 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00001688 }
1689 };
1690
1691 /// IrregularPartialArrayDestroy - a cleanup which performs a
1692 /// partial array destroy where the end pointer is irregularly
1693 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001694 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001695 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00001696 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00001697 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001698 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001699 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00001700 public:
John McCall178360e2011-07-11 08:38:19 +00001701 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001702 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001703 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001704 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001705 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001706 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00001707 ElementType(elementType), Destroyer(destroyer),
1708 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00001709
Craig Topper4f12f102014-03-12 06:41:41 +00001710 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001711 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001712 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001713 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001714 }
1715 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001716} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00001717
John McCall178360e2011-07-11 08:38:19 +00001718/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001719/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001720/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001721///
John McCall82fe67b2011-07-09 01:37:26 +00001722/// \param elementType - the immediate element type of the array;
1723/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001724void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001725 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001726 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001727 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001728 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001729 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1730 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00001731 elementType, elementAlign,
1732 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001733}
1734
1735/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1736/// already-constructed elements of the given array. The cleanup
1737/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001738///
John McCall178360e2011-07-11 08:38:19 +00001739/// \param elementType - the immediate element type of the array;
1740/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00001741void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1742 llvm::Value *arrayEnd,
1743 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001744 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001745 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001746 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00001747 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001748 elementType, elementAlign,
1749 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001750}
1751
Nadav Rotem1da30942013-03-23 06:43:35 +00001752/// Lazily declare the @llvm.lifetime.start intrinsic.
1753llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00001754 if (LifetimeStartFn)
1755 return LifetimeStartFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00001756 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001757 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00001758 return LifetimeStartFn;
1759}
1760
1761/// Lazily declare the @llvm.lifetime.end intrinsic.
1762llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00001763 if (LifetimeEndFn)
1764 return LifetimeEndFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00001765 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001766 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00001767 return LifetimeEndFn;
1768}
1769
John McCall31168b02011-06-15 23:02:42 +00001770namespace {
1771 /// A cleanup to perform a release of an object at the end of a
1772 /// function. This is used to balance out the incoming +1 of a
1773 /// ns_consumed argument when we can't reasonably do that just by
1774 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00001775 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00001776 ConsumeARCParameter(llvm::Value *param,
1777 ARCPreciseLifetime_t precise)
1778 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00001779
1780 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00001781 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00001782
Craig Topper4f12f102014-03-12 06:41:41 +00001783 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001784 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00001785 }
1786 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001787} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00001788
Mike Stump11289f42009-09-09 15:08:12 +00001789/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00001790/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00001791void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1792 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001793 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00001794 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001795 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00001796
John McCall7f416cc2015-09-08 08:05:57 +00001797 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00001798
Adrian Prantl51936dd2013-03-14 17:53:33 +00001799 QualType Ty = D.getType();
1800
John McCall147d0212011-02-22 22:38:33 +00001801 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00001802 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00001803 // The only implicit argument a block has is its literal.
John McCall7f416cc2015-09-08 08:05:57 +00001804 // We assume this is always passed directly.
John McCall147d0212011-02-22 22:38:33 +00001805 if (BlockInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001806 setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
John McCall147d0212011-02-22 22:38:33 +00001807 return;
1808 }
Reid Klecknere5a321b2016-09-07 18:21:30 +00001809
1810 // Apply any prologue 'this' adjustments required by the ABI. Be careful to
1811 // handle the case where 'this' is passed indirectly as part of an inalloca
1812 // struct.
1813 if (const CXXMethodDecl *MD =
1814 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
1815 if (MD->isVirtual() && IPD == CXXABIThisDecl) {
1816 llvm::Value *This = Arg.isIndirect()
1817 ? Builder.CreateLoad(Arg.getIndirectAddress())
1818 : Arg.getDirectValue();
1819 This = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue(
1820 *this, CurGD, This);
1821 if (Arg.isIndirect())
1822 Builder.CreateStore(This, Arg.getIndirectAddress());
1823 else
1824 Arg = ParamValue::forDirect(This);
1825 }
1826 }
John McCall147d0212011-02-22 22:38:33 +00001827 }
1828
John McCall7f416cc2015-09-08 08:05:57 +00001829 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001830 bool DoStore = false;
1831 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001832 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001833 if (Arg.isIndirect()) {
1834 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001835 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00001836 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00001837 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00001838 if (DeclPtr.getType() != IRTy)
1839 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1840
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001841 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00001842 // Don't push a cleanup in a thunk for a method that will also emit a
1843 // cleanup.
1844 if (!IsScalar && !CurFuncIsThunk &&
Reid Kleckner739756c2013-12-04 19:23:12 +00001845 getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001846 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1847 if (RD && RD->hasNonTrivialDestructor())
1848 pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00001849 }
Chris Lattner53621a52007-06-13 20:44:40 +00001850 } else {
Daniel Dunbar3d33fab2010-02-08 22:53:07 +00001851 // Otherwise, create a temporary to hold the value.
John McCall7f416cc2015-09-08 08:05:57 +00001852 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1853 D.getName() + ".addr");
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001854 DoStore = true;
1855 }
Mike Stump11289f42009-09-09 15:08:12 +00001856
John McCall7f416cc2015-09-08 08:05:57 +00001857 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1858
1859 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001860 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00001861 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00001862 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1863 // We honor __attribute__((ns_consumed)) for types with lifetime.
1864 // For __strong, it's handled by just skipping the initial retain;
1865 // otherwise we have to balance out the initial +1 with an extra
1866 // cleanup to do the release at the end of the function.
1867 bool isConsumed = D.hasAttr<NSConsumedAttr>();
1868
1869 // 'self' is always formally __strong, but if this is not an
1870 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00001871 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00001872 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1873 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00001874 assert(lt == Qualifiers::OCL_Strong);
1875 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00001876 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00001877 (void) method;
John McCall31168b02011-06-15 23:02:42 +00001878 lt = Qualifiers::OCL_ExplicitNone;
1879 }
1880
1881 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001882 if (!isConsumed) {
1883 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1884 // use objc_storeStrong(&dest, value) for retaining the
1885 // object. But first, store a null into 'dest' because
1886 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001887 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001888 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
John McCall7f416cc2015-09-08 08:05:57 +00001889 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001890 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001891 }
1892 else
John McCall31168b02011-06-15 23:02:42 +00001893 // Don't use objc_retainBlock for block pointers, because we
1894 // don't want to Block_copy something just because we got it
1895 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00001896 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00001897 }
John McCall31168b02011-06-15 23:02:42 +00001898 } else {
1899 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00001900 if (isConsumed) {
1901 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1902 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00001903 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00001904 precise);
1905 }
John McCall31168b02011-06-15 23:02:42 +00001906
1907 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00001908 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001909 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00001910 }
1911 }
1912
1913 // Enter the cleanup scope.
1914 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1915 }
Chris Lattner53621a52007-06-13 20:44:40 +00001916 }
1917
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001918 // Store the initial value into the alloca.
1919 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00001920 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001921
John McCall7f416cc2015-09-08 08:05:57 +00001922 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001923
1924 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00001925 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00001926 if (CGM.getCodeGenOpts().getDebugInfo() >=
1927 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001928 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00001929 }
1930 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001931
1932 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001933 EmitVarAnnotations(&D, DeclPtr.getPointer());
Vedant Kumar42c17ec2017-03-14 01:56:34 +00001934
1935 // We can only check return value nullability if all arguments to the
1936 // function satisfy their nullability preconditions. This makes it necessary
1937 // to emit null checks for args in the function body itself.
1938 if (requiresReturnValueNullabilityCheck()) {
1939 auto Nullability = Ty->getNullability(getContext());
1940 if (Nullability && *Nullability == NullabilityKind::NonNull) {
1941 SanitizerScope SanScope(this);
1942 RetValNullabilityPrecondition =
1943 Builder.CreateAnd(RetValNullabilityPrecondition,
1944 Builder.CreateIsNotNull(Arg.getAnyValue()));
1945 }
1946 }
Chris Lattner53621a52007-06-13 20:44:40 +00001947}
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00001948
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001949void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1950 CodeGenFunction *CGF) {
1951 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1952 return;
1953 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
1954}