blob: 3a5bc0e46943d8655a9679a7d3102743cfa39e31 [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"
John McCallde0fe072017-08-15 21:42:52 +000022#include "ConstantEmitter.h"
Yaxun Liu6d96f1632017-05-18 18:51:09 +000023#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000024#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000025#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000026#include "clang/AST/Decl.h"
Anders Carlsson4c03d982008-08-25 01:38:19 +000027#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000028#include "clang/AST/DeclOpenMP.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000029#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000030#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000031#include "clang/CodeGen/CGFunctionInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000032#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/GlobalVariable.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/Type.h"
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +000037
Chris Lattner84915fa2007-06-02 04:16:21 +000038using namespace clang;
39using namespace CodeGen;
40
Chris Lattner1ad38f82007-06-09 01:20:56 +000041void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000042 switch (D.getKind()) {
David Majnemerd9b1a4f2015-11-04 03:40:30 +000043 case Decl::BuiltinTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000044 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +000045 case Decl::ExternCContext:
Douglas Gregor19043f02010-04-23 02:02:43 +000046 case Decl::Namespace:
47 case Decl::UnresolvedUsingTypename:
48 case Decl::ClassTemplateSpecialization:
49 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000050 case Decl::VarTemplateSpecialization:
51 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000052 case Decl::TemplateTypeParm:
53 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000054 case Decl::NonTypeTemplateParm:
Richard Smithbc491202017-02-17 20:05:37 +000055 case Decl::CXXDeductionGuide:
Douglas Gregor19043f02010-04-23 02:02:43 +000056 case Decl::CXXMethod:
57 case Decl::CXXConstructor:
58 case Decl::CXXDestructor:
59 case Decl::CXXConversion:
60 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000061 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000062 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000063 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000064 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000065 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000066 case Decl::ImplicitParam:
67 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000068 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000069 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000070 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000071 case Decl::TemplateTemplateParm:
72 case Decl::ObjCMethod:
73 case Decl::ObjCCategory:
74 case Decl::ObjCProtocol:
75 case Decl::ObjCInterface:
76 case Decl::ObjCCategoryImpl:
77 case Decl::ObjCImplementation:
78 case Decl::ObjCProperty:
79 case Decl::ObjCCompatibleAlias:
Nico Weber66220292016-03-02 17:28:48 +000080 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +000081 case Decl::PragmaDetectMismatch:
Abramo Bagnarad7340582010-06-05 05:09:32 +000082 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000083 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +000084 case Decl::Export:
Douglas Gregor19043f02010-04-23 02:02:43 +000085 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000086 case Decl::FileScopeAsm:
87 case Decl::Friend:
88 case Decl::FriendTemplate:
89 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000090 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000091 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000092 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +000093 case Decl::ConstructorUsingShadow:
Douglas Gregor85f3f952015-07-07 03:57:15 +000094 case Decl::ObjCTypeParam:
Richard Smithda383632016-08-15 01:33:41 +000095 case Decl::Binding:
David Blaikie83d382b2011-09-23 05:06:16 +000096 llvm_unreachable("Declaration should not be in declstmts!");
Amjad Abouddc4531e2016-04-30 01:44:38 +000097 case Decl::Function: // void X();
98 case Decl::Record: // struct/union/class X;
99 case Decl::Enum: // enum X;
100 case Decl::EnumConstant: // enum ? { X = ? }
101 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +0000102 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +0000103 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +0000104 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000105 case Decl::OMPThreadPrivate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000106 case Decl::OMPCapturedExpr:
Michael Han84324352013-02-22 17:15:32 +0000107 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +0000108 // None of these decls require codegen support.
109 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +0000110
David Blaikief121b932013-05-20 22:50:41 +0000111 case Decl::NamespaceAlias:
112 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000113 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
David Blaikief121b932013-05-20 22:50:41 +0000114 return;
David Blaikiebd483762013-05-20 04:58:53 +0000115 case Decl::Using: // using X; [C++]
116 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000117 DI->EmitUsingDecl(cast<UsingDecl>(D));
David Blaikiebd483762013-05-20 04:58:53 +0000118 return;
Richard Smith151c4562016-12-20 21:35:28 +0000119 case Decl::UsingPack:
120 for (auto *Using : cast<UsingPackDecl>(D).expansions())
121 EmitDecl(*Using);
122 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000123 case Decl::UsingDirective: // using namespace X; [C++]
124 if (CGDebugInfo *DI = getDebugInfo())
125 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
126 return;
Richard Smithbdb84f32016-07-22 23:36:59 +0000127 case Decl::Var:
128 case Decl::Decomposition: {
Daniel Dunbara7998072008-08-29 17:28:43 +0000129 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000130 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000131 "Should not see file-scope variables inside a function!");
Richard Smithda383632016-08-15 01:33:41 +0000132 EmitVarDecl(VD);
133 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
134 for (auto *B : DD->bindings())
135 if (auto *HD = B->getHoldingVar())
136 EmitVarDecl(*HD);
137 return;
Chris Lattner84915fa2007-06-02 04:16:21 +0000138 }
Mike Stump11289f42009-09-09 15:08:12 +0000139
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000140 case Decl::OMPDeclareReduction:
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000141 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000142
Richard Smithdda56e42011-04-15 14:24:37 +0000143 case Decl::Typedef: // typedef int X;
144 case Decl::TypeAlias: { // using X = int; [C++0x]
145 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000146 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000147
Anders Carlsson5d985f52008-12-20 21:51:53 +0000148 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000149 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000150 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000151 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000152}
Chris Lattner03df1222007-06-02 04:53:11 +0000153
John McCall1c9c3fd2010-10-15 04:57:14 +0000154/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000155/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000156void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Yaxun Liu4f33b3d2017-05-15 14:47:47 +0000157 if (D.hasExternalStorage())
158 // Don't emit it now, allow it to be emitted lazily on its first use.
159 return;
160
161 // Some function-scope variable does not have static storage but still
162 // needs to be emitted like a static variable, e.g. a function-scope
163 // variable in constant address space in OpenCL.
164 if (D.getStorageDuration() != SD_Automatic) {
Alexey Baderbed40092017-11-15 11:38:17 +0000165 // Static sampler variables translated to function calls.
166 if (D.getType()->isSamplerT())
167 return;
168
Eric Christopher31ab1302011-08-23 22:38:00 +0000169 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000170 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000171
David Majnemer27d69db2014-04-28 22:17:59 +0000172 // FIXME: We need to force the emission/use of a guard variable for
173 // some variables even if we can constant-evaluate them because
174 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000175
John McCall1c9c3fd2010-10-15 04:57:14 +0000176 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000177 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000178
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000179 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000180 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
181
182 assert(D.hasLocalStorage());
183 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000184}
185
Reid Kleckner453e0562014-10-08 01:07:54 +0000186static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
187 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000188 return CGM.getMangledName(&D).str();
189
Reid Kleckner453e0562014-10-08 01:07:54 +0000190 // If this isn't C++, we don't need a mangled name, just a pretty one.
191 assert(!D.isExternallyVisible() && "name shouldn't matter");
192 std::string ContextName;
193 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000194 if (auto *CD = dyn_cast<CapturedDecl>(DC))
195 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000196 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000197 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000198 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
199 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
200 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
201 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000202 else
David Blaikie83d382b2011-09-23 05:06:16 +0000203 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000204
Reid Kleckner453e0562014-10-08 01:07:54 +0000205 ContextName += "." + D.getNameAsString();
206 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000207}
208
Reid Kleckner453e0562014-10-08 01:07:54 +0000209llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
210 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
211 // In general, we don't always emit static var decls once before we reference
212 // them. It is possible to reference them before emitting the function that
213 // contains them, and it is possible to emit the containing function multiple
214 // times.
215 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
216 return ExistingGV;
217
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000218 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000219 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000220
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000221 // Use the label if the variable is renamed with the asm-label extension.
222 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000223 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000224 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000225 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000226 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000227
Reid Kleckner453e0562014-10-08 01:07:54 +0000228 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Alexander Richardson6d989432017-10-15 18:48:14 +0000229 LangAS AS = GetGlobalVarAddressSpace(&D);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000230 unsigned TargetAS = getContext().getTargetAddressSpace(AS);
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000231
Yaxun Liua64a4912018-04-02 17:38:24 +0000232 // OpenCL variables in local address space and CUDA shared
233 // variables cannot have an initializer.
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000234 llvm::Constant *Init = nullptr;
Yaxun Liua64a4912018-04-02 17:38:24 +0000235 if (Ty.getAddressSpace() == LangAS::opencl_local ||
236 D.hasAttr<CUDASharedAttr>())
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000237 Init = llvm::UndefValue::get(LTy);
Yaxun Liua64a4912018-04-02 17:38:24 +0000238 else
239 Init = EmitNullConstant(Ty);
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000240
Yaxun Liucbf647c2017-07-08 13:24:52 +0000241 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
242 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
243 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
Ken Dyck160146e2010-01-27 17:10:57 +0000244 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000245
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000246 if (supportsCOMDAT() && GV->isWeakForLinker())
247 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000248
Richard Smithfd3834f2013-04-13 02:43:54 +0000249 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000250 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000251
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000252 setGVProperties(GV, &D);
253
Eli Benderskycb399432014-03-24 22:05:38 +0000254 // Make sure the result is of the correct type.
Alexander Richardson6d989432017-10-15 18:48:14 +0000255 LangAS ExpectedAS = Ty.getAddressSpace();
Reid Kleckner453e0562014-10-08 01:07:54 +0000256 llvm::Constant *Addr = GV;
Yaxun Liucbf647c2017-07-08 13:24:52 +0000257 if (AS != ExpectedAS) {
258 Addr = getTargetCodeGenInfo().performAddrSpaceCast(
259 *this, GV, AS, ExpectedAS,
260 LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
Eli Benderskycb399432014-03-24 22:05:38 +0000261 }
262
Reid Kleckner453e0562014-10-08 01:07:54 +0000263 setStaticLocalDeclAddress(&D, Addr);
264
265 // Ensure that the static local gets initialized by making sure the parent
266 // function gets emitted eventually.
267 const Decl *DC = cast<Decl>(D.getDeclContext());
268
269 // We can't name blocks or captured statements directly, so try to emit their
270 // parents.
271 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
272 DC = DC->getNonClosureContext();
273 // FIXME: Ensure that global blocks get emitted.
274 if (!DC)
275 return Addr;
276 }
277
278 GlobalDecl GD;
279 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
280 GD = GlobalDecl(CD, Ctor_Base);
281 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
282 GD = GlobalDecl(DD, Dtor_Base);
283 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
284 GD = GlobalDecl(FD);
285 else {
286 // Don't do anything for Obj-C method decls or global closures. We should
287 // never defer them.
288 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
289 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +0000290 if (GD.getDecl()) {
291 // Disable emission of the parent function for the OpenMP device codegen.
292 CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
Reid Kleckner453e0562014-10-08 01:07:54 +0000293 (void)GetAddrOfGlobal(GD);
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +0000294 }
Reid Kleckner453e0562014-10-08 01:07:54 +0000295
296 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000297}
298
Richard Smith6331c402012-02-13 22:16:19 +0000299/// hasNontrivialDestruction - Determine whether a type's destruction is
300/// non-trivial. If so, and the variable uses static initialization, we must
301/// register its destructor to run on exit.
302static bool hasNontrivialDestruction(QualType T) {
303 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
304 return RD && !RD->hasTrivialDestructor();
305}
306
Chandler Carruth84537952012-03-30 19:44:53 +0000307/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
308/// global variable that has already been created for it. If the initializer
309/// has a different type than GV does, this may free GV and return a different
310/// one. Otherwise it just returns GV.
311llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000312CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000313 llvm::GlobalVariable *GV) {
John McCallde0fe072017-08-15 21:42:52 +0000314 ConstantEmitter emitter(*this);
315 llvm::Constant *Init = emitter.tryEmitForInitializer(D);
John McCall70013b62010-07-15 23:40:35 +0000316
Chris Lattnere99c1102009-12-05 08:22:11 +0000317 // If constant emission failed, then this should be a C++ static
318 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000319 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000320 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000321 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
Matthias Braun44bfe032017-01-10 17:43:01 +0000322 else if (HaveInsertPoint()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000323 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000324 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000325 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000326
Chandler Carruth84537952012-03-30 19:44:53 +0000327 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000328 }
Chandler Carruth84537952012-03-30 19:44:53 +0000329 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000330 }
John McCall70013b62010-07-15 23:40:35 +0000331
Chris Lattnere99c1102009-12-05 08:22:11 +0000332 // The initializer may differ in type from the global. Rewrite
333 // the global to match the initializer. (We have to do this
334 // because some types, like unions, can't be completely represented
335 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000336 if (GV->getType()->getElementType() != Init->getType()) {
337 llvm::GlobalVariable *OldGV = GV;
338
339 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
340 OldGV->isConstant(),
341 OldGV->getLinkage(), Init, "",
342 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000343 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000344 CGM.getContext().getTargetAddressSpace(D.getType()));
345 GV->setVisibility(OldGV->getVisibility());
Rafael Espindola699f5d62018-02-07 22:15:33 +0000346 GV->setDSOLocal(OldGV->isDSOLocal());
Reid Klecknereab97d32015-07-20 20:35:30 +0000347 GV->setComdat(OldGV->getComdat());
Eric Christopher31ab1302011-08-23 22:38:00 +0000348
Chris Lattnere99c1102009-12-05 08:22:11 +0000349 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000350 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000351
Chris Lattnere99c1102009-12-05 08:22:11 +0000352 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000353 llvm::Constant *NewPtrForOldDecl =
354 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
355 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000356
Chris Lattnere99c1102009-12-05 08:22:11 +0000357 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000358 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000359 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000360
Chandler Carruth84537952012-03-30 19:44:53 +0000361 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
362 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000363
John McCallde0fe072017-08-15 21:42:52 +0000364 emitter.finalize(GV);
365
Matthias Braun44bfe032017-01-10 17:43:01 +0000366 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
Richard Smith6331c402012-02-13 22:16:19 +0000367 // We have a constant initializer, but a nontrivial destructor. We still
368 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000369 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000370 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000371 }
372
Chandler Carruth84537952012-03-30 19:44:53 +0000373 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000374}
375
John McCall1c9c3fd2010-10-15 04:57:14 +0000376void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000377 llvm::GlobalValue::LinkageTypes Linkage) {
John McCallb88a5662012-03-30 21:00:39 +0000378 // Check to see if we already have a global variable for this
379 // declaration. This can happen when double-emitting function
380 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000381 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
John McCall7f416cc2015-09-08 08:05:57 +0000382 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara374e602009-02-25 19:45:19 +0000383
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000384 // Store into LocalDeclMap before generating initializer to handle
385 // circular references.
John McCall7f416cc2015-09-08 08:05:57 +0000386 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000387
John McCall4a39ab82010-05-04 20:45:42 +0000388 // We can't have a VLA here, but we can have a pointer to a VLA,
389 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000390 // Make sure to evaluate VLA bounds now so that we have them for later.
391 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000392 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000393
John McCallb88a5662012-03-30 21:00:39 +0000394 // Save the type in case adding the initializer forces a type change.
395 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000396
Eli Benderskycb399432014-03-24 22:05:38 +0000397 llvm::GlobalVariable *var =
398 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Artem Belevich4d430ba2016-05-09 22:09:56 +0000399
400 // CUDA's local and local static __shared__ variables should not
401 // have any non-empty initializers. This is ensured by Sema.
402 // Whatever initializer such variable may have when it gets here is
403 // a no-op and should not be emitted.
404 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
405 D.hasAttr<CUDASharedAttr>();
Chris Lattnere99c1102009-12-05 08:22:11 +0000406 // If this value has an initializer, emit it.
Artem Belevich4d430ba2016-05-09 22:09:56 +0000407 if (D.getInit() && !isCudaSharedVar)
John McCallb88a5662012-03-30 21:00:39 +0000408 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000409
John McCall7f416cc2015-09-08 08:05:57 +0000410 var->setAlignment(alignment.getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000411
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000412 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000413 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000414
Javed Absar2a67c9e2017-06-05 10:11:57 +0000415 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
416 var->addAttribute("bss-section", SA->getName());
417 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
418 var->addAttribute("data-section", SA->getName());
419 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
420 var->addAttribute("rodata-section", SA->getName());
421
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000422 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000423 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000424
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000425 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000426 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000427
Chandler Carruth84537952012-03-30 19:44:53 +0000428 // We may have to cast the constant because of the initializer
429 // mismatch above.
430 //
431 // FIXME: It is really dangerous to store this in the map; if anyone
432 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000433 llvm::Constant *castedAddr =
434 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCall7f416cc2015-09-08 08:05:57 +0000435 if (var != castedAddr)
436 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCallb88a5662012-03-30 21:00:39 +0000437 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000438
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000439 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000440
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000441 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000442 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000443 if (DI &&
Benjamin Kramer8c305922016-02-02 11:06:51 +0000444 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000445 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000446 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000447 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000448}
Mike Stump11289f42009-09-09 15:08:12 +0000449
John McCall2b7fc382010-07-13 20:32:21 +0000450namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000451 struct DestroyObject final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000452 DestroyObject(Address addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000453 CodeGenFunction::Destroyer *destroyer,
454 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000455 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000456 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000457
John McCall7f416cc2015-09-08 08:05:57 +0000458 Address addr;
John McCall82fe67b2011-07-09 01:37:26 +0000459 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000460 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000461 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000462
Craig Topper4f12f102014-03-12 06:41:41 +0000463 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000464 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000465 bool useEHCleanupForArray =
466 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000467
468 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000469 }
470 };
471
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000472 template <class Derived>
473 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
474 DestroyNRVOVariable(Address addr, llvm::Value *NRVOFlag)
475 : NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000476
John McCall2b7fc382010-07-13 20:32:21 +0000477 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000478 Address Loc;
John McCall2b7fc382010-07-13 20:32:21 +0000479
Craig Topper4f12f102014-03-12 06:41:41 +0000480 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000481 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000482 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000483
Craig Topper8a13c412014-05-21 05:09:00 +0000484 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000485 if (NRVO) {
486 // If we exited via NRVO, we skip the destructor call.
487 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
488 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000489 llvm::Value *DidNRVO =
490 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000491 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
492 CGF.EmitBlock(RunDtorBB);
493 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000494
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000495 static_cast<Derived *>(this)->emitDestructorCall(CGF);
John McCall2b7fc382010-07-13 20:32:21 +0000496
497 if (NRVO) CGF.EmitBlock(SkipDtorBB);
498 }
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000499
500 virtual ~DestroyNRVOVariable() = default;
501 };
502
503 struct DestroyNRVOVariableCXX final
504 : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
505 DestroyNRVOVariableCXX(Address addr, const CXXDestructorDecl *Dtor,
506 llvm::Value *NRVOFlag)
507 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, NRVOFlag),
508 Dtor(Dtor) {}
509
510 const CXXDestructorDecl *Dtor;
511
512 void emitDestructorCall(CodeGenFunction &CGF) {
513 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
514 /*ForVirtualBase=*/false,
515 /*Delegating=*/false, Loc);
516 }
517 };
518
519 struct DestroyNRVOVariableC final
520 : DestroyNRVOVariable<DestroyNRVOVariableC> {
521 DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
522 : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, NRVOFlag), Ty(Ty) {}
523
524 QualType Ty;
525
526 void emitDestructorCall(CodeGenFunction &CGF) {
527 CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
528 }
John McCall2b7fc382010-07-13 20:32:21 +0000529 };
John McCall2b7fc382010-07-13 20:32:21 +0000530
David Blaikie7e70d682015-08-18 22:40:54 +0000531 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000532 Address Stack;
533 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000534 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000535 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
John McCalla464ff92010-07-21 06:13:08 +0000536 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
537 CGF.Builder.CreateCall(F, V);
538 }
539 };
540
David Blaikie7e70d682015-08-18 22:40:54 +0000541 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000542 const VarDecl &Var;
543 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
544
Craig Topper4f12f102014-03-12 06:41:41 +0000545 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000546 // Compute the address of the local variable, in case it's a
547 // byref or something.
John McCall113bee02012-03-10 09:33:50 +0000548 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
549 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000550 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
551 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000552 CGF.EmitExtendGCLifetime(value);
553 }
554 };
555
David Blaikie7e70d682015-08-18 22:40:54 +0000556 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000557 llvm::Constant *CleanupFn;
558 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000559 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000560
John McCalla464ff92010-07-21 06:13:08 +0000561 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000562 const VarDecl *Var)
563 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000564
Craig Topper4f12f102014-03-12 06:41:41 +0000565 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall113bee02012-03-10 09:33:50 +0000566 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
567 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000568 // Compute the address of the local variable, in case it's a byref
569 // or something.
John McCall7f416cc2015-09-08 08:05:57 +0000570 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCallc533cb72011-02-22 06:44:22 +0000571
John McCalla464ff92010-07-21 06:13:08 +0000572 // In some cases, the type of the function argument will be different from
573 // the type of the pointer. An example of this is
574 // void f(void* arg);
575 // __attribute__((cleanup(f))) void *g;
576 //
577 // To fix this we insert a bitcast here.
578 QualType ArgTy = FnInfo.arg_begin()->type;
579 llvm::Value *Arg =
580 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
581
582 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000583 Args.add(RValue::get(Arg),
584 CGF.getContext().getPointerType(Var.getType()));
John McCallb92ab1a2016-10-26 23:46:34 +0000585 auto Callee = CGCallee::forDirect(CleanupFn);
586 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
John McCalla464ff92010-07-21 06:13:08 +0000587 }
588 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000589} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000590
John McCall31168b02011-06-15 23:02:42 +0000591/// EmitAutoVarWithLifetime - Does the setup required for an automatic
592/// variable with lifetime.
593static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000594 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000595 Qualifiers::ObjCLifetime lifetime) {
596 switch (lifetime) {
597 case Qualifiers::OCL_None:
598 llvm_unreachable("present but none");
599
600 case Qualifiers::OCL_ExplicitNone:
601 // nothing to do
602 break;
603
604 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000605 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000606 (var.hasAttr<ObjCPreciseLifetimeAttr>()
607 ? CodeGenFunction::destroyARCStrongPrecise
608 : CodeGenFunction::destroyARCStrongImprecise);
609
610 CleanupKind cleanupKind = CGF.getARCCleanupKind();
611 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
612 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000613 break;
614 }
615 case Qualifiers::OCL_Autoreleasing:
616 // nothing to do
617 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000618
John McCall31168b02011-06-15 23:02:42 +0000619 case Qualifiers::OCL_Weak:
620 // __weak objects always get EH cleanups; otherwise, exceptions
621 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000622 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
623 CodeGenFunction::destroyARCWeak,
624 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000625 break;
626 }
627}
628
629static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
630 if (const Expr *e = dyn_cast<Expr>(s)) {
631 // Skip the most common kinds of expressions that make
632 // hierarchy-walking expensive.
633 s = e = e->IgnoreParenCasts();
634
635 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
636 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000637 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
638 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000639 for (const auto &I : block->captures()) {
640 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000641 return true;
642 }
643 }
John McCall31168b02011-06-15 23:02:42 +0000644 }
645
Benjamin Kramer642f1732015-07-02 21:03:14 +0000646 for (const Stmt *SubStmt : s->children())
647 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
648 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000649 return true;
650
651 return false;
652}
653
654static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
655 if (!decl) return false;
656 if (!isa<VarDecl>(decl)) return false;
657 const VarDecl *var = cast<VarDecl>(decl);
658 return isAccessedBy(*var, e);
659}
660
John McCallf8a9b662015-10-21 18:06:31 +0000661static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
662 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000663 bool needsCast = false;
664
John McCallf8a9b662015-10-21 18:06:31 +0000665 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
666 switch (castExpr->getCastKind()) {
667 // Look through casts that don't require representation changes.
668 case CK_NoOp:
669 case CK_BitCast:
670 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000671 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000672 break;
673
674 // If we find an l-value to r-value cast from a __weak variable,
675 // emit this operation as a copy or move.
676 case CK_LValueToRValue: {
677 const Expr *srcExpr = castExpr->getSubExpr();
678 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
679 return false;
680
681 // Emit the source l-value.
682 LValue srcLV = CGF.EmitLValue(srcExpr);
683
John McCall0204e342015-11-16 22:11:41 +0000684 // Handle a formal type change to avoid asserting.
685 auto srcAddr = srcLV.getAddress();
686 if (needsCast) {
687 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
688 destLV.getAddress().getElementType());
689 }
690
John McCallf8a9b662015-10-21 18:06:31 +0000691 // If it was an l-value, use objc_copyWeak.
692 if (srcExpr->getValueKind() == VK_LValue) {
John McCall0204e342015-11-16 22:11:41 +0000693 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000694 } else {
695 assert(srcExpr->getValueKind() == VK_XValue);
John McCall0204e342015-11-16 22:11:41 +0000696 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000697 }
698 return true;
699 }
700
701 // Stop at anything else.
702 default:
703 return false;
704 }
705
706 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000707 }
708 return false;
709}
710
John McCall1553b192011-06-16 04:16:24 +0000711static void drillIntoBlockVariable(CodeGenFunction &CGF,
712 LValue &lvalue,
713 const VarDecl *var) {
John McCall7f416cc2015-09-08 08:05:57 +0000714 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCall1553b192011-06-16 04:16:24 +0000715}
716
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000717void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
718 SourceLocation Loc) {
719 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
720 return;
721
722 auto Nullability = LHS.getType()->getNullability(getContext());
723 if (!Nullability || *Nullability != NullabilityKind::NonNull)
724 return;
725
726 // Check if the right hand side of the assignment is nonnull, if the left
727 // hand side must be nonnull.
728 SanitizerScope SanScope(this);
729 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000730 llvm::Constant *StaticData[] = {
731 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
Simon Pilgrim2df19982017-03-14 21:43:52 +0000732 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
Vedant Kumar2b9f48a2017-03-14 16:48:29 +0000733 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000734 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
735 SanitizerHandler::TypeMismatch, StaticData, RHS);
736}
737
David Blaikie73ca5692014-12-09 00:32:22 +0000738void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000739 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000740 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000741 if (!lifetime) {
742 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000743 if (capturedByInit)
744 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000745 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
David Blaikie66e41972015-01-14 07:38:27 +0000746 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000747 return;
748 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000749
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000750 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
751 init = DIE->getExpr();
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000752
John McCall31168b02011-06-15 23:02:42 +0000753 // If we're emitting a value with lifetime, we have to do the
754 // initialization *before* we leave the cleanup scopes.
John McCall08ef4662011-11-10 08:15:53 +0000755 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
756 enterFullExpression(ewc);
John McCall31168b02011-06-15 23:02:42 +0000757 init = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000758 }
759 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000760
761 // We have to maintain the illusion that the variable is
762 // zero-initialized. If the variable might be accessed in its
763 // initializer, zero-initialize before running the initializer, then
764 // actually perform the initialization with an assign.
765 bool accessedByInit = false;
766 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000767 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000768 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000769 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000770 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000771 if (capturedByInit) {
772 // We can use a simple GEP for this because it can't have been
773 // moved yet.
John McCall7f416cc2015-09-08 08:05:57 +0000774 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
775 cast<VarDecl>(D),
776 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000777 }
778
John McCall7f416cc2015-09-08 08:05:57 +0000779 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
Yaxun Liu402804b2016-12-15 08:09:08 +0000780 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000781
John McCall31168b02011-06-15 23:02:42 +0000782 // If __weak, we want to use a barrier under certain conditions.
783 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000784 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000785
786 // Otherwise just do a simple store.
787 else
David Chisnallfa35df62012-01-16 17:27:18 +0000788 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000789 }
790
791 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000792 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000793
794 switch (lifetime) {
795 case Qualifiers::OCL_None:
796 llvm_unreachable("present but none");
797
798 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000799 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000800 break;
801
802 case Qualifiers::OCL_Strong: {
803 value = EmitARCRetainScalarExpr(init);
804 break;
805 }
806
807 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000808 // If it's not accessed by the initializer, try to emit the
809 // initialization with a copy or move.
810 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
811 return;
812 }
813
John McCall31168b02011-06-15 23:02:42 +0000814 // No way to optimize a producing initializer into this. It's not
815 // worth optimizing for, because the value will immediately
816 // disappear in the common case.
817 value = EmitScalarExpr(init);
818
John McCall1553b192011-06-16 04:16:24 +0000819 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000820 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000821 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000822 else
John McCall1553b192011-06-16 04:16:24 +0000823 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000824 return;
825 }
826
827 case Qualifiers::OCL_Autoreleasing:
828 value = EmitARCRetainAutoreleaseScalarExpr(init);
829 break;
830 }
831
John McCall1553b192011-06-16 04:16:24 +0000832 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000833
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000834 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
835
John McCall31168b02011-06-15 23:02:42 +0000836 // If the variable might have been accessed by its initializer, we
837 // might have to initialize with a barrier. We have to do this for
838 // both __weak and __strong, but __weak got filtered out above.
839 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000840 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000841 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000842 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000843 return;
844 }
845
David Chisnallfa35df62012-01-16 17:27:18 +0000846 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000847}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000848
JF Bastiened92f602018-07-20 23:37:12 +0000849/// Decide whether we can emit the non-zero parts of the specified initializer
850/// with equal or fewer than NumStores scalar stores.
851static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
852 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000853 // Zero and Undef never requires any extra stores.
854 if (isa<llvm::ConstantAggregateZero>(Init) ||
855 isa<llvm::ConstantPointerNull>(Init) ||
856 isa<llvm::UndefValue>(Init))
857 return true;
858 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
859 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
860 isa<llvm::ConstantExpr>(Init))
861 return Init->isNullValue() || NumStores--;
862
863 // See if we can emit each element.
864 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
865 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
866 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
JF Bastiened92f602018-07-20 23:37:12 +0000867 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
Chris Lattnere6af8862010-12-02 01:58:41 +0000868 return false;
869 }
870 return true;
871 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000872
Chris Lattner236b3572012-01-31 04:36:19 +0000873 if (llvm::ConstantDataSequential *CDS =
874 dyn_cast<llvm::ConstantDataSequential>(Init)) {
875 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
876 llvm::Constant *Elt = CDS->getElementAsConstant(i);
JF Bastiened92f602018-07-20 23:37:12 +0000877 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
Chris Lattner236b3572012-01-31 04:36:19 +0000878 return false;
879 }
880 return true;
881 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000882
Chris Lattnerb85025f2010-12-01 02:05:19 +0000883 // Anything else is hard and scary.
884 return false;
885}
886
JF Bastiened92f602018-07-20 23:37:12 +0000887/// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
888/// the scalar stores that would be required.
889static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
890 llvm::Constant *Init, Address Loc,
891 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000892 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
JF Bastiened92f602018-07-20 23:37:12 +0000893 "called emitStoresForInitAfterBZero for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000894
Chris Lattnere6af8862010-12-02 01:58:41 +0000895 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
896 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
897 isa<llvm::ConstantExpr>(Init)) {
JF Bastien9aab85a2018-07-13 20:33:23 +0000898 Builder.CreateStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000899 return;
900 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000901
902 if (llvm::ConstantDataSequential *CDS =
903 dyn_cast<llvm::ConstantDataSequential>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000904 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
905 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000906
907 // If necessary, get a pointer to the element and emit it.
908 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
JF Bastiened92f602018-07-20 23:37:12 +0000909 emitStoresForInitAfterBZero(
JF Bastien9aab85a2018-07-13 20:33:23 +0000910 CGM, Elt,
911 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i, CGM.getDataLayout()),
David Blaikie17ea2662015-04-04 21:07:17 +0000912 isVolatile, Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000913 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000914 return;
915 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000916
Chris Lattnere6af8862010-12-02 01:58:41 +0000917 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
918 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000919
Chris Lattnere6af8862010-12-02 01:58:41 +0000920 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
921 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000922
923 // If necessary, get a pointer to the element and emit it.
924 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
JF Bastiened92f602018-07-20 23:37:12 +0000925 emitStoresForInitAfterBZero(
JF Bastien9aab85a2018-07-13 20:33:23 +0000926 CGM, Elt,
927 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i, CGM.getDataLayout()),
David Blaikie17ea2662015-04-04 21:07:17 +0000928 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000929 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000930}
931
JF Bastiened92f602018-07-20 23:37:12 +0000932/// Decide whether we should use bzero plus some stores to initialize a local
933/// variable instead of using a memcpy from a constant global. It is beneficial
934/// to use bzero if the global is all zeros, or mostly zeros and large.
935static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
936 uint64_t GlobalSize) {
937 // If a global is all zeros, always use a bzero.
Chris Lattnerb85025f2010-12-01 02:05:19 +0000938 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
939
Chris Lattnerb85025f2010-12-01 02:05:19 +0000940 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
941 // do it if it will require 6 or fewer scalar stores.
942 // TODO: Should budget depends on the size? Avoiding a large global warrants
943 // plopping in more stores.
944 unsigned StoreBudget = 6;
945 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000946
947 return GlobalSize > SizeLimit &&
JF Bastiened92f602018-07-20 23:37:12 +0000948 canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
Chris Lattnerb85025f2010-12-01 02:05:19 +0000949}
950
JF Bastien65089292018-07-25 04:29:03 +0000951/// A byte pattern.
952///
953/// Can be "any" pattern if the value was padding or known to be undef.
954/// Can be "none" pattern if a sequence doesn't exist.
955class BytePattern {
956 uint8_t Val;
957 enum class ValueType : uint8_t { Specific, Any, None } Type;
958 BytePattern(ValueType Type) : Type(Type) {}
959
960public:
961 BytePattern(uint8_t Value) : Val(Value), Type(ValueType::Specific) {}
962 static BytePattern Any() { return BytePattern(ValueType::Any); }
963 static BytePattern None() { return BytePattern(ValueType::None); }
964 bool isAny() const { return Type == ValueType::Any; }
965 bool isNone() const { return Type == ValueType::None; }
966 bool isValued() const { return Type == ValueType::Specific; }
967 uint8_t getValue() const {
968 assert(isValued());
969 return Val;
970 }
971 BytePattern merge(const BytePattern Other) const {
972 if (isNone() || Other.isNone())
973 return None();
974 if (isAny())
975 return Other;
976 if (Other.isAny())
977 return *this;
978 if (getValue() == Other.getValue())
979 return *this;
980 return None();
981 }
982};
983
984/// Figures out whether the constant can be initialized with memset.
985static BytePattern constantIsRepeatedBytePattern(llvm::Constant *C) {
986 if (isa<llvm::ConstantAggregateZero>(C) || isa<llvm::ConstantPointerNull>(C))
987 return BytePattern(0x00);
988 if (isa<llvm::UndefValue>(C))
989 return BytePattern::Any();
990
991 if (isa<llvm::ConstantInt>(C)) {
992 auto *Int = cast<llvm::ConstantInt>(C);
993 if (Int->getBitWidth() % 8 != 0)
994 return BytePattern::None();
995 const llvm::APInt &Value = Int->getValue();
996 if (Value.isSplat(8))
997 return BytePattern(Value.getLoBits(8).getLimitedValue());
998 return BytePattern::None();
999 }
1000
1001 if (isa<llvm::ConstantFP>(C)) {
1002 auto *FP = cast<llvm::ConstantFP>(C);
1003 llvm::APInt Bits = FP->getValueAPF().bitcastToAPInt();
1004 if (Bits.getBitWidth() % 8 != 0)
1005 return BytePattern::None();
1006 if (!Bits.isSplat(8))
1007 return BytePattern::None();
1008 return BytePattern(Bits.getLimitedValue() & 0xFF);
1009 }
1010
1011 if (isa<llvm::ConstantVector>(C)) {
1012 llvm::Constant *Splat = cast<llvm::ConstantVector>(C)->getSplatValue();
1013 if (Splat)
1014 return constantIsRepeatedBytePattern(Splat);
1015 return BytePattern::None();
1016 }
1017
1018 if (isa<llvm::ConstantArray>(C) || isa<llvm::ConstantStruct>(C)) {
1019 BytePattern Pattern(BytePattern::Any());
1020 for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I) {
1021 llvm::Constant *Elt = cast<llvm::Constant>(C->getOperand(I));
1022 Pattern = Pattern.merge(constantIsRepeatedBytePattern(Elt));
1023 if (Pattern.isNone())
1024 return Pattern;
1025 }
1026 return Pattern;
1027 }
1028
1029 if (llvm::ConstantDataSequential *CDS =
1030 dyn_cast<llvm::ConstantDataSequential>(C)) {
1031 BytePattern Pattern(BytePattern::Any());
1032 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) {
1033 llvm::Constant *Elt = CDS->getElementAsConstant(I);
1034 Pattern = Pattern.merge(constantIsRepeatedBytePattern(Elt));
1035 if (Pattern.isNone())
1036 return Pattern;
1037 }
1038 return Pattern;
1039 }
1040
1041 // BlockAddress, ConstantExpr, and everything else is scary.
1042 return BytePattern::None();
1043}
1044
1045/// Decide whether we should use memset to initialize a local variable instead
1046/// of using a memcpy from a constant global. Assumes we've already decided to
1047/// not user bzero.
1048/// FIXME We could be more clever, as we are for bzero above, and generate
1049/// memset followed by stores. It's unclear that's worth the effort.
1050static BytePattern shouldUseMemSetToInitialize(llvm::Constant *Init,
1051 uint64_t GlobalSize) {
1052 uint64_t SizeLimit = 32;
1053 if (GlobalSize <= SizeLimit)
1054 return BytePattern::None();
1055 return constantIsRepeatedBytePattern(Init);
1056}
1057
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001058static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
1059 Address Loc, bool isVolatile,
1060 CGBuilderTy &Builder,
1061 llvm::Constant *constant) {
1062 auto *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1063 auto *IntPtrTy = CGM.getDataLayout().getIntPtrType(CGM.getLLVMContext());
1064
1065 // If the initializer is all or mostly the same, codegen with bzero / memset
1066 // then do a few stores afterward.
1067 uint64_t ConstantSize =
1068 CGM.getDataLayout().getTypeAllocSize(constant->getType());
1069 auto *SizeVal = llvm::ConstantInt::get(IntPtrTy, ConstantSize);
1070 if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1071 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1072 isVolatile);
1073
1074 bool valueAlreadyCorrect =
1075 constant->isNullValue() || isa<llvm::UndefValue>(constant);
1076 if (!valueAlreadyCorrect) {
1077 Loc = Builder.CreateBitCast(
1078 Loc, constant->getType()->getPointerTo(Loc.getAddressSpace()));
1079 emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder);
1080 }
1081 return;
1082 }
1083
1084 BytePattern Pattern = shouldUseMemSetToInitialize(constant, ConstantSize);
1085 if (!Pattern.isNone()) {
1086 uint8_t Value = Pattern.isAny() ? 0x00 : Pattern.getValue();
1087 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, Value), SizeVal,
1088 isVolatile);
1089 return;
1090 }
1091
1092 // Otherwise, create a temporary global with the initializer then memcpy from
1093 // the global to the alloca.
1094 std::string Name = getStaticDeclName(CGM, D);
1095 unsigned AS = CGM.getContext().getTargetAddressSpace(
1096 CGM.getStringLiteralAddressSpace());
1097 llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(), AS);
1098
1099 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1100 CGM.getModule(), constant->getType(), true,
1101 llvm::GlobalValue::PrivateLinkage, constant, Name, nullptr,
1102 llvm::GlobalValue::NotThreadLocal, AS);
1103 GV->setAlignment(Loc.getAlignment().getQuantity());
1104 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1105
1106 Address SrcPtr = Address(GV, Loc.getAlignment());
1107 if (SrcPtr.getType() != BP)
1108 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1109
1110 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
1111}
1112
Nick Lewycky8a7d90b2010-12-30 20:21:55 +00001113/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +00001114/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +00001115/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +00001116void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1117 AutoVarEmission emission = EmitAutoVarAlloca(D);
1118 EmitAutoVarInit(emission);
1119 EmitAutoVarCleanups(emission);
1120}
Chris Lattner03df1222007-06-02 04:53:11 +00001121
David Majnemerdc012fa2015-04-22 21:38:15 +00001122/// Emit a lifetime.begin marker if some criteria are satisfied.
1123/// \return a pointer to the temporary size Value if a marker was emitted, null
1124/// otherwise
1125llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
1126 llvm::Value *Addr) {
Vitaly Buka1c943322016-10-26 01:59:57 +00001127 if (!ShouldEmitLifetimeMarkers)
Reid Kleckner1ef49212015-04-23 18:07:13 +00001128 return nullptr;
1129
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001130 assert(Addr->getType()->getPointerAddressSpace() ==
1131 CGM.getDataLayout().getAllocaAddrSpace() &&
1132 "Pointer should be in alloca address space");
David Majnemerdc012fa2015-04-22 21:38:15 +00001133 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001134 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +00001135 llvm::CallInst *C =
1136 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +00001137 C->setDoesNotThrow();
1138 return SizeV;
1139}
1140
1141void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001142 assert(Addr->getType()->getPointerAddressSpace() ==
1143 CGM.getDataLayout().getAllocaAddrSpace() &&
1144 "Pointer should be in alloca address space");
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001145 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +00001146 llvm::CallInst *C =
1147 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +00001148 C->setDoesNotThrow();
1149}
1150
Sander de Smalen891af03a2018-02-03 13:55:59 +00001151void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1152 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1153 // For each dimension stores its QualType and corresponding
1154 // size-expression Value.
1155 SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
1156
1157 // Break down the array into individual dimensions.
1158 QualType Type1D = D.getType();
1159 while (getContext().getAsVariableArrayType(Type1D)) {
1160 auto VlaSize = getVLAElements1D(Type1D);
1161 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1162 Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1163 else {
Sander de Smalen9084a3b2018-02-13 07:49:34 +00001164 auto SizeExprAddr = CreateDefaultAlignTempAlloca(
1165 VlaSize.NumElts->getType(), "__vla_expr");
Sander de Smalen891af03a2018-02-03 13:55:59 +00001166 Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1167 Dimensions.emplace_back(SizeExprAddr.getPointer(),
1168 Type1D.getUnqualifiedType());
1169 }
1170 Type1D = VlaSize.Type;
1171 }
1172
1173 if (!EmitDebugInfo)
1174 return;
1175
1176 // Register each dimension's size-expression with a DILocalVariable,
1177 // so that it can be used by CGDebugInfo when instantiating a DISubrange
1178 // to describe this array.
1179 for (auto &VlaSize : Dimensions) {
1180 llvm::Metadata *MD;
1181 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1182 MD = llvm::ConstantAsMetadata::get(C);
1183 else {
1184 // Create an artificial VarDecl to generate debug info for.
1185 IdentifierInfo &NameIdent = getContext().Idents.getOwn(
1186 cast<llvm::AllocaInst>(VlaSize.NumElts)->getName());
1187 auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
1188 auto QT = getContext().getIntTypeForBitwidth(
1189 VlaExprTy->getScalarSizeInBits(), false);
1190 auto *ArtificialDecl = VarDecl::Create(
1191 getContext(), const_cast<DeclContext *>(D.getDeclContext()),
1192 D.getLocation(), D.getLocation(), &NameIdent, QT,
1193 getContext().CreateTypeSourceInfo(QT), SC_Auto);
Sander de Smalen9084a3b2018-02-13 07:49:34 +00001194 ArtificialDecl->setImplicit();
Sander de Smalen891af03a2018-02-03 13:55:59 +00001195
1196 MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1197 Builder);
1198 }
1199 assert(MD && "No Size expression debug node created");
1200 DI->registerVLASizeExpression(VlaSize.Type, MD);
1201 }
1202}
1203
John McCallc533cb72011-02-22 06:44:22 +00001204/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001205/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +00001206CodeGenFunction::AutoVarEmission
1207CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1208 QualType Ty = D.getType();
Yaxun Liub7318e02017-10-13 03:37:48 +00001209 assert(
1210 Ty.getAddressSpace() == LangAS::Default ||
1211 (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
John McCallc533cb72011-02-22 06:44:22 +00001212
1213 AutoVarEmission emission(D);
1214
1215 bool isByRef = D.hasAttr<BlocksAttr>();
1216 emission.IsByRef = isByRef;
1217
1218 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +00001219
John McCall23c29fe2011-06-24 21:55:10 +00001220 // If the type is variably-modified, emit all the VLA sizes for it.
1221 if (Ty->isVariablyModifiedType())
1222 EmitVariablyModifiedType(Ty);
1223
Sander de Smalen891af03a2018-02-03 13:55:59 +00001224 auto *DI = getDebugInfo();
1225 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().getDebugInfo() >=
1226 codegenoptions::LimitedDebugInfo;
1227
John McCall7f416cc2015-09-08 08:05:57 +00001228 Address address = Address::invalid();
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001229 Address AllocaAddr = Address::invalid();
Eli Friedmana682d392008-02-15 12:20:59 +00001230 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001231 bool NRVO = getLangOpts().ElideConstructors &&
1232 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +00001233
Richard Smith2bcde3a2013-06-02 00:09:52 +00001234 // If this value is an array or struct with a statically determinable
1235 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +00001236 //
1237 // TODO: We should constant-evaluate the initializer of any variable,
1238 // as long as it is initialized by a constant expression. Currently,
1239 // isConstantInitializer produces wrong answers for structs with
1240 // reference or bitfield members, and a few other cases, and checking
1241 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +00001242 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1243 (D.isConstexpr() ||
1244 ((Ty.isPODType(getContext()) ||
1245 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1246 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +00001247
Rafael Espindola609f5d92013-03-26 18:41:47 +00001248 // If the variable's a const type, and it's neither an NRVO
1249 // candidate nor a __block variable and has no mutable members,
1250 // emit it as a global instead.
Anastasia Stulovae4a1c382016-11-29 17:01:19 +00001251 // Exception is if a variable is located in non-constant address space
1252 // in OpenCL.
1253 if ((!getLangOpts().OpenCL ||
1254 Ty.getAddressSpace() == LangAS::opencl_constant) &&
1255 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
1256 CGM.isTypeConstant(Ty, true))) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001257 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +00001258
John McCall7f416cc2015-09-08 08:05:57 +00001259 // Signal this condition to later callbacks.
1260 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +00001261 assert(emission.wasEmittedAsGlobal());
1262 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +00001263 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001264
Rafael Espindola609f5d92013-03-26 18:41:47 +00001265 // Otherwise, tell the initialization code that we're in this case.
1266 emission.IsConstantAggregate = true;
1267 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001268
Rafael Espindola609f5d92013-03-26 18:41:47 +00001269 // A normal fixed sized variable becomes an alloca in the entry block,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001270 // unless:
1271 // - it's an NRVO variable.
1272 // - we are compiling OpenMP and it's an OpenMP local variable.
Eric Christopher31ab1302011-08-23 22:38:00 +00001273
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001274 Address OpenMPLocalAddr =
1275 getLangOpts().OpenMP
1276 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
1277 : Address::invalid();
1278 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1279 address = OpenMPLocalAddr;
1280 } else if (NRVO) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001281 // The named return value optimization: allocate this variable in the
1282 // return slot, so that we can elide the copy when returning this
1283 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +00001284 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +00001285
Rafael Espindola609f5d92013-03-26 18:41:47 +00001286 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001287 const auto *RD = RecordTy->getDecl();
1288 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1289 if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1290 RD->isNonTrivialToPrimitiveDestroy()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001291 // Create a flag that is used to indicate when the NRVO was applied
1292 // to this variable. Set it to zero to indicate that NRVO was not
1293 // applied.
1294 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +00001295 Address NRVOFlag =
1296 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +00001297 EnsureInsertPoint();
1298 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +00001299
Rafael Espindola609f5d92013-03-26 18:41:47 +00001300 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +00001301 NRVOFlags[&D] = NRVOFlag.getPointer();
1302 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +00001303 }
Douglas Gregor290c93e2010-05-15 06:46:45 +00001304 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001305 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001306 CharUnits allocaAlignment;
1307 llvm::Type *allocaTy;
1308 if (isByRef) {
1309 auto &byrefInfo = getBlockByrefInfo(&D);
1310 allocaTy = byrefInfo.Type;
1311 allocaAlignment = byrefInfo.ByrefAlignment;
1312 } else {
1313 allocaTy = ConvertTypeForMem(Ty);
1314 allocaAlignment = alignment;
1315 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001316
John McCall999110f2015-09-08 09:18:30 +00001317 // Create the alloca. Note that we set the name separately from
1318 // building the instruction so that it's there even in no-asserts
1319 // builds.
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001320 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1321 /*ArraySize=*/nullptr, &AllocaAddr);
Rafael Espindola609f5d92013-03-26 18:41:47 +00001322
Reid Kleckner1f88e932015-10-07 21:03:41 +00001323 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1324 // the catch parameter starts in the catchpad instruction, and we can't
1325 // insert code in those basic blocks.
1326 bool IsMSCatchParam =
1327 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1328
Vitaly Buka64c80b42016-10-26 05:42:30 +00001329 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1330 // if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001331 if (HaveInsertPoint() && !IsMSCatchParam) {
Akira Hatanakafdcd18b2017-01-25 22:55:13 +00001332 // If there's a jump into the lifetime of this variable, its lifetime
1333 // gets broken up into several regions in IR, which requires more work
1334 // to handle correctly. For now, just omit the intrinsics; this is a
1335 // rare case, and it's better to just be conservatively correct.
1336 // PR28267.
1337 //
1338 // We have to do this in all language modes if there's a jump past the
1339 // declaration. We also have to do it in C if there's a jump to an
1340 // earlier point in the current block because non-VLA lifetimes begin as
1341 // soon as the containing block is entered, not when its variables
1342 // actually come into scope; suppressing the lifetime annotations
1343 // completely in this case is unnecessarily pessimistic, but again, this
1344 // is rare.
1345 if (!Bypasses.IsBypassed(&D) &&
1346 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
Vitaly Buka64c80b42016-10-26 05:42:30 +00001347 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1348 emission.SizeForLifetimeMarkers =
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001349 EmitLifetimeStart(size, AllocaAddr.getPointer());
Vitaly Buka64c80b42016-10-26 05:42:30 +00001350 }
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001351 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001352 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001353 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001354 }
Chris Lattner03df1222007-06-02 04:53:11 +00001355 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001356 EnsureInsertPoint();
1357
Anders Carlsson15949b32009-02-09 20:41:50 +00001358 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001359 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001360 Address Stack =
1361 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001362
Anders Carlsson30032882008-12-12 07:38:43 +00001363 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001364 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001365 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001366
1367 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001368
John McCalla464ff92010-07-21 06:13:08 +00001369 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001370 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001371 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001372 }
Mike Stump11289f42009-09-09 15:08:12 +00001373
Sander de Smalen891af03a2018-02-03 13:55:59 +00001374 auto VlaSize = getVLASize(Ty);
1375 llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
Anders Carlsson30032882008-12-12 07:38:43 +00001376
1377 // Allocate memory for the array.
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001378 address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1379 &AllocaAddr);
Sander de Smalen891af03a2018-02-03 13:55:59 +00001380
1381 // If we have debug info enabled, properly describe the VLA dimensions for
1382 // this type by registering the vla size expression for each of the
1383 // dimensions.
1384 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
Chris Lattner03df1222007-06-02 04:53:11 +00001385 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001386
John McCall7f416cc2015-09-08 08:05:57 +00001387 setAddrOfLocalVar(&D, address);
1388 emission.Addr = address;
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001389 emission.AllocaAddr = AllocaAddr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001390
1391 // Emit debug info for local var declaration.
Sander de Smalen891af03a2018-02-03 13:55:59 +00001392 if (EmitDebugInfo && HaveInsertPoint()) {
1393 DI->setLocation(D.getLocation());
1394 (void)DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1395 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001396
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001397 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001398 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001399
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001400 // Make sure we call @llvm.lifetime.end.
1401 if (emission.useLifetimeMarkers())
1402 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001403 emission.getOriginalAllocatedAddress(),
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001404 emission.getSizeForLifetimeMarkers());
1405
John McCallc533cb72011-02-22 06:44:22 +00001406 return emission;
1407}
1408
JF Bastien6b239722018-05-19 04:21:26 +00001409static bool isCapturedBy(const VarDecl &, const Expr *);
1410
1411/// Determines whether the given __block variable is potentially
1412/// captured by the given statement.
1413static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1414 if (const Expr *E = dyn_cast<Expr>(S))
1415 return isCapturedBy(Var, E);
1416 for (const Stmt *SubStmt : S->children())
1417 if (isCapturedBy(Var, SubStmt))
1418 return true;
1419 return false;
1420}
1421
John McCallc533cb72011-02-22 06:44:22 +00001422/// Determines whether the given __block variable is potentially
1423/// captured by the given expression.
JF Bastien6b239722018-05-19 04:21:26 +00001424static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
John McCallc533cb72011-02-22 06:44:22 +00001425 // Skip the most common kinds of expressions that make
1426 // hierarchy-walking expensive.
JF Bastien6b239722018-05-19 04:21:26 +00001427 E = E->IgnoreParenCasts();
John McCallc533cb72011-02-22 06:44:22 +00001428
JF Bastien6b239722018-05-19 04:21:26 +00001429 if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1430 const BlockDecl *Block = BE->getBlockDecl();
1431 for (const auto &I : Block->captures()) {
1432 if (I.getVariable() == &Var)
John McCallc533cb72011-02-22 06:44:22 +00001433 return true;
1434 }
1435
1436 // No need to walk into the subexpressions.
1437 return false;
1438 }
1439
JF Bastien6b239722018-05-19 04:21:26 +00001440 if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001441 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001442 for (const auto *BI : CS->body())
JF Bastien6b239722018-05-19 04:21:26 +00001443 if (const auto *BIE = dyn_cast<Expr>(BI)) {
1444 if (isCapturedBy(Var, BIE))
1445 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001446 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001447 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001448 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001449 for (const auto *I : DS->decls()) {
1450 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1451 const Expr *Init = VD->getInit();
JF Bastien6b239722018-05-19 04:21:26 +00001452 if (Init && isCapturedBy(Var, Init))
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001453 return true;
1454 }
1455 }
1456 }
1457 else
1458 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1459 // Later, provide code to poke into statements for capture analysis.
1460 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001461 return false;
1462 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001463
JF Bastien6b239722018-05-19 04:21:26 +00001464 for (const Stmt *SubStmt : E->children())
1465 if (isCapturedBy(Var, SubStmt))
John McCallc533cb72011-02-22 06:44:22 +00001466 return true;
1467
1468 return false;
1469}
1470
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001471/// Determine whether the given initializer is trivial in the sense
Douglas Gregor82e1af22011-07-01 21:08:19 +00001472/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001473bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001474 if (!Init)
1475 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001476
Douglas Gregor82e1af22011-07-01 21:08:19 +00001477 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1478 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1479 if (Constructor->isTrivial() &&
1480 Constructor->isDefaultConstructor() &&
1481 !Construct->requiresZeroInitialization())
1482 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001483
Douglas Gregor82e1af22011-07-01 21:08:19 +00001484 return false;
1485}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001486
John McCallc533cb72011-02-22 06:44:22 +00001487void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001488 assert(emission.Variable && "emission was not valid!");
1489
John McCallc533cb72011-02-22 06:44:22 +00001490 // If this was emitted as a global constant, we're done.
1491 if (emission.wasEmittedAsGlobal()) return;
1492
John McCall9e2e22f2011-02-22 07:16:58 +00001493 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001494 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001495 QualType type = D.getType();
1496
Chris Lattner07eb7332007-07-12 00:39:48 +00001497 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001498 const Expr *Init = D.getInit();
1499
1500 // If we are at an unreachable point, we don't need to emit the initializer
1501 // unless it contains a label.
1502 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001503 if (!Init || !ContainsLabel(Init)) return;
1504 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001505 }
1506
John McCall73064872011-03-31 01:59:53 +00001507 // Initialize the structure of a __block variable.
1508 if (emission.IsByRef)
1509 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001510
Akira Hatanaka7275da02018-02-28 07:15:55 +00001511 // Initialize the variable here if it doesn't have a initializer and it is a
1512 // C struct that is non-trivial to initialize or an array containing such a
1513 // struct.
1514 if (!Init &&
1515 type.isNonTrivialToPrimitiveDefaultInitialize() ==
1516 QualType::PDIK_Struct) {
1517 LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
1518 if (emission.IsByRef)
1519 drillIntoBlockVariable(*this, Dst, &D);
1520 defaultInitNonTrivialCStructVar(Dst);
1521 return;
1522 }
1523
Douglas Gregor82e1af22011-07-01 21:08:19 +00001524 if (isTrivialInitializer(Init))
1525 return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001526
John McCallc533cb72011-02-22 06:44:22 +00001527 // Check whether this is a byref variable that's potentially
1528 // captured and moved by its own initializer. If so, we'll need to
1529 // emit the initializer first, then copy into the variable.
1530 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1531
John McCall7f416cc2015-09-08 08:05:57 +00001532 Address Loc =
1533 capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
John McCallc533cb72011-02-22 06:44:22 +00001534
Craig Topper8a13c412014-05-21 05:09:00 +00001535 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001536 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001537 assert(!capturedByInit && "constant init contains a capturing block?");
John McCallde0fe072017-08-15 21:42:52 +00001538 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
Richard Smithfddd3842011-12-30 21:15:51 +00001539 }
1540
1541 if (!constant) {
John McCall7f416cc2015-09-08 08:05:57 +00001542 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001543 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001544 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001545 }
John McCall91ca10f2011-03-08 09:11:50 +00001546
Richard Smith2bcde3a2013-06-02 00:09:52 +00001547 if (!emission.IsConstantAggregate) {
1548 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001549 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001550 lv.setNonGC(true);
1551 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1552 }
1553
John McCallc533cb72011-02-22 06:44:22 +00001554 // If this is a simple aggregate initialization, we can optimize it
1555 // in various ways.
John McCall91ca10f2011-03-08 09:11:50 +00001556 bool isVolatile = type.isVolatileQualified();
John McCallc533cb72011-02-22 06:44:22 +00001557
Yaxun Liudaceb1e2018-05-14 19:20:12 +00001558 llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
John McCall7f416cc2015-09-08 08:05:57 +00001559 if (Loc.getType() != BP)
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001560 Loc = Builder.CreateBitCast(Loc, BP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001561
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001562 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
John McCall91ca10f2011-03-08 09:11:50 +00001563}
1564
Richard Smithe78fac52018-04-05 20:52:58 +00001565/// Emit an expression as an initializer for an object (variable, field, etc.)
1566/// at the given location. The expression is not necessarily the normal
1567/// initializer for the object, and the address is not necessarily
John McCall91ca10f2011-03-08 09:11:50 +00001568/// its normal location.
1569///
1570/// \param init the initializing expression
Richard Smithe78fac52018-04-05 20:52:58 +00001571/// \param D the object to act as if we're initializing
John McCall91ca10f2011-03-08 09:11:50 +00001572/// \param loc the address to initialize; its type is a pointer
Richard Smithe78fac52018-04-05 20:52:58 +00001573/// to the LLVM mapping of the object's type
John McCall91ca10f2011-03-08 09:11:50 +00001574/// \param alignment the alignment of the address
Richard Smithe78fac52018-04-05 20:52:58 +00001575/// \param capturedByInit true if \p D is a __block variable
John McCall91ca10f2011-03-08 09:11:50 +00001576/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001577void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001578 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001579 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001580
1581 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001582 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001583 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001584 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001585 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001586 return;
1587 }
1588 switch (getEvaluationKind(type)) {
1589 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001590 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001591 return;
1592 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001593 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001594 if (capturedByInit)
1595 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001596 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001597 return;
1598 }
1599 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001600 if (type->isAtomicType()) {
1601 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1602 } else {
Richard Smithe78fac52018-04-05 20:52:58 +00001603 AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
1604 if (isa<VarDecl>(D))
1605 Overlap = AggValueSlot::DoesNotOverlap;
1606 else if (auto *FD = dyn_cast<FieldDecl>(D))
1607 Overlap = overlapForFieldInit(FD);
John McCalla8ec7eb2013-03-07 21:37:17 +00001608 // TODO: how can we delay here if D is captured by its initializer?
1609 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001610 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001611 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001612 AggValueSlot::IsNotAliased,
1613 Overlap));
John McCalla8ec7eb2013-03-07 21:37:17 +00001614 }
John McCall47fb9502013-03-07 21:37:08 +00001615 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001616 }
John McCall47fb9502013-03-07 21:37:08 +00001617 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001618}
John McCallbd309292010-07-06 01:34:17 +00001619
John McCall82fe67b2011-07-09 01:37:26 +00001620/// Enter a destroy cleanup for the given local variable.
1621void CodeGenFunction::emitAutoVarTypeCleanup(
1622 const CodeGenFunction::AutoVarEmission &emission,
1623 QualType::DestructionKind dtorKind) {
1624 assert(dtorKind != QualType::DK_none);
1625
1626 // Note that for __block variables, we want to destroy the
1627 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001628 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001629
1630 const VarDecl *var = emission.Variable;
1631 QualType type = var->getType();
1632
1633 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001634 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001635
1636 switch (dtorKind) {
1637 case QualType::DK_none:
1638 llvm_unreachable("no cleanup for trivially-destructible variable");
1639
1640 case QualType::DK_cxx_destructor:
1641 // If there's an NRVO flag on the emission, we need a different
1642 // cleanup.
1643 if (emission.NRVOFlag) {
1644 assert(!type->isArrayType());
1645 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001646 EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, dtor,
1647 emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001648 return;
1649 }
1650 break;
1651
1652 case QualType::DK_objc_strong_lifetime:
1653 // Suppress cleanups for pseudo-strong variables.
1654 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001655
John McCall82fe67b2011-07-09 01:37:26 +00001656 // Otherwise, consider whether to use an EH cleanup or not.
1657 cleanupKind = getARCCleanupKind();
1658
1659 // Use the imprecise destroyer by default.
1660 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1661 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1662 break;
1663
1664 case QualType::DK_objc_weak_lifetime:
1665 break;
Akira Hatanaka7275da02018-02-28 07:15:55 +00001666
1667 case QualType::DK_nontrivial_c_struct:
1668 destroyer = CodeGenFunction::destroyNonTrivialCStruct;
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001669 if (emission.NRVOFlag) {
1670 assert(!type->isArrayType());
1671 EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
1672 emission.NRVOFlag, type);
1673 return;
1674 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00001675 break;
John McCall82fe67b2011-07-09 01:37:26 +00001676 }
1677
1678 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001679 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001680
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001681 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001682 // is being pushed as an EH cleanup.
1683 bool useEHCleanup = (cleanupKind & EHCleanup);
1684 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1685 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001686}
1687
John McCallc533cb72011-02-22 06:44:22 +00001688void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001689 assert(emission.Variable && "emission was not valid!");
1690
John McCallc533cb72011-02-22 06:44:22 +00001691 // If this was emitted as a global constant, we're done.
1692 if (emission.wasEmittedAsGlobal()) return;
1693
John McCall8c38d352012-04-13 18:44:05 +00001694 // If we don't have an insertion point, we're done. Sema prevents
1695 // us from jumping into any of these scopes anyway.
1696 if (!HaveInsertPoint()) return;
1697
John McCall9e2e22f2011-02-22 07:16:58 +00001698 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001699
John McCall82fe67b2011-07-09 01:37:26 +00001700 // Check the type for a cleanup.
1701 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1702 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001703
John McCall1bd25562011-06-24 23:21:27 +00001704 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001705 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001706 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1707 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1708 }
1709
John McCallc533cb72011-02-22 06:44:22 +00001710 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001711 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001712 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001713
John McCallc533cb72011-02-22 06:44:22 +00001714 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001715 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001716
John McCalla729c622012-02-17 03:33:10 +00001717 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001718 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001719 }
Mike Stump626aecc2009-03-05 01:23:13 +00001720
John McCallc533cb72011-02-22 06:44:22 +00001721 // If this is a block variable, call _Block_object_destroy
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001722 // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
1723 // mode.
1724 if (emission.IsByRef && CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
1725 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
1726 if (emission.Variable->getType().isObjCGCWeak())
1727 Flags |= BLOCK_FIELD_IS_WEAK;
1728 enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
1729 /*LoadBlockVarAddr*/ false);
1730 }
Chris Lattner03df1222007-06-02 04:53:11 +00001731}
Chris Lattner53621a52007-06-13 20:44:40 +00001732
Peter Collingbourne1425b452012-01-26 03:33:36 +00001733CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001734CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1735 switch (kind) {
1736 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00001737 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001738 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00001739 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001740 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00001741 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00001742 return destroyARCWeak;
Akira Hatanaka7275da02018-02-28 07:15:55 +00001743 case QualType::DK_nontrivial_c_struct:
1744 return destroyNonTrivialCStruct;
John McCall82fe67b2011-07-09 01:37:26 +00001745 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00001746 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00001747}
1748
John McCall12cc42a2013-02-01 05:11:40 +00001749/// pushEHDestroy - Push the standard destructor for the given type as
1750/// an EH-only cleanup.
1751void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001752 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00001753 assert(dtorKind && "cannot push destructor for trivial type");
1754 assert(needsEHCleanup(dtorKind));
1755
1756 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1757}
1758
1759/// pushDestroy - Push the standard destructor for the given type as
1760/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00001761void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00001762 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00001763 assert(dtorKind && "cannot push destructor for trivial type");
1764
1765 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1766 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1767 cleanupKind & EHCleanup);
1768}
1769
John McCall7f416cc2015-09-08 08:05:57 +00001770void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001771 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001772 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00001773 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1774 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001775}
1776
John McCall7f416cc2015-09-08 08:05:57 +00001777void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001778 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1779}
1780
Richard Smith736a9472013-06-12 20:42:33 +00001781void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00001782 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00001783 Destroyer *destroyer, bool useEHCleanupForArray) {
Richard Smith736a9472013-06-12 20:42:33 +00001784 // Push an EH-only cleanup for the object now.
1785 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1786 // around in case a temporary's destructor throws an exception.
1787 if (cleanupKind & EHCleanup)
1788 EHStack.pushCleanup<DestroyObject>(
1789 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1790 destroyer, useEHCleanupForArray);
1791
1792 // Remember that we need to push a full cleanup for the object at the
1793 // end of the full-expression.
1794 pushCleanupAfterFullExpr<DestroyObject>(
1795 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1796}
1797
John McCall178360e2011-07-11 08:38:19 +00001798/// emitDestroy - Immediately perform the destruction of the given
1799/// object.
1800///
1801/// \param addr - the address of the object; a type*
1802/// \param type - the type of the object; if an array type, all
1803/// objects are destroyed in reverse order
1804/// \param destroyer - the function to call to destroy individual
1805/// elements
1806/// \param useEHCleanupForArray - whether an EH cleanup should be
1807/// used when destroying array elements, in case one of the
1808/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00001809void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001810 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00001811 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00001812 const ArrayType *arrayType = getContext().getAsArrayType(type);
1813 if (!arrayType)
1814 return destroyer(*this, addr, type);
1815
John McCall7f416cc2015-09-08 08:05:57 +00001816 llvm::Value *length = emitArrayLength(arrayType, type, addr);
1817
1818 CharUnits elementAlign =
1819 addr.getAlignment()
1820 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00001821
1822 // Normally we have to check whether the array is zero-length.
1823 bool checkZeroLength = true;
1824
1825 // But if the array length is constant, we can suppress that.
1826 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1827 // ...and if it's constant zero, we can just skip the entire thing.
1828 if (constLength->isZero()) return;
1829 checkZeroLength = false;
1830 }
1831
John McCall7f416cc2015-09-08 08:05:57 +00001832 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00001833 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00001834 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001835 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00001836}
1837
John McCall178360e2011-07-11 08:38:19 +00001838/// emitArrayDestroy - Destroys all the elements of the given array,
1839/// beginning from last to first. The array cannot be zero-length.
1840///
1841/// \param begin - a type* denoting the first element of the array
1842/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00001843/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00001844/// \param destroyer - the function to call to destroy elements
1845/// \param useEHCleanup - whether to push an EH cleanup to destroy
1846/// the remaining elements in case the destruction of a single
1847/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00001848void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1849 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001850 QualType elementType,
1851 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001852 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001853 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00001854 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00001855 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00001856
1857 // The basic structure here is a do-while loop, because we don't
1858 // need to check for the zero-element case.
1859 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1860 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1861
John McCall97eab0a2011-07-13 08:09:46 +00001862 if (checkZeroLength) {
1863 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1864 "arraydestroy.isempty");
1865 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1866 }
1867
John McCall82fe67b2011-07-09 01:37:26 +00001868 // Enter the loop body, making that address the current address.
1869 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1870 EmitBlock(bodyBB);
1871 llvm::PHINode *elementPast =
1872 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1873 elementPast->addIncoming(end, entryBB);
1874
1875 // Shift the address back by one element.
1876 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1877 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1878 "arraydestroy.element");
1879
John McCall178360e2011-07-11 08:38:19 +00001880 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00001881 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1882 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001883
John McCall82fe67b2011-07-09 01:37:26 +00001884 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00001885 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00001886
John McCall178360e2011-07-11 08:38:19 +00001887 if (useEHCleanup)
1888 PopCleanupBlock();
1889
John McCall82fe67b2011-07-09 01:37:26 +00001890 // Check whether we've reached the end.
1891 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1892 Builder.CreateCondBr(done, doneBB, bodyBB);
1893 elementPast->addIncoming(element, Builder.GetInsertBlock());
1894
1895 // Done.
1896 EmitBlock(doneBB);
1897}
1898
John McCall178360e2011-07-11 08:38:19 +00001899/// Perform partial array destruction as if in an EH cleanup. Unlike
1900/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00001901static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1902 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00001903 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001904 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00001905 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00001906 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00001907 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1908 // VLAs don't require a GEP index to walk into.
1909 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00001910 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00001911 type = arrayType->getElementType();
1912 }
John McCall97eab0a2011-07-13 08:09:46 +00001913
1914 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00001915 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00001916
John McCallf0f0b7a2015-09-14 18:57:08 +00001917 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00001918 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1919 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00001920 }
1921
John McCall97eab0a2011-07-13 08:09:46 +00001922 // Destroy the array. We don't ever need an EH cleanup because we
1923 // assume that we're in an EH cleanup ourselves, so a throwing
1924 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00001925 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00001926 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00001927}
1928
John McCall82fe67b2011-07-09 01:37:26 +00001929namespace {
John McCall178360e2011-07-11 08:38:19 +00001930 /// RegularPartialArrayDestroy - a cleanup which performs a partial
1931 /// array destroy where the end pointer is regularly determined and
1932 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001933 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00001934 llvm::Value *ArrayBegin;
1935 llvm::Value *ArrayEnd;
1936 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001937 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001938 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00001939 public:
1940 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001941 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001942 CodeGenFunction::Destroyer *destroyer)
1943 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00001944 ElementType(elementType), Destroyer(destroyer),
1945 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00001946
Craig Topper4f12f102014-03-12 06:41:41 +00001947 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00001948 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001949 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00001950 }
1951 };
1952
1953 /// IrregularPartialArrayDestroy - a cleanup which performs a
1954 /// partial array destroy where the end pointer is irregularly
1955 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00001956 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00001957 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00001958 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00001959 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001960 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00001961 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00001962 public:
John McCall178360e2011-07-11 08:38:19 +00001963 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001964 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001965 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001966 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00001967 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00001968 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00001969 ElementType(elementType), Destroyer(destroyer),
1970 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00001971
Craig Topper4f12f102014-03-12 06:41:41 +00001972 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00001973 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00001974 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00001975 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00001976 }
1977 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001978} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00001979
John McCall178360e2011-07-11 08:38:19 +00001980/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00001981/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00001982/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00001983///
John McCall82fe67b2011-07-09 01:37:26 +00001984/// \param elementType - the immediate element type of the array;
1985/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00001986void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00001987 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00001988 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00001989 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00001990 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00001991 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1992 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00001993 elementType, elementAlign,
1994 destroyer);
John McCall178360e2011-07-11 08:38:19 +00001995}
1996
1997/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1998/// already-constructed elements of the given array. The cleanup
1999/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00002000///
John McCall178360e2011-07-11 08:38:19 +00002001/// \param elementType - the immediate element type of the array;
2002/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00002003void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2004 llvm::Value *arrayEnd,
2005 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00002006 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002007 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00002008 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00002009 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002010 elementType, elementAlign,
2011 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00002012}
2013
Nadav Rotem1da30942013-03-23 06:43:35 +00002014/// Lazily declare the @llvm.lifetime.start intrinsic.
2015llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00002016 if (LifetimeStartFn)
2017 return LifetimeStartFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00002018 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00002019 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00002020 return LifetimeStartFn;
2021}
2022
2023/// Lazily declare the @llvm.lifetime.end intrinsic.
2024llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00002025 if (LifetimeEndFn)
2026 return LifetimeEndFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00002027 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00002028 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00002029 return LifetimeEndFn;
2030}
2031
John McCall31168b02011-06-15 23:02:42 +00002032namespace {
2033 /// A cleanup to perform a release of an object at the end of a
2034 /// function. This is used to balance out the incoming +1 of a
2035 /// ns_consumed argument when we can't reasonably do that just by
2036 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00002037 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00002038 ConsumeARCParameter(llvm::Value *param,
2039 ARCPreciseLifetime_t precise)
2040 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00002041
2042 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00002043 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00002044
Craig Topper4f12f102014-03-12 06:41:41 +00002045 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00002046 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00002047 }
2048 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002049} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00002050
Mike Stump11289f42009-09-09 15:08:12 +00002051/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00002052/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00002053void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2054 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00002055 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00002056 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00002057 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00002058
John McCall7f416cc2015-09-08 08:05:57 +00002059 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00002060
Adrian Prantl51936dd2013-03-14 17:53:33 +00002061 QualType Ty = D.getType();
2062
John McCall147d0212011-02-22 22:38:33 +00002063 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00002064 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00002065 // The only implicit argument a block has is its literal.
Saleem Abdulrasoolc1b46382018-02-21 21:47:51 +00002066 // This may be passed as an inalloca'ed value on Windows x86.
John McCall147d0212011-02-22 22:38:33 +00002067 if (BlockInfo) {
Saleem Abdulrasoolc1b46382018-02-21 21:47:51 +00002068 llvm::Value *V = Arg.isIndirect()
2069 ? Builder.CreateLoad(Arg.getIndirectAddress())
2070 : Arg.getDirectValue();
2071 setBlockContextParameter(IPD, ArgNo, V);
John McCall147d0212011-02-22 22:38:33 +00002072 return;
2073 }
2074 }
2075
John McCall7f416cc2015-09-08 08:05:57 +00002076 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002077 bool DoStore = false;
2078 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002079 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002080 if (Arg.isIndirect()) {
2081 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00002082 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00002083 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00002084 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00002085 if (DeclPtr.getType() != IRTy)
2086 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
Yaxun Liu5b330e82018-03-15 15:25:19 +00002087 // Indirect argument is in alloca address space, which may be different
2088 // from the default address space.
2089 auto AllocaAS = CGM.getASTAllocaAddressSpace();
2090 auto *V = DeclPtr.getPointer();
2091 auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2092 auto DestLangAS =
2093 getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
2094 if (SrcLangAS != DestLangAS) {
2095 assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2096 CGM.getDataLayout().getAllocaAddrSpace());
2097 auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2098 auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
2099 DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
2100 *this, V, SrcLangAS, DestLangAS, T, true),
2101 DeclPtr.getAlignment());
2102 }
John McCall7f416cc2015-09-08 08:05:57 +00002103
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002104 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00002105 // Don't push a cleanup in a thunk for a method that will also emit a
2106 // cleanup.
Akira Hatanaka85282972018-05-15 21:00:30 +00002107 if (hasAggregateEvaluationKind(Ty) && !CurFuncIsThunk &&
2108 Ty->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
Akira Hatanaka7275da02018-02-28 07:15:55 +00002109 if (QualType::DestructionKind DtorKind = Ty.isDestructedType()) {
2110 assert((DtorKind == QualType::DK_cxx_destructor ||
2111 DtorKind == QualType::DK_nontrivial_c_struct) &&
2112 "unexpected destructor type");
2113 pushDestroy(DtorKind, DeclPtr, Ty);
Akira Hatanakaccda3d22018-04-27 06:57:00 +00002114 CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2115 EHStack.stable_begin();
Akira Hatanaka7275da02018-02-28 07:15:55 +00002116 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002117 }
Chris Lattner53621a52007-06-13 20:44:40 +00002118 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002119 // Check if the parameter address is controlled by OpenMP runtime.
2120 Address OpenMPLocalAddr =
2121 getLangOpts().OpenMP
2122 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
2123 : Address::invalid();
2124 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2125 DeclPtr = OpenMPLocalAddr;
2126 } else {
2127 // Otherwise, create a temporary to hold the value.
2128 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2129 D.getName() + ".addr");
2130 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002131 DoStore = true;
2132 }
Mike Stump11289f42009-09-09 15:08:12 +00002133
John McCall7f416cc2015-09-08 08:05:57 +00002134 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2135
2136 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002137 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00002138 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00002139 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2140 // We honor __attribute__((ns_consumed)) for types with lifetime.
2141 // For __strong, it's handled by just skipping the initial retain;
2142 // otherwise we have to balance out the initial +1 with an extra
2143 // cleanup to do the release at the end of the function.
2144 bool isConsumed = D.hasAttr<NSConsumedAttr>();
2145
2146 // 'self' is always formally __strong, but if this is not an
2147 // init method then we don't want to retain it.
John McCalld4631322011-06-17 06:42:21 +00002148 if (D.isARCPseudoStrong()) {
John McCall31168b02011-06-15 23:02:42 +00002149 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
2150 assert(&D == method->getSelfDecl());
John McCalld4631322011-06-17 06:42:21 +00002151 assert(lt == Qualifiers::OCL_Strong);
2152 assert(qs.hasConst());
John McCall31168b02011-06-15 23:02:42 +00002153 assert(method->getMethodFamily() != OMF_init);
John McCall10123692011-06-15 23:40:09 +00002154 (void) method;
John McCall31168b02011-06-15 23:02:42 +00002155 lt = Qualifiers::OCL_ExplicitNone;
2156 }
2157
Saleem Abdulrasoolda6784e2017-06-27 18:37:51 +00002158 // Load objects passed indirectly.
2159 if (Arg.isIndirect() && !ArgVal)
2160 ArgVal = Builder.CreateLoad(DeclPtr);
2161
John McCall31168b02011-06-15 23:02:42 +00002162 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002163 if (!isConsumed) {
2164 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2165 // use objc_storeStrong(&dest, value) for retaining the
2166 // object. But first, store a null into 'dest' because
2167 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002168 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002169 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
John McCall7f416cc2015-09-08 08:05:57 +00002170 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002171 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002172 }
2173 else
John McCall31168b02011-06-15 23:02:42 +00002174 // Don't use objc_retainBlock for block pointers, because we
2175 // don't want to Block_copy something just because we got it
2176 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00002177 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002178 }
John McCall31168b02011-06-15 23:02:42 +00002179 } else {
2180 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00002181 if (isConsumed) {
2182 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2183 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00002184 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00002185 precise);
2186 }
John McCall31168b02011-06-15 23:02:42 +00002187
2188 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00002189 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002190 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00002191 }
2192 }
2193
2194 // Enter the cleanup scope.
2195 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2196 }
Chris Lattner53621a52007-06-13 20:44:40 +00002197 }
2198
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002199 // Store the initial value into the alloca.
2200 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00002201 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002202
John McCall7f416cc2015-09-08 08:05:57 +00002203 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00002204
2205 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00002206 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002207 if (CGM.getCodeGenOpts().getDebugInfo() >=
2208 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002209 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00002210 }
2211 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002212
2213 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002214 EmitVarAnnotations(&D, DeclPtr.getPointer());
Vedant Kumar42c17ec2017-03-14 01:56:34 +00002215
2216 // We can only check return value nullability if all arguments to the
2217 // function satisfy their nullability preconditions. This makes it necessary
2218 // to emit null checks for args in the function body itself.
2219 if (requiresReturnValueNullabilityCheck()) {
2220 auto Nullability = Ty->getNullability(getContext());
2221 if (Nullability && *Nullability == NullabilityKind::NonNull) {
2222 SanitizerScope SanScope(this);
2223 RetValNullabilityPrecondition =
2224 Builder.CreateAnd(RetValNullabilityPrecondition,
2225 Builder.CreateIsNotNull(Arg.getAnyValue()));
2226 }
2227 }
Chris Lattner53621a52007-06-13 20:44:40 +00002228}
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002229
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002230void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2231 CodeGenFunction *CGF) {
2232 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2233 return;
2234 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2235}