blob: 80bdedebbcdc7080c78c458a4f31db7bd789257f [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"
Yaxun Liu6d96f1632017-05-18 18:51:09 +000022#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000023#include "clang/AST/ASTContext.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000024#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000025#include "clang/AST/Decl.h"
Anders Carlsson4c03d982008-08-25 01:38:19 +000026#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000027#include "clang/AST/DeclOpenMP.h"
Richard Trieu63688182018-12-11 03:18:39 +000028#include "clang/Basic/CodeGenOptions.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000029#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000030#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000031#include "clang/CodeGen/CGFunctionInfo.h"
JF Bastien2f0582f2018-09-21 13:54:09 +000032#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/GlobalVariable.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/Type.h"
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +000037
Chris Lattner84915fa2007-06-02 04:16:21 +000038using namespace clang;
39using namespace CodeGen;
40
Chris Lattner1ad38f82007-06-09 01:20:56 +000041void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000042 switch (D.getKind()) {
David Majnemerd9b1a4f2015-11-04 03:40:30 +000043 case Decl::BuiltinTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000044 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +000045 case Decl::ExternCContext:
Douglas Gregor19043f02010-04-23 02:02:43 +000046 case Decl::Namespace:
47 case Decl::UnresolvedUsingTypename:
48 case Decl::ClassTemplateSpecialization:
49 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000050 case Decl::VarTemplateSpecialization:
51 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000052 case Decl::TemplateTypeParm:
53 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000054 case Decl::NonTypeTemplateParm:
Richard Smithbc491202017-02-17 20:05:37 +000055 case Decl::CXXDeductionGuide:
Douglas Gregor19043f02010-04-23 02:02:43 +000056 case Decl::CXXMethod:
57 case Decl::CXXConstructor:
58 case Decl::CXXDestructor:
59 case Decl::CXXConversion:
60 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000061 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000062 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000063 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000064 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000065 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000066 case Decl::ImplicitParam:
67 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000068 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000069 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000070 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000071 case Decl::TemplateTemplateParm:
72 case Decl::ObjCMethod:
73 case Decl::ObjCCategory:
74 case Decl::ObjCProtocol:
75 case Decl::ObjCInterface:
76 case Decl::ObjCCategoryImpl:
77 case Decl::ObjCImplementation:
78 case Decl::ObjCProperty:
79 case Decl::ObjCCompatibleAlias:
Nico Weber66220292016-03-02 17:28:48 +000080 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +000081 case Decl::PragmaDetectMismatch:
Abramo Bagnarad7340582010-06-05 05:09:32 +000082 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000083 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +000084 case Decl::Export:
Douglas Gregor19043f02010-04-23 02:02:43 +000085 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000086 case Decl::FileScopeAsm:
87 case Decl::Friend:
88 case Decl::FriendTemplate:
89 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000090 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000091 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000092 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +000093 case Decl::ConstructorUsingShadow:
Douglas Gregor85f3f952015-07-07 03:57:15 +000094 case Decl::ObjCTypeParam:
Richard Smithda383632016-08-15 01:33:41 +000095 case Decl::Binding:
David Blaikie83d382b2011-09-23 05:06:16 +000096 llvm_unreachable("Declaration should not be in declstmts!");
Amjad Abouddc4531e2016-04-30 01:44:38 +000097 case Decl::Function: // void X();
98 case Decl::Record: // struct/union/class X;
99 case Decl::Enum: // enum X;
100 case Decl::EnumConstant: // enum ? { X = ? }
101 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +0000102 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +0000103 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +0000104 case Decl::Import:
Alexey Bataeva769e072013-03-22 06:34:35 +0000105 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000106 case Decl::OMPAllocate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000107 case Decl::OMPCapturedExpr:
Kelvin Li1408f912018-09-26 04:28:39 +0000108 case Decl::OMPRequires:
Michael Han84324352013-02-22 17:15:32 +0000109 case Decl::Empty:
Chris Lattner84915fa2007-06-02 04:16:21 +0000110 // None of these decls require codegen support.
111 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +0000112
David Blaikief121b932013-05-20 22:50:41 +0000113 case Decl::NamespaceAlias:
114 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000115 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
David Blaikief121b932013-05-20 22:50:41 +0000116 return;
David Blaikiebd483762013-05-20 04:58:53 +0000117 case Decl::Using: // using X; [C++]
118 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000119 DI->EmitUsingDecl(cast<UsingDecl>(D));
David Blaikiebd483762013-05-20 04:58:53 +0000120 return;
Richard Smith151c4562016-12-20 21:35:28 +0000121 case Decl::UsingPack:
122 for (auto *Using : cast<UsingPackDecl>(D).expansions())
123 EmitDecl(*Using);
124 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000125 case Decl::UsingDirective: // using namespace X; [C++]
126 if (CGDebugInfo *DI = getDebugInfo())
127 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
128 return;
Richard Smithbdb84f32016-07-22 23:36:59 +0000129 case Decl::Var:
130 case Decl::Decomposition: {
Daniel Dunbara7998072008-08-29 17:28:43 +0000131 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000132 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000133 "Should not see file-scope variables inside a function!");
Richard Smithda383632016-08-15 01:33:41 +0000134 EmitVarDecl(VD);
135 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
136 for (auto *B : DD->bindings())
137 if (auto *HD = B->getHoldingVar())
138 EmitVarDecl(*HD);
139 return;
Chris Lattner84915fa2007-06-02 04:16:21 +0000140 }
Mike Stump11289f42009-09-09 15:08:12 +0000141
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000142 case Decl::OMPDeclareReduction:
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000143 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000144
Michael Kruse251e1482019-02-01 20:25:04 +0000145 case Decl::OMPDeclareMapper:
146 return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
147
Richard Smithdda56e42011-04-15 14:24:37 +0000148 case Decl::Typedef: // typedef int X;
149 case Decl::TypeAlias: { // using X = int; [C++0x]
150 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000151 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000152
Anders Carlsson5d985f52008-12-20 21:51:53 +0000153 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000154 EmitVariablyModifiedType(Ty);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000155 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000156 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000157}
Chris Lattner03df1222007-06-02 04:53:11 +0000158
John McCall1c9c3fd2010-10-15 04:57:14 +0000159/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000160/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000161void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Yaxun Liu4f33b3d2017-05-15 14:47:47 +0000162 if (D.hasExternalStorage())
163 // Don't emit it now, allow it to be emitted lazily on its first use.
164 return;
165
166 // Some function-scope variable does not have static storage but still
167 // needs to be emitted like a static variable, e.g. a function-scope
168 // variable in constant address space in OpenCL.
169 if (D.getStorageDuration() != SD_Automatic) {
Alexey Baderbed40092017-11-15 11:38:17 +0000170 // Static sampler variables translated to function calls.
171 if (D.getType()->isSamplerT())
172 return;
173
Eric Christopher31ab1302011-08-23 22:38:00 +0000174 llvm::GlobalValue::LinkageTypes Linkage =
David Majnemer27d69db2014-04-28 22:17:59 +0000175 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000176
David Majnemer27d69db2014-04-28 22:17:59 +0000177 // FIXME: We need to force the emission/use of a guard variable for
178 // some variables even if we can constant-evaluate them because
179 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000180
John McCall1c9c3fd2010-10-15 04:57:14 +0000181 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000182 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000183
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000184 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000185 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
186
187 assert(D.hasLocalStorage());
188 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000189}
190
Reid Kleckner453e0562014-10-08 01:07:54 +0000191static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
192 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000193 return CGM.getMangledName(&D).str();
194
Reid Kleckner453e0562014-10-08 01:07:54 +0000195 // If this isn't C++, we don't need a mangled name, just a pretty one.
196 assert(!D.isExternallyVisible() && "name shouldn't matter");
197 std::string ContextName;
198 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000199 if (auto *CD = dyn_cast<CapturedDecl>(DC))
200 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000201 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000202 ContextName = CGM.getMangledName(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000203 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
204 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD);
205 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
206 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000207 else
David Blaikie83d382b2011-09-23 05:06:16 +0000208 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000209
Reid Kleckner453e0562014-10-08 01:07:54 +0000210 ContextName += "." + D.getNameAsString();
211 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000212}
213
Reid Kleckner453e0562014-10-08 01:07:54 +0000214llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
215 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
216 // In general, we don't always emit static var decls once before we reference
217 // them. It is possible to reference them before emitting the function that
218 // contains them, and it is possible to emit the containing function multiple
219 // times.
220 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
221 return ExistingGV;
222
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000223 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000224 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000225
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000226 // Use the label if the variable is renamed with the asm-label extension.
227 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000228 if (D.hasAttr<AsmLabelAttr>())
Reid Kleckner453e0562014-10-08 01:07:54 +0000229 Name = getMangledName(&D);
Benjamin Kramer5642e192011-11-21 15:47:23 +0000230 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000231 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000232
Reid Kleckner453e0562014-10-08 01:07:54 +0000233 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Alexander Richardson6d989432017-10-15 18:48:14 +0000234 LangAS AS = GetGlobalVarAddressSpace(&D);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000235 unsigned TargetAS = getContext().getTargetAddressSpace(AS);
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000236
Yaxun Liua64a4912018-04-02 17:38:24 +0000237 // OpenCL variables in local address space and CUDA shared
238 // variables cannot have an initializer.
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000239 llvm::Constant *Init = nullptr;
Yaxun Liua64a4912018-04-02 17:38:24 +0000240 if (Ty.getAddressSpace() == LangAS::opencl_local ||
241 D.hasAttr<CUDASharedAttr>())
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000242 Init = llvm::UndefValue::get(LTy);
Yaxun Liua64a4912018-04-02 17:38:24 +0000243 else
244 Init = EmitNullConstant(Ty);
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000245
Yaxun Liucbf647c2017-07-08 13:24:52 +0000246 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
247 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
248 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
Ken Dyck160146e2010-01-27 17:10:57 +0000249 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000250
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000251 if (supportsCOMDAT() && GV->isWeakForLinker())
252 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000253
Richard Smithfd3834f2013-04-13 02:43:54 +0000254 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000255 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000256
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000257 setGVProperties(GV, &D);
258
Eli Benderskycb399432014-03-24 22:05:38 +0000259 // Make sure the result is of the correct type.
Alexander Richardson6d989432017-10-15 18:48:14 +0000260 LangAS ExpectedAS = Ty.getAddressSpace();
Reid Kleckner453e0562014-10-08 01:07:54 +0000261 llvm::Constant *Addr = GV;
Yaxun Liucbf647c2017-07-08 13:24:52 +0000262 if (AS != ExpectedAS) {
263 Addr = getTargetCodeGenInfo().performAddrSpaceCast(
264 *this, GV, AS, ExpectedAS,
265 LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
Eli Benderskycb399432014-03-24 22:05:38 +0000266 }
267
Reid Kleckner453e0562014-10-08 01:07:54 +0000268 setStaticLocalDeclAddress(&D, Addr);
269
270 // Ensure that the static local gets initialized by making sure the parent
271 // function gets emitted eventually.
272 const Decl *DC = cast<Decl>(D.getDeclContext());
273
274 // We can't name blocks or captured statements directly, so try to emit their
275 // parents.
276 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
277 DC = DC->getNonClosureContext();
278 // FIXME: Ensure that global blocks get emitted.
279 if (!DC)
280 return Addr;
281 }
282
283 GlobalDecl GD;
284 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
285 GD = GlobalDecl(CD, Ctor_Base);
286 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
287 GD = GlobalDecl(DD, Dtor_Base);
288 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
289 GD = GlobalDecl(FD);
290 else {
291 // Don't do anything for Obj-C method decls or global closures. We should
292 // never defer them.
293 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
294 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +0000295 if (GD.getDecl()) {
296 // Disable emission of the parent function for the OpenMP device codegen.
297 CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
Reid Kleckner453e0562014-10-08 01:07:54 +0000298 (void)GetAddrOfGlobal(GD);
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +0000299 }
Reid Kleckner453e0562014-10-08 01:07:54 +0000300
301 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000302}
303
Richard Smith6331c402012-02-13 22:16:19 +0000304/// hasNontrivialDestruction - Determine whether a type's destruction is
305/// non-trivial. If so, and the variable uses static initialization, we must
306/// register its destructor to run on exit.
307static bool hasNontrivialDestruction(QualType T) {
308 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
309 return RD && !RD->hasTrivialDestructor();
310}
311
Chandler Carruth84537952012-03-30 19:44:53 +0000312/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
313/// global variable that has already been created for it. If the initializer
314/// has a different type than GV does, this may free GV and return a different
315/// one. Otherwise it just returns GV.
316llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000317CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000318 llvm::GlobalVariable *GV) {
John McCallde0fe072017-08-15 21:42:52 +0000319 ConstantEmitter emitter(*this);
320 llvm::Constant *Init = emitter.tryEmitForInitializer(D);
John McCall70013b62010-07-15 23:40:35 +0000321
Chris Lattnere99c1102009-12-05 08:22:11 +0000322 // If constant emission failed, then this should be a C++ static
323 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000324 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000325 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000326 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
Matthias Braun44bfe032017-01-10 17:43:01 +0000327 else if (HaveInsertPoint()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000328 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000329 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000330 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000331
Chandler Carruth84537952012-03-30 19:44:53 +0000332 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000333 }
Chandler Carruth84537952012-03-30 19:44:53 +0000334 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000335 }
John McCall70013b62010-07-15 23:40:35 +0000336
Chris Lattnere99c1102009-12-05 08:22:11 +0000337 // The initializer may differ in type from the global. Rewrite
338 // the global to match the initializer. (We have to do this
339 // because some types, like unions, can't be completely represented
340 // in the LLVM type system.)
Chandler Carruth84537952012-03-30 19:44:53 +0000341 if (GV->getType()->getElementType() != Init->getType()) {
342 llvm::GlobalVariable *OldGV = GV;
343
344 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
345 OldGV->isConstant(),
346 OldGV->getLinkage(), Init, "",
347 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000348 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000349 CGM.getContext().getTargetAddressSpace(D.getType()));
350 GV->setVisibility(OldGV->getVisibility());
Rafael Espindola699f5d62018-02-07 22:15:33 +0000351 GV->setDSOLocal(OldGV->isDSOLocal());
Reid Klecknereab97d32015-07-20 20:35:30 +0000352 GV->setComdat(OldGV->getComdat());
Eric Christopher31ab1302011-08-23 22:38:00 +0000353
Chris Lattnere99c1102009-12-05 08:22:11 +0000354 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000355 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000356
Chris Lattnere99c1102009-12-05 08:22:11 +0000357 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000358 llvm::Constant *NewPtrForOldDecl =
359 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
360 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000361
Chris Lattnere99c1102009-12-05 08:22:11 +0000362 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000363 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000364 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000365
Chandler Carruth84537952012-03-30 19:44:53 +0000366 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
367 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000368
John McCallde0fe072017-08-15 21:42:52 +0000369 emitter.finalize(GV);
370
Matthias Braun44bfe032017-01-10 17:43:01 +0000371 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) {
Richard Smith6331c402012-02-13 22:16:19 +0000372 // We have a constant initializer, but a nontrivial destructor. We still
373 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000374 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000375 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000376 }
377
Chandler Carruth84537952012-03-30 19:44:53 +0000378 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000379}
380
John McCall1c9c3fd2010-10-15 04:57:14 +0000381void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000382 llvm::GlobalValue::LinkageTypes Linkage) {
John McCallb88a5662012-03-30 21:00:39 +0000383 // Check to see if we already have a global variable for this
384 // declaration. This can happen when double-emitting function
385 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000386 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
John McCall7f416cc2015-09-08 08:05:57 +0000387 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara374e602009-02-25 19:45:19 +0000388
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000389 // Store into LocalDeclMap before generating initializer to handle
390 // circular references.
John McCall7f416cc2015-09-08 08:05:57 +0000391 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000392
John McCall4a39ab82010-05-04 20:45:42 +0000393 // We can't have a VLA here, but we can have a pointer to a VLA,
394 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000395 // Make sure to evaluate VLA bounds now so that we have them for later.
396 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000397 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000398
John McCallb88a5662012-03-30 21:00:39 +0000399 // Save the type in case adding the initializer forces a type change.
400 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000401
Eli Benderskycb399432014-03-24 22:05:38 +0000402 llvm::GlobalVariable *var =
403 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Artem Belevich4d430ba2016-05-09 22:09:56 +0000404
405 // CUDA's local and local static __shared__ variables should not
406 // have any non-empty initializers. This is ensured by Sema.
407 // Whatever initializer such variable may have when it gets here is
408 // a no-op and should not be emitted.
409 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
410 D.hasAttr<CUDASharedAttr>();
Chris Lattnere99c1102009-12-05 08:22:11 +0000411 // If this value has an initializer, emit it.
Artem Belevich4d430ba2016-05-09 22:09:56 +0000412 if (D.getInit() && !isCudaSharedVar)
John McCallb88a5662012-03-30 21:00:39 +0000413 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000414
John McCall7f416cc2015-09-08 08:05:57 +0000415 var->setAlignment(alignment.getQuantity());
Chris Lattner4d941092010-03-10 23:59:59 +0000416
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000417 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000418 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000419
Javed Absar2a67c9e2017-06-05 10:11:57 +0000420 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
421 var->addAttribute("bss-section", SA->getName());
422 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
423 var->addAttribute("data-section", SA->getName());
424 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
425 var->addAttribute("rodata-section", SA->getName());
426
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000427 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000428 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000429
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000430 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000431 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000432
Chandler Carruth84537952012-03-30 19:44:53 +0000433 // We may have to cast the constant because of the initializer
434 // mismatch above.
435 //
436 // FIXME: It is really dangerous to store this in the map; if anyone
437 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000438 llvm::Constant *castedAddr =
439 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCall7f416cc2015-09-08 08:05:57 +0000440 if (var != castedAddr)
441 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCallb88a5662012-03-30 21:00:39 +0000442 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000443
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000444 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000445
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000446 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000447 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov74a38682012-05-04 07:39:27 +0000448 if (DI &&
Benjamin Kramer8c305922016-02-02 11:06:51 +0000449 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000450 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000451 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000452 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000453}
Mike Stump11289f42009-09-09 15:08:12 +0000454
John McCall2b7fc382010-07-13 20:32:21 +0000455namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000456 struct DestroyObject final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000457 DestroyObject(Address addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000458 CodeGenFunction::Destroyer *destroyer,
459 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000460 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000461 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000462
John McCall7f416cc2015-09-08 08:05:57 +0000463 Address addr;
John McCall82fe67b2011-07-09 01:37:26 +0000464 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000465 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000466 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000467
Craig Topper4f12f102014-03-12 06:41:41 +0000468 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000469 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000470 bool useEHCleanupForArray =
471 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000472
473 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000474 }
475 };
476
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000477 template <class Derived>
478 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
479 DestroyNRVOVariable(Address addr, llvm::Value *NRVOFlag)
480 : NRVOFlag(NRVOFlag), Loc(addr) {}
John McCall2b7fc382010-07-13 20:32:21 +0000481
John McCall2b7fc382010-07-13 20:32:21 +0000482 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000483 Address Loc;
John McCall2b7fc382010-07-13 20:32:21 +0000484
Craig Topper4f12f102014-03-12 06:41:41 +0000485 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000486 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000487 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000488
Craig Topper8a13c412014-05-21 05:09:00 +0000489 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000490 if (NRVO) {
491 // If we exited via NRVO, we skip the destructor call.
492 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
493 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000494 llvm::Value *DidNRVO =
495 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000496 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
497 CGF.EmitBlock(RunDtorBB);
498 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000499
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000500 static_cast<Derived *>(this)->emitDestructorCall(CGF);
John McCall2b7fc382010-07-13 20:32:21 +0000501
502 if (NRVO) CGF.EmitBlock(SkipDtorBB);
503 }
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000504
505 virtual ~DestroyNRVOVariable() = default;
506 };
507
508 struct DestroyNRVOVariableCXX final
509 : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
510 DestroyNRVOVariableCXX(Address addr, const CXXDestructorDecl *Dtor,
511 llvm::Value *NRVOFlag)
512 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, NRVOFlag),
513 Dtor(Dtor) {}
514
515 const CXXDestructorDecl *Dtor;
516
517 void emitDestructorCall(CodeGenFunction &CGF) {
518 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
519 /*ForVirtualBase=*/false,
520 /*Delegating=*/false, Loc);
521 }
522 };
523
524 struct DestroyNRVOVariableC final
525 : DestroyNRVOVariable<DestroyNRVOVariableC> {
526 DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
527 : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, NRVOFlag), Ty(Ty) {}
528
529 QualType Ty;
530
531 void emitDestructorCall(CodeGenFunction &CGF) {
532 CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
533 }
John McCall2b7fc382010-07-13 20:32:21 +0000534 };
John McCall2b7fc382010-07-13 20:32:21 +0000535
David Blaikie7e70d682015-08-18 22:40:54 +0000536 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000537 Address Stack;
538 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000539 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000540 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
James Y Knight8799cae2019-02-03 21:53:49 +0000541 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
John McCalla464ff92010-07-21 06:13:08 +0000542 CGF.Builder.CreateCall(F, V);
543 }
544 };
545
David Blaikie7e70d682015-08-18 22:40:54 +0000546 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000547 const VarDecl &Var;
548 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
549
Craig Topper4f12f102014-03-12 06:41:41 +0000550 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000551 // Compute the address of the local variable, in case it's a
552 // byref or something.
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000553 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
John McCall113bee02012-03-10 09:33:50 +0000554 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000555 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
556 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000557 CGF.EmitExtendGCLifetime(value);
558 }
559 };
560
David Blaikie7e70d682015-08-18 22:40:54 +0000561 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000562 llvm::Constant *CleanupFn;
563 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000564 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000565
John McCalla464ff92010-07-21 06:13:08 +0000566 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000567 const VarDecl *Var)
568 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000569
Craig Topper4f12f102014-03-12 06:41:41 +0000570 void Emit(CodeGenFunction &CGF, Flags flags) override {
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000571 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
John McCall113bee02012-03-10 09:33:50 +0000572 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000573 // Compute the address of the local variable, in case it's a byref
574 // or something.
John McCall7f416cc2015-09-08 08:05:57 +0000575 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer();
John McCallc533cb72011-02-22 06:44:22 +0000576
John McCalla464ff92010-07-21 06:13:08 +0000577 // In some cases, the type of the function argument will be different from
578 // the type of the pointer. An example of this is
579 // void f(void* arg);
580 // __attribute__((cleanup(f))) void *g;
581 //
582 // To fix this we insert a bitcast here.
583 QualType ArgTy = FnInfo.arg_begin()->type;
584 llvm::Value *Arg =
585 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
586
587 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000588 Args.add(RValue::get(Arg),
589 CGF.getContext().getPointerType(Var.getType()));
John McCallb92ab1a2016-10-26 23:46:34 +0000590 auto Callee = CGCallee::forDirect(CleanupFn);
591 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
John McCalla464ff92010-07-21 06:13:08 +0000592 }
593 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000594} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000595
John McCall31168b02011-06-15 23:02:42 +0000596/// EmitAutoVarWithLifetime - Does the setup required for an automatic
597/// variable with lifetime.
598static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000599 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000600 Qualifiers::ObjCLifetime lifetime) {
601 switch (lifetime) {
602 case Qualifiers::OCL_None:
603 llvm_unreachable("present but none");
604
605 case Qualifiers::OCL_ExplicitNone:
606 // nothing to do
607 break;
608
609 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000610 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000611 (var.hasAttr<ObjCPreciseLifetimeAttr>()
612 ? CodeGenFunction::destroyARCStrongPrecise
613 : CodeGenFunction::destroyARCStrongImprecise);
614
615 CleanupKind cleanupKind = CGF.getARCCleanupKind();
616 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
617 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000618 break;
619 }
620 case Qualifiers::OCL_Autoreleasing:
621 // nothing to do
622 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000623
John McCall31168b02011-06-15 23:02:42 +0000624 case Qualifiers::OCL_Weak:
625 // __weak objects always get EH cleanups; otherwise, exceptions
626 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000627 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
628 CodeGenFunction::destroyARCWeak,
629 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000630 break;
631 }
632}
633
634static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
635 if (const Expr *e = dyn_cast<Expr>(s)) {
636 // Skip the most common kinds of expressions that make
637 // hierarchy-walking expensive.
638 s = e = e->IgnoreParenCasts();
639
640 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
641 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000642 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
643 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000644 for (const auto &I : block->captures()) {
645 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000646 return true;
647 }
648 }
John McCall31168b02011-06-15 23:02:42 +0000649 }
650
Benjamin Kramer642f1732015-07-02 21:03:14 +0000651 for (const Stmt *SubStmt : s->children())
652 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
653 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000654 return true;
655
656 return false;
657}
658
659static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
660 if (!decl) return false;
661 if (!isa<VarDecl>(decl)) return false;
662 const VarDecl *var = cast<VarDecl>(decl);
663 return isAccessedBy(*var, e);
664}
665
John McCallf8a9b662015-10-21 18:06:31 +0000666static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
667 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000668 bool needsCast = false;
669
John McCallf8a9b662015-10-21 18:06:31 +0000670 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
671 switch (castExpr->getCastKind()) {
672 // Look through casts that don't require representation changes.
673 case CK_NoOp:
674 case CK_BitCast:
675 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000676 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000677 break;
678
679 // If we find an l-value to r-value cast from a __weak variable,
680 // emit this operation as a copy or move.
681 case CK_LValueToRValue: {
682 const Expr *srcExpr = castExpr->getSubExpr();
683 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
684 return false;
685
686 // Emit the source l-value.
687 LValue srcLV = CGF.EmitLValue(srcExpr);
688
John McCall0204e342015-11-16 22:11:41 +0000689 // Handle a formal type change to avoid asserting.
690 auto srcAddr = srcLV.getAddress();
691 if (needsCast) {
692 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr,
693 destLV.getAddress().getElementType());
694 }
695
John McCallf8a9b662015-10-21 18:06:31 +0000696 // If it was an l-value, use objc_copyWeak.
697 if (srcExpr->getValueKind() == VK_LValue) {
John McCall0204e342015-11-16 22:11:41 +0000698 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000699 } else {
700 assert(srcExpr->getValueKind() == VK_XValue);
John McCall0204e342015-11-16 22:11:41 +0000701 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000702 }
703 return true;
704 }
705
706 // Stop at anything else.
707 default:
708 return false;
709 }
710
711 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000712 }
713 return false;
714}
715
John McCall1553b192011-06-16 04:16:24 +0000716static void drillIntoBlockVariable(CodeGenFunction &CGF,
717 LValue &lvalue,
718 const VarDecl *var) {
John McCall7f416cc2015-09-08 08:05:57 +0000719 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var));
John McCall1553b192011-06-16 04:16:24 +0000720}
721
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000722void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
723 SourceLocation Loc) {
724 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
725 return;
726
727 auto Nullability = LHS.getType()->getNullability(getContext());
728 if (!Nullability || *Nullability != NullabilityKind::NonNull)
729 return;
730
731 // Check if the right hand side of the assignment is nonnull, if the left
732 // hand side must be nonnull.
733 SanitizerScope SanScope(this);
734 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000735 llvm::Constant *StaticData[] = {
736 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
Simon Pilgrim2df19982017-03-14 21:43:52 +0000737 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
Vedant Kumar2b9f48a2017-03-14 16:48:29 +0000738 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000739 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
740 SanitizerHandler::TypeMismatch, StaticData, RHS);
741}
742
David Blaikie73ca5692014-12-09 00:32:22 +0000743void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000744 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000745 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000746 if (!lifetime) {
747 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000748 if (capturedByInit)
749 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000750 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
David Blaikie66e41972015-01-14 07:38:27 +0000751 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000752 return;
753 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000754
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000755 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
756 init = DIE->getExpr();
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000757
John McCall31168b02011-06-15 23:02:42 +0000758 // If we're emitting a value with lifetime, we have to do the
759 // initialization *before* we leave the cleanup scopes.
Bill Wendling7c44da22018-10-31 03:48:47 +0000760 if (const FullExpr *fe = dyn_cast<FullExpr>(init)) {
761 enterFullExpression(fe);
762 init = fe->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000763 }
764 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000765
766 // We have to maintain the illusion that the variable is
767 // zero-initialized. If the variable might be accessed in its
768 // initializer, zero-initialize before running the initializer, then
769 // actually perform the initialization with an assign.
770 bool accessedByInit = false;
771 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000772 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000773 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000774 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000775 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000776 if (capturedByInit) {
777 // We can use a simple GEP for this because it can't have been
778 // moved yet.
John McCall7f416cc2015-09-08 08:05:57 +0000779 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(),
780 cast<VarDecl>(D),
781 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000782 }
783
John McCall7f416cc2015-09-08 08:05:57 +0000784 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType());
Yaxun Liu402804b2016-12-15 08:09:08 +0000785 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000786
John McCall31168b02011-06-15 23:02:42 +0000787 // If __weak, we want to use a barrier under certain conditions.
788 if (lifetime == Qualifiers::OCL_Weak)
John McCall1553b192011-06-16 04:16:24 +0000789 EmitARCInitWeak(tempLV.getAddress(), zero);
John McCall31168b02011-06-15 23:02:42 +0000790
791 // Otherwise just do a simple store.
792 else
David Chisnallfa35df62012-01-16 17:27:18 +0000793 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000794 }
795
796 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000797 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000798
799 switch (lifetime) {
800 case Qualifiers::OCL_None:
801 llvm_unreachable("present but none");
802
Erik Pilkington1e368822019-01-04 18:33:06 +0000803 case Qualifiers::OCL_Strong: {
804 if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
805 value = EmitARCRetainScalarExpr(init);
806 break;
807 }
808 // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
809 // that we omit the retain, and causes non-autoreleased return values to be
810 // immediately released.
811 LLVM_FALLTHROUGH;
812 }
813
John McCall31168b02011-06-15 23:02:42 +0000814 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000815 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000816 break;
817
John McCall31168b02011-06-15 23:02:42 +0000818 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000819 // If it's not accessed by the initializer, try to emit the
820 // initialization with a copy or move.
821 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
822 return;
823 }
824
John McCall31168b02011-06-15 23:02:42 +0000825 // No way to optimize a producing initializer into this. It's not
826 // worth optimizing for, because the value will immediately
827 // disappear in the common case.
828 value = EmitScalarExpr(init);
829
John McCall1553b192011-06-16 04:16:24 +0000830 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000831 if (accessedByInit)
John McCall1553b192011-06-16 04:16:24 +0000832 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000833 else
John McCall1553b192011-06-16 04:16:24 +0000834 EmitARCInitWeak(lvalue.getAddress(), value);
John McCall31168b02011-06-15 23:02:42 +0000835 return;
836 }
837
838 case Qualifiers::OCL_Autoreleasing:
839 value = EmitARCRetainAutoreleaseScalarExpr(init);
840 break;
841 }
842
John McCall1553b192011-06-16 04:16:24 +0000843 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000844
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000845 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
846
John McCall31168b02011-06-15 23:02:42 +0000847 // If the variable might have been accessed by its initializer, we
848 // might have to initialize with a barrier. We have to do this for
849 // both __weak and __strong, but __weak got filtered out above.
850 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000851 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000852 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000853 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000854 return;
855 }
856
David Chisnallfa35df62012-01-16 17:27:18 +0000857 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000858}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000859
JF Bastiened92f602018-07-20 23:37:12 +0000860/// Decide whether we can emit the non-zero parts of the specified initializer
861/// with equal or fewer than NumStores scalar stores.
862static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
863 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000864 // Zero and Undef never requires any extra stores.
865 if (isa<llvm::ConstantAggregateZero>(Init) ||
866 isa<llvm::ConstantPointerNull>(Init) ||
867 isa<llvm::UndefValue>(Init))
868 return true;
869 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
870 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
871 isa<llvm::ConstantExpr>(Init))
872 return Init->isNullValue() || NumStores--;
873
874 // See if we can emit each element.
875 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
876 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
877 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
JF Bastiened92f602018-07-20 23:37:12 +0000878 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
Chris Lattnere6af8862010-12-02 01:58:41 +0000879 return false;
880 }
881 return true;
882 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000883
Chris Lattner236b3572012-01-31 04:36:19 +0000884 if (llvm::ConstantDataSequential *CDS =
885 dyn_cast<llvm::ConstantDataSequential>(Init)) {
886 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
887 llvm::Constant *Elt = CDS->getElementAsConstant(i);
JF Bastiened92f602018-07-20 23:37:12 +0000888 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
Chris Lattner236b3572012-01-31 04:36:19 +0000889 return false;
890 }
891 return true;
892 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000893
Chris Lattnerb85025f2010-12-01 02:05:19 +0000894 // Anything else is hard and scary.
895 return false;
896}
897
JF Bastiened92f602018-07-20 23:37:12 +0000898/// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
899/// the scalar stores that would be required.
900static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
901 llvm::Constant *Init, Address Loc,
902 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000903 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
JF Bastiened92f602018-07-20 23:37:12 +0000904 "called emitStoresForInitAfterBZero for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000905
Chris Lattnere6af8862010-12-02 01:58:41 +0000906 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
907 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
908 isa<llvm::ConstantExpr>(Init)) {
JF Bastien9aab85a2018-07-13 20:33:23 +0000909 Builder.CreateStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000910 return;
911 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000912
913 if (llvm::ConstantDataSequential *CDS =
914 dyn_cast<llvm::ConstantDataSequential>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000915 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
916 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000917
918 // If necessary, get a pointer to the element and emit it.
919 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
JF Bastiened92f602018-07-20 23:37:12 +0000920 emitStoresForInitAfterBZero(
James Y Knight751fe282019-02-09 22:22:28 +0000921 CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,
922 Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000923 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000924 return;
925 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000926
Chris Lattnere6af8862010-12-02 01:58:41 +0000927 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
928 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000929
Chris Lattnere6af8862010-12-02 01:58:41 +0000930 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
931 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000932
933 // If necessary, get a pointer to the element and emit it.
934 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
James Y Knight751fe282019-02-09 22:22:28 +0000935 emitStoresForInitAfterBZero(CGM, Elt,
936 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),
937 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000938 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000939}
940
JF Bastiened92f602018-07-20 23:37:12 +0000941/// Decide whether we should use bzero plus some stores to initialize a local
942/// variable instead of using a memcpy from a constant global. It is beneficial
943/// to use bzero if the global is all zeros, or mostly zeros and large.
944static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
945 uint64_t GlobalSize) {
946 // If a global is all zeros, always use a bzero.
Chris Lattnerb85025f2010-12-01 02:05:19 +0000947 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
948
Chris Lattnerb85025f2010-12-01 02:05:19 +0000949 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
950 // do it if it will require 6 or fewer scalar stores.
951 // TODO: Should budget depends on the size? Avoiding a large global warrants
952 // plopping in more stores.
953 unsigned StoreBudget = 6;
954 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000955
956 return GlobalSize > SizeLimit &&
JF Bastiened92f602018-07-20 23:37:12 +0000957 canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
Chris Lattnerb85025f2010-12-01 02:05:19 +0000958}
959
JF Bastien65089292018-07-25 04:29:03 +0000960/// Decide whether we should use memset to initialize a local variable instead
961/// of using a memcpy from a constant global. Assumes we've already decided to
962/// not user bzero.
963/// FIXME We could be more clever, as we are for bzero above, and generate
964/// memset followed by stores. It's unclear that's worth the effort.
JF Bastien2f0582f2018-09-21 13:54:09 +0000965static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
966 uint64_t GlobalSize) {
JF Bastien65089292018-07-25 04:29:03 +0000967 uint64_t SizeLimit = 32;
968 if (GlobalSize <= SizeLimit)
JF Bastien2f0582f2018-09-21 13:54:09 +0000969 return nullptr;
970 return llvm::isBytewiseValue(Init);
JF Bastien65089292018-07-25 04:29:03 +0000971}
972
JF Bastienb5e5bc72019-03-08 01:26:49 +0000973/// Decide whether we want to split a constant structure or array store into a
974/// sequence of its fields' stores. This may cost us code size and compilation
975/// speed, but plays better with store optimizations.
976static bool shouldSplitConstantStore(CodeGenModule &CGM,
977 uint64_t GlobalByteSize) {
978 // Don't break things that occupy more than one cacheline.
Alexander Potapenkofa61ddd2019-03-01 09:00:41 +0000979 uint64_t ByteSizeLimit = 64;
980 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
981 return false;
982 if (GlobalByteSize <= ByteSizeLimit)
983 return true;
984 return false;
985}
986
JF Bastien14daa202018-12-18 05:12:21 +0000987static llvm::Constant *patternFor(CodeGenModule &CGM, llvm::Type *Ty) {
988 // The following value is a guaranteed unmappable pointer value and has a
989 // repeated byte-pattern which makes it easier to synthesize. We use it for
990 // pointers as well as integers so that aggregates are likely to be
991 // initialized with this repeated value.
992 constexpr uint64_t LargeValue = 0xAAAAAAAAAAAAAAAAull;
993 // For 32-bit platforms it's a bit trickier because, across systems, only the
994 // zero page can reasonably be expected to be unmapped, and even then we need
995 // a very low address. We use a smaller value, and that value sadly doesn't
996 // have a repeated byte-pattern. We don't use it for integers.
997 constexpr uint32_t SmallValue = 0x000000AA;
998 // Floating-point values are initialized as NaNs because they propagate. Using
999 // a repeated byte pattern means that it will be easier to initialize
1000 // all-floating-point aggregates and arrays with memset. Further, aggregates
1001 // which mix integral and a few floats might also initialize with memset
1002 // followed by a handful of stores for the floats. Using fairly unique NaNs
1003 // also means they'll be easier to distinguish in a crash.
1004 constexpr bool NegativeNaN = true;
1005 constexpr uint64_t NaNPayload = 0xFFFFFFFFFFFFFFFFull;
1006 if (Ty->isIntOrIntVectorTy()) {
1007 unsigned BitWidth = cast<llvm::IntegerType>(
1008 Ty->isVectorTy() ? Ty->getVectorElementType() : Ty)
1009 ->getBitWidth();
1010 if (BitWidth <= 64)
1011 return llvm::ConstantInt::get(Ty, LargeValue);
1012 return llvm::ConstantInt::get(
1013 Ty, llvm::APInt::getSplat(BitWidth, llvm::APInt(64, LargeValue)));
1014 }
1015 if (Ty->isPtrOrPtrVectorTy()) {
1016 auto *PtrTy = cast<llvm::PointerType>(
1017 Ty->isVectorTy() ? Ty->getVectorElementType() : Ty);
1018 unsigned PtrWidth = CGM.getContext().getTargetInfo().getPointerWidth(
1019 PtrTy->getAddressSpace());
1020 llvm::Type *IntTy = llvm::IntegerType::get(CGM.getLLVMContext(), PtrWidth);
1021 uint64_t IntValue;
1022 switch (PtrWidth) {
1023 default:
1024 llvm_unreachable("pattern initialization of unsupported pointer width");
1025 case 64:
1026 IntValue = LargeValue;
1027 break;
1028 case 32:
1029 IntValue = SmallValue;
1030 break;
1031 }
1032 auto *Int = llvm::ConstantInt::get(IntTy, IntValue);
1033 return llvm::ConstantExpr::getIntToPtr(Int, PtrTy);
1034 }
1035 if (Ty->isFPOrFPVectorTy()) {
1036 unsigned BitWidth = llvm::APFloat::semanticsSizeInBits(
1037 (Ty->isVectorTy() ? Ty->getVectorElementType() : Ty)
1038 ->getFltSemantics());
1039 llvm::APInt Payload(64, NaNPayload);
1040 if (BitWidth >= 64)
1041 Payload = llvm::APInt::getSplat(BitWidth, Payload);
1042 return llvm::ConstantFP::getQNaN(Ty, NegativeNaN, &Payload);
1043 }
1044 if (Ty->isArrayTy()) {
1045 // Note: this doesn't touch tail padding (at the end of an object, before
1046 // the next array object). It is instead handled by replaceUndef.
1047 auto *ArrTy = cast<llvm::ArrayType>(Ty);
1048 llvm::SmallVector<llvm::Constant *, 8> Element(
1049 ArrTy->getNumElements(), patternFor(CGM, ArrTy->getElementType()));
1050 return llvm::ConstantArray::get(ArrTy, Element);
1051 }
1052
1053 // Note: this doesn't touch struct padding. It will initialize as much union
1054 // padding as is required for the largest type in the union. Padding is
1055 // instead handled by replaceUndef. Stores to structs with volatile members
1056 // don't have a volatile qualifier when initialized according to C++. This is
1057 // fine because stack-based volatiles don't really have volatile semantics
1058 // anyways, and the initialization shouldn't be observable.
1059 auto *StructTy = cast<llvm::StructType>(Ty);
1060 llvm::SmallVector<llvm::Constant *, 8> Struct(StructTy->getNumElements());
1061 for (unsigned El = 0; El != Struct.size(); ++El)
1062 Struct[El] = patternFor(CGM, StructTy->getElementType(El));
1063 return llvm::ConstantStruct::get(StructTy, Struct);
1064}
1065
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001066enum class IsPattern { No, Yes };
1067
1068/// Generate a constant filled with either a pattern or zeroes.
1069static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
1070 llvm::Type *Ty) {
1071 if (isPattern == IsPattern::Yes)
1072 return patternFor(CGM, Ty);
1073 else
1074 return llvm::Constant::getNullValue(Ty);
1075}
1076
1077static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1078 llvm::Constant *constant);
1079
1080/// Helper function for constWithPadding() to deal with padding in structures.
1081static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
1082 IsPattern isPattern,
1083 llvm::StructType *STy,
1084 llvm::Constant *constant) {
1085 const llvm::DataLayout &DL = CGM.getDataLayout();
1086 const llvm::StructLayout *Layout = DL.getStructLayout(STy);
1087 llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1088 unsigned SizeSoFar = 0;
1089 SmallVector<llvm::Constant *, 8> Values;
1090 bool NestedIntact = true;
1091 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1092 unsigned CurOff = Layout->getElementOffset(i);
1093 if (SizeSoFar < CurOff) {
1094 assert(!STy->isPacked());
1095 auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);
1096 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1097 }
1098 llvm::Constant *CurOp;
1099 if (constant->isZeroValue())
1100 CurOp = llvm::Constant::getNullValue(STy->getElementType(i));
1101 else
1102 CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));
1103 auto *NewOp = constWithPadding(CGM, isPattern, CurOp);
1104 if (CurOp != NewOp)
1105 NestedIntact = false;
1106 Values.push_back(NewOp);
1107 SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());
1108 }
1109 unsigned TotalSize = Layout->getSizeInBytes();
1110 if (SizeSoFar < TotalSize) {
1111 auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);
1112 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1113 }
1114 if (NestedIntact && Values.size() == STy->getNumElements())
1115 return constant;
Peter Collingbourne68b46732019-03-16 19:25:39 +00001116 return llvm::ConstantStruct::getAnon(Values, STy->isPacked());
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001117}
1118
1119/// Replace all padding bytes in a given constant with either a pattern byte or
1120/// 0x00.
1121static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1122 llvm::Constant *constant) {
1123 llvm::Type *OrigTy = constant->getType();
1124 if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))
1125 return constStructWithPadding(CGM, isPattern, STy, constant);
1126 if (auto *STy = dyn_cast<llvm::SequentialType>(OrigTy)) {
1127 llvm::SmallVector<llvm::Constant *, 8> Values;
1128 unsigned Size = STy->getNumElements();
1129 if (!Size)
1130 return constant;
1131 llvm::Type *ElemTy = STy->getElementType();
1132 bool ZeroInitializer = constant->isZeroValue();
1133 llvm::Constant *OpValue, *PaddedOp;
1134 if (ZeroInitializer) {
1135 OpValue = llvm::Constant::getNullValue(ElemTy);
1136 PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1137 }
1138 for (unsigned Op = 0; Op != Size; ++Op) {
1139 if (!ZeroInitializer) {
1140 OpValue = constant->getAggregateElement(Op);
1141 PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1142 }
1143 Values.push_back(PaddedOp);
1144 }
1145 auto *NewElemTy = Values[0]->getType();
1146 if (NewElemTy == ElemTy)
1147 return constant;
1148 if (OrigTy->isArrayTy()) {
1149 auto *ArrayTy = llvm::ArrayType::get(NewElemTy, Size);
1150 return llvm::ConstantArray::get(ArrayTy, Values);
1151 } else {
1152 return llvm::ConstantVector::get(Values);
1153 }
1154 }
1155 return constant;
1156}
1157
JF Bastien3a881e62018-11-15 00:19:18 +00001158static Address createUnnamedGlobalFrom(CodeGenModule &CGM, const VarDecl &D,
1159 CGBuilderTy &Builder,
1160 llvm::Constant *Constant,
1161 CharUnits Align) {
1162 auto FunctionName = [&](const DeclContext *DC) -> std::string {
1163 if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1164 if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
1165 return CC->getNameAsString();
1166 if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
1167 return CD->getNameAsString();
1168 return CGM.getMangledName(FD);
1169 } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
1170 return OM->getNameAsString();
Mikael Holmenee846762018-11-15 13:01:54 +00001171 } else if (isa<BlockDecl>(DC)) {
JF Bastien3a881e62018-11-15 00:19:18 +00001172 return "<block>";
Mikael Holmenee846762018-11-15 13:01:54 +00001173 } else if (isa<CapturedDecl>(DC)) {
JF Bastien3a881e62018-11-15 00:19:18 +00001174 return "<captured>";
1175 } else {
1176 llvm::llvm_unreachable_internal("expected a function or method");
1177 }
1178 };
1179
1180 auto *Ty = Constant->getType();
1181 bool isConstant = true;
1182 llvm::GlobalVariable *InsertBefore = nullptr;
1183 unsigned AS = CGM.getContext().getTargetAddressSpace(
1184 CGM.getStringLiteralAddressSpace());
1185 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1186 CGM.getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
1187 Constant,
1188 "__const." + FunctionName(D.getParentFunctionOrMethod()) + "." +
1189 D.getName(),
1190 InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
1191 GV->setAlignment(Align.getQuantity());
1192 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1193
1194 Address SrcPtr = Address(GV, Align);
1195 llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(), AS);
1196 if (SrcPtr.getType() != BP)
1197 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1198 return SrcPtr;
1199}
1200
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001201static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
1202 Address Loc, bool isVolatile,
1203 CGBuilderTy &Builder,
1204 llvm::Constant *constant) {
JF Bastien14daa202018-12-18 05:12:21 +00001205 auto *Ty = constant->getType();
JF Bastienb5e5bc72019-03-08 01:26:49 +00001206 bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
1207 Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
1208 if (canDoSingleStore) {
JF Bastien14daa202018-12-18 05:12:21 +00001209 Builder.CreateStore(constant, Loc, isVolatile);
1210 return;
1211 }
1212
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001213 auto *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1214 auto *IntPtrTy = CGM.getDataLayout().getIntPtrType(CGM.getLLVMContext());
1215
JF Bastien14daa202018-12-18 05:12:21 +00001216 uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
Alexander Potapenkofa61ddd2019-03-01 09:00:41 +00001217 if (!ConstantSize)
1218 return;
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001219 auto *SizeVal = llvm::ConstantInt::get(IntPtrTy, ConstantSize);
JF Bastienb5e5bc72019-03-08 01:26:49 +00001220
1221 // If the initializer is all or mostly the same, codegen with bzero / memset
1222 // then do a few stores afterward.
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001223 if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1224 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1225 isVolatile);
1226
1227 bool valueAlreadyCorrect =
1228 constant->isNullValue() || isa<llvm::UndefValue>(constant);
1229 if (!valueAlreadyCorrect) {
JF Bastien14daa202018-12-18 05:12:21 +00001230 Loc = Builder.CreateBitCast(Loc, Ty->getPointerTo(Loc.getAddressSpace()));
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001231 emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder);
1232 }
1233 return;
1234 }
1235
JF Bastienb5e5bc72019-03-08 01:26:49 +00001236 // If the initializer is a repeated byte pattern, use memset.
JF Bastien2f0582f2018-09-21 13:54:09 +00001237 llvm::Value *Pattern = shouldUseMemSetToInitialize(constant, ConstantSize);
1238 if (Pattern) {
1239 uint64_t Value = 0x00;
1240 if (!isa<llvm::UndefValue>(Pattern)) {
1241 const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1242 assert(AP.getBitWidth() <= 8);
1243 Value = AP.getLimitedValue();
1244 }
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001245 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, Value), SizeVal,
1246 isVolatile);
1247 return;
1248 }
1249
JF Bastienb5e5bc72019-03-08 01:26:49 +00001250 // If the initializer is small, use a handful of stores.
1251 if (shouldSplitConstantStore(CGM, ConstantSize)) {
1252 if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
1253 // FIXME: handle the case when STy != Loc.getElementType().
1254 if (STy == Loc.getElementType()) {
1255 for (unsigned i = 0; i != constant->getNumOperands(); i++) {
1256 Address EltPtr = Builder.CreateStructGEP(Loc, i);
1257 emitStoresForConstant(
1258 CGM, D, EltPtr, isVolatile, Builder,
1259 cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)));
1260 }
1261 return;
1262 }
1263 } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
1264 // FIXME: handle the case when ATy != Loc.getElementType().
1265 if (ATy == Loc.getElementType()) {
1266 for (unsigned i = 0; i != ATy->getNumElements(); i++) {
1267 Address EltPtr = Builder.CreateConstArrayGEP(Loc, i);
1268 emitStoresForConstant(
1269 CGM, D, EltPtr, isVolatile, Builder,
1270 cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)));
1271 }
1272 return;
1273 }
Alexander Potapenkofa61ddd2019-03-01 09:00:41 +00001274 }
Alexander Potapenkofa61ddd2019-03-01 09:00:41 +00001275 }
1276
JF Bastienb5e5bc72019-03-08 01:26:49 +00001277 // Copy from a global.
JF Bastien3a881e62018-11-15 00:19:18 +00001278 Builder.CreateMemCpy(
1279 Loc,
1280 createUnnamedGlobalFrom(CGM, D, Builder, constant, Loc.getAlignment()),
1281 SizeVal, isVolatile);
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001282}
1283
JF Bastien14daa202018-12-18 05:12:21 +00001284static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
1285 Address Loc, bool isVolatile,
1286 CGBuilderTy &Builder) {
1287 llvm::Type *ElTy = Loc.getElementType();
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001288 llvm::Constant *constant =
1289 constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
JF Bastien14daa202018-12-18 05:12:21 +00001290 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1291}
1292
1293static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
1294 Address Loc, bool isVolatile,
1295 CGBuilderTy &Builder) {
1296 llvm::Type *ElTy = Loc.getElementType();
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001297 llvm::Constant *constant =
1298 constWithPadding(CGM, IsPattern::Yes, patternFor(CGM, ElTy));
JF Bastien14daa202018-12-18 05:12:21 +00001299 assert(!isa<llvm::UndefValue>(constant));
1300 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1301}
1302
1303static bool containsUndef(llvm::Constant *constant) {
1304 auto *Ty = constant->getType();
1305 if (isa<llvm::UndefValue>(constant))
1306 return true;
1307 if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1308 for (llvm::Use &Op : constant->operands())
1309 if (containsUndef(cast<llvm::Constant>(Op)))
1310 return true;
1311 return false;
1312}
1313
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001314static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
1315 llvm::Constant *constant) {
JF Bastien14daa202018-12-18 05:12:21 +00001316 auto *Ty = constant->getType();
1317 if (isa<llvm::UndefValue>(constant))
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001318 return patternOrZeroFor(CGM, isPattern, Ty);
JF Bastien14daa202018-12-18 05:12:21 +00001319 if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1320 return constant;
1321 if (!containsUndef(constant))
1322 return constant;
1323 llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1324 for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1325 auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001326 Values[Op] = replaceUndef(CGM, isPattern, OpValue);
JF Bastien14daa202018-12-18 05:12:21 +00001327 }
1328 if (Ty->isStructTy())
1329 return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
1330 if (Ty->isArrayTy())
1331 return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
1332 assert(Ty->isVectorTy());
1333 return llvm::ConstantVector::get(Values);
1334}
1335
Nick Lewycky8a7d90b2010-12-30 20:21:55 +00001336/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +00001337/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +00001338/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +00001339void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1340 AutoVarEmission emission = EmitAutoVarAlloca(D);
1341 EmitAutoVarInit(emission);
1342 EmitAutoVarCleanups(emission);
1343}
Chris Lattner03df1222007-06-02 04:53:11 +00001344
David Majnemerdc012fa2015-04-22 21:38:15 +00001345/// Emit a lifetime.begin marker if some criteria are satisfied.
1346/// \return a pointer to the temporary size Value if a marker was emitted, null
1347/// otherwise
1348llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
1349 llvm::Value *Addr) {
Vitaly Buka1c943322016-10-26 01:59:57 +00001350 if (!ShouldEmitLifetimeMarkers)
Reid Kleckner1ef49212015-04-23 18:07:13 +00001351 return nullptr;
1352
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001353 assert(Addr->getType()->getPointerAddressSpace() ==
1354 CGM.getDataLayout().getAllocaAddrSpace() &&
1355 "Pointer should be in alloca address space");
David Majnemerdc012fa2015-04-22 21:38:15 +00001356 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001357 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +00001358 llvm::CallInst *C =
1359 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +00001360 C->setDoesNotThrow();
1361 return SizeV;
1362}
1363
1364void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001365 assert(Addr->getType()->getPointerAddressSpace() ==
1366 CGM.getDataLayout().getAllocaAddrSpace() &&
1367 "Pointer should be in alloca address space");
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001368 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +00001369 llvm::CallInst *C =
1370 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +00001371 C->setDoesNotThrow();
1372}
1373
Sander de Smalen891af03a2018-02-03 13:55:59 +00001374void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1375 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1376 // For each dimension stores its QualType and corresponding
1377 // size-expression Value.
1378 SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
Adrian Prantla40cce82018-11-09 19:17:56 +00001379 SmallVector<IdentifierInfo *, 4> VLAExprNames;
Sander de Smalen891af03a2018-02-03 13:55:59 +00001380
1381 // Break down the array into individual dimensions.
1382 QualType Type1D = D.getType();
1383 while (getContext().getAsVariableArrayType(Type1D)) {
1384 auto VlaSize = getVLAElements1D(Type1D);
1385 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1386 Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1387 else {
Adrian Prantla40cce82018-11-09 19:17:56 +00001388 // Generate a locally unique name for the size expression.
1389 Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1390 SmallString<12> Buffer;
1391 StringRef NameRef = Name.toStringRef(Buffer);
1392 auto &Ident = getContext().Idents.getOwn(NameRef);
1393 VLAExprNames.push_back(&Ident);
1394 auto SizeExprAddr =
1395 CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
Sander de Smalen891af03a2018-02-03 13:55:59 +00001396 Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1397 Dimensions.emplace_back(SizeExprAddr.getPointer(),
1398 Type1D.getUnqualifiedType());
1399 }
1400 Type1D = VlaSize.Type;
1401 }
1402
1403 if (!EmitDebugInfo)
1404 return;
1405
1406 // Register each dimension's size-expression with a DILocalVariable,
1407 // so that it can be used by CGDebugInfo when instantiating a DISubrange
1408 // to describe this array.
Adrian Prantla40cce82018-11-09 19:17:56 +00001409 unsigned NameIdx = 0;
Sander de Smalen891af03a2018-02-03 13:55:59 +00001410 for (auto &VlaSize : Dimensions) {
1411 llvm::Metadata *MD;
1412 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1413 MD = llvm::ConstantAsMetadata::get(C);
1414 else {
1415 // Create an artificial VarDecl to generate debug info for.
Adrian Prantla40cce82018-11-09 19:17:56 +00001416 IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
Sander de Smalen891af03a2018-02-03 13:55:59 +00001417 auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
1418 auto QT = getContext().getIntTypeForBitwidth(
1419 VlaExprTy->getScalarSizeInBits(), false);
1420 auto *ArtificialDecl = VarDecl::Create(
1421 getContext(), const_cast<DeclContext *>(D.getDeclContext()),
Adrian Prantla40cce82018-11-09 19:17:56 +00001422 D.getLocation(), D.getLocation(), NameIdent, QT,
Sander de Smalen891af03a2018-02-03 13:55:59 +00001423 getContext().CreateTypeSourceInfo(QT), SC_Auto);
Sander de Smalen9084a3b2018-02-13 07:49:34 +00001424 ArtificialDecl->setImplicit();
Sander de Smalen891af03a2018-02-03 13:55:59 +00001425
1426 MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1427 Builder);
1428 }
1429 assert(MD && "No Size expression debug node created");
1430 DI->registerVLASizeExpression(VlaSize.Type, MD);
1431 }
1432}
1433
John McCallc533cb72011-02-22 06:44:22 +00001434/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001435/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +00001436CodeGenFunction::AutoVarEmission
1437CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1438 QualType Ty = D.getType();
Yaxun Liub7318e02017-10-13 03:37:48 +00001439 assert(
1440 Ty.getAddressSpace() == LangAS::Default ||
1441 (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
John McCallc533cb72011-02-22 06:44:22 +00001442
1443 AutoVarEmission emission(D);
1444
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001445 bool isEscapingByRef = D.isEscapingByref();
1446 emission.IsEscapingByRef = isEscapingByRef;
John McCallc533cb72011-02-22 06:44:22 +00001447
1448 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +00001449
John McCall23c29fe2011-06-24 21:55:10 +00001450 // If the type is variably-modified, emit all the VLA sizes for it.
1451 if (Ty->isVariablyModifiedType())
1452 EmitVariablyModifiedType(Ty);
1453
Sander de Smalen891af03a2018-02-03 13:55:59 +00001454 auto *DI = getDebugInfo();
1455 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().getDebugInfo() >=
1456 codegenoptions::LimitedDebugInfo;
1457
John McCall7f416cc2015-09-08 08:05:57 +00001458 Address address = Address::invalid();
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001459 Address AllocaAddr = Address::invalid();
Eli Friedmana682d392008-02-15 12:20:59 +00001460 if (Ty->isConstantSizeType()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001461 bool NRVO = getLangOpts().ElideConstructors &&
1462 D.isNRVOVariable();
John McCallc533cb72011-02-22 06:44:22 +00001463
Richard Smith2bcde3a2013-06-02 00:09:52 +00001464 // If this value is an array or struct with a statically determinable
1465 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +00001466 //
1467 // TODO: We should constant-evaluate the initializer of any variable,
1468 // as long as it is initialized by a constant expression. Currently,
1469 // isConstantInitializer produces wrong answers for structs with
1470 // reference or bitfield members, and a few other cases, and checking
1471 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +00001472 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1473 (D.isConstexpr() ||
1474 ((Ty.isPODType(getContext()) ||
1475 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1476 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +00001477
Rafael Espindola609f5d92013-03-26 18:41:47 +00001478 // If the variable's a const type, and it's neither an NRVO
1479 // candidate nor a __block variable and has no mutable members,
1480 // emit it as a global instead.
Anastasia Stulovae4a1c382016-11-29 17:01:19 +00001481 // Exception is if a variable is located in non-constant address space
1482 // in OpenCL.
1483 if ((!getLangOpts().OpenCL ||
1484 Ty.getAddressSpace() == LangAS::opencl_constant) &&
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001485 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1486 !isEscapingByRef && CGM.isTypeConstant(Ty, true))) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001487 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +00001488
John McCall7f416cc2015-09-08 08:05:57 +00001489 // Signal this condition to later callbacks.
1490 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +00001491 assert(emission.wasEmittedAsGlobal());
1492 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +00001493 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001494
Rafael Espindola609f5d92013-03-26 18:41:47 +00001495 // Otherwise, tell the initialization code that we're in this case.
1496 emission.IsConstantAggregate = true;
1497 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001498
Rafael Espindola609f5d92013-03-26 18:41:47 +00001499 // A normal fixed sized variable becomes an alloca in the entry block,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001500 // unless:
1501 // - it's an NRVO variable.
1502 // - we are compiling OpenMP and it's an OpenMP local variable.
Eric Christopher31ab1302011-08-23 22:38:00 +00001503
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001504 Address OpenMPLocalAddr =
1505 getLangOpts().OpenMP
1506 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
1507 : Address::invalid();
1508 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1509 address = OpenMPLocalAddr;
1510 } else if (NRVO) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001511 // The named return value optimization: allocate this variable in the
1512 // return slot, so that we can elide the copy when returning this
1513 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +00001514 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +00001515
Rafael Espindola609f5d92013-03-26 18:41:47 +00001516 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001517 const auto *RD = RecordTy->getDecl();
1518 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1519 if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1520 RD->isNonTrivialToPrimitiveDestroy()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001521 // Create a flag that is used to indicate when the NRVO was applied
1522 // to this variable. Set it to zero to indicate that NRVO was not
1523 // applied.
1524 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +00001525 Address NRVOFlag =
1526 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +00001527 EnsureInsertPoint();
1528 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +00001529
Rafael Espindola609f5d92013-03-26 18:41:47 +00001530 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +00001531 NRVOFlags[&D] = NRVOFlag.getPointer();
1532 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +00001533 }
Douglas Gregor290c93e2010-05-15 06:46:45 +00001534 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001535 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001536 CharUnits allocaAlignment;
1537 llvm::Type *allocaTy;
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001538 if (isEscapingByRef) {
John McCall7f416cc2015-09-08 08:05:57 +00001539 auto &byrefInfo = getBlockByrefInfo(&D);
1540 allocaTy = byrefInfo.Type;
1541 allocaAlignment = byrefInfo.ByrefAlignment;
1542 } else {
1543 allocaTy = ConvertTypeForMem(Ty);
1544 allocaAlignment = alignment;
1545 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001546
John McCall999110f2015-09-08 09:18:30 +00001547 // Create the alloca. Note that we set the name separately from
1548 // building the instruction so that it's there even in no-asserts
1549 // builds.
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001550 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1551 /*ArraySize=*/nullptr, &AllocaAddr);
Rafael Espindola609f5d92013-03-26 18:41:47 +00001552
Reid Kleckner1f88e932015-10-07 21:03:41 +00001553 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1554 // the catch parameter starts in the catchpad instruction, and we can't
1555 // insert code in those basic blocks.
1556 bool IsMSCatchParam =
1557 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1558
Vitaly Buka64c80b42016-10-26 05:42:30 +00001559 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1560 // if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001561 if (HaveInsertPoint() && !IsMSCatchParam) {
Akira Hatanakafdcd18b2017-01-25 22:55:13 +00001562 // If there's a jump into the lifetime of this variable, its lifetime
1563 // gets broken up into several regions in IR, which requires more work
1564 // to handle correctly. For now, just omit the intrinsics; this is a
1565 // rare case, and it's better to just be conservatively correct.
1566 // PR28267.
1567 //
1568 // We have to do this in all language modes if there's a jump past the
1569 // declaration. We also have to do it in C if there's a jump to an
1570 // earlier point in the current block because non-VLA lifetimes begin as
1571 // soon as the containing block is entered, not when its variables
1572 // actually come into scope; suppressing the lifetime annotations
1573 // completely in this case is unnecessarily pessimistic, but again, this
1574 // is rare.
1575 if (!Bypasses.IsBypassed(&D) &&
1576 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
Vitaly Buka64c80b42016-10-26 05:42:30 +00001577 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1578 emission.SizeForLifetimeMarkers =
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001579 EmitLifetimeStart(size, AllocaAddr.getPointer());
Vitaly Buka64c80b42016-10-26 05:42:30 +00001580 }
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001581 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001582 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001583 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001584 }
Chris Lattner03df1222007-06-02 04:53:11 +00001585 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001586 EnsureInsertPoint();
1587
Anders Carlsson15949b32009-02-09 20:41:50 +00001588 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001589 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001590 Address Stack =
1591 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001592
James Y Knight8799cae2019-02-03 21:53:49 +00001593 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001594 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001595 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001596
1597 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001598
John McCalla464ff92010-07-21 06:13:08 +00001599 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001600 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001601 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001602 }
Mike Stump11289f42009-09-09 15:08:12 +00001603
Sander de Smalen891af03a2018-02-03 13:55:59 +00001604 auto VlaSize = getVLASize(Ty);
1605 llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
Anders Carlsson30032882008-12-12 07:38:43 +00001606
1607 // Allocate memory for the array.
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001608 address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1609 &AllocaAddr);
Sander de Smalen891af03a2018-02-03 13:55:59 +00001610
1611 // If we have debug info enabled, properly describe the VLA dimensions for
1612 // this type by registering the vla size expression for each of the
1613 // dimensions.
1614 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
Chris Lattner03df1222007-06-02 04:53:11 +00001615 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001616
John McCall7f416cc2015-09-08 08:05:57 +00001617 setAddrOfLocalVar(&D, address);
1618 emission.Addr = address;
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001619 emission.AllocaAddr = AllocaAddr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001620
1621 // Emit debug info for local var declaration.
Sander de Smalen891af03a2018-02-03 13:55:59 +00001622 if (EmitDebugInfo && HaveInsertPoint()) {
1623 DI->setLocation(D.getLocation());
1624 (void)DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1625 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001626
Volodymyr Sapsai93317d82019-03-01 02:15:39 +00001627 if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
John McCall7f416cc2015-09-08 08:05:57 +00001628 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001629
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001630 // Make sure we call @llvm.lifetime.end.
1631 if (emission.useLifetimeMarkers())
1632 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001633 emission.getOriginalAllocatedAddress(),
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001634 emission.getSizeForLifetimeMarkers());
1635
John McCallc533cb72011-02-22 06:44:22 +00001636 return emission;
1637}
1638
JF Bastien6b239722018-05-19 04:21:26 +00001639static bool isCapturedBy(const VarDecl &, const Expr *);
1640
1641/// Determines whether the given __block variable is potentially
1642/// captured by the given statement.
1643static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1644 if (const Expr *E = dyn_cast<Expr>(S))
1645 return isCapturedBy(Var, E);
1646 for (const Stmt *SubStmt : S->children())
1647 if (isCapturedBy(Var, SubStmt))
1648 return true;
1649 return false;
1650}
1651
John McCallc533cb72011-02-22 06:44:22 +00001652/// Determines whether the given __block variable is potentially
1653/// captured by the given expression.
JF Bastien6b239722018-05-19 04:21:26 +00001654static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
John McCallc533cb72011-02-22 06:44:22 +00001655 // Skip the most common kinds of expressions that make
1656 // hierarchy-walking expensive.
JF Bastien6b239722018-05-19 04:21:26 +00001657 E = E->IgnoreParenCasts();
John McCallc533cb72011-02-22 06:44:22 +00001658
JF Bastien6b239722018-05-19 04:21:26 +00001659 if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1660 const BlockDecl *Block = BE->getBlockDecl();
1661 for (const auto &I : Block->captures()) {
1662 if (I.getVariable() == &Var)
John McCallc533cb72011-02-22 06:44:22 +00001663 return true;
1664 }
1665
1666 // No need to walk into the subexpressions.
1667 return false;
1668 }
1669
JF Bastien6b239722018-05-19 04:21:26 +00001670 if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001671 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001672 for (const auto *BI : CS->body())
JF Bastien6b239722018-05-19 04:21:26 +00001673 if (const auto *BIE = dyn_cast<Expr>(BI)) {
1674 if (isCapturedBy(Var, BIE))
1675 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001676 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001677 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001678 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001679 for (const auto *I : DS->decls()) {
1680 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1681 const Expr *Init = VD->getInit();
JF Bastien6b239722018-05-19 04:21:26 +00001682 if (Init && isCapturedBy(Var, Init))
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001683 return true;
1684 }
1685 }
1686 }
1687 else
1688 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1689 // Later, provide code to poke into statements for capture analysis.
1690 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001691 return false;
1692 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001693
JF Bastien6b239722018-05-19 04:21:26 +00001694 for (const Stmt *SubStmt : E->children())
1695 if (isCapturedBy(Var, SubStmt))
John McCallc533cb72011-02-22 06:44:22 +00001696 return true;
1697
1698 return false;
1699}
1700
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001701/// Determine whether the given initializer is trivial in the sense
Douglas Gregor82e1af22011-07-01 21:08:19 +00001702/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001703bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001704 if (!Init)
1705 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001706
Douglas Gregor82e1af22011-07-01 21:08:19 +00001707 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1708 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1709 if (Constructor->isTrivial() &&
1710 Constructor->isDefaultConstructor() &&
1711 !Construct->requiresZeroInitialization())
1712 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001713
Douglas Gregor82e1af22011-07-01 21:08:19 +00001714 return false;
1715}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001716
John McCallc533cb72011-02-22 06:44:22 +00001717void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001718 assert(emission.Variable && "emission was not valid!");
1719
John McCallc533cb72011-02-22 06:44:22 +00001720 // If this was emitted as a global constant, we're done.
1721 if (emission.wasEmittedAsGlobal()) return;
1722
John McCall9e2e22f2011-02-22 07:16:58 +00001723 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001724 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001725 QualType type = D.getType();
1726
JF Bastien14daa202018-12-18 05:12:21 +00001727 bool isVolatile = type.isVolatileQualified();
1728
Chris Lattner07eb7332007-07-12 00:39:48 +00001729 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001730 const Expr *Init = D.getInit();
1731
1732 // If we are at an unreachable point, we don't need to emit the initializer
1733 // unless it contains a label.
1734 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001735 if (!Init || !ContainsLabel(Init)) return;
1736 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001737 }
1738
John McCall73064872011-03-31 01:59:53 +00001739 // Initialize the structure of a __block variable.
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001740 if (emission.IsEscapingByRef)
John McCall73064872011-03-31 01:59:53 +00001741 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001742
Akira Hatanaka7275da02018-02-28 07:15:55 +00001743 // Initialize the variable here if it doesn't have a initializer and it is a
1744 // C struct that is non-trivial to initialize or an array containing such a
1745 // struct.
1746 if (!Init &&
1747 type.isNonTrivialToPrimitiveDefaultInitialize() ==
1748 QualType::PDIK_Struct) {
1749 LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001750 if (emission.IsEscapingByRef)
Akira Hatanaka7275da02018-02-28 07:15:55 +00001751 drillIntoBlockVariable(*this, Dst, &D);
1752 defaultInitNonTrivialCStructVar(Dst);
1753 return;
1754 }
1755
John McCallc533cb72011-02-22 06:44:22 +00001756 // Check whether this is a byref variable that's potentially
1757 // captured and moved by its own initializer. If so, we'll need to
1758 // emit the initializer first, then copy into the variable.
JF Bastien14daa202018-12-18 05:12:21 +00001759 bool capturedByInit =
1760 Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
John McCallc533cb72011-02-22 06:44:22 +00001761
JF Bastien0bae08a2019-02-15 17:26:29 +00001762 bool locIsByrefHeader = !capturedByInit;
1763 const Address Loc =
1764 locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
JF Bastien14daa202018-12-18 05:12:21 +00001765
1766 // Note: constexpr already initializes everything correctly.
1767 LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
1768 (D.isConstexpr()
1769 ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1770 : (D.getAttr<UninitializedAttr>()
1771 ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1772 : getContext().getLangOpts().getTrivialAutoVarInit()));
1773
JF Bastienb347e752019-02-08 01:29:17 +00001774 auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
JF Bastien14daa202018-12-18 05:12:21 +00001775 if (trivialAutoVarInit ==
1776 LangOptions::TrivialAutoVarInitKind::Uninitialized)
1777 return;
1778
JF Bastienb347e752019-02-08 01:29:17 +00001779 // Only initialize a __block's storage: we always initialize the header.
JF Bastien0bae08a2019-02-15 17:26:29 +00001780 if (emission.IsEscapingByRef && !locIsByrefHeader)
JF Bastienb347e752019-02-08 01:29:17 +00001781 Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
1782
JF Bastien14daa202018-12-18 05:12:21 +00001783 CharUnits Size = getContext().getTypeSizeInChars(type);
1784 if (!Size.isZero()) {
1785 switch (trivialAutoVarInit) {
1786 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1787 llvm_unreachable("Uninitialized handled above");
1788 case LangOptions::TrivialAutoVarInitKind::Zero:
1789 emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
1790 break;
1791 case LangOptions::TrivialAutoVarInitKind::Pattern:
1792 emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
1793 break;
1794 }
1795 return;
1796 }
1797
1798 // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1799 // them, so emit a memcpy with the VLA size to initialize each element.
1800 // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1801 // will catch that code, but there exists code which generates zero-sized
1802 // VLAs. Be nice and initialize whatever they requested.
JF Bastienddeb2f22019-02-08 00:51:05 +00001803 const auto *VlaType = getContext().getAsVariableArrayType(type);
JF Bastien14daa202018-12-18 05:12:21 +00001804 if (!VlaType)
1805 return;
1806 auto VlaSize = getVLASize(VlaType);
1807 auto SizeVal = VlaSize.NumElts;
1808 CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1809 switch (trivialAutoVarInit) {
1810 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1811 llvm_unreachable("Uninitialized handled above");
1812
1813 case LangOptions::TrivialAutoVarInitKind::Zero:
1814 if (!EltSize.isOne())
1815 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1816 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1817 isVolatile);
1818 break;
1819
1820 case LangOptions::TrivialAutoVarInitKind::Pattern: {
1821 llvm::Type *ElTy = Loc.getElementType();
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001822 llvm::Constant *Constant =
1823 constWithPadding(CGM, IsPattern::Yes, patternFor(CGM, ElTy));
JF Bastien14daa202018-12-18 05:12:21 +00001824 CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
1825 llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
1826 llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
1827 llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
1828 llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1829 SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
1830 "vla.iszerosized");
1831 Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
1832 EmitBlock(SetupBB);
1833 if (!EltSize.isOne())
1834 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1835 llvm::Value *BaseSizeInChars =
1836 llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
1837 Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
1838 llvm::Value *End =
1839 Builder.CreateInBoundsGEP(Begin.getPointer(), SizeVal, "vla.end");
1840 llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1841 EmitBlock(LoopBB);
1842 llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
1843 Cur->addIncoming(Begin.getPointer(), OriginBB);
1844 CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
1845 Builder.CreateMemCpy(
1846 Address(Cur, CurAlign),
1847 createUnnamedGlobalFrom(CGM, D, Builder, Constant, ConstantAlign),
1848 BaseSizeInChars, isVolatile);
1849 llvm::Value *Next =
1850 Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
1851 llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
1852 Builder.CreateCondBr(Done, ContBB, LoopBB);
1853 Cur->addIncoming(Next, LoopBB);
1854 EmitBlock(ContBB);
1855 } break;
1856 }
1857 };
1858
1859 if (isTrivialInitializer(Init)) {
JF Bastienb347e752019-02-08 01:29:17 +00001860 initializeWhatIsTechnicallyUninitialized(Loc);
JF Bastien14daa202018-12-18 05:12:21 +00001861 return;
1862 }
John McCallc533cb72011-02-22 06:44:22 +00001863
Craig Topper8a13c412014-05-21 05:09:00 +00001864 llvm::Constant *constant = nullptr;
Richard Smith2bcde3a2013-06-02 00:09:52 +00001865 if (emission.IsConstantAggregate || D.isConstexpr()) {
Richard Smithfddd3842011-12-30 21:15:51 +00001866 assert(!capturedByInit && "constant init contains a capturing block?");
John McCallde0fe072017-08-15 21:42:52 +00001867 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
JF Bastien14daa202018-12-18 05:12:21 +00001868 if (constant && trivialAutoVarInit !=
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001869 LangOptions::TrivialAutoVarInitKind::Uninitialized) {
1870 IsPattern isPattern =
1871 (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
1872 ? IsPattern::Yes
1873 : IsPattern::No;
1874 constant = constWithPadding(CGM, isPattern,
1875 replaceUndef(CGM, isPattern, constant));
1876 }
Richard Smithfddd3842011-12-30 21:15:51 +00001877 }
1878
1879 if (!constant) {
JF Bastienb347e752019-02-08 01:29:17 +00001880 initializeWhatIsTechnicallyUninitialized(Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001881 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001882 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001883 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001884 }
John McCall91ca10f2011-03-08 09:11:50 +00001885
Richard Smith2bcde3a2013-06-02 00:09:52 +00001886 if (!emission.IsConstantAggregate) {
1887 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001888 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001889 lv.setNonGC(true);
1890 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1891 }
1892
Yaxun Liudaceb1e2018-05-14 19:20:12 +00001893 llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
JF Bastien0bae08a2019-02-15 17:26:29 +00001894 emitStoresForConstant(
1895 CGM, D, (Loc.getType() == BP) ? Loc : Builder.CreateBitCast(Loc, BP),
1896 isVolatile, Builder, constant);
John McCall91ca10f2011-03-08 09:11:50 +00001897}
1898
Richard Smithe78fac52018-04-05 20:52:58 +00001899/// Emit an expression as an initializer for an object (variable, field, etc.)
1900/// at the given location. The expression is not necessarily the normal
1901/// initializer for the object, and the address is not necessarily
John McCall91ca10f2011-03-08 09:11:50 +00001902/// its normal location.
1903///
1904/// \param init the initializing expression
Richard Smithe78fac52018-04-05 20:52:58 +00001905/// \param D the object to act as if we're initializing
John McCall91ca10f2011-03-08 09:11:50 +00001906/// \param loc the address to initialize; its type is a pointer
Richard Smithe78fac52018-04-05 20:52:58 +00001907/// to the LLVM mapping of the object's type
John McCall91ca10f2011-03-08 09:11:50 +00001908/// \param alignment the alignment of the address
Richard Smithe78fac52018-04-05 20:52:58 +00001909/// \param capturedByInit true if \p D is a __block variable
John McCall91ca10f2011-03-08 09:11:50 +00001910/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001911void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001912 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001913 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001914
1915 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001916 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001917 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001918 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001919 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001920 return;
1921 }
1922 switch (getEvaluationKind(type)) {
1923 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001924 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001925 return;
1926 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001927 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001928 if (capturedByInit)
1929 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001930 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001931 return;
1932 }
1933 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001934 if (type->isAtomicType()) {
1935 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1936 } else {
Richard Smithe78fac52018-04-05 20:52:58 +00001937 AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
1938 if (isa<VarDecl>(D))
1939 Overlap = AggValueSlot::DoesNotOverlap;
1940 else if (auto *FD = dyn_cast<FieldDecl>(D))
1941 Overlap = overlapForFieldInit(FD);
John McCalla8ec7eb2013-03-07 21:37:17 +00001942 // TODO: how can we delay here if D is captured by its initializer?
1943 EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001944 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001945 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001946 AggValueSlot::IsNotAliased,
1947 Overlap));
John McCalla8ec7eb2013-03-07 21:37:17 +00001948 }
John McCall47fb9502013-03-07 21:37:08 +00001949 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001950 }
John McCall47fb9502013-03-07 21:37:08 +00001951 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001952}
John McCallbd309292010-07-06 01:34:17 +00001953
John McCall82fe67b2011-07-09 01:37:26 +00001954/// Enter a destroy cleanup for the given local variable.
1955void CodeGenFunction::emitAutoVarTypeCleanup(
1956 const CodeGenFunction::AutoVarEmission &emission,
1957 QualType::DestructionKind dtorKind) {
1958 assert(dtorKind != QualType::DK_none);
1959
1960 // Note that for __block variables, we want to destroy the
1961 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001962 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001963
1964 const VarDecl *var = emission.Variable;
1965 QualType type = var->getType();
1966
1967 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001968 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001969
1970 switch (dtorKind) {
1971 case QualType::DK_none:
1972 llvm_unreachable("no cleanup for trivially-destructible variable");
1973
1974 case QualType::DK_cxx_destructor:
1975 // If there's an NRVO flag on the emission, we need a different
1976 // cleanup.
1977 if (emission.NRVOFlag) {
1978 assert(!type->isArrayType());
1979 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001980 EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, dtor,
1981 emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001982 return;
1983 }
1984 break;
1985
1986 case QualType::DK_objc_strong_lifetime:
1987 // Suppress cleanups for pseudo-strong variables.
1988 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001989
John McCall82fe67b2011-07-09 01:37:26 +00001990 // Otherwise, consider whether to use an EH cleanup or not.
1991 cleanupKind = getARCCleanupKind();
1992
1993 // Use the imprecise destroyer by default.
1994 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1995 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1996 break;
1997
1998 case QualType::DK_objc_weak_lifetime:
1999 break;
Akira Hatanaka7275da02018-02-28 07:15:55 +00002000
2001 case QualType::DK_nontrivial_c_struct:
2002 destroyer = CodeGenFunction::destroyNonTrivialCStruct;
Akira Hatanaka673af7a2018-03-29 17:56:24 +00002003 if (emission.NRVOFlag) {
2004 assert(!type->isArrayType());
2005 EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
2006 emission.NRVOFlag, type);
2007 return;
2008 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00002009 break;
John McCall82fe67b2011-07-09 01:37:26 +00002010 }
2011
2012 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00002013 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00002014
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002015 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00002016 // is being pushed as an EH cleanup.
2017 bool useEHCleanup = (cleanupKind & EHCleanup);
2018 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
2019 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00002020}
2021
John McCallc533cb72011-02-22 06:44:22 +00002022void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00002023 assert(emission.Variable && "emission was not valid!");
2024
John McCallc533cb72011-02-22 06:44:22 +00002025 // If this was emitted as a global constant, we're done.
2026 if (emission.wasEmittedAsGlobal()) return;
2027
John McCall8c38d352012-04-13 18:44:05 +00002028 // If we don't have an insertion point, we're done. Sema prevents
2029 // us from jumping into any of these scopes anyway.
2030 if (!HaveInsertPoint()) return;
2031
John McCall9e2e22f2011-02-22 07:16:58 +00002032 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00002033
John McCall82fe67b2011-07-09 01:37:26 +00002034 // Check the type for a cleanup.
2035 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
2036 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00002037
John McCall1bd25562011-06-24 23:21:27 +00002038 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002039 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00002040 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
2041 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
2042 }
2043
John McCallc533cb72011-02-22 06:44:22 +00002044 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002045 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00002046 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002047
John McCallc533cb72011-02-22 06:44:22 +00002048 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00002049 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00002050
John McCalla729c622012-02-17 03:33:10 +00002051 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00002052 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00002053 }
Mike Stump626aecc2009-03-05 01:23:13 +00002054
John McCallc533cb72011-02-22 06:44:22 +00002055 // If this is a block variable, call _Block_object_destroy
Akira Hatanakacb6a9332018-07-26 16:51:21 +00002056 // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
2057 // mode.
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002058 if (emission.IsEscapingByRef &&
2059 CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
Akira Hatanakacb6a9332018-07-26 16:51:21 +00002060 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2061 if (emission.Variable->getType().isObjCGCWeak())
2062 Flags |= BLOCK_FIELD_IS_WEAK;
2063 enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
Akira Hatanaka9978da32018-08-10 15:09:24 +00002064 /*LoadBlockVarAddr*/ false,
2065 cxxDestructorCanThrow(emission.Variable->getType()));
Akira Hatanakacb6a9332018-07-26 16:51:21 +00002066 }
Chris Lattner03df1222007-06-02 04:53:11 +00002067}
Chris Lattner53621a52007-06-13 20:44:40 +00002068
Peter Collingbourne1425b452012-01-26 03:33:36 +00002069CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00002070CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
2071 switch (kind) {
2072 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00002073 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00002074 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00002075 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00002076 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00002077 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00002078 return destroyARCWeak;
Akira Hatanaka7275da02018-02-28 07:15:55 +00002079 case QualType::DK_nontrivial_c_struct:
2080 return destroyNonTrivialCStruct;
John McCall82fe67b2011-07-09 01:37:26 +00002081 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00002082 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00002083}
2084
John McCall12cc42a2013-02-01 05:11:40 +00002085/// pushEHDestroy - Push the standard destructor for the given type as
2086/// an EH-only cleanup.
2087void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00002088 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00002089 assert(dtorKind && "cannot push destructor for trivial type");
2090 assert(needsEHCleanup(dtorKind));
2091
2092 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
2093}
2094
2095/// pushDestroy - Push the standard destructor for the given type as
2096/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00002097void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00002098 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00002099 assert(dtorKind && "cannot push destructor for trivial type");
2100
2101 CleanupKind cleanupKind = getCleanupKind(dtorKind);
2102 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
2103 cleanupKind & EHCleanup);
2104}
2105
John McCall7f416cc2015-09-08 08:05:57 +00002106void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002107 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00002108 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00002109 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
2110 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00002111}
2112
John McCall7f416cc2015-09-08 08:05:57 +00002113void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002114 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
2115}
2116
Richard Smith736a9472013-06-12 20:42:33 +00002117void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00002118 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00002119 Destroyer *destroyer, bool useEHCleanupForArray) {
Richard Smith736a9472013-06-12 20:42:33 +00002120 // Push an EH-only cleanup for the object now.
2121 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
2122 // around in case a temporary's destructor throws an exception.
2123 if (cleanupKind & EHCleanup)
2124 EHStack.pushCleanup<DestroyObject>(
2125 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
2126 destroyer, useEHCleanupForArray);
2127
2128 // Remember that we need to push a full cleanup for the object at the
2129 // end of the full-expression.
2130 pushCleanupAfterFullExpr<DestroyObject>(
2131 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
2132}
2133
John McCall178360e2011-07-11 08:38:19 +00002134/// emitDestroy - Immediately perform the destruction of the given
2135/// object.
2136///
2137/// \param addr - the address of the object; a type*
2138/// \param type - the type of the object; if an array type, all
2139/// objects are destroyed in reverse order
2140/// \param destroyer - the function to call to destroy individual
2141/// elements
2142/// \param useEHCleanupForArray - whether an EH cleanup should be
2143/// used when destroying array elements, in case one of the
2144/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00002145void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002146 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00002147 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00002148 const ArrayType *arrayType = getContext().getAsArrayType(type);
2149 if (!arrayType)
2150 return destroyer(*this, addr, type);
2151
John McCall7f416cc2015-09-08 08:05:57 +00002152 llvm::Value *length = emitArrayLength(arrayType, type, addr);
2153
2154 CharUnits elementAlign =
2155 addr.getAlignment()
2156 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00002157
2158 // Normally we have to check whether the array is zero-length.
2159 bool checkZeroLength = true;
2160
2161 // But if the array length is constant, we can suppress that.
2162 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
2163 // ...and if it's constant zero, we can just skip the entire thing.
2164 if (constLength->isZero()) return;
2165 checkZeroLength = false;
2166 }
2167
John McCall7f416cc2015-09-08 08:05:57 +00002168 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00002169 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00002170 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00002171 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00002172}
2173
John McCall178360e2011-07-11 08:38:19 +00002174/// emitArrayDestroy - Destroys all the elements of the given array,
2175/// beginning from last to first. The array cannot be zero-length.
2176///
2177/// \param begin - a type* denoting the first element of the array
2178/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00002179/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00002180/// \param destroyer - the function to call to destroy elements
2181/// \param useEHCleanup - whether to push an EH cleanup to destroy
2182/// the remaining elements in case the destruction of a single
2183/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00002184void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2185 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00002186 QualType elementType,
2187 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002188 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00002189 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00002190 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00002191 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00002192
2193 // The basic structure here is a do-while loop, because we don't
2194 // need to check for the zero-element case.
2195 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
2196 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
2197
John McCall97eab0a2011-07-13 08:09:46 +00002198 if (checkZeroLength) {
2199 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
2200 "arraydestroy.isempty");
2201 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
2202 }
2203
John McCall82fe67b2011-07-09 01:37:26 +00002204 // Enter the loop body, making that address the current address.
2205 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2206 EmitBlock(bodyBB);
2207 llvm::PHINode *elementPast =
2208 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
2209 elementPast->addIncoming(end, entryBB);
2210
2211 // Shift the address back by one element.
2212 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
2213 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
2214 "arraydestroy.element");
2215
John McCall178360e2011-07-11 08:38:19 +00002216 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00002217 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
2218 destroyer);
John McCall178360e2011-07-11 08:38:19 +00002219
John McCall82fe67b2011-07-09 01:37:26 +00002220 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00002221 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00002222
John McCall178360e2011-07-11 08:38:19 +00002223 if (useEHCleanup)
2224 PopCleanupBlock();
2225
John McCall82fe67b2011-07-09 01:37:26 +00002226 // Check whether we've reached the end.
2227 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
2228 Builder.CreateCondBr(done, doneBB, bodyBB);
2229 elementPast->addIncoming(element, Builder.GetInsertBlock());
2230
2231 // Done.
2232 EmitBlock(doneBB);
2233}
2234
John McCall178360e2011-07-11 08:38:19 +00002235/// Perform partial array destruction as if in an EH cleanup. Unlike
2236/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00002237static void emitPartialArrayDestroy(CodeGenFunction &CGF,
2238 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00002239 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002240 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00002241 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00002242 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00002243 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
2244 // VLAs don't require a GEP index to walk into.
2245 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00002246 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00002247 type = arrayType->getElementType();
2248 }
John McCall97eab0a2011-07-13 08:09:46 +00002249
2250 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00002251 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00002252
John McCallf0f0b7a2015-09-14 18:57:08 +00002253 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00002254 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
2255 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00002256 }
2257
John McCall97eab0a2011-07-13 08:09:46 +00002258 // Destroy the array. We don't ever need an EH cleanup because we
2259 // assume that we're in an EH cleanup ourselves, so a throwing
2260 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00002261 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00002262 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00002263}
2264
John McCall82fe67b2011-07-09 01:37:26 +00002265namespace {
John McCall178360e2011-07-11 08:38:19 +00002266 /// RegularPartialArrayDestroy - a cleanup which performs a partial
2267 /// array destroy where the end pointer is regularly determined and
2268 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00002269 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00002270 llvm::Value *ArrayBegin;
2271 llvm::Value *ArrayEnd;
2272 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00002273 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00002274 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00002275 public:
2276 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002277 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00002278 CodeGenFunction::Destroyer *destroyer)
2279 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00002280 ElementType(elementType), Destroyer(destroyer),
2281 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00002282
Craig Topper4f12f102014-03-12 06:41:41 +00002283 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00002284 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002285 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00002286 }
2287 };
2288
2289 /// IrregularPartialArrayDestroy - a cleanup which performs a
2290 /// partial array destroy where the end pointer is irregularly
2291 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00002292 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00002293 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00002294 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00002295 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00002296 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00002297 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00002298 public:
John McCall178360e2011-07-11 08:38:19 +00002299 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00002300 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00002301 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00002302 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00002303 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00002304 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00002305 ElementType(elementType), Destroyer(destroyer),
2306 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00002307
Craig Topper4f12f102014-03-12 06:41:41 +00002308 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00002309 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00002310 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002311 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00002312 }
2313 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002314} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00002315
John McCall178360e2011-07-11 08:38:19 +00002316/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00002317/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00002318/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00002319///
John McCall82fe67b2011-07-09 01:37:26 +00002320/// \param elementType - the immediate element type of the array;
2321/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00002322void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00002323 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00002324 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00002325 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002326 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00002327 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
2328 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00002329 elementType, elementAlign,
2330 destroyer);
John McCall178360e2011-07-11 08:38:19 +00002331}
2332
2333/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2334/// already-constructed elements of the given array. The cleanup
2335/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00002336///
John McCall178360e2011-07-11 08:38:19 +00002337/// \param elementType - the immediate element type of the array;
2338/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00002339void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2340 llvm::Value *arrayEnd,
2341 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00002342 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002343 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00002344 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00002345 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002346 elementType, elementAlign,
2347 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00002348}
2349
Nadav Rotem1da30942013-03-23 06:43:35 +00002350/// Lazily declare the @llvm.lifetime.start intrinsic.
James Y Knight76f78742019-02-05 19:17:50 +00002351llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00002352 if (LifetimeStartFn)
2353 return LifetimeStartFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00002354 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00002355 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00002356 return LifetimeStartFn;
2357}
2358
2359/// Lazily declare the @llvm.lifetime.end intrinsic.
James Y Knight76f78742019-02-05 19:17:50 +00002360llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00002361 if (LifetimeEndFn)
2362 return LifetimeEndFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00002363 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00002364 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00002365 return LifetimeEndFn;
2366}
2367
John McCall31168b02011-06-15 23:02:42 +00002368namespace {
2369 /// A cleanup to perform a release of an object at the end of a
2370 /// function. This is used to balance out the incoming +1 of a
2371 /// ns_consumed argument when we can't reasonably do that just by
2372 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00002373 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00002374 ConsumeARCParameter(llvm::Value *param,
2375 ARCPreciseLifetime_t precise)
2376 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00002377
2378 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00002379 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00002380
Craig Topper4f12f102014-03-12 06:41:41 +00002381 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00002382 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00002383 }
2384 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002385} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00002386
Mike Stump11289f42009-09-09 15:08:12 +00002387/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00002388/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00002389void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2390 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00002391 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00002392 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00002393 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00002394
John McCall7f416cc2015-09-08 08:05:57 +00002395 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00002396
Adrian Prantl51936dd2013-03-14 17:53:33 +00002397 QualType Ty = D.getType();
2398
John McCall147d0212011-02-22 22:38:33 +00002399 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00002400 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00002401 // The only implicit argument a block has is its literal.
Saleem Abdulrasoolc1b46382018-02-21 21:47:51 +00002402 // This may be passed as an inalloca'ed value on Windows x86.
John McCall147d0212011-02-22 22:38:33 +00002403 if (BlockInfo) {
Saleem Abdulrasoolc1b46382018-02-21 21:47:51 +00002404 llvm::Value *V = Arg.isIndirect()
2405 ? Builder.CreateLoad(Arg.getIndirectAddress())
2406 : Arg.getDirectValue();
2407 setBlockContextParameter(IPD, ArgNo, V);
John McCall147d0212011-02-22 22:38:33 +00002408 return;
2409 }
2410 }
2411
John McCall7f416cc2015-09-08 08:05:57 +00002412 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002413 bool DoStore = false;
2414 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002415 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002416 if (Arg.isIndirect()) {
2417 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00002418 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00002419 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00002420 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00002421 if (DeclPtr.getType() != IRTy)
2422 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
Yaxun Liu5b330e82018-03-15 15:25:19 +00002423 // Indirect argument is in alloca address space, which may be different
2424 // from the default address space.
2425 auto AllocaAS = CGM.getASTAllocaAddressSpace();
2426 auto *V = DeclPtr.getPointer();
2427 auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2428 auto DestLangAS =
2429 getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
2430 if (SrcLangAS != DestLangAS) {
2431 assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2432 CGM.getDataLayout().getAllocaAddrSpace());
2433 auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2434 auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
2435 DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
2436 *this, V, SrcLangAS, DestLangAS, T, true),
2437 DeclPtr.getAlignment());
2438 }
John McCall7f416cc2015-09-08 08:05:57 +00002439
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002440 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00002441 // Don't push a cleanup in a thunk for a method that will also emit a
2442 // cleanup.
Akira Hatanaka85282972018-05-15 21:00:30 +00002443 if (hasAggregateEvaluationKind(Ty) && !CurFuncIsThunk &&
2444 Ty->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
Akira Hatanaka7275da02018-02-28 07:15:55 +00002445 if (QualType::DestructionKind DtorKind = Ty.isDestructedType()) {
2446 assert((DtorKind == QualType::DK_cxx_destructor ||
2447 DtorKind == QualType::DK_nontrivial_c_struct) &&
2448 "unexpected destructor type");
2449 pushDestroy(DtorKind, DeclPtr, Ty);
Akira Hatanakaccda3d22018-04-27 06:57:00 +00002450 CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2451 EHStack.stable_begin();
Akira Hatanaka7275da02018-02-28 07:15:55 +00002452 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002453 }
Chris Lattner53621a52007-06-13 20:44:40 +00002454 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002455 // Check if the parameter address is controlled by OpenMP runtime.
2456 Address OpenMPLocalAddr =
2457 getLangOpts().OpenMP
2458 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
2459 : Address::invalid();
2460 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2461 DeclPtr = OpenMPLocalAddr;
2462 } else {
2463 // Otherwise, create a temporary to hold the value.
2464 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2465 D.getName() + ".addr");
2466 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002467 DoStore = true;
2468 }
Mike Stump11289f42009-09-09 15:08:12 +00002469
John McCall7f416cc2015-09-08 08:05:57 +00002470 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2471
2472 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002473 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00002474 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00002475 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2476 // We honor __attribute__((ns_consumed)) for types with lifetime.
2477 // For __strong, it's handled by just skipping the initial retain;
2478 // otherwise we have to balance out the initial +1 with an extra
2479 // cleanup to do the release at the end of the function.
2480 bool isConsumed = D.hasAttr<NSConsumedAttr>();
2481
Erik Pilkington1e368822019-01-04 18:33:06 +00002482 // If a parameter is pseudo-strong then we can omit the implicit retain.
John McCalld4631322011-06-17 06:42:21 +00002483 if (D.isARCPseudoStrong()) {
Erik Pilkington1e368822019-01-04 18:33:06 +00002484 assert(lt == Qualifiers::OCL_Strong &&
2485 "pseudo-strong variable isn't strong?");
2486 assert(qs.hasConst() && "pseudo-strong variable should be const!");
John McCall31168b02011-06-15 23:02:42 +00002487 lt = Qualifiers::OCL_ExplicitNone;
2488 }
2489
Saleem Abdulrasoolda6784e2017-06-27 18:37:51 +00002490 // Load objects passed indirectly.
2491 if (Arg.isIndirect() && !ArgVal)
2492 ArgVal = Builder.CreateLoad(DeclPtr);
2493
John McCall31168b02011-06-15 23:02:42 +00002494 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002495 if (!isConsumed) {
2496 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2497 // use objc_storeStrong(&dest, value) for retaining the
2498 // object. But first, store a null into 'dest' because
2499 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002500 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002501 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
John McCall7f416cc2015-09-08 08:05:57 +00002502 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002503 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002504 }
2505 else
John McCall31168b02011-06-15 23:02:42 +00002506 // Don't use objc_retainBlock for block pointers, because we
2507 // don't want to Block_copy something just because we got it
2508 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00002509 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002510 }
John McCall31168b02011-06-15 23:02:42 +00002511 } else {
2512 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00002513 if (isConsumed) {
2514 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2515 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00002516 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00002517 precise);
2518 }
John McCall31168b02011-06-15 23:02:42 +00002519
2520 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00002521 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002522 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00002523 }
2524 }
2525
2526 // Enter the cleanup scope.
2527 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2528 }
Chris Lattner53621a52007-06-13 20:44:40 +00002529 }
2530
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002531 // Store the initial value into the alloca.
2532 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00002533 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002534
John McCall7f416cc2015-09-08 08:05:57 +00002535 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00002536
2537 // Emit debug info for param declaration.
Alexey Samsonov74a38682012-05-04 07:39:27 +00002538 if (CGDebugInfo *DI = getDebugInfo()) {
Benjamin Kramer8c305922016-02-02 11:06:51 +00002539 if (CGM.getCodeGenOpts().getDebugInfo() >=
2540 codegenoptions::LimitedDebugInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002541 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00002542 }
2543 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002544
2545 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002546 EmitVarAnnotations(&D, DeclPtr.getPointer());
Vedant Kumar42c17ec2017-03-14 01:56:34 +00002547
2548 // We can only check return value nullability if all arguments to the
2549 // function satisfy their nullability preconditions. This makes it necessary
2550 // to emit null checks for args in the function body itself.
2551 if (requiresReturnValueNullabilityCheck()) {
2552 auto Nullability = Ty->getNullability(getContext());
2553 if (Nullability && *Nullability == NullabilityKind::NonNull) {
2554 SanitizerScope SanScope(this);
2555 RetValNullabilityPrecondition =
2556 Builder.CreateAnd(RetValNullabilityPrecondition,
2557 Builder.CreateIsNotNull(Arg.getAnyValue()));
2558 }
2559 }
Chris Lattner53621a52007-06-13 20:44:40 +00002560}
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002561
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002562void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2563 CodeGenFunction *CGF) {
2564 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2565 return;
2566 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2567}
Kelvin Li1408f912018-09-26 04:28:39 +00002568
Michael Kruse251e1482019-02-01 20:25:04 +00002569void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
2570 CodeGenFunction *CGF) {
2571 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2572 return;
2573 // FIXME: need to implement mapper code generation
2574}
2575
Kelvin Li1408f912018-09-26 04:28:39 +00002576void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
Patrick Lyster8f7f5862018-11-19 15:09:33 +00002577 getOpenMPRuntime().checkArchForUnifiedAddressing(*this, D);
Kelvin Li1408f912018-09-26 04:28:39 +00002578}