blob: db18ac49c6ecc87325fca3e354c58bdbe0e5add1 [file] [log] [blame]
Chris Lattner84915fa2007-06-02 04:16:21 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner84915fa2007-06-02 04:16:21 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Decl nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
John McCall7f416cc2015-09-08 08:05:57 +000013#include "CGBlocks.h"
Reid Klecknere5a321b2016-09-07 18:21:30 +000014#include "CGCXXABI.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000015#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CGDebugInfo.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000017#include "CGOpenCLRuntime.h"
Alexey Bataevc5b1d322016-03-04 09:22:22 +000018#include "CGOpenMPRuntime.h"
Yaxun Liu6d96f1632017-05-18 18:51:09 +000019#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000021#include "ConstantEmitter.h"
JF Bastienef202c32019-04-12 00:11:27 +000022#include "PatternInit.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"
Richard Trieu63688182018-12-11 03:18:39 +000029#include "clang/Basic/CodeGenOptions.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000030#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000031#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000032#include "clang/CodeGen/CGFunctionInfo.h"
JF Bastien2f0582f2018-09-21 13:54:09 +000033#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000034#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/GlobalVariable.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Type.h"
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +000038
Chris Lattner84915fa2007-06-02 04:16:21 +000039using namespace clang;
40using namespace CodeGen;
41
Chris Lattner1ad38f82007-06-09 01:20:56 +000042void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000043 switch (D.getKind()) {
David Majnemerd9b1a4f2015-11-04 03:40:30 +000044 case Decl::BuiltinTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000045 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +000046 case Decl::ExternCContext:
Douglas Gregor19043f02010-04-23 02:02:43 +000047 case Decl::Namespace:
48 case Decl::UnresolvedUsingTypename:
49 case Decl::ClassTemplateSpecialization:
50 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000051 case Decl::VarTemplateSpecialization:
52 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000053 case Decl::TemplateTypeParm:
54 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000055 case Decl::NonTypeTemplateParm:
Richard Smithbc491202017-02-17 20:05:37 +000056 case Decl::CXXDeductionGuide:
Douglas Gregor19043f02010-04-23 02:02:43 +000057 case Decl::CXXMethod:
58 case Decl::CXXConstructor:
59 case Decl::CXXDestructor:
60 case Decl::CXXConversion:
61 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000062 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000063 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000064 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000065 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000066 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000067 case Decl::ImplicitParam:
68 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000069 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000070 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000071 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000072 case Decl::TemplateTemplateParm:
73 case Decl::ObjCMethod:
74 case Decl::ObjCCategory:
75 case Decl::ObjCProtocol:
76 case Decl::ObjCInterface:
77 case Decl::ObjCCategoryImpl:
78 case Decl::ObjCImplementation:
79 case Decl::ObjCProperty:
80 case Decl::ObjCCompatibleAlias:
Nico Weber66220292016-03-02 17:28:48 +000081 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +000082 case Decl::PragmaDetectMismatch:
Abramo Bagnarad7340582010-06-05 05:09:32 +000083 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000084 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +000085 case Decl::Export:
Douglas Gregor19043f02010-04-23 02:02:43 +000086 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000087 case Decl::FileScopeAsm:
88 case Decl::Friend:
89 case Decl::FriendTemplate:
90 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000091 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000092 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000093 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +000094 case Decl::ConstructorUsingShadow:
Douglas Gregor85f3f952015-07-07 03:57:15 +000095 case Decl::ObjCTypeParam:
Richard Smithda383632016-08-15 01:33:41 +000096 case Decl::Binding:
David Blaikie83d382b2011-09-23 05:06:16 +000097 llvm_unreachable("Declaration should not be in declstmts!");
Amjad Abouddc4531e2016-04-30 01:44:38 +000098 case Decl::Function: // void X();
99 case Decl::Record: // struct/union/class X;
100 case Decl::Enum: // enum X;
101 case Decl::EnumConstant: // enum ? { X = ? }
102 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +0000103 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +0000104 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +0000105 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000106 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000107 case Decl::OMPAllocate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000108 case Decl::OMPCapturedExpr:
Kelvin Li1408f912018-09-26 04:28:39 +0000109 case Decl::OMPRequires:
Michael Han84324352013-02-22 17:15:32 +0000110 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +0000111 // None of these decls require codegen support.
112 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +0000113
David Blaikief121b932013-05-20 22:50:41 +0000114 case Decl::NamespaceAlias:
115 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000116 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
David Blaikief121b932013-05-20 22:50:41 +0000117 return;
David Blaikiebd483762013-05-20 04:58:53 +0000118 case Decl::Using: // using X; [C++]
119 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000120 DI->EmitUsingDecl(cast<UsingDecl>(D));
David Blaikiebd483762013-05-20 04:58:53 +0000121 return;
Richard Smith151c4562016-12-20 21:35:28 +0000122 case Decl::UsingPack:
123 for (auto *Using : cast<UsingPackDecl>(D).expansions())
124 EmitDecl(*Using);
125 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000126 case Decl::UsingDirective: // using namespace X; [C++]
127 if (CGDebugInfo *DI = getDebugInfo())
128 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
129 return;
Richard Smithbdb84f32016-07-22 23:36:59 +0000130 case Decl::Var:
131 case Decl::Decomposition: {
Daniel Dunbara7998072008-08-29 17:28:43 +0000132 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000133 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000134 "Should not see file-scope variables inside a function!");
Richard Smithda383632016-08-15 01:33:41 +0000135 EmitVarDecl(VD);
136 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
137 for (auto *B : DD->bindings())
138 if (auto *HD = B->getHoldingVar())
139 EmitVarDecl(*HD);
140 return;
Chris Lattner84915fa2007-06-02 04:16:21 +0000141 }
Mike Stump11289f42009-09-09 15:08:12 +0000142
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000143 case Decl::OMPDeclareReduction:
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000144 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000145
Michael Kruse251e1482019-02-01 20:25:04 +0000146 case Decl::OMPDeclareMapper:
147 return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
148
Richard Smithdda56e42011-04-15 14:24:37 +0000149 case Decl::Typedef: // typedef int X;
150 case Decl::TypeAlias: { // using X = int; [C++0x]
151 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000152 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000153
Anders Carlsson5d985f52008-12-20 21:51:53 +0000154 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000155 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000156 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000157 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000158}
Chris Lattner03df1222007-06-02 04:53:11 +0000159
John McCall1c9c3fd2010-10-15 04:57:14 +0000160/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000161/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000162void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Yaxun Liu4f33b3d2017-05-15 14:47:47 +0000163 if (D.hasExternalStorage())
164 // Don't emit it now, allow it to be emitted lazily on its first use.
165 return;
166
167 // Some function-scope variable does not have static storage but still
168 // needs to be emitted like a static variable, e.g. a function-scope
169 // variable in constant address space in OpenCL.
170 if (D.getStorageDuration() != SD_Automatic) {
Alexey Baderbed40092017-11-15 11:38:17 +0000171 // Static sampler variables translated to function calls.
172 if (D.getType()->isSamplerT())
173 return;
174
Eric Christopher31ab1302011-08-23 22:38:00 +0000175 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000176 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000177
David Majnemer27d69db2014-04-28 22:17:59 +0000178 // FIXME: We need to force the emission/use of a guard variable for
179 // some variables even if we can constant-evaluate them because
180 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000181
John McCall1c9c3fd2010-10-15 04:57:14 +0000182 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000183 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000184
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000185 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000186 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
187
188 assert(D.hasLocalStorage());
189 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000190}
191
Reid Kleckner453e0562014-10-08 01:07:54 +0000192static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
193 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000194 return CGM.getMangledName(&D).str();
195
Reid Kleckner453e0562014-10-08 01:07:54 +0000196 // If this isn't C++, we don't need a mangled name, just a pretty one.
197 assert(!D.isExternallyVisible() && "name shouldn't matter");
198 std::string ContextName;
199 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000200 if (auto *CD = dyn_cast<CapturedDecl>(DC))
201 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000202 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000203 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000204 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
205 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
206 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
207 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000208 else
David Blaikie83d382b2011-09-23 05:06:16 +0000209 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000210
Reid Kleckner453e0562014-10-08 01:07:54 +0000211 ContextName += "." + D.getNameAsString();
212 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000213}
214
Reid Kleckner453e0562014-10-08 01:07:54 +0000215llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
216 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
217 // In general, we don't always emit static var decls once before we reference
218 // them. It is possible to reference them before emitting the function that
219 // contains them, and it is possible to emit the containing function multiple
220 // times.
221 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
222 return ExistingGV;
223
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000224 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000225 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000226
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000227 // Use the label if the variable is renamed with the asm-label extension.
228 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000229 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000230 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000231 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000232 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000233
Reid Kleckner453e0562014-10-08 01:07:54 +0000234 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Alexander Richardson6d989432017-10-15 18:48:14 +0000235 LangAS AS = GetGlobalVarAddressSpace(&D);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000236 unsigned TargetAS = getContext().getTargetAddressSpace(AS);
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000237
Yaxun Liua64a4912018-04-02 17:38:24 +0000238 // OpenCL variables in local address space and CUDA shared
239 // variables cannot have an initializer.
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000240 llvm::Constant *Init = nullptr;
Yaxun Liua64a4912018-04-02 17:38:24 +0000241 if (Ty.getAddressSpace() == LangAS::opencl_local ||
242 D.hasAttr<CUDASharedAttr>())
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000243 Init = llvm::UndefValue::get(LTy);
Yaxun Liua64a4912018-04-02 17:38:24 +0000244 else
245 Init = EmitNullConstant(Ty);
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000246
Yaxun Liucbf647c2017-07-08 13:24:52 +0000247 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
248 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
249 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
Ken Dyck160146e2010-01-27 17:10:57 +0000250 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000251
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000252 if (supportsCOMDAT() && GV->isWeakForLinker())
253 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000254
Richard Smithfd3834f2013-04-13 02:43:54 +0000255 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000256 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000257
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000258 setGVProperties(GV, &D);
259
Eli Benderskycb399432014-03-24 22:05:38 +0000260 // Make sure the result is of the correct type.
Alexander Richardson6d989432017-10-15 18:48:14 +0000261 LangAS ExpectedAS = Ty.getAddressSpace();
Reid Kleckner453e0562014-10-08 01:07:54 +0000262 llvm::Constant *Addr = GV;
Yaxun Liucbf647c2017-07-08 13:24:52 +0000263 if (AS != ExpectedAS) {
264 Addr = getTargetCodeGenInfo().performAddrSpaceCast(
265 *this, GV, AS, ExpectedAS,
266 LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
Eli Benderskycb399432014-03-24 22:05:38 +0000267 }
268
Reid Kleckner453e0562014-10-08 01:07:54 +0000269 setStaticLocalDeclAddress(&D, Addr);
270
271 // Ensure that the static local gets initialized by making sure the parent
272 // function gets emitted eventually.
273 const Decl *DC = cast<Decl>(D.getDeclContext());
274
275 // We can't name blocks or captured statements directly, so try to emit their
276 // parents.
277 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
278 DC = DC->getNonClosureContext();
279 // FIXME: Ensure that global blocks get emitted.
280 if (!DC)
281 return Addr;
282 }
283
284 GlobalDecl GD;
285 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
286 GD = GlobalDecl(CD, Ctor_Base);
287 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
288 GD = GlobalDecl(DD, Dtor_Base);
289 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
290 GD = GlobalDecl(FD);
291 else {
292 // Don't do anything for Obj-C method decls or global closures. We should
293 // never defer them.
294 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
295 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +0000296 if (GD.getDecl()) {
297 // Disable emission of the parent function for the OpenMP device codegen.
298 CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
Reid Kleckner453e0562014-10-08 01:07:54 +0000299 (void)GetAddrOfGlobal(GD);
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +0000300 }
Reid Kleckner453e0562014-10-08 01:07:54 +0000301
302 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000303}
304
Richard Smith6331c402012-02-13 22:16:19 +0000305/// hasNontrivialDestruction - Determine whether a type's destruction is
306/// non-trivial. If so, and the variable uses static initialization, we must
307/// register its destructor to run on exit.
308static bool hasNontrivialDestruction(QualType T) {
309 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
310 return RD && !RD->hasTrivialDestructor();
311}
312
Chandler Carruth84537952012-03-30 19:44:53 +0000313/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
314/// global variable that has already been created for it. If the initializer
315/// has a different type than GV does, this may free GV and return a different
316/// one. Otherwise it just returns GV.
317llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000318CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000319 llvm::GlobalVariable *GV) {
John McCallde0fe072017-08-15 21:42:52 +0000320 ConstantEmitter emitter(*this);
321 llvm::Constant *Init = emitter.tryEmitForInitializer(D);
John McCall70013b62010-07-15 23:40:35 +0000322
Chris Lattnere99c1102009-12-05 08:22:11 +0000323 // If constant emission failed, then this should be a C++ static
324 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000325 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000326 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000327 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
Matthias Braun44bfe032017-01-10 17:43:01 +0000328 else if (HaveInsertPoint()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000329 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000330 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000331 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000332
Chandler Carruth84537952012-03-30 19:44:53 +0000333 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000334 }
Chandler Carruth84537952012-03-30 19:44:53 +0000335 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000336 }
John McCall70013b62010-07-15 23:40:35 +0000337
Chris Lattnere99c1102009-12-05 08:22:11 +0000338 // The initializer may differ in type from the global. Rewrite
339 // the global to match the initializer. (We have to do this
340 // because some types, like unions, can't be completely represented
341 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000342 if (GV->getType()->getElementType() != Init->getType()) {
343 llvm::GlobalVariable *OldGV = GV;
344
345 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
346 OldGV->isConstant(),
347 OldGV->getLinkage(), Init, "",
348 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000349 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000350 CGM.getContext().getTargetAddressSpace(D.getType()));
351 GV->setVisibility(OldGV->getVisibility());
Rafael Espindola699f5d62018-02-07 22:15:33 +0000352 GV->setDSOLocal(OldGV->isDSOLocal());
Reid Klecknereab97d32015-07-20 20:35:30 +0000353 GV->setComdat(OldGV->getComdat());
Eric Christopher31ab1302011-08-23 22:38:00 +0000354
Chris Lattnere99c1102009-12-05 08:22:11 +0000355 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000356 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000357
Chris Lattnere99c1102009-12-05 08:22:11 +0000358 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000359 llvm::Constant *NewPtrForOldDecl =
360 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
361 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000362
Chris Lattnere99c1102009-12-05 08:22:11 +0000363 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000364 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000365 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000366
Chandler Carruth84537952012-03-30 19:44:53 +0000367 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
368 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000369
John McCallde0fe072017-08-15 21:42:52 +0000370 emitter.finalize(GV);
371
Matthias Braun44bfe032017-01-10 17:43:01 +0000372 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
Richard Smith6331c402012-02-13 22:16:19 +0000373 // We have a constant initializer, but a nontrivial destructor. We still
374 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000375 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000376 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000377 }
378
Chandler Carruth84537952012-03-30 19:44:53 +0000379 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000380}
381
John McCall1c9c3fd2010-10-15 04:57:14 +0000382void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000383 llvm::GlobalValue::LinkageTypes Linkage) {
John McCallb88a5662012-03-30 21:00:39 +0000384 // Check to see if we already have a global variable for this
385 // declaration. This can happen when double-emitting function
386 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000387 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
John McCall7f416cc2015-09-08 08:05:57 +0000388 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara374e602009-02-25 19:45:19 +0000389
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000390 // Store into LocalDeclMap before generating initializer to handle
391 // circular references.
John McCall7f416cc2015-09-08 08:05:57 +0000392 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000393
John McCall4a39ab82010-05-04 20:45:42 +0000394 // We can't have a VLA here, but we can have a pointer to a VLA,
395 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000396 // Make sure to evaluate VLA bounds now so that we have them for later.
397 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000398 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000399
John McCallb88a5662012-03-30 21:00:39 +0000400 // Save the type in case adding the initializer forces a type change.
401 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000402
Eli Benderskycb399432014-03-24 22:05:38 +0000403 llvm::GlobalVariable *var =
404 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Artem Belevich4d430ba2016-05-09 22:09:56 +0000405
406 // CUDA's local and local static __shared__ variables should not
407 // have any non-empty initializers. This is ensured by Sema.
408 // Whatever initializer such variable may have when it gets here is
409 // a no-op and should not be emitted.
410 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
411 D.hasAttr<CUDASharedAttr>();
Chris Lattnere99c1102009-12-05 08:22:11 +0000412 // If this value has an initializer, emit it.
Artem Belevich4d430ba2016-05-09 22:09:56 +0000413 if (D.getInit() && !isCudaSharedVar)
John McCallb88a5662012-03-30 21:00:39 +0000414 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000415
John McCall7f416cc2015-09-08 08:05:57 +0000416 var->setAlignment(alignment.getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000417
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000418 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000419 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000420
Javed Absar2a67c9e2017-06-05 10:11:57 +0000421 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
422 var->addAttribute("bss-section", SA->getName());
423 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
424 var->addAttribute("data-section", SA->getName());
425 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
426 var->addAttribute("rodata-section", SA->getName());
427
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000428 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000429 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000430
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000431 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000432 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000433
Chandler Carruth84537952012-03-30 19:44:53 +0000434 // We may have to cast the constant because of the initializer
435 // mismatch above.
436 //
437 // FIXME: It is really dangerous to store this in the map; if anyone
438 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000439 llvm::Constant *castedAddr =
440 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCall7f416cc2015-09-08 08:05:57 +0000441 if (var != castedAddr)
442 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCallb88a5662012-03-30 21:00:39 +0000443 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000444
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000445 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000446
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000447 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000448 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000449 if (DI &&
Benjamin Kramer8c305922016-02-02 11:06:51 +0000450 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000451 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000452 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000453 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000454}
Mike Stump11289f42009-09-09 15:08:12 +0000455
John McCall2b7fc382010-07-13 20:32:21 +0000456namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000457 struct DestroyObject final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000458 DestroyObject(Address addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000459 CodeGenFunction::Destroyer *destroyer,
460 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000461 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000462 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000463
John McCall7f416cc2015-09-08 08:05:57 +0000464 Address addr;
John McCall82fe67b2011-07-09 01:37:26 +0000465 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000466 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000467 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000468
Craig Topper4f12f102014-03-12 06:41:41 +0000469 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000470 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000471 bool useEHCleanupForArray =
472 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000473
474 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000475 }
476 };
477
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000478 template <class Derived>
479 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
480 DestroyNRVOVariable(Address addr, llvm::Value *NRVOFlag)
481 : NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000482
John McCall2b7fc382010-07-13 20:32:21 +0000483 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000484 Address Loc;
John McCall2b7fc382010-07-13 20:32:21 +0000485
Craig Topper4f12f102014-03-12 06:41:41 +0000486 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000487 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000488 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000489
Craig Topper8a13c412014-05-21 05:09:00 +0000490 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000491 if (NRVO) {
492 // If we exited via NRVO, we skip the destructor call.
493 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
494 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000495 llvm::Value *DidNRVO =
496 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000497 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
498 CGF.EmitBlock(RunDtorBB);
499 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000500
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000501 static_cast<Derived *>(this)->emitDestructorCall(CGF);
John McCall2b7fc382010-07-13 20:32:21 +0000502
503 if (NRVO) CGF.EmitBlock(SkipDtorBB);
504 }
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000505
506 virtual ~DestroyNRVOVariable() = default;
507 };
508
509 struct DestroyNRVOVariableCXX final
510 : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
511 DestroyNRVOVariableCXX(Address addr, const CXXDestructorDecl *Dtor,
512 llvm::Value *NRVOFlag)
513 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, NRVOFlag),
514 Dtor(Dtor) {}
515
516 const CXXDestructorDecl *Dtor;
517
518 void emitDestructorCall(CodeGenFunction &CGF) {
519 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
520 /*ForVirtualBase=*/false,
521 /*Delegating=*/false, Loc);
522 }
523 };
524
525 struct DestroyNRVOVariableC final
526 : DestroyNRVOVariable<DestroyNRVOVariableC> {
527 DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
528 : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, NRVOFlag), Ty(Ty) {}
529
530 QualType Ty;
531
532 void emitDestructorCall(CodeGenFunction &CGF) {
533 CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
534 }
John McCall2b7fc382010-07-13 20:32:21 +0000535 };
John McCall2b7fc382010-07-13 20:32:21 +0000536
David Blaikie7e70d682015-08-18 22:40:54 +0000537 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000538 Address Stack;
539 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000540 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000541 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
James Y Knight8799cae2019-02-03 21:53:49 +0000542 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
John McCalla464ff92010-07-21 06:13:08 +0000543 CGF.Builder.CreateCall(F, V);
544 }
545 };
546
David Blaikie7e70d682015-08-18 22:40:54 +0000547 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000548 const VarDecl &Var;
549 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
550
Craig Topper4f12f102014-03-12 06:41:41 +0000551 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000552 // Compute the address of the local variable, in case it's a
553 // byref or something.
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000554 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
John McCall113bee02012-03-10 09:33:50 +0000555 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000556 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
557 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000558 CGF.EmitExtendGCLifetime(value);
559 }
560 };
561
David Blaikie7e70d682015-08-18 22:40:54 +0000562 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000563 llvm::Constant *CleanupFn;
564 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000565 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000566
John McCalla464ff92010-07-21 06:13:08 +0000567 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000568 const VarDecl *Var)
569 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000570
Craig Topper4f12f102014-03-12 06:41:41 +0000571 void Emit(CodeGenFunction &CGF, Flags flags) override {
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000572 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
John McCall113bee02012-03-10 09:33:50 +0000573 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000574 // Compute the address of the local variable, in case it's a byref
575 // or something.
John McCall7f416cc2015-09-08 08:05:57 +0000576 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCallc533cb72011-02-22 06:44:22 +0000577
John McCalla464ff92010-07-21 06:13:08 +0000578 // In some cases, the type of the function argument will be different from
579 // the type of the pointer. An example of this is
580 // void f(void* arg);
581 // __attribute__((cleanup(f))) void *g;
582 //
583 // To fix this we insert a bitcast here.
584 QualType ArgTy = FnInfo.arg_begin()->type;
585 llvm::Value *Arg =
586 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
587
588 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000589 Args.add(RValue::get(Arg),
590 CGF.getContext().getPointerType(Var.getType()));
John McCallb92ab1a2016-10-26 23:46:34 +0000591 auto Callee = CGCallee::forDirect(CleanupFn);
592 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
John McCalla464ff92010-07-21 06:13:08 +0000593 }
594 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000595} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000596
John McCall31168b02011-06-15 23:02:42 +0000597/// EmitAutoVarWithLifetime - Does the setup required for an automatic
598/// variable with lifetime.
599static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000600 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000601 Qualifiers::ObjCLifetime lifetime) {
602 switch (lifetime) {
603 case Qualifiers::OCL_None:
604 llvm_unreachable("present but none");
605
606 case Qualifiers::OCL_ExplicitNone:
607 // nothing to do
608 break;
609
610 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000611 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000612 (var.hasAttr<ObjCPreciseLifetimeAttr>()
613 ? CodeGenFunction::destroyARCStrongPrecise
614 : CodeGenFunction::destroyARCStrongImprecise);
615
616 CleanupKind cleanupKind = CGF.getARCCleanupKind();
617 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
618 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000619 break;
620 }
621 case Qualifiers::OCL_Autoreleasing:
622 // nothing to do
623 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000624
John McCall31168b02011-06-15 23:02:42 +0000625 case Qualifiers::OCL_Weak:
626 // __weak objects always get EH cleanups; otherwise, exceptions
627 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000628 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
629 CodeGenFunction::destroyARCWeak,
630 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000631 break;
632 }
633}
634
635static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
636 if (const Expr *e = dyn_cast<Expr>(s)) {
637 // Skip the most common kinds of expressions that make
638 // hierarchy-walking expensive.
639 s = e = e->IgnoreParenCasts();
640
641 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
642 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000643 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
644 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000645 for (const auto &I : block->captures()) {
646 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000647 return true;
648 }
649 }
John McCall31168b02011-06-15 23:02:42 +0000650 }
651
Benjamin Kramer642f1732015-07-02 21:03:14 +0000652 for (const Stmt *SubStmt : s->children())
653 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
654 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000655 return true;
656
657 return false;
658}
659
660static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
661 if (!decl) return false;
662 if (!isa<VarDecl>(decl)) return false;
663 const VarDecl *var = cast<VarDecl>(decl);
664 return isAccessedBy(*var, e);
665}
666
John McCallf8a9b662015-10-21 18:06:31 +0000667static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
668 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000669 bool needsCast = false;
670
John McCallf8a9b662015-10-21 18:06:31 +0000671 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
672 switch (castExpr->getCastKind()) {
673 // Look through casts that don't require representation changes.
674 case CK_NoOp:
675 case CK_BitCast:
676 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000677 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000678 break;
679
680 // If we find an l-value to r-value cast from a __weak variable,
681 // emit this operation as a copy or move.
682 case CK_LValueToRValue: {
683 const Expr *srcExpr = castExpr->getSubExpr();
684 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
685 return false;
686
687 // Emit the source l-value.
688 LValue srcLV = CGF.EmitLValue(srcExpr);
689
John McCall0204e342015-11-16 22:11:41 +0000690 // Handle a formal type change to avoid asserting.
691 auto srcAddr = srcLV.getAddress();
692 if (needsCast) {
693 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
694 destLV.getAddress().getElementType());
695 }
696
John McCallf8a9b662015-10-21 18:06:31 +0000697 // If it was an l-value, use objc_copyWeak.
698 if (srcExpr->getValueKind() == VK_LValue) {
John McCall0204e342015-11-16 22:11:41 +0000699 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000700 } else {
701 assert(srcExpr->getValueKind() == VK_XValue);
John McCall0204e342015-11-16 22:11:41 +0000702 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000703 }
704 return true;
705 }
706
707 // Stop at anything else.
708 default:
709 return false;
710 }
711
712 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000713 }
714 return false;
715}
716
John McCall1553b192011-06-16 04:16:24 +0000717static void drillIntoBlockVariable(CodeGenFunction &CGF,
718 LValue &lvalue,
719 const VarDecl *var) {
John McCall7f416cc2015-09-08 08:05:57 +0000720 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCall1553b192011-06-16 04:16:24 +0000721}
722
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000723void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
724 SourceLocation Loc) {
725 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
726 return;
727
728 auto Nullability = LHS.getType()->getNullability(getContext());
729 if (!Nullability || *Nullability != NullabilityKind::NonNull)
730 return;
731
732 // Check if the right hand side of the assignment is nonnull, if the left
733 // hand side must be nonnull.
734 SanitizerScope SanScope(this);
735 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000736 llvm::Constant *StaticData[] = {
737 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
Simon Pilgrim2df19982017-03-14 21:43:52 +0000738 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
Vedant Kumar2b9f48a2017-03-14 16:48:29 +0000739 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000740 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
741 SanitizerHandler::TypeMismatch, StaticData, RHS);
742}
743
David Blaikie73ca5692014-12-09 00:32:22 +0000744void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000745 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000746 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000747 if (!lifetime) {
748 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000749 if (capturedByInit)
750 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000751 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
David Blaikie66e41972015-01-14 07:38:27 +0000752 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000753 return;
754 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000755
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000756 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
757 init = DIE->getExpr();
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000758
John McCall31168b02011-06-15 23:02:42 +0000759 // If we're emitting a value with lifetime, we have to do the
760 // initialization *before* we leave the cleanup scopes.
Bill Wendling7c44da22018-10-31 03:48:47 +0000761 if (const FullExpr *fe = dyn_cast<FullExpr>(init)) {
762 enterFullExpression(fe);
763 init = fe->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000764 }
765 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000766
767 // We have to maintain the illusion that the variable is
768 // zero-initialized. If the variable might be accessed in its
769 // initializer, zero-initialize before running the initializer, then
770 // actually perform the initialization with an assign.
771 bool accessedByInit = false;
772 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000773 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000774 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000775 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000776 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000777 if (capturedByInit) {
778 // We can use a simple GEP for this because it can't have been
779 // moved yet.
John McCall7f416cc2015-09-08 08:05:57 +0000780 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
781 cast<VarDecl>(D),
782 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000783 }
784
John McCall7f416cc2015-09-08 08:05:57 +0000785 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
Yaxun Liu402804b2016-12-15 08:09:08 +0000786 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000787
John McCall31168b02011-06-15 23:02:42 +0000788 // If __weak, we want to use a barrier under certain conditions.
789 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000790 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000791
792 // Otherwise just do a simple store.
793 else
David Chisnallfa35df62012-01-16 17:27:18 +0000794 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000795 }
796
797 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000798 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000799
800 switch (lifetime) {
801 case Qualifiers::OCL_None:
802 llvm_unreachable("present but none");
803
Erik Pilkington1e368822019-01-04 18:33:06 +0000804 case Qualifiers::OCL_Strong: {
805 if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
806 value = EmitARCRetainScalarExpr(init);
807 break;
808 }
809 // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
810 // that we omit the retain, and causes non-autoreleased return values to be
811 // immediately released.
812 LLVM_FALLTHROUGH;
813 }
814
John McCall31168b02011-06-15 23:02:42 +0000815 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000816 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000817 break;
818
John McCall31168b02011-06-15 23:02:42 +0000819 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000820 // If it's not accessed by the initializer, try to emit the
821 // initialization with a copy or move.
822 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
823 return;
824 }
825
John McCall31168b02011-06-15 23:02:42 +0000826 // No way to optimize a producing initializer into this. It's not
827 // worth optimizing for, because the value will immediately
828 // disappear in the common case.
829 value = EmitScalarExpr(init);
830
John McCall1553b192011-06-16 04:16:24 +0000831 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000832 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000833 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000834 else
John McCall1553b192011-06-16 04:16:24 +0000835 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000836 return;
837 }
838
839 case Qualifiers::OCL_Autoreleasing:
840 value = EmitARCRetainAutoreleaseScalarExpr(init);
841 break;
842 }
843
John McCall1553b192011-06-16 04:16:24 +0000844 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000845
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000846 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
847
John McCall31168b02011-06-15 23:02:42 +0000848 // If the variable might have been accessed by its initializer, we
849 // might have to initialize with a barrier. We have to do this for
850 // both __weak and __strong, but __weak got filtered out above.
851 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000852 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000853 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000854 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000855 return;
856 }
857
David Chisnallfa35df62012-01-16 17:27:18 +0000858 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000859}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000860
JF Bastiened92f602018-07-20 23:37:12 +0000861/// Decide whether we can emit the non-zero parts of the specified initializer
862/// with equal or fewer than NumStores scalar stores.
863static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
864 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000865 // Zero and Undef never requires any extra stores.
866 if (isa<llvm::ConstantAggregateZero>(Init) ||
867 isa<llvm::ConstantPointerNull>(Init) ||
868 isa<llvm::UndefValue>(Init))
869 return true;
870 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
871 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
872 isa<llvm::ConstantExpr>(Init))
873 return Init->isNullValue() || NumStores--;
874
875 // See if we can emit each element.
876 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
877 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
878 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
JF Bastiened92f602018-07-20 23:37:12 +0000879 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
Chris Lattnere6af8862010-12-02 01:58:41 +0000880 return false;
881 }
882 return true;
883 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000884
Chris Lattner236b3572012-01-31 04:36:19 +0000885 if (llvm::ConstantDataSequential *CDS =
886 dyn_cast<llvm::ConstantDataSequential>(Init)) {
887 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
888 llvm::Constant *Elt = CDS->getElementAsConstant(i);
JF Bastiened92f602018-07-20 23:37:12 +0000889 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
Chris Lattner236b3572012-01-31 04:36:19 +0000890 return false;
891 }
892 return true;
893 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000894
Chris Lattnerb85025f2010-12-01 02:05:19 +0000895 // Anything else is hard and scary.
896 return false;
897}
898
JF Bastiened92f602018-07-20 23:37:12 +0000899/// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
900/// the scalar stores that would be required.
901static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
902 llvm::Constant *Init, Address Loc,
903 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000904 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
JF Bastiened92f602018-07-20 23:37:12 +0000905 "called emitStoresForInitAfterBZero for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000906
Chris Lattnere6af8862010-12-02 01:58:41 +0000907 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
908 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
909 isa<llvm::ConstantExpr>(Init)) {
JF Bastien9aab85a2018-07-13 20:33:23 +0000910 Builder.CreateStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000911 return;
912 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000913
914 if (llvm::ConstantDataSequential *CDS =
915 dyn_cast<llvm::ConstantDataSequential>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000916 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
917 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000918
919 // If necessary, get a pointer to the element and emit it.
920 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
JF Bastiened92f602018-07-20 23:37:12 +0000921 emitStoresForInitAfterBZero(
James Y Knight751fe282019-02-09 22:22:28 +0000922 CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,
923 Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000924 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000925 return;
926 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000927
Chris Lattnere6af8862010-12-02 01:58:41 +0000928 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
929 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000930
Chris Lattnere6af8862010-12-02 01:58:41 +0000931 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
932 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000933
934 // If necessary, get a pointer to the element and emit it.
935 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
James Y Knight751fe282019-02-09 22:22:28 +0000936 emitStoresForInitAfterBZero(CGM, Elt,
937 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),
938 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000939 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000940}
941
JF Bastiened92f602018-07-20 23:37:12 +0000942/// Decide whether we should use bzero plus some stores to initialize a local
943/// variable instead of using a memcpy from a constant global. It is beneficial
944/// to use bzero if the global is all zeros, or mostly zeros and large.
945static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
946 uint64_t GlobalSize) {
947 // If a global is all zeros, always use a bzero.
Chris Lattnerb85025f2010-12-01 02:05:19 +0000948 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
949
Chris Lattnerb85025f2010-12-01 02:05:19 +0000950 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
951 // do it if it will require 6 or fewer scalar stores.
952 // TODO: Should budget depends on the size? Avoiding a large global warrants
953 // plopping in more stores.
954 unsigned StoreBudget = 6;
955 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000956
957 return GlobalSize > SizeLimit &&
JF Bastiened92f602018-07-20 23:37:12 +0000958 canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
Chris Lattnerb85025f2010-12-01 02:05:19 +0000959}
960
JF Bastien65089292018-07-25 04:29:03 +0000961/// Decide whether we should use memset to initialize a local variable instead
962/// of using a memcpy from a constant global. Assumes we've already decided to
963/// not user bzero.
964/// FIXME We could be more clever, as we are for bzero above, and generate
965/// memset followed by stores. It's unclear that's worth the effort.
JF Bastien2f0582f2018-09-21 13:54:09 +0000966static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
967 uint64_t GlobalSize) {
JF Bastien65089292018-07-25 04:29:03 +0000968 uint64_t SizeLimit = 32;
969 if (GlobalSize <= SizeLimit)
JF Bastien2f0582f2018-09-21 13:54:09 +0000970 return nullptr;
971 return llvm::isBytewiseValue(Init);
JF Bastien65089292018-07-25 04:29:03 +0000972}
973
JF Bastienb5e5bc72019-03-08 01:26:49 +0000974/// Decide whether we want to split a constant structure or array store into a
975/// sequence of its fields' stores. This may cost us code size and compilation
976/// speed, but plays better with store optimizations.
977static bool shouldSplitConstantStore(CodeGenModule &CGM,
978 uint64_t GlobalByteSize) {
979 // Don't break things that occupy more than one cacheline.
Alexander Potapenkofa61ddd2019-03-01 09:00:41 +0000980 uint64_t ByteSizeLimit = 64;
981 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
982 return false;
983 if (GlobalByteSize <= ByteSizeLimit)
984 return true;
985 return false;
986}
987
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +0000988enum class IsPattern { No, Yes };
989
990/// Generate a constant filled with either a pattern or zeroes.
991static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
992 llvm::Type *Ty) {
993 if (isPattern == IsPattern::Yes)
JF Bastienef202c32019-04-12 00:11:27 +0000994 return initializationPatternFor(CGM, Ty);
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +0000995 else
996 return llvm::Constant::getNullValue(Ty);
997}
998
999static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1000 llvm::Constant *constant);
1001
1002/// Helper function for constWithPadding() to deal with padding in structures.
1003static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
1004 IsPattern isPattern,
1005 llvm::StructType *STy,
1006 llvm::Constant *constant) {
1007 const llvm::DataLayout &DL = CGM.getDataLayout();
1008 const llvm::StructLayout *Layout = DL.getStructLayout(STy);
1009 llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1010 unsigned SizeSoFar = 0;
1011 SmallVector<llvm::Constant *, 8> Values;
1012 bool NestedIntact = true;
1013 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1014 unsigned CurOff = Layout->getElementOffset(i);
1015 if (SizeSoFar < CurOff) {
1016 assert(!STy->isPacked());
1017 auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);
1018 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1019 }
1020 llvm::Constant *CurOp;
1021 if (constant->isZeroValue())
1022 CurOp = llvm::Constant::getNullValue(STy->getElementType(i));
1023 else
1024 CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));
1025 auto *NewOp = constWithPadding(CGM, isPattern, CurOp);
1026 if (CurOp != NewOp)
1027 NestedIntact = false;
1028 Values.push_back(NewOp);
1029 SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());
1030 }
1031 unsigned TotalSize = Layout->getSizeInBytes();
1032 if (SizeSoFar < TotalSize) {
1033 auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);
1034 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1035 }
1036 if (NestedIntact && Values.size() == STy->getNumElements())
1037 return constant;
Peter Collingbourne68b46732019-03-16 19:25:39 +00001038 return llvm::ConstantStruct::getAnon(Values, STy->isPacked());
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001039}
1040
1041/// Replace all padding bytes in a given constant with either a pattern byte or
1042/// 0x00.
1043static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1044 llvm::Constant *constant) {
1045 llvm::Type *OrigTy = constant->getType();
1046 if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))
1047 return constStructWithPadding(CGM, isPattern, STy, constant);
1048 if (auto *STy = dyn_cast<llvm::SequentialType>(OrigTy)) {
1049 llvm::SmallVector<llvm::Constant *, 8> Values;
1050 unsigned Size = STy->getNumElements();
1051 if (!Size)
1052 return constant;
1053 llvm::Type *ElemTy = STy->getElementType();
1054 bool ZeroInitializer = constant->isZeroValue();
1055 llvm::Constant *OpValue, *PaddedOp;
1056 if (ZeroInitializer) {
1057 OpValue = llvm::Constant::getNullValue(ElemTy);
1058 PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1059 }
1060 for (unsigned Op = 0; Op != Size; ++Op) {
1061 if (!ZeroInitializer) {
1062 OpValue = constant->getAggregateElement(Op);
1063 PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1064 }
1065 Values.push_back(PaddedOp);
1066 }
1067 auto *NewElemTy = Values[0]->getType();
1068 if (NewElemTy == ElemTy)
1069 return constant;
1070 if (OrigTy->isArrayTy()) {
1071 auto *ArrayTy = llvm::ArrayType::get(NewElemTy, Size);
1072 return llvm::ConstantArray::get(ArrayTy, Values);
1073 } else {
1074 return llvm::ConstantVector::get(Values);
1075 }
1076 }
1077 return constant;
1078}
1079
Nico Weber3d02b892019-06-14 04:05:17 +00001080static Address createUnnamedGlobalFrom(CodeGenModule &CGM, const VarDecl &D,
1081 CGBuilderTy &Builder,
1082 llvm::Constant *Constant,
1083 CharUnits Align) {
JF Bastien3a881e62018-11-15 00:19:18 +00001084 auto FunctionName = [&](const DeclContext *DC) -> std::string {
1085 if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1086 if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
1087 return CC->getNameAsString();
1088 if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
1089 return CD->getNameAsString();
Nico Weber3d02b892019-06-14 04:05:17 +00001090 return CGM.getMangledName(FD);
JF Bastien3a881e62018-11-15 00:19:18 +00001091 } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
1092 return OM->getNameAsString();
Mikael Holmenee846762018-11-15 13:01:54 +00001093 } else if (isa<BlockDecl>(DC)) {
JF Bastien3a881e62018-11-15 00:19:18 +00001094 return "<block>";
Mikael Holmenee846762018-11-15 13:01:54 +00001095 } else if (isa<CapturedDecl>(DC)) {
JF Bastien3a881e62018-11-15 00:19:18 +00001096 return "<captured>";
1097 } else {
1098 llvm::llvm_unreachable_internal("expected a function or method");
1099 }
1100 };
1101
Nico Weber3d02b892019-06-14 04:05:17 +00001102 auto *Ty = Constant->getType();
1103 bool isConstant = true;
1104 llvm::GlobalVariable *InsertBefore = nullptr;
1105 unsigned AS = CGM.getContext().getTargetAddressSpace(
1106 CGM.getStringLiteralAddressSpace());
1107 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1108 CGM.getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
1109 Constant,
1110 "__const." + FunctionName(D.getParentFunctionOrMethod()) + "." +
1111 D.getName(),
1112 InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
1113 GV->setAlignment(Align.getQuantity());
1114 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
JF Bastien3a881e62018-11-15 00:19:18 +00001115
Nico Weber3d02b892019-06-14 04:05:17 +00001116 Address SrcPtr = Address(GV, Align);
1117 llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(), AS);
JF Bastien3a881e62018-11-15 00:19:18 +00001118 if (SrcPtr.getType() != BP)
1119 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1120 return SrcPtr;
1121}
1122
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001123static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
1124 Address Loc, bool isVolatile,
1125 CGBuilderTy &Builder,
1126 llvm::Constant *constant) {
JF Bastien14daa202018-12-18 05:12:21 +00001127 auto *Ty = constant->getType();
JF Bastienb5e5bc72019-03-08 01:26:49 +00001128 bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
1129 Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
1130 if (canDoSingleStore) {
JF Bastien14daa202018-12-18 05:12:21 +00001131 Builder.CreateStore(constant, Loc, isVolatile);
1132 return;
1133 }
1134
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001135 auto *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1136 auto *IntPtrTy = CGM.getDataLayout().getIntPtrType(CGM.getLLVMContext());
1137
JF Bastien14daa202018-12-18 05:12:21 +00001138 uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
Alexander Potapenkofa61ddd2019-03-01 09:00:41 +00001139 if (!ConstantSize)
1140 return;
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001141 auto *SizeVal = llvm::ConstantInt::get(IntPtrTy, ConstantSize);
JF Bastienb5e5bc72019-03-08 01:26:49 +00001142
1143 // If the initializer is all or mostly the same, codegen with bzero / memset
1144 // then do a few stores afterward.
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001145 if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1146 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1147 isVolatile);
1148
1149 bool valueAlreadyCorrect =
1150 constant->isNullValue() || isa<llvm::UndefValue>(constant);
1151 if (!valueAlreadyCorrect) {
JF Bastien14daa202018-12-18 05:12:21 +00001152 Loc = Builder.CreateBitCast(Loc, Ty->getPointerTo(Loc.getAddressSpace()));
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001153 emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder);
1154 }
1155 return;
1156 }
1157
JF Bastienb5e5bc72019-03-08 01:26:49 +00001158 // If the initializer is a repeated byte pattern, use memset.
JF Bastien2f0582f2018-09-21 13:54:09 +00001159 llvm::Value *Pattern = shouldUseMemSetToInitialize(constant, ConstantSize);
1160 if (Pattern) {
1161 uint64_t Value = 0x00;
1162 if (!isa<llvm::UndefValue>(Pattern)) {
1163 const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1164 assert(AP.getBitWidth() <= 8);
1165 Value = AP.getLimitedValue();
1166 }
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001167 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, Value), SizeVal,
1168 isVolatile);
1169 return;
1170 }
1171
JF Bastienb5e5bc72019-03-08 01:26:49 +00001172 // If the initializer is small, use a handful of stores.
1173 if (shouldSplitConstantStore(CGM, ConstantSize)) {
1174 if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
1175 // FIXME: handle the case when STy != Loc.getElementType().
1176 if (STy == Loc.getElementType()) {
1177 for (unsigned i = 0; i != constant->getNumOperands(); i++) {
1178 Address EltPtr = Builder.CreateStructGEP(Loc, i);
1179 emitStoresForConstant(
1180 CGM, D, EltPtr, isVolatile, Builder,
1181 cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)));
1182 }
1183 return;
1184 }
1185 } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
1186 // FIXME: handle the case when ATy != Loc.getElementType().
1187 if (ATy == Loc.getElementType()) {
1188 for (unsigned i = 0; i != ATy->getNumElements(); i++) {
1189 Address EltPtr = Builder.CreateConstArrayGEP(Loc, i);
1190 emitStoresForConstant(
1191 CGM, D, EltPtr, isVolatile, Builder,
1192 cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)));
1193 }
1194 return;
1195 }
Alexander Potapenkofa61ddd2019-03-01 09:00:41 +00001196 }
Alexander Potapenkofa61ddd2019-03-01 09:00:41 +00001197 }
1198
JF Bastienb5e5bc72019-03-08 01:26:49 +00001199 // Copy from a global.
Nico Weber3d02b892019-06-14 04:05:17 +00001200 Builder.CreateMemCpy(
1201 Loc,
1202 createUnnamedGlobalFrom(CGM, D, Builder, constant, Loc.getAlignment()),
1203 SizeVal, isVolatile);
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001204}
1205
JF Bastien14daa202018-12-18 05:12:21 +00001206static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
1207 Address Loc, bool isVolatile,
1208 CGBuilderTy &Builder) {
1209 llvm::Type *ElTy = Loc.getElementType();
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001210 llvm::Constant *constant =
1211 constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
JF Bastien14daa202018-12-18 05:12:21 +00001212 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1213}
1214
1215static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
1216 Address Loc, bool isVolatile,
1217 CGBuilderTy &Builder) {
1218 llvm::Type *ElTy = Loc.getElementType();
JF Bastienef202c32019-04-12 00:11:27 +00001219 llvm::Constant *constant = constWithPadding(
1220 CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
JF Bastien14daa202018-12-18 05:12:21 +00001221 assert(!isa<llvm::UndefValue>(constant));
1222 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1223}
1224
1225static bool containsUndef(llvm::Constant *constant) {
1226 auto *Ty = constant->getType();
1227 if (isa<llvm::UndefValue>(constant))
1228 return true;
1229 if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1230 for (llvm::Use &Op : constant->operands())
1231 if (containsUndef(cast<llvm::Constant>(Op)))
1232 return true;
1233 return false;
1234}
1235
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001236static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
1237 llvm::Constant *constant) {
JF Bastien14daa202018-12-18 05:12:21 +00001238 auto *Ty = constant->getType();
1239 if (isa<llvm::UndefValue>(constant))
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001240 return patternOrZeroFor(CGM, isPattern, Ty);
JF Bastien14daa202018-12-18 05:12:21 +00001241 if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1242 return constant;
1243 if (!containsUndef(constant))
1244 return constant;
1245 llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1246 for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1247 auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001248 Values[Op] = replaceUndef(CGM, isPattern, OpValue);
JF Bastien14daa202018-12-18 05:12:21 +00001249 }
1250 if (Ty->isStructTy())
1251 return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
1252 if (Ty->isArrayTy())
1253 return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
1254 assert(Ty->isVectorTy());
1255 return llvm::ConstantVector::get(Values);
1256}
1257
Nick Lewycky8a7d90b2010-12-30 20:21:55 +00001258/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +00001259/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +00001260/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +00001261void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1262 AutoVarEmission emission = EmitAutoVarAlloca(D);
1263 EmitAutoVarInit(emission);
1264 EmitAutoVarCleanups(emission);
1265}
Chris Lattner03df1222007-06-02 04:53:11 +00001266
David Majnemerdc012fa2015-04-22 21:38:15 +00001267/// Emit a lifetime.begin marker if some criteria are satisfied.
1268/// \return a pointer to the temporary size Value if a marker was emitted, null
1269/// otherwise
1270llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
1271 llvm::Value *Addr) {
Vitaly Buka1c943322016-10-26 01:59:57 +00001272 if (!ShouldEmitLifetimeMarkers)
Reid Kleckner1ef49212015-04-23 18:07:13 +00001273 return nullptr;
1274
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001275 assert(Addr->getType()->getPointerAddressSpace() ==
1276 CGM.getDataLayout().getAllocaAddrSpace() &&
1277 "Pointer should be in alloca address space");
David Majnemerdc012fa2015-04-22 21:38:15 +00001278 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001279 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +00001280 llvm::CallInst *C =
1281 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +00001282 C->setDoesNotThrow();
1283 return SizeV;
1284}
1285
1286void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001287 assert(Addr->getType()->getPointerAddressSpace() ==
1288 CGM.getDataLayout().getAllocaAddrSpace() &&
1289 "Pointer should be in alloca address space");
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001290 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +00001291 llvm::CallInst *C =
1292 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +00001293 C->setDoesNotThrow();
1294}
1295
Sander de Smalen891af03a2018-02-03 13:55:59 +00001296void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1297 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1298 // For each dimension stores its QualType and corresponding
1299 // size-expression Value.
1300 SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
Adrian Prantla40cce82018-11-09 19:17:56 +00001301 SmallVector<IdentifierInfo *, 4> VLAExprNames;
Sander de Smalen891af03a2018-02-03 13:55:59 +00001302
1303 // Break down the array into individual dimensions.
1304 QualType Type1D = D.getType();
1305 while (getContext().getAsVariableArrayType(Type1D)) {
1306 auto VlaSize = getVLAElements1D(Type1D);
1307 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1308 Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1309 else {
Adrian Prantla40cce82018-11-09 19:17:56 +00001310 // Generate a locally unique name for the size expression.
1311 Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1312 SmallString<12> Buffer;
1313 StringRef NameRef = Name.toStringRef(Buffer);
1314 auto &Ident = getContext().Idents.getOwn(NameRef);
1315 VLAExprNames.push_back(&Ident);
1316 auto SizeExprAddr =
1317 CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
Sander de Smalen891af03a2018-02-03 13:55:59 +00001318 Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1319 Dimensions.emplace_back(SizeExprAddr.getPointer(),
1320 Type1D.getUnqualifiedType());
1321 }
1322 Type1D = VlaSize.Type;
1323 }
1324
1325 if (!EmitDebugInfo)
1326 return;
1327
1328 // Register each dimension's size-expression with a DILocalVariable,
1329 // so that it can be used by CGDebugInfo when instantiating a DISubrange
1330 // to describe this array.
Adrian Prantla40cce82018-11-09 19:17:56 +00001331 unsigned NameIdx = 0;
Sander de Smalen891af03a2018-02-03 13:55:59 +00001332 for (auto &VlaSize : Dimensions) {
1333 llvm::Metadata *MD;
1334 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1335 MD = llvm::ConstantAsMetadata::get(C);
1336 else {
1337 // Create an artificial VarDecl to generate debug info for.
Adrian Prantla40cce82018-11-09 19:17:56 +00001338 IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
Sander de Smalen891af03a2018-02-03 13:55:59 +00001339 auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
1340 auto QT = getContext().getIntTypeForBitwidth(
1341 VlaExprTy->getScalarSizeInBits(), false);
1342 auto *ArtificialDecl = VarDecl::Create(
1343 getContext(), const_cast<DeclContext *>(D.getDeclContext()),
Adrian Prantla40cce82018-11-09 19:17:56 +00001344 D.getLocation(), D.getLocation(), NameIdent, QT,
Sander de Smalen891af03a2018-02-03 13:55:59 +00001345 getContext().CreateTypeSourceInfo(QT), SC_Auto);
Sander de Smalen9084a3b2018-02-13 07:49:34 +00001346 ArtificialDecl->setImplicit();
Sander de Smalen891af03a2018-02-03 13:55:59 +00001347
1348 MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1349 Builder);
1350 }
1351 assert(MD && "No Size expression debug node created");
1352 DI->registerVLASizeExpression(VlaSize.Type, MD);
1353 }
1354}
1355
John McCallc533cb72011-02-22 06:44:22 +00001356/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001357/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +00001358CodeGenFunction::AutoVarEmission
1359CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1360 QualType Ty = D.getType();
Yaxun Liub7318e02017-10-13 03:37:48 +00001361 assert(
1362 Ty.getAddressSpace() == LangAS::Default ||
1363 (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
John McCallc533cb72011-02-22 06:44:22 +00001364
1365 AutoVarEmission emission(D);
1366
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001367 bool isEscapingByRef = D.isEscapingByref();
1368 emission.IsEscapingByRef = isEscapingByRef;
John McCallc533cb72011-02-22 06:44:22 +00001369
1370 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +00001371
John McCall23c29fe2011-06-24 21:55:10 +00001372 // If the type is variably-modified, emit all the VLA sizes for it.
1373 if (Ty->isVariablyModifiedType())
1374 EmitVariablyModifiedType(Ty);
1375
Sander de Smalen891af03a2018-02-03 13:55:59 +00001376 auto *DI = getDebugInfo();
1377 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().getDebugInfo() >=
1378 codegenoptions::LimitedDebugInfo;
1379
John McCall7f416cc2015-09-08 08:05:57 +00001380 Address address = Address::invalid();
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001381 Address AllocaAddr = Address::invalid();
Alexey Bataev9c397812019-04-03 17:57:06 +00001382 Address OpenMPLocalAddr =
1383 getLangOpts().OpenMP
1384 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
1385 : Address::invalid();
1386 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1387 address = OpenMPLocalAddr;
1388 } else if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001389 bool NRVO = getLangOpts().ElideConstructors &&
1390 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +00001391
Richard Smith2bcde3a2013-06-02 00:09:52 +00001392 // If this value is an array or struct with a statically determinable
1393 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +00001394 //
1395 // TODO: We should constant-evaluate the initializer of any variable,
1396 // as long as it is initialized by a constant expression. Currently,
1397 // isConstantInitializer produces wrong answers for structs with
1398 // reference or bitfield members, and a few other cases, and checking
1399 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +00001400 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1401 (D.isConstexpr() ||
1402 ((Ty.isPODType(getContext()) ||
1403 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1404 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +00001405
Rafael Espindola609f5d92013-03-26 18:41:47 +00001406 // If the variable's a const type, and it's neither an NRVO
1407 // candidate nor a __block variable and has no mutable members,
1408 // emit it as a global instead.
Anastasia Stulovae4a1c382016-11-29 17:01:19 +00001409 // Exception is if a variable is located in non-constant address space
1410 // in OpenCL.
1411 if ((!getLangOpts().OpenCL ||
1412 Ty.getAddressSpace() == LangAS::opencl_constant) &&
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001413 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1414 !isEscapingByRef && CGM.isTypeConstant(Ty, true))) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001415 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +00001416
John McCall7f416cc2015-09-08 08:05:57 +00001417 // Signal this condition to later callbacks.
1418 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +00001419 assert(emission.wasEmittedAsGlobal());
1420 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +00001421 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001422
Rafael Espindola609f5d92013-03-26 18:41:47 +00001423 // Otherwise, tell the initialization code that we're in this case.
1424 emission.IsConstantAggregate = true;
1425 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001426
Rafael Espindola609f5d92013-03-26 18:41:47 +00001427 // A normal fixed sized variable becomes an alloca in the entry block,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001428 // unless:
1429 // - it's an NRVO variable.
1430 // - we are compiling OpenMP and it's an OpenMP local variable.
Alexey Bataev9c397812019-04-03 17:57:06 +00001431 if (NRVO) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001432 // The named return value optimization: allocate this variable in the
1433 // return slot, so that we can elide the copy when returning this
1434 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +00001435 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +00001436
Rafael Espindola609f5d92013-03-26 18:41:47 +00001437 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001438 const auto *RD = RecordTy->getDecl();
1439 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1440 if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1441 RD->isNonTrivialToPrimitiveDestroy()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001442 // Create a flag that is used to indicate when the NRVO was applied
1443 // to this variable. Set it to zero to indicate that NRVO was not
1444 // applied.
1445 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +00001446 Address NRVOFlag =
1447 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +00001448 EnsureInsertPoint();
1449 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +00001450
Rafael Espindola609f5d92013-03-26 18:41:47 +00001451 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +00001452 NRVOFlags[&D] = NRVOFlag.getPointer();
1453 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +00001454 }
Douglas Gregor290c93e2010-05-15 06:46:45 +00001455 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001456 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001457 CharUnits allocaAlignment;
1458 llvm::Type *allocaTy;
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001459 if (isEscapingByRef) {
John McCall7f416cc2015-09-08 08:05:57 +00001460 auto &byrefInfo = getBlockByrefInfo(&D);
1461 allocaTy = byrefInfo.Type;
1462 allocaAlignment = byrefInfo.ByrefAlignment;
1463 } else {
1464 allocaTy = ConvertTypeForMem(Ty);
1465 allocaAlignment = alignment;
1466 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001467
John McCall999110f2015-09-08 09:18:30 +00001468 // Create the alloca. Note that we set the name separately from
1469 // building the instruction so that it's there even in no-asserts
1470 // builds.
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001471 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1472 /*ArraySize=*/nullptr, &AllocaAddr);
Rafael Espindola609f5d92013-03-26 18:41:47 +00001473
Reid Kleckner1f88e932015-10-07 21:03:41 +00001474 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1475 // the catch parameter starts in the catchpad instruction, and we can't
1476 // insert code in those basic blocks.
1477 bool IsMSCatchParam =
1478 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1479
Vitaly Buka64c80b42016-10-26 05:42:30 +00001480 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1481 // if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001482 if (HaveInsertPoint() && !IsMSCatchParam) {
Akira Hatanakafdcd18b2017-01-25 22:55:13 +00001483 // If there's a jump into the lifetime of this variable, its lifetime
1484 // gets broken up into several regions in IR, which requires more work
1485 // to handle correctly. For now, just omit the intrinsics; this is a
1486 // rare case, and it's better to just be conservatively correct.
1487 // PR28267.
1488 //
1489 // We have to do this in all language modes if there's a jump past the
1490 // declaration. We also have to do it in C if there's a jump to an
1491 // earlier point in the current block because non-VLA lifetimes begin as
1492 // soon as the containing block is entered, not when its variables
1493 // actually come into scope; suppressing the lifetime annotations
1494 // completely in this case is unnecessarily pessimistic, but again, this
1495 // is rare.
1496 if (!Bypasses.IsBypassed(&D) &&
1497 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
Vitaly Buka64c80b42016-10-26 05:42:30 +00001498 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1499 emission.SizeForLifetimeMarkers =
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001500 EmitLifetimeStart(size, AllocaAddr.getPointer());
Vitaly Buka64c80b42016-10-26 05:42:30 +00001501 }
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001502 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001503 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001504 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001505 }
Chris Lattner03df1222007-06-02 04:53:11 +00001506 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001507 EnsureInsertPoint();
1508
Anders Carlsson15949b32009-02-09 20:41:50 +00001509 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001510 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001511 Address Stack =
1512 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001513
James Y Knight8799cae2019-02-03 21:53:49 +00001514 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001515 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001516 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001517
1518 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001519
John McCalla464ff92010-07-21 06:13:08 +00001520 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001521 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001522 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001523 }
Mike Stump11289f42009-09-09 15:08:12 +00001524
Sander de Smalen891af03a2018-02-03 13:55:59 +00001525 auto VlaSize = getVLASize(Ty);
1526 llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
Anders Carlsson30032882008-12-12 07:38:43 +00001527
1528 // Allocate memory for the array.
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001529 address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1530 &AllocaAddr);
Sander de Smalen891af03a2018-02-03 13:55:59 +00001531
1532 // If we have debug info enabled, properly describe the VLA dimensions for
1533 // this type by registering the vla size expression for each of the
1534 // dimensions.
1535 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
Chris Lattner03df1222007-06-02 04:53:11 +00001536 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001537
John McCall7f416cc2015-09-08 08:05:57 +00001538 setAddrOfLocalVar(&D, address);
1539 emission.Addr = address;
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001540 emission.AllocaAddr = AllocaAddr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001541
1542 // Emit debug info for local var declaration.
Sander de Smalen891af03a2018-02-03 13:55:59 +00001543 if (EmitDebugInfo && HaveInsertPoint()) {
1544 DI->setLocation(D.getLocation());
1545 (void)DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1546 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001547
Volodymyr Sapsai93317d82019-03-01 02:15:39 +00001548 if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
John McCall7f416cc2015-09-08 08:05:57 +00001549 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001550
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001551 // Make sure we call @llvm.lifetime.end.
1552 if (emission.useLifetimeMarkers())
1553 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001554 emission.getOriginalAllocatedAddress(),
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001555 emission.getSizeForLifetimeMarkers());
1556
John McCallc533cb72011-02-22 06:44:22 +00001557 return emission;
1558}
1559
JF Bastien6b239722018-05-19 04:21:26 +00001560static bool isCapturedBy(const VarDecl &, const Expr *);
1561
1562/// Determines whether the given __block variable is potentially
1563/// captured by the given statement.
1564static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1565 if (const Expr *E = dyn_cast<Expr>(S))
1566 return isCapturedBy(Var, E);
1567 for (const Stmt *SubStmt : S->children())
1568 if (isCapturedBy(Var, SubStmt))
1569 return true;
1570 return false;
1571}
1572
John McCallc533cb72011-02-22 06:44:22 +00001573/// Determines whether the given __block variable is potentially
1574/// captured by the given expression.
JF Bastien6b239722018-05-19 04:21:26 +00001575static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
John McCallc533cb72011-02-22 06:44:22 +00001576 // Skip the most common kinds of expressions that make
1577 // hierarchy-walking expensive.
JF Bastien6b239722018-05-19 04:21:26 +00001578 E = E->IgnoreParenCasts();
John McCallc533cb72011-02-22 06:44:22 +00001579
JF Bastien6b239722018-05-19 04:21:26 +00001580 if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1581 const BlockDecl *Block = BE->getBlockDecl();
1582 for (const auto &I : Block->captures()) {
1583 if (I.getVariable() == &Var)
John McCallc533cb72011-02-22 06:44:22 +00001584 return true;
1585 }
1586
1587 // No need to walk into the subexpressions.
1588 return false;
1589 }
1590
JF Bastien6b239722018-05-19 04:21:26 +00001591 if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001592 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001593 for (const auto *BI : CS->body())
JF Bastien6b239722018-05-19 04:21:26 +00001594 if (const auto *BIE = dyn_cast<Expr>(BI)) {
1595 if (isCapturedBy(Var, BIE))
1596 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001597 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001598 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001599 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001600 for (const auto *I : DS->decls()) {
1601 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1602 const Expr *Init = VD->getInit();
JF Bastien6b239722018-05-19 04:21:26 +00001603 if (Init && isCapturedBy(Var, Init))
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001604 return true;
1605 }
1606 }
1607 }
1608 else
1609 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1610 // Later, provide code to poke into statements for capture analysis.
1611 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001612 return false;
1613 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001614
JF Bastien6b239722018-05-19 04:21:26 +00001615 for (const Stmt *SubStmt : E->children())
1616 if (isCapturedBy(Var, SubStmt))
John McCallc533cb72011-02-22 06:44:22 +00001617 return true;
1618
1619 return false;
1620}
1621
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001622/// Determine whether the given initializer is trivial in the sense
Douglas Gregor82e1af22011-07-01 21:08:19 +00001623/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001624bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001625 if (!Init)
1626 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001627
Douglas Gregor82e1af22011-07-01 21:08:19 +00001628 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1629 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1630 if (Constructor->isTrivial() &&
1631 Constructor->isDefaultConstructor() &&
1632 !Construct->requiresZeroInitialization())
1633 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001634
Douglas Gregor82e1af22011-07-01 21:08:19 +00001635 return false;
1636}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001637
John McCallc533cb72011-02-22 06:44:22 +00001638void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001639 assert(emission.Variable && "emission was not valid!");
1640
John McCallc533cb72011-02-22 06:44:22 +00001641 // If this was emitted as a global constant, we're done.
1642 if (emission.wasEmittedAsGlobal()) return;
1643
John McCall9e2e22f2011-02-22 07:16:58 +00001644 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001645 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001646 QualType type = D.getType();
1647
JF Bastien14daa202018-12-18 05:12:21 +00001648 bool isVolatile = type.isVolatileQualified();
1649
Chris Lattner07eb7332007-07-12 00:39:48 +00001650 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001651 const Expr *Init = D.getInit();
1652
1653 // If we are at an unreachable point, we don't need to emit the initializer
1654 // unless it contains a label.
1655 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001656 if (!Init || !ContainsLabel(Init)) return;
1657 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001658 }
1659
John McCall73064872011-03-31 01:59:53 +00001660 // Initialize the structure of a __block variable.
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001661 if (emission.IsEscapingByRef)
John McCall73064872011-03-31 01:59:53 +00001662 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001663
Akira Hatanaka7275da02018-02-28 07:15:55 +00001664 // Initialize the variable here if it doesn't have a initializer and it is a
1665 // C struct that is non-trivial to initialize or an array containing such a
1666 // struct.
1667 if (!Init &&
1668 type.isNonTrivialToPrimitiveDefaultInitialize() ==
1669 QualType::PDIK_Struct) {
1670 LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001671 if (emission.IsEscapingByRef)
Akira Hatanaka7275da02018-02-28 07:15:55 +00001672 drillIntoBlockVariable(*this, Dst, &D);
1673 defaultInitNonTrivialCStructVar(Dst);
1674 return;
1675 }
1676
John McCallc533cb72011-02-22 06:44:22 +00001677 // Check whether this is a byref variable that's potentially
1678 // captured and moved by its own initializer. If so, we'll need to
1679 // emit the initializer first, then copy into the variable.
JF Bastien14daa202018-12-18 05:12:21 +00001680 bool capturedByInit =
1681 Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
John McCallc533cb72011-02-22 06:44:22 +00001682
JF Bastien0bae08a2019-02-15 17:26:29 +00001683 bool locIsByrefHeader = !capturedByInit;
1684 const Address Loc =
1685 locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
JF Bastien14daa202018-12-18 05:12:21 +00001686
1687 // Note: constexpr already initializes everything correctly.
1688 LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
1689 (D.isConstexpr()
1690 ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1691 : (D.getAttr<UninitializedAttr>()
1692 ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1693 : getContext().getLangOpts().getTrivialAutoVarInit()));
1694
JF Bastienb347e752019-02-08 01:29:17 +00001695 auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
JF Bastien14daa202018-12-18 05:12:21 +00001696 if (trivialAutoVarInit ==
1697 LangOptions::TrivialAutoVarInitKind::Uninitialized)
1698 return;
1699
JF Bastienb347e752019-02-08 01:29:17 +00001700 // Only initialize a __block's storage: we always initialize the header.
JF Bastien0bae08a2019-02-15 17:26:29 +00001701 if (emission.IsEscapingByRef && !locIsByrefHeader)
JF Bastienb347e752019-02-08 01:29:17 +00001702 Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
1703
JF Bastien14daa202018-12-18 05:12:21 +00001704 CharUnits Size = getContext().getTypeSizeInChars(type);
1705 if (!Size.isZero()) {
1706 switch (trivialAutoVarInit) {
1707 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1708 llvm_unreachable("Uninitialized handled above");
1709 case LangOptions::TrivialAutoVarInitKind::Zero:
1710 emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
1711 break;
1712 case LangOptions::TrivialAutoVarInitKind::Pattern:
1713 emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
1714 break;
1715 }
1716 return;
1717 }
1718
1719 // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1720 // them, so emit a memcpy with the VLA size to initialize each element.
1721 // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1722 // will catch that code, but there exists code which generates zero-sized
1723 // VLAs. Be nice and initialize whatever they requested.
JF Bastienddeb2f22019-02-08 00:51:05 +00001724 const auto *VlaType = getContext().getAsVariableArrayType(type);
JF Bastien14daa202018-12-18 05:12:21 +00001725 if (!VlaType)
1726 return;
1727 auto VlaSize = getVLASize(VlaType);
1728 auto SizeVal = VlaSize.NumElts;
1729 CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1730 switch (trivialAutoVarInit) {
1731 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1732 llvm_unreachable("Uninitialized handled above");
1733
1734 case LangOptions::TrivialAutoVarInitKind::Zero:
1735 if (!EltSize.isOne())
1736 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1737 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1738 isVolatile);
1739 break;
1740
1741 case LangOptions::TrivialAutoVarInitKind::Pattern: {
1742 llvm::Type *ElTy = Loc.getElementType();
JF Bastienef202c32019-04-12 00:11:27 +00001743 llvm::Constant *Constant = constWithPadding(
1744 CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
JF Bastien14daa202018-12-18 05:12:21 +00001745 CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
1746 llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
1747 llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
1748 llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
1749 llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1750 SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
1751 "vla.iszerosized");
1752 Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
1753 EmitBlock(SetupBB);
1754 if (!EltSize.isOne())
1755 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1756 llvm::Value *BaseSizeInChars =
1757 llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
1758 Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
1759 llvm::Value *End =
1760 Builder.CreateInBoundsGEP(Begin.getPointer(), SizeVal, "vla.end");
1761 llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1762 EmitBlock(LoopBB);
1763 llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
1764 Cur->addIncoming(Begin.getPointer(), OriginBB);
1765 CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
Nico Weber3d02b892019-06-14 04:05:17 +00001766 Builder.CreateMemCpy(
1767 Address(Cur, CurAlign),
1768 createUnnamedGlobalFrom(CGM, D, Builder, Constant, ConstantAlign),
1769 BaseSizeInChars, isVolatile);
JF Bastien14daa202018-12-18 05:12:21 +00001770 llvm::Value *Next =
1771 Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
1772 llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
1773 Builder.CreateCondBr(Done, ContBB, LoopBB);
1774 Cur->addIncoming(Next, LoopBB);
1775 EmitBlock(ContBB);
1776 } break;
1777 }
1778 };
1779
1780 if (isTrivialInitializer(Init)) {
JF Bastienb347e752019-02-08 01:29:17 +00001781 initializeWhatIsTechnicallyUninitialized(Loc);
JF Bastien14daa202018-12-18 05:12:21 +00001782 return;
1783 }
John McCallc533cb72011-02-22 06:44:22 +00001784
Craig Topper8a13c412014-05-21 05:09:00 +00001785 llvm::Constant *constant = nullptr;
Richard Smith715f7a12019-06-11 17:50:32 +00001786 if (emission.IsConstantAggregate ||
1787 D.mightBeUsableInConstantExpressions(getContext())) {
Richard Smithfddd3842011-12-30 21:15:51 +00001788 assert(!capturedByInit && "constant init contains a capturing block?");
John McCallde0fe072017-08-15 21:42:52 +00001789 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
JF Bastiend39fbc72019-04-30 22:56:53 +00001790 if (constant && !constant->isZeroValue() &&
1791 (trivialAutoVarInit !=
1792 LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001793 IsPattern isPattern =
1794 (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
1795 ? IsPattern::Yes
1796 : IsPattern::No;
JF Bastiend39fbc72019-04-30 22:56:53 +00001797 // C guarantees that brace-init with fewer initializers than members in
1798 // the aggregate will initialize the rest of the aggregate as-if it were
1799 // static initialization. In turn static initialization guarantees that
1800 // padding is initialized to zero bits. We could instead pattern-init if D
1801 // has any ImplicitValueInitExpr, but that seems to be unintuitive
1802 // behavior.
1803 constant = constWithPadding(CGM, IsPattern::No,
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001804 replaceUndef(CGM, isPattern, constant));
1805 }
Richard Smithfddd3842011-12-30 21:15:51 +00001806 }
1807
1808 if (!constant) {
JF Bastienb347e752019-02-08 01:29:17 +00001809 initializeWhatIsTechnicallyUninitialized(Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001810 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001811 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001812 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001813 }
John McCall91ca10f2011-03-08 09:11:50 +00001814
Richard Smith2bcde3a2013-06-02 00:09:52 +00001815 if (!emission.IsConstantAggregate) {
1816 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001817 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001818 lv.setNonGC(true);
1819 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1820 }
1821
Yaxun Liudaceb1e2018-05-14 19:20:12 +00001822 llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
JF Bastien0bae08a2019-02-15 17:26:29 +00001823 emitStoresForConstant(
1824 CGM, D, (Loc.getType() == BP) ? Loc : Builder.CreateBitCast(Loc, BP),
1825 isVolatile, Builder, constant);
John McCall91ca10f2011-03-08 09:11:50 +00001826}
1827
Richard Smithe78fac52018-04-05 20:52:58 +00001828/// Emit an expression as an initializer for an object (variable, field, etc.)
1829/// at the given location. The expression is not necessarily the normal
1830/// initializer for the object, and the address is not necessarily
John McCall91ca10f2011-03-08 09:11:50 +00001831/// its normal location.
1832///
1833/// \param init the initializing expression
Richard Smithe78fac52018-04-05 20:52:58 +00001834/// \param D the object to act as if we're initializing
John McCall91ca10f2011-03-08 09:11:50 +00001835/// \param loc the address to initialize; its type is a pointer
Richard Smithe78fac52018-04-05 20:52:58 +00001836/// to the LLVM mapping of the object's type
John McCall91ca10f2011-03-08 09:11:50 +00001837/// \param alignment the alignment of the address
Richard Smithe78fac52018-04-05 20:52:58 +00001838/// \param capturedByInit true if \p D is a __block variable
John McCall91ca10f2011-03-08 09:11:50 +00001839/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001840void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001841 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001842 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001843
1844 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001845 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001846 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001847 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001848 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001849 return;
1850 }
1851 switch (getEvaluationKind(type)) {
1852 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001853 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001854 return;
1855 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001856 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001857 if (capturedByInit)
1858 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001859 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001860 return;
1861 }
1862 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001863 if (type->isAtomicType()) {
1864 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1865 } else {
Richard Smithe78fac52018-04-05 20:52:58 +00001866 AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
1867 if (isa<VarDecl>(D))
1868 Overlap = AggValueSlot::DoesNotOverlap;
1869 else if (auto *FD = dyn_cast<FieldDecl>(D))
1870 Overlap = overlapForFieldInit(FD);
John McCalla8ec7eb2013-03-07 21:37:17 +00001871 // TODO: how can we delay here if D is captured by its initializer?
1872 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001873 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001874 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001875 AggValueSlot::IsNotAliased,
1876 Overlap));
John McCalla8ec7eb2013-03-07 21:37:17 +00001877 }
John McCall47fb9502013-03-07 21:37:08 +00001878 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001879 }
John McCall47fb9502013-03-07 21:37:08 +00001880 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001881}
John McCallbd309292010-07-06 01:34:17 +00001882
John McCall82fe67b2011-07-09 01:37:26 +00001883/// Enter a destroy cleanup for the given local variable.
1884void CodeGenFunction::emitAutoVarTypeCleanup(
1885 const CodeGenFunction::AutoVarEmission &emission,
1886 QualType::DestructionKind dtorKind) {
1887 assert(dtorKind != QualType::DK_none);
1888
1889 // Note that for __block variables, we want to destroy the
1890 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001891 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001892
1893 const VarDecl *var = emission.Variable;
1894 QualType type = var->getType();
1895
1896 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001897 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001898
1899 switch (dtorKind) {
1900 case QualType::DK_none:
1901 llvm_unreachable("no cleanup for trivially-destructible variable");
1902
1903 case QualType::DK_cxx_destructor:
1904 // If there's an NRVO flag on the emission, we need a different
1905 // cleanup.
1906 if (emission.NRVOFlag) {
1907 assert(!type->isArrayType());
1908 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001909 EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, dtor,
1910 emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001911 return;
1912 }
1913 break;
1914
1915 case QualType::DK_objc_strong_lifetime:
1916 // Suppress cleanups for pseudo-strong variables.
1917 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001918
John McCall82fe67b2011-07-09 01:37:26 +00001919 // Otherwise, consider whether to use an EH cleanup or not.
1920 cleanupKind = getARCCleanupKind();
1921
1922 // Use the imprecise destroyer by default.
1923 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1924 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1925 break;
1926
1927 case QualType::DK_objc_weak_lifetime:
1928 break;
Akira Hatanaka7275da02018-02-28 07:15:55 +00001929
1930 case QualType::DK_nontrivial_c_struct:
1931 destroyer = CodeGenFunction::destroyNonTrivialCStruct;
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001932 if (emission.NRVOFlag) {
1933 assert(!type->isArrayType());
1934 EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
1935 emission.NRVOFlag, type);
1936 return;
1937 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00001938 break;
John McCall82fe67b2011-07-09 01:37:26 +00001939 }
1940
1941 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001942 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001943
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001944 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001945 // is being pushed as an EH cleanup.
1946 bool useEHCleanup = (cleanupKind & EHCleanup);
1947 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1948 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001949}
1950
John McCallc533cb72011-02-22 06:44:22 +00001951void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001952 assert(emission.Variable && "emission was not valid!");
1953
John McCallc533cb72011-02-22 06:44:22 +00001954 // If this was emitted as a global constant, we're done.
1955 if (emission.wasEmittedAsGlobal()) return;
1956
John McCall8c38d352012-04-13 18:44:05 +00001957 // If we don't have an insertion point, we're done. Sema prevents
1958 // us from jumping into any of these scopes anyway.
1959 if (!HaveInsertPoint()) return;
1960
John McCall9e2e22f2011-02-22 07:16:58 +00001961 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001962
John McCall82fe67b2011-07-09 01:37:26 +00001963 // Check the type for a cleanup.
1964 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1965 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00001966
John McCall1bd25562011-06-24 23:21:27 +00001967 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001968 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00001969 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1970 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1971 }
1972
John McCallc533cb72011-02-22 06:44:22 +00001973 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001974 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001975 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001976
John McCallc533cb72011-02-22 06:44:22 +00001977 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001978 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00001979
John McCalla729c622012-02-17 03:33:10 +00001980 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00001981 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001982 }
Mike Stump626aecc2009-03-05 01:23:13 +00001983
John McCallc533cb72011-02-22 06:44:22 +00001984 // If this is a block variable, call _Block_object_destroy
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001985 // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
1986 // mode.
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001987 if (emission.IsEscapingByRef &&
1988 CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001989 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
1990 if (emission.Variable->getType().isObjCGCWeak())
1991 Flags |= BLOCK_FIELD_IS_WEAK;
1992 enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
Akira Hatanaka9978da32018-08-10 15:09:24 +00001993 /*LoadBlockVarAddr*/ false,
1994 cxxDestructorCanThrow(emission.Variable->getType()));
Akira Hatanakacb6a9332018-07-26 16:51:21 +00001995 }
Chris Lattner03df1222007-06-02 04:53:11 +00001996}
Chris Lattner53621a52007-06-13 20:44:40 +00001997
Peter Collingbourne1425b452012-01-26 03:33:36 +00001998CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00001999CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
2000 switch (kind) {
2001 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00002002 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00002003 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00002004 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00002005 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00002006 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00002007 return destroyARCWeak;
Akira Hatanaka7275da02018-02-28 07:15:55 +00002008 case QualType::DK_nontrivial_c_struct:
2009 return destroyNonTrivialCStruct;
John McCall82fe67b2011-07-09 01:37:26 +00002010 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00002011 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00002012}
2013
John McCall12cc42a2013-02-01 05:11:40 +00002014/// pushEHDestroy - Push the standard destructor for the given type as
2015/// an EH-only cleanup.
2016void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00002017 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00002018 assert(dtorKind && "cannot push destructor for trivial type");
2019 assert(needsEHCleanup(dtorKind));
2020
2021 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
2022}
2023
2024/// pushDestroy - Push the standard destructor for the given type as
2025/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00002026void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00002027 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00002028 assert(dtorKind && "cannot push destructor for trivial type");
2029
2030 CleanupKind cleanupKind = getCleanupKind(dtorKind);
2031 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
2032 cleanupKind & EHCleanup);
2033}
2034
John McCall7f416cc2015-09-08 08:05:57 +00002035void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002036 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00002037 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00002038 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
2039 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00002040}
2041
John McCall7f416cc2015-09-08 08:05:57 +00002042void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002043 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
2044}
2045
Richard Smith736a9472013-06-12 20:42:33 +00002046void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00002047 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00002048 Destroyer *destroyer, bool useEHCleanupForArray) {
Richard Smith736a9472013-06-12 20:42:33 +00002049 // Push an EH-only cleanup for the object now.
2050 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
2051 // around in case a temporary's destructor throws an exception.
2052 if (cleanupKind & EHCleanup)
2053 EHStack.pushCleanup<DestroyObject>(
2054 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
2055 destroyer, useEHCleanupForArray);
2056
2057 // Remember that we need to push a full cleanup for the object at the
2058 // end of the full-expression.
2059 pushCleanupAfterFullExpr<DestroyObject>(
2060 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
2061}
2062
John McCall178360e2011-07-11 08:38:19 +00002063/// emitDestroy - Immediately perform the destruction of the given
2064/// object.
2065///
2066/// \param addr - the address of the object; a type*
2067/// \param type - the type of the object; if an array type, all
2068/// objects are destroyed in reverse order
2069/// \param destroyer - the function to call to destroy individual
2070/// elements
2071/// \param useEHCleanupForArray - whether an EH cleanup should be
2072/// used when destroying array elements, in case one of the
2073/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00002074void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002075 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00002076 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00002077 const ArrayType *arrayType = getContext().getAsArrayType(type);
2078 if (!arrayType)
2079 return destroyer(*this, addr, type);
2080
John McCall7f416cc2015-09-08 08:05:57 +00002081 llvm::Value *length = emitArrayLength(arrayType, type, addr);
2082
2083 CharUnits elementAlign =
2084 addr.getAlignment()
2085 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00002086
2087 // Normally we have to check whether the array is zero-length.
2088 bool checkZeroLength = true;
2089
2090 // But if the array length is constant, we can suppress that.
2091 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
2092 // ...and if it's constant zero, we can just skip the entire thing.
2093 if (constLength->isZero()) return;
2094 checkZeroLength = false;
2095 }
2096
John McCall7f416cc2015-09-08 08:05:57 +00002097 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00002098 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00002099 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00002100 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00002101}
2102
John McCall178360e2011-07-11 08:38:19 +00002103/// emitArrayDestroy - Destroys all the elements of the given array,
2104/// beginning from last to first. The array cannot be zero-length.
2105///
2106/// \param begin - a type* denoting the first element of the array
2107/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00002108/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00002109/// \param destroyer - the function to call to destroy elements
2110/// \param useEHCleanup - whether to push an EH cleanup to destroy
2111/// the remaining elements in case the destruction of a single
2112/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00002113void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2114 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00002115 QualType elementType,
2116 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002117 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00002118 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00002119 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00002120 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00002121
2122 // The basic structure here is a do-while loop, because we don't
2123 // need to check for the zero-element case.
2124 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
2125 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
2126
John McCall97eab0a2011-07-13 08:09:46 +00002127 if (checkZeroLength) {
2128 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
2129 "arraydestroy.isempty");
2130 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
2131 }
2132
John McCall82fe67b2011-07-09 01:37:26 +00002133 // Enter the loop body, making that address the current address.
2134 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2135 EmitBlock(bodyBB);
2136 llvm::PHINode *elementPast =
2137 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
2138 elementPast->addIncoming(end, entryBB);
2139
2140 // Shift the address back by one element.
2141 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
2142 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
2143 "arraydestroy.element");
2144
John McCall178360e2011-07-11 08:38:19 +00002145 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00002146 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
2147 destroyer);
John McCall178360e2011-07-11 08:38:19 +00002148
John McCall82fe67b2011-07-09 01:37:26 +00002149 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00002150 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00002151
John McCall178360e2011-07-11 08:38:19 +00002152 if (useEHCleanup)
2153 PopCleanupBlock();
2154
John McCall82fe67b2011-07-09 01:37:26 +00002155 // Check whether we've reached the end.
2156 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
2157 Builder.CreateCondBr(done, doneBB, bodyBB);
2158 elementPast->addIncoming(element, Builder.GetInsertBlock());
2159
2160 // Done.
2161 EmitBlock(doneBB);
2162}
2163
John McCall178360e2011-07-11 08:38:19 +00002164/// Perform partial array destruction as if in an EH cleanup. Unlike
2165/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00002166static void emitPartialArrayDestroy(CodeGenFunction &CGF,
2167 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00002168 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002169 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00002170 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00002171 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00002172 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
2173 // VLAs don't require a GEP index to walk into.
2174 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00002175 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00002176 type = arrayType->getElementType();
2177 }
John McCall97eab0a2011-07-13 08:09:46 +00002178
2179 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00002180 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00002181
John McCallf0f0b7a2015-09-14 18:57:08 +00002182 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00002183 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
2184 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00002185 }
2186
John McCall97eab0a2011-07-13 08:09:46 +00002187 // Destroy the array. We don't ever need an EH cleanup because we
2188 // assume that we're in an EH cleanup ourselves, so a throwing
2189 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00002190 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00002191 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00002192}
2193
John McCall82fe67b2011-07-09 01:37:26 +00002194namespace {
John McCall178360e2011-07-11 08:38:19 +00002195 /// RegularPartialArrayDestroy - a cleanup which performs a partial
2196 /// array destroy where the end pointer is regularly determined and
2197 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00002198 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00002199 llvm::Value *ArrayBegin;
2200 llvm::Value *ArrayEnd;
2201 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00002202 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00002203 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00002204 public:
2205 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002206 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00002207 CodeGenFunction::Destroyer *destroyer)
2208 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00002209 ElementType(elementType), Destroyer(destroyer),
2210 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00002211
Craig Topper4f12f102014-03-12 06:41:41 +00002212 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00002213 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002214 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00002215 }
2216 };
2217
2218 /// IrregularPartialArrayDestroy - a cleanup which performs a
2219 /// partial array destroy where the end pointer is irregularly
2220 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00002221 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00002222 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00002223 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00002224 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00002225 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00002226 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00002227 public:
John McCall178360e2011-07-11 08:38:19 +00002228 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00002229 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00002230 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00002231 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00002232 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00002233 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00002234 ElementType(elementType), Destroyer(destroyer),
2235 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00002236
Craig Topper4f12f102014-03-12 06:41:41 +00002237 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00002238 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00002239 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002240 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00002241 }
2242 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002243} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00002244
John McCall178360e2011-07-11 08:38:19 +00002245/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00002246/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00002247/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00002248///
John McCall82fe67b2011-07-09 01:37:26 +00002249/// \param elementType - the immediate element type of the array;
2250/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00002251void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00002252 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00002253 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00002254 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002255 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00002256 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
2257 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00002258 elementType, elementAlign,
2259 destroyer);
John McCall178360e2011-07-11 08:38:19 +00002260}
2261
2262/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2263/// already-constructed elements of the given array. The cleanup
2264/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00002265///
John McCall178360e2011-07-11 08:38:19 +00002266/// \param elementType - the immediate element type of the array;
2267/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00002268void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2269 llvm::Value *arrayEnd,
2270 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00002271 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002272 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00002273 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00002274 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002275 elementType, elementAlign,
2276 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00002277}
2278
Nadav Rotem1da30942013-03-23 06:43:35 +00002279/// Lazily declare the @llvm.lifetime.start intrinsic.
James Y Knight76f78742019-02-05 19:17:50 +00002280llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00002281 if (LifetimeStartFn)
2282 return LifetimeStartFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00002283 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00002284 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00002285 return LifetimeStartFn;
2286}
2287
2288/// Lazily declare the @llvm.lifetime.end intrinsic.
James Y Knight76f78742019-02-05 19:17:50 +00002289llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00002290 if (LifetimeEndFn)
2291 return LifetimeEndFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00002292 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00002293 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00002294 return LifetimeEndFn;
2295}
2296
John McCall31168b02011-06-15 23:02:42 +00002297namespace {
2298 /// A cleanup to perform a release of an object at the end of a
2299 /// function. This is used to balance out the incoming +1 of a
2300 /// ns_consumed argument when we can't reasonably do that just by
2301 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00002302 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00002303 ConsumeARCParameter(llvm::Value *param,
2304 ARCPreciseLifetime_t precise)
2305 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00002306
2307 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00002308 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00002309
Craig Topper4f12f102014-03-12 06:41:41 +00002310 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00002311 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00002312 }
2313 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002314} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00002315
Mike Stump11289f42009-09-09 15:08:12 +00002316/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00002317/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00002318void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2319 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00002320 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00002321 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00002322 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00002323
John McCall7f416cc2015-09-08 08:05:57 +00002324 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00002325
Adrian Prantl51936dd2013-03-14 17:53:33 +00002326 QualType Ty = D.getType();
2327
John McCall147d0212011-02-22 22:38:33 +00002328 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00002329 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00002330 // The only implicit argument a block has is its literal.
Saleem Abdulrasoolc1b46382018-02-21 21:47:51 +00002331 // This may be passed as an inalloca'ed value on Windows x86.
John McCall147d0212011-02-22 22:38:33 +00002332 if (BlockInfo) {
Saleem Abdulrasoolc1b46382018-02-21 21:47:51 +00002333 llvm::Value *V = Arg.isIndirect()
2334 ? Builder.CreateLoad(Arg.getIndirectAddress())
2335 : Arg.getDirectValue();
2336 setBlockContextParameter(IPD, ArgNo, V);
John McCall147d0212011-02-22 22:38:33 +00002337 return;
2338 }
2339 }
2340
John McCall7f416cc2015-09-08 08:05:57 +00002341 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002342 bool DoStore = false;
2343 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002344 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002345 if (Arg.isIndirect()) {
2346 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00002347 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00002348 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00002349 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00002350 if (DeclPtr.getType() != IRTy)
2351 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
Yaxun Liu5b330e82018-03-15 15:25:19 +00002352 // Indirect argument is in alloca address space, which may be different
2353 // from the default address space.
2354 auto AllocaAS = CGM.getASTAllocaAddressSpace();
2355 auto *V = DeclPtr.getPointer();
2356 auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2357 auto DestLangAS =
2358 getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
2359 if (SrcLangAS != DestLangAS) {
2360 assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2361 CGM.getDataLayout().getAllocaAddrSpace());
2362 auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2363 auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
2364 DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
2365 *this, V, SrcLangAS, DestLangAS, T, true),
2366 DeclPtr.getAlignment());
2367 }
John McCall7f416cc2015-09-08 08:05:57 +00002368
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002369 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00002370 // Don't push a cleanup in a thunk for a method that will also emit a
2371 // cleanup.
Akira Hatanaka85282972018-05-15 21:00:30 +00002372 if (hasAggregateEvaluationKind(Ty) && !CurFuncIsThunk &&
2373 Ty->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
Akira Hatanaka7275da02018-02-28 07:15:55 +00002374 if (QualType::DestructionKind DtorKind = Ty.isDestructedType()) {
2375 assert((DtorKind == QualType::DK_cxx_destructor ||
2376 DtorKind == QualType::DK_nontrivial_c_struct) &&
2377 "unexpected destructor type");
2378 pushDestroy(DtorKind, DeclPtr, Ty);
Akira Hatanakaccda3d22018-04-27 06:57:00 +00002379 CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2380 EHStack.stable_begin();
Akira Hatanaka7275da02018-02-28 07:15:55 +00002381 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002382 }
Chris Lattner53621a52007-06-13 20:44:40 +00002383 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002384 // Check if the parameter address is controlled by OpenMP runtime.
2385 Address OpenMPLocalAddr =
2386 getLangOpts().OpenMP
2387 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
2388 : Address::invalid();
2389 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2390 DeclPtr = OpenMPLocalAddr;
2391 } else {
2392 // Otherwise, create a temporary to hold the value.
2393 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2394 D.getName() + ".addr");
2395 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002396 DoStore = true;
2397 }
Mike Stump11289f42009-09-09 15:08:12 +00002398
John McCall7f416cc2015-09-08 08:05:57 +00002399 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2400
2401 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002402 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00002403 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00002404 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2405 // We honor __attribute__((ns_consumed)) for types with lifetime.
2406 // For __strong, it's handled by just skipping the initial retain;
2407 // otherwise we have to balance out the initial +1 with an extra
2408 // cleanup to do the release at the end of the function.
2409 bool isConsumed = D.hasAttr<NSConsumedAttr>();
2410
Erik Pilkington1e368822019-01-04 18:33:06 +00002411 // If a parameter is pseudo-strong then we can omit the implicit retain.
John McCalld4631322011-06-17 06:42:21 +00002412 if (D.isARCPseudoStrong()) {
Erik Pilkington1e368822019-01-04 18:33:06 +00002413 assert(lt == Qualifiers::OCL_Strong &&
2414 "pseudo-strong variable isn't strong?");
2415 assert(qs.hasConst() && "pseudo-strong variable should be const!");
John McCall31168b02011-06-15 23:02:42 +00002416 lt = Qualifiers::OCL_ExplicitNone;
2417 }
2418
Saleem Abdulrasoolda6784e2017-06-27 18:37:51 +00002419 // Load objects passed indirectly.
2420 if (Arg.isIndirect() && !ArgVal)
2421 ArgVal = Builder.CreateLoad(DeclPtr);
2422
John McCall31168b02011-06-15 23:02:42 +00002423 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002424 if (!isConsumed) {
2425 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2426 // use objc_storeStrong(&dest, value) for retaining the
2427 // object. But first, store a null into 'dest' because
2428 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002429 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002430 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
John McCall7f416cc2015-09-08 08:05:57 +00002431 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002432 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002433 }
2434 else
John McCall31168b02011-06-15 23:02:42 +00002435 // Don't use objc_retainBlock for block pointers, because we
2436 // don't want to Block_copy something just because we got it
2437 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00002438 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002439 }
John McCall31168b02011-06-15 23:02:42 +00002440 } else {
2441 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00002442 if (isConsumed) {
2443 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2444 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00002445 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00002446 precise);
2447 }
John McCall31168b02011-06-15 23:02:42 +00002448
2449 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00002450 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002451 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00002452 }
2453 }
2454
2455 // Enter the cleanup scope.
2456 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2457 }
Chris Lattner53621a52007-06-13 20:44:40 +00002458 }
2459
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002460 // Store the initial value into the alloca.
2461 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00002462 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002463
John McCall7f416cc2015-09-08 08:05:57 +00002464 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00002465
2466 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00002467 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002468 if (CGM.getCodeGenOpts().getDebugInfo() >=
2469 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002470 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00002471 }
2472 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002473
2474 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002475 EmitVarAnnotations(&D, DeclPtr.getPointer());
Vedant Kumar42c17ec2017-03-14 01:56:34 +00002476
2477 // We can only check return value nullability if all arguments to the
2478 // function satisfy their nullability preconditions. This makes it necessary
2479 // to emit null checks for args in the function body itself.
2480 if (requiresReturnValueNullabilityCheck()) {
2481 auto Nullability = Ty->getNullability(getContext());
2482 if (Nullability && *Nullability == NullabilityKind::NonNull) {
2483 SanitizerScope SanScope(this);
2484 RetValNullabilityPrecondition =
2485 Builder.CreateAnd(RetValNullabilityPrecondition,
2486 Builder.CreateIsNotNull(Arg.getAnyValue()));
2487 }
2488 }
Chris Lattner53621a52007-06-13 20:44:40 +00002489}
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002490
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002491void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2492 CodeGenFunction *CGF) {
2493 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2494 return;
2495 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2496}
Kelvin Li1408f912018-09-26 04:28:39 +00002497
Michael Kruse251e1482019-02-01 20:25:04 +00002498void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
2499 CodeGenFunction *CGF) {
2500 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2501 return;
2502 // FIXME: need to implement mapper code generation
2503}
2504
Kelvin Li1408f912018-09-26 04:28:39 +00002505void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
Alexey Bataev982a35e2019-03-19 17:09:52 +00002506 getOpenMPRuntime().checkArchForUnifiedAddressing(D);
Kelvin Li1408f912018-09-26 04:28:39 +00002507}