blob: 528cc125798b09b0ccbf4b59bcf9c82376e9e3de [file] [log] [blame]
Chris Lattner84915fa2007-06-02 04:16:21 +00001//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner84915fa2007-06-02 04:16:21 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Decl nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
John McCall7f416cc2015-09-08 08:05:57 +000013#include "CGBlocks.h"
Reid Klecknere5a321b2016-09-07 18:21:30 +000014#include "CGCXXABI.h"
David Majnemerdc012fa2015-04-22 21:38:15 +000015#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CGDebugInfo.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000017#include "CGOpenCLRuntime.h"
Alexey Bataevc5b1d322016-03-04 09:22:22 +000018#include "CGOpenMPRuntime.h"
Yaxun Liu6d96f1632017-05-18 18:51:09 +000019#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000021#include "ConstantEmitter.h"
JF Bastienef202c32019-04-12 00:11:27 +000022#include "PatternInit.h"
Yaxun Liu6d96f1632017-05-18 18:51:09 +000023#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000024#include "clang/AST/ASTContext.h"
Reid Kleckner98031782019-12-09 16:11:56 -080025#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000026#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000027#include "clang/AST/Decl.h"
Anders Carlsson4c03d982008-08-25 01:38:19 +000028#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000029#include "clang/AST/DeclOpenMP.h"
Richard Trieu63688182018-12-11 03:18:39 +000030#include "clang/Basic/CodeGenOptions.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000031#include "clang/Basic/SourceManager.h"
Chris Lattnerb781dc792008-05-08 05:58:21 +000032#include "clang/Basic/TargetInfo.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000033#include "clang/CodeGen/CGFunctionInfo.h"
Reid Kleckner01943a52020-01-30 13:33:38 -080034#include "clang/Sema/Sema.h"
JF Bastien2f0582f2018-09-21 13:54:09 +000035#include "llvm/Analysis/ValueTracking.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000036#include "llvm/IR/DataLayout.h"
37#include "llvm/IR/GlobalVariable.h"
38#include "llvm/IR/Intrinsics.h"
39#include "llvm/IR/Type.h"
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +000040
Chris Lattner84915fa2007-06-02 04:16:21 +000041using namespace clang;
42using namespace CodeGen;
43
Reid Kleckner01943a52020-01-30 13:33:38 -080044static_assert(clang::Sema::MaximumAlignment <= llvm::Value::MaximumAlignment,
45 "Clang max alignment greater than what LLVM supports?");
46
Chris Lattner1ad38f82007-06-09 01:20:56 +000047void CodeGenFunction::EmitDecl(const Decl &D) {
Chris Lattner1ad38f82007-06-09 01:20:56 +000048 switch (D.getKind()) {
David Majnemerd9b1a4f2015-11-04 03:40:30 +000049 case Decl::BuiltinTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000050 case Decl::TranslationUnit:
Richard Smithf19e1272015-03-07 00:04:49 +000051 case Decl::ExternCContext:
Douglas Gregor19043f02010-04-23 02:02:43 +000052 case Decl::Namespace:
53 case Decl::UnresolvedUsingTypename:
54 case Decl::ClassTemplateSpecialization:
55 case Decl::ClassTemplatePartialSpecialization:
Larisse Voufo39a1e502013-08-06 01:03:05 +000056 case Decl::VarTemplateSpecialization:
57 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor19043f02010-04-23 02:02:43 +000058 case Decl::TemplateTypeParm:
59 case Decl::UnresolvedUsingValue:
Alexis Hunted053252010-05-30 07:21:58 +000060 case Decl::NonTypeTemplateParm:
Richard Smithbc491202017-02-17 20:05:37 +000061 case Decl::CXXDeductionGuide:
Douglas Gregor19043f02010-04-23 02:02:43 +000062 case Decl::CXXMethod:
63 case Decl::CXXConstructor:
64 case Decl::CXXDestructor:
65 case Decl::CXXConversion:
66 case Decl::Field:
John McCall5e77d762013-04-16 07:28:30 +000067 case Decl::MSProperty:
Francois Pichetdf946c32010-11-21 06:49:41 +000068 case Decl::IndirectField:
Douglas Gregor19043f02010-04-23 02:02:43 +000069 case Decl::ObjCIvar:
Eric Christopher31ab1302011-08-23 22:38:00 +000070 case Decl::ObjCAtDefsField:
Chris Lattnerba9dddb2007-10-08 21:37:32 +000071 case Decl::ParmVar:
Douglas Gregor19043f02010-04-23 02:02:43 +000072 case Decl::ImplicitParam:
73 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +000074 case Decl::VarTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000075 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +000076 case Decl::TypeAliasTemplate:
Douglas Gregor19043f02010-04-23 02:02:43 +000077 case Decl::TemplateTemplateParm:
78 case Decl::ObjCMethod:
79 case Decl::ObjCCategory:
80 case Decl::ObjCProtocol:
81 case Decl::ObjCInterface:
82 case Decl::ObjCCategoryImpl:
83 case Decl::ObjCImplementation:
84 case Decl::ObjCProperty:
85 case Decl::ObjCCompatibleAlias:
Nico Weber66220292016-03-02 17:28:48 +000086 case Decl::PragmaComment:
Nico Webercbbaeb12016-03-02 19:28:54 +000087 case Decl::PragmaDetectMismatch:
Abramo Bagnarad7340582010-06-05 05:09:32 +000088 case Decl::AccessSpec:
Douglas Gregor19043f02010-04-23 02:02:43 +000089 case Decl::LinkageSpec:
Richard Smith8df390f2016-09-08 23:14:54 +000090 case Decl::Export:
Douglas Gregor19043f02010-04-23 02:02:43 +000091 case Decl::ObjCPropertyImpl:
Douglas Gregor19043f02010-04-23 02:02:43 +000092 case Decl::FileScopeAsm:
93 case Decl::Friend:
94 case Decl::FriendTemplate:
95 case Decl::Block:
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +000096 case Decl::Captured:
Francois Pichet00c7e6c2011-08-14 03:52:19 +000097 case Decl::ClassScopeFunctionSpecialization:
David Blaikiebd483762013-05-20 04:58:53 +000098 case Decl::UsingShadow:
Richard Smith5179eb72016-06-28 19:03:57 +000099 case Decl::ConstructorUsingShadow:
Douglas Gregor85f3f952015-07-07 03:57:15 +0000100 case Decl::ObjCTypeParam:
Richard Smithda383632016-08-15 01:33:41 +0000101 case Decl::Binding:
David Blaikie83d382b2011-09-23 05:06:16 +0000102 llvm_unreachable("Declaration should not be in declstmts!");
Amjad Abouddc4531e2016-04-30 01:44:38 +0000103 case Decl::Function: // void X();
104 case Decl::Record: // struct/union/class X;
105 case Decl::Enum: // enum X;
106 case Decl::EnumConstant: // enum ? { X = ? }
107 case Decl::CXXRecord: // struct/union/class X; [C++]
Anders Carlssonce2cd012009-12-03 17:26:31 +0000108 case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
Chris Lattner43e7f312011-02-18 02:08:43 +0000109 case Decl::Label: // __label__ x;
Douglas Gregorba345522011-12-02 23:23:56 +0000110 case Decl::Import:
Richard Smithbab6df82020-04-11 22:15:29 -0700111 case Decl::MSGuid: // __declspec(uuid("..."))
Alexey Bataeva769e072013-03-22 06:34:35 +0000112 case Decl::OMPThreadPrivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000113 case Decl::OMPAllocate:
Alexey Bataev4244be22016-02-11 05:35:55 +0000114 case Decl::OMPCapturedExpr:
Kelvin Li1408f912018-09-26 04:28:39 +0000115 case Decl::OMPRequires:
Michael Han84324352013-02-22 17:15:32 +0000116 case Decl::Empty:
Saar Razd7aae332019-07-10 21:25:49 +0000117 case Decl::Concept:
Tykerb0561b32019-11-17 11:41:55 +0100118 case Decl::LifetimeExtendedTemporary:
Saar Raza0f50d72020-01-18 09:11:43 +0200119 case Decl::RequiresExprBody:
Chris Lattner84915fa2007-06-02 04:16:21 +0000120 // None of these decls require codegen support.
121 return;
David Blaikieb7d1e1f2013-02-02 00:39:32 +0000122
David Blaikief121b932013-05-20 22:50:41 +0000123 case Decl::NamespaceAlias:
124 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000125 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
David Blaikief121b932013-05-20 22:50:41 +0000126 return;
David Blaikiebd483762013-05-20 04:58:53 +0000127 case Decl::Using: // using X; [C++]
128 if (CGDebugInfo *DI = getDebugInfo())
Amjad Abouddc4531e2016-04-30 01:44:38 +0000129 DI->EmitUsingDecl(cast<UsingDecl>(D));
David Blaikiebd483762013-05-20 04:58:53 +0000130 return;
Richard Smith151c4562016-12-20 21:35:28 +0000131 case Decl::UsingPack:
132 for (auto *Using : cast<UsingPackDecl>(D).expansions())
133 EmitDecl(*Using);
134 return;
David Blaikie9f88fe82013-04-22 06:13:21 +0000135 case Decl::UsingDirective: // using namespace X; [C++]
136 if (CGDebugInfo *DI = getDebugInfo())
137 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
138 return;
Richard Smithbdb84f32016-07-22 23:36:59 +0000139 case Decl::Var:
140 case Decl::Decomposition: {
Daniel Dunbara7998072008-08-29 17:28:43 +0000141 const VarDecl &VD = cast<VarDecl>(D);
John McCall1c9c3fd2010-10-15 04:57:14 +0000142 assert(VD.isLocalVarDecl() &&
Daniel Dunbara7998072008-08-29 17:28:43 +0000143 "Should not see file-scope variables inside a function!");
Richard Smithda383632016-08-15 01:33:41 +0000144 EmitVarDecl(VD);
145 if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
146 for (auto *B : DD->bindings())
147 if (auto *HD = B->getHoldingVar())
148 EmitVarDecl(*HD);
149 return;
Chris Lattner84915fa2007-06-02 04:16:21 +0000150 }
Mike Stump11289f42009-09-09 15:08:12 +0000151
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000152 case Decl::OMPDeclareReduction:
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000153 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +0000154
Michael Kruse251e1482019-02-01 20:25:04 +0000155 case Decl::OMPDeclareMapper:
156 return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
157
Richard Smithdda56e42011-04-15 14:24:37 +0000158 case Decl::Typedef: // typedef int X;
159 case Decl::TypeAlias: { // using X = int; [C++0x]
160 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
Anders Carlsson5d985f52008-12-20 21:51:53 +0000161 QualType Ty = TD.getUnderlyingType();
Mike Stump11289f42009-09-09 15:08:12 +0000162
Anders Carlsson5d985f52008-12-20 21:51:53 +0000163 if (Ty->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000164 EmitVariablyModifiedType(Ty);
Hamza Soodd14003d2019-07-05 14:36:08 +0000165
166 return;
Anders Carlsson5d985f52008-12-20 21:51:53 +0000167 }
Daniel Dunbara7998072008-08-29 17:28:43 +0000168 }
Chris Lattner84915fa2007-06-02 04:16:21 +0000169}
Chris Lattner03df1222007-06-02 04:53:11 +0000170
John McCall1c9c3fd2010-10-15 04:57:14 +0000171/// EmitVarDecl - This method handles emission of any variable declaration
Chris Lattner03df1222007-06-02 04:53:11 +0000172/// inside a function, including static vars etc.
John McCall1c9c3fd2010-10-15 04:57:14 +0000173void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
Yaxun Liu4f33b3d2017-05-15 14:47:47 +0000174 if (D.hasExternalStorage())
175 // Don't emit it now, allow it to be emitted lazily on its first use.
176 return;
177
178 // Some function-scope variable does not have static storage but still
179 // needs to be emitted like a static variable, e.g. a function-scope
180 // variable in constant address space in OpenCL.
181 if (D.getStorageDuration() != SD_Automatic) {
Alexey Baderbed40092017-11-15 11:38:17 +0000182 // Static sampler variables translated to function calls.
183 if (D.getType()->isSamplerT())
184 return;
185
Eric Christopher31ab1302011-08-23 22:38:00 +0000186 llvm::GlobalValue::LinkageTypes Linkage =
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000187 CGM.getLLVMLinkageVarDefinition(&D, /*IsConstant=*/false);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000188
David Majnemer27d69db2014-04-28 22:17:59 +0000189 // FIXME: We need to force the emission/use of a guard variable for
190 // some variables even if we can constant-evaluate them because
191 // we can't guarantee every translation unit will constant-evaluate them.
Eric Christopher31ab1302011-08-23 22:38:00 +0000192
John McCall1c9c3fd2010-10-15 04:57:14 +0000193 return EmitStaticVarDecl(D, Linkage);
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000194 }
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000195
Anastasia Stulovabcea6962015-09-30 14:08:20 +0000196 if (D.getType().getAddressSpace() == LangAS::opencl_local)
Enea Zaffanellacf51a8a2013-05-16 11:27:56 +0000197 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
198
199 assert(D.hasLocalStorage());
200 return EmitAutoVarDecl(D);
Chris Lattner03df1222007-06-02 04:53:11 +0000201}
202
Reid Kleckner453e0562014-10-08 01:07:54 +0000203static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
204 if (CGM.getLangOpts().CPlusPlus)
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000205 return CGM.getMangledName(&D).str();
206
Reid Kleckner453e0562014-10-08 01:07:54 +0000207 // If this isn't C++, we don't need a mangled name, just a pretty one.
208 assert(!D.isExternallyVisible() && "name shouldn't matter");
209 std::string ContextName;
210 const DeclContext *DC = D.getDeclContext();
Alexey Bataev43f74392015-05-07 06:28:46 +0000211 if (auto *CD = dyn_cast<CapturedDecl>(DC))
212 DC = cast<DeclContext>(CD->getNonClosureContext());
Reid Kleckner453e0562014-10-08 01:07:54 +0000213 if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Benjamin Krameradcd0262020-01-28 20:23:46 +0100214 ContextName = std::string(CGM.getMangledName(FD));
Reid Kleckner453e0562014-10-08 01:07:54 +0000215 else if (const auto *BD = dyn_cast<BlockDecl>(DC))
Benjamin Krameradcd0262020-01-28 20:23:46 +0100216 ContextName = std::string(CGM.getBlockMangledName(GlobalDecl(), BD));
Reid Kleckner453e0562014-10-08 01:07:54 +0000217 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
218 ContextName = OMD->getSelector().getAsString();
Chris Lattnere99c1102009-12-05 08:22:11 +0000219 else
David Blaikie83d382b2011-09-23 05:06:16 +0000220 llvm_unreachable("Unknown context for static var decl");
Eric Christopher31ab1302011-08-23 22:38:00 +0000221
Reid Kleckner453e0562014-10-08 01:07:54 +0000222 ContextName += "." + D.getNameAsString();
223 return ContextName;
Chris Lattnere99c1102009-12-05 08:22:11 +0000224}
225
Reid Kleckner453e0562014-10-08 01:07:54 +0000226llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
227 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
228 // In general, we don't always emit static var decls once before we reference
229 // them. It is possible to reference them before emitting the function that
230 // contains them, and it is possible to emit the containing function multiple
231 // times.
232 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
233 return ExistingGV;
234
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000235 QualType Ty = D.getType();
Eli Friedmana682d392008-02-15 12:20:59 +0000236 assert(Ty->isConstantSizeType() && "VLAs can't be static");
Nate Begemanfaae0812008-04-19 04:17:09 +0000237
Benjamin Kramerddbb2b82011-11-20 21:05:04 +0000238 // Use the label if the variable is renamed with the asm-label extension.
239 std::string Name;
Benjamin Kramer5642e192011-11-21 15:47:23 +0000240 if (D.hasAttr<AsmLabelAttr>())
Benjamin Krameradcd0262020-01-28 20:23:46 +0100241 Name = std::string(getMangledName(&D));
Benjamin Kramer5642e192011-11-21 15:47:23 +0000242 else
Reid Kleckner453e0562014-10-08 01:07:54 +0000243 Name = getStaticDeclName(*this, D);
Nate Begemanfaae0812008-04-19 04:17:09 +0000244
Reid Kleckner453e0562014-10-08 01:07:54 +0000245 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
Alexander Richardson6d989432017-10-15 18:48:14 +0000246 LangAS AS = GetGlobalVarAddressSpace(&D);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000247 unsigned TargetAS = getContext().getTargetAddressSpace(AS);
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000248
Yaxun Liua64a4912018-04-02 17:38:24 +0000249 // OpenCL variables in local address space and CUDA shared
250 // variables cannot have an initializer.
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000251 llvm::Constant *Init = nullptr;
Yaxun Liua64a4912018-04-02 17:38:24 +0000252 if (Ty.getAddressSpace() == LangAS::opencl_local ||
Jon Chesterfieldc45eaea2020-03-17 21:22:04 +0000253 D.hasAttr<CUDASharedAttr>() || D.hasAttr<LoaderUninitializedAttr>())
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000254 Init = llvm::UndefValue::get(LTy);
Yaxun Liua64a4912018-04-02 17:38:24 +0000255 else
256 Init = EmitNullConstant(Ty);
Matt Arsenault3f6469b2014-11-03 16:51:53 +0000257
Yaxun Liucbf647c2017-07-08 13:24:52 +0000258 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
259 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
260 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
Guillaume Chateletc79099e2019-10-03 13:00:29 +0000261 GV->setAlignment(getContext().getDeclAlign(&D).getAsAlign());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000262
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +0000263 if (supportsCOMDAT() && GV->isWeakForLinker())
264 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindola0d4fb982015-01-12 22:13:53 +0000265
Richard Smithfd3834f2013-04-13 02:43:54 +0000266 if (D.getTLSKind())
Reid Kleckner453e0562014-10-08 01:07:54 +0000267 setTLSMode(GV, D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000268
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000269 setGVProperties(GV, &D);
270
Eli Benderskycb399432014-03-24 22:05:38 +0000271 // Make sure the result is of the correct type.
Alexander Richardson6d989432017-10-15 18:48:14 +0000272 LangAS ExpectedAS = Ty.getAddressSpace();
Reid Kleckner453e0562014-10-08 01:07:54 +0000273 llvm::Constant *Addr = GV;
Yaxun Liucbf647c2017-07-08 13:24:52 +0000274 if (AS != ExpectedAS) {
275 Addr = getTargetCodeGenInfo().performAddrSpaceCast(
276 *this, GV, AS, ExpectedAS,
277 LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
Eli Benderskycb399432014-03-24 22:05:38 +0000278 }
279
Reid Kleckner453e0562014-10-08 01:07:54 +0000280 setStaticLocalDeclAddress(&D, Addr);
281
282 // Ensure that the static local gets initialized by making sure the parent
283 // function gets emitted eventually.
284 const Decl *DC = cast<Decl>(D.getDeclContext());
285
286 // We can't name blocks or captured statements directly, so try to emit their
287 // parents.
288 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
289 DC = DC->getNonClosureContext();
290 // FIXME: Ensure that global blocks get emitted.
291 if (!DC)
292 return Addr;
293 }
294
295 GlobalDecl GD;
296 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
297 GD = GlobalDecl(CD, Ctor_Base);
298 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
299 GD = GlobalDecl(DD, Dtor_Base);
300 else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
Michael Liao4cf01ed2020-03-18 01:43:20 -0400301 GD = GlobalDecl(FD);
Reid Kleckner453e0562014-10-08 01:07:54 +0000302 else {
303 // Don't do anything for Obj-C method decls or global closures. We should
304 // never defer them.
305 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
306 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +0000307 if (GD.getDecl()) {
308 // Disable emission of the parent function for the OpenMP device codegen.
309 CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
Reid Kleckner453e0562014-10-08 01:07:54 +0000310 (void)GetAddrOfGlobal(GD);
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +0000311 }
Reid Kleckner453e0562014-10-08 01:07:54 +0000312
313 return Addr;
Daniel Dunbar22a87f92009-02-25 19:24:29 +0000314}
315
Chandler Carruth84537952012-03-30 19:44:53 +0000316/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
317/// global variable that has already been created for it. If the initializer
318/// has a different type than GV does, this may free GV and return a different
319/// one. Otherwise it just returns GV.
320llvm::GlobalVariable *
John McCall1c9c3fd2010-10-15 04:57:14 +0000321CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000322 llvm::GlobalVariable *GV) {
John McCallde0fe072017-08-15 21:42:52 +0000323 ConstantEmitter emitter(*this);
324 llvm::Constant *Init = emitter.tryEmitForInitializer(D);
John McCall70013b62010-07-15 23:40:35 +0000325
Chris Lattnere99c1102009-12-05 08:22:11 +0000326 // If constant emission failed, then this should be a C++ static
327 // initializer.
Chandler Carruth84537952012-03-30 19:44:53 +0000328 if (!Init) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000329 if (!getLangOpts().CPlusPlus)
Chris Lattnere99c1102009-12-05 08:22:11 +0000330 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
Matthias Braun44bfe032017-01-10 17:43:01 +0000331 else if (HaveInsertPoint()) {
Eric Christopher31ab1302011-08-23 22:38:00 +0000332 // Since we have a static initializer, this global variable can't
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000333 // be constant.
Chandler Carruth84537952012-03-30 19:44:53 +0000334 GV->setConstant(false);
John McCall68ff0372010-09-08 01:44:27 +0000335
Chandler Carruth84537952012-03-30 19:44:53 +0000336 EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
Anders Carlsson20bbbd42010-01-26 04:02:23 +0000337 }
Chandler Carruth84537952012-03-30 19:44:53 +0000338 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000339 }
John McCall70013b62010-07-15 23:40:35 +0000340
Chris Lattnere99c1102009-12-05 08:22:11 +0000341 // The initializer may differ in type from the global. Rewrite
342 // the global to match the initializer. (We have to do this
343 // because some types, like unions, can't be completely represented
344 // in the LLVM type system.)
Eli Friedman83fa8112020-04-03 15:11:40 -0700345 if (GV->getValueType() != Init->getType()) {
Chandler Carruth84537952012-03-30 19:44:53 +0000346 llvm::GlobalVariable *OldGV = GV;
347
348 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
349 OldGV->isConstant(),
350 OldGV->getLinkage(), Init, "",
351 /*InsertBefore*/ OldGV,
Hans Wennborgd3b01bc2012-06-23 11:51:46 +0000352 OldGV->getThreadLocalMode(),
Chandler Carruth84537952012-03-30 19:44:53 +0000353 CGM.getContext().getTargetAddressSpace(D.getType()));
354 GV->setVisibility(OldGV->getVisibility());
Rafael Espindola699f5d62018-02-07 22:15:33 +0000355 GV->setDSOLocal(OldGV->isDSOLocal());
Reid Klecknereab97d32015-07-20 20:35:30 +0000356 GV->setComdat(OldGV->getComdat());
Eric Christopher31ab1302011-08-23 22:38:00 +0000357
Chris Lattnere99c1102009-12-05 08:22:11 +0000358 // Steal the name of the old global
Chandler Carruth84537952012-03-30 19:44:53 +0000359 GV->takeName(OldGV);
Eric Christopher31ab1302011-08-23 22:38:00 +0000360
Chris Lattnere99c1102009-12-05 08:22:11 +0000361 // Replace all uses of the old global with the new global
Chandler Carruth84537952012-03-30 19:44:53 +0000362 llvm::Constant *NewPtrForOldDecl =
363 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
364 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
Eric Christopher31ab1302011-08-23 22:38:00 +0000365
Chris Lattnere99c1102009-12-05 08:22:11 +0000366 // Erase the old global, since it is no longer used.
Chandler Carruth84537952012-03-30 19:44:53 +0000367 OldGV->eraseFromParent();
Chris Lattnere99c1102009-12-05 08:22:11 +0000368 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000369
Chandler Carruth84537952012-03-30 19:44:53 +0000370 GV->setConstant(CGM.isTypeConstant(D.getType(), true));
371 GV->setInitializer(Init);
Richard Smith6331c402012-02-13 22:16:19 +0000372
John McCallde0fe072017-08-15 21:42:52 +0000373 emitter.finalize(GV);
374
Richard Smith7a384682020-01-10 15:16:15 -0800375 if (D.needsDestruction(getContext()) == QualType::DK_cxx_destructor &&
376 HaveInsertPoint()) {
Richard Smith6331c402012-02-13 22:16:19 +0000377 // We have a constant initializer, but a nontrivial destructor. We still
378 // need to perform a guarded "initialization" in order to register the
Richard Smithe070fd22012-02-17 06:48:11 +0000379 // destructor.
Chandler Carruth84537952012-03-30 19:44:53 +0000380 EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
Richard Smith6331c402012-02-13 22:16:19 +0000381 }
382
Chandler Carruth84537952012-03-30 19:44:53 +0000383 return GV;
Chris Lattnere99c1102009-12-05 08:22:11 +0000384}
385
John McCall1c9c3fd2010-10-15 04:57:14 +0000386void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
Anders Carlssoncee2d2f2010-02-07 02:03:08 +0000387 llvm::GlobalValue::LinkageTypes Linkage) {
John McCallb88a5662012-03-30 21:00:39 +0000388 // Check to see if we already have a global variable for this
389 // declaration. This can happen when double-emitting function
390 // bodies, e.g. with complete and base constructors.
Reid Kleckner453e0562014-10-08 01:07:54 +0000391 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
John McCall7f416cc2015-09-08 08:05:57 +0000392 CharUnits alignment = getContext().getDeclAlign(&D);
Daniel Dunbara374e602009-02-25 19:45:19 +0000393
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000394 // Store into LocalDeclMap before generating initializer to handle
395 // circular references.
John McCall7f416cc2015-09-08 08:05:57 +0000396 setAddrOfLocalVar(&D, Address(addr, alignment));
Daniel Dunbar1cdbc542009-02-25 20:08:33 +0000397
John McCall4a39ab82010-05-04 20:45:42 +0000398 // We can't have a VLA here, but we can have a pointer to a VLA,
399 // even though that doesn't really make any sense.
Eli Friedmanbc633be2009-04-20 03:54:15 +0000400 // Make sure to evaluate VLA bounds now so that we have them for later.
401 if (D.getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000402 EmitVariablyModifiedType(D.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000403
John McCallb88a5662012-03-30 21:00:39 +0000404 // Save the type in case adding the initializer forces a type change.
405 llvm::Type *expectedType = addr->getType();
Eli Friedmanbc633be2009-04-20 03:54:15 +0000406
Eli Benderskycb399432014-03-24 22:05:38 +0000407 llvm::GlobalVariable *var =
408 cast<llvm::GlobalVariable>(addr->stripPointerCasts());
Artem Belevich4d430ba2016-05-09 22:09:56 +0000409
410 // CUDA's local and local static __shared__ variables should not
411 // have any non-empty initializers. This is ensured by Sema.
412 // Whatever initializer such variable may have when it gets here is
413 // a no-op and should not be emitted.
414 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
415 D.hasAttr<CUDASharedAttr>();
Chris Lattnere99c1102009-12-05 08:22:11 +0000416 // If this value has an initializer, emit it.
Artem Belevich4d430ba2016-05-09 22:09:56 +0000417 if (D.getInit() && !isCudaSharedVar)
John McCallb88a5662012-03-30 21:00:39 +0000418 var = AddInitializerToStaticVarDecl(D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000419
Guillaume Chateletc79099e2019-10-03 13:00:29 +0000420 var->setAlignment(alignment.getAsAlign());
Chris Lattner4d941092010-03-10 23:59:59 +0000421
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000422 if (D.hasAttr<AnnotateAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000423 CGM.AddGlobalAnnotations(&D, var);
Nate Begemanfaae0812008-04-19 04:17:09 +0000424
Javed Absar2a67c9e2017-06-05 10:11:57 +0000425 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
426 var->addAttribute("bss-section", SA->getName());
427 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
428 var->addAttribute("data-section", SA->getName());
429 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
430 var->addAttribute("rodata-section", SA->getName());
Dmitry Mikulinf14642f2019-10-15 18:31:10 +0000431 if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>())
432 var->addAttribute("relro-section", SA->getName());
Javed Absar2a67c9e2017-06-05 10:11:57 +0000433
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000434 if (const SectionAttr *SA = D.getAttr<SectionAttr>())
John McCallb88a5662012-03-30 21:00:39 +0000435 var->setSection(SA->getName());
Mike Stump11289f42009-09-09 15:08:12 +0000436
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000437 if (D.hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000438 CGM.addUsedGlobal(var);
Daniel Dunbar128a1382009-02-13 22:08:43 +0000439
Chandler Carruth84537952012-03-30 19:44:53 +0000440 // We may have to cast the constant because of the initializer
441 // mismatch above.
442 //
443 // FIXME: It is really dangerous to store this in the map; if anyone
444 // RAUW's the GV uses of this constant will be invalid.
Eli Benderskycb399432014-03-24 22:05:38 +0000445 llvm::Constant *castedAddr =
446 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
John McCall7f416cc2015-09-08 08:05:57 +0000447 if (var != castedAddr)
448 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
John McCallb88a5662012-03-30 21:00:39 +0000449 CGM.setStaticLocalDeclAddress(&D, castedAddr);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000450
Alexey Samsonov4b8de112014-08-01 21:35:28 +0000451 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000452
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000453 // Emit global variable debug descriptor for static vars.
Anders Carlsson63784f42009-02-13 08:11:52 +0000454 CGDebugInfo *DI = getDebugInfo();
Amy Huang53539bb2020-01-13 15:54:54 -0800455 if (DI && CGM.getCodeGenOpts().hasReducedDebugInfo()) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +0000456 DI->setLocation(D.getLocation());
John McCallb88a5662012-03-30 21:00:39 +0000457 DI->EmitGlobalVariable(var, &D);
Sanjiv Gupta158143a2008-06-05 08:59:10 +0000458 }
Anders Carlssonf94cd1f2007-10-17 00:52:43 +0000459}
Mike Stump11289f42009-09-09 15:08:12 +0000460
John McCall2b7fc382010-07-13 20:32:21 +0000461namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000462 struct DestroyObject final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000463 DestroyObject(Address addr, QualType type,
John McCall178360e2011-07-11 08:38:19 +0000464 CodeGenFunction::Destroyer *destroyer,
465 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000466 : addr(addr), type(type), destroyer(destroyer),
John McCall178360e2011-07-11 08:38:19 +0000467 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall2b7fc382010-07-13 20:32:21 +0000468
John McCall7f416cc2015-09-08 08:05:57 +0000469 Address addr;
John McCall82fe67b2011-07-09 01:37:26 +0000470 QualType type;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000471 CodeGenFunction::Destroyer *destroyer;
John McCall178360e2011-07-11 08:38:19 +0000472 bool useEHCleanupForArray;
John McCall2b7fc382010-07-13 20:32:21 +0000473
Craig Topper4f12f102014-03-12 06:41:41 +0000474 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +0000475 // Don't use an EH cleanup recursively from an EH cleanup.
John McCall30317fd2011-07-12 20:27:29 +0000476 bool useEHCleanupForArray =
477 flags.isForNormalCleanup() && this->useEHCleanupForArray;
John McCall178360e2011-07-11 08:38:19 +0000478
479 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
John McCall2b7fc382010-07-13 20:32:21 +0000480 }
481 };
482
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000483 template <class Derived>
484 struct DestroyNRVOVariable : EHScopeStack::Cleanup {
Marco Antognini88559632019-07-22 09:39:13 +0000485 DestroyNRVOVariable(Address addr, QualType type, llvm::Value *NRVOFlag)
486 : NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}
John McCall2b7fc382010-07-13 20:32:21 +0000487
John McCall2b7fc382010-07-13 20:32:21 +0000488 llvm::Value *NRVOFlag;
John McCall7f416cc2015-09-08 08:05:57 +0000489 Address Loc;
Marco Antognini88559632019-07-22 09:39:13 +0000490 QualType Ty;
John McCall2b7fc382010-07-13 20:32:21 +0000491
Craig Topper4f12f102014-03-12 06:41:41 +0000492 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall2b7fc382010-07-13 20:32:21 +0000493 // Along the exceptions path we always execute the dtor.
John McCall30317fd2011-07-12 20:27:29 +0000494 bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
John McCall2b7fc382010-07-13 20:32:21 +0000495
Craig Topper8a13c412014-05-21 05:09:00 +0000496 llvm::BasicBlock *SkipDtorBB = nullptr;
John McCall2b7fc382010-07-13 20:32:21 +0000497 if (NRVO) {
498 // If we exited via NRVO, we skip the destructor call.
499 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
500 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
John McCall7f416cc2015-09-08 08:05:57 +0000501 llvm::Value *DidNRVO =
502 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
John McCall2b7fc382010-07-13 20:32:21 +0000503 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
504 CGF.EmitBlock(RunDtorBB);
505 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000506
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000507 static_cast<Derived *>(this)->emitDestructorCall(CGF);
John McCall2b7fc382010-07-13 20:32:21 +0000508
509 if (NRVO) CGF.EmitBlock(SkipDtorBB);
510 }
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000511
512 virtual ~DestroyNRVOVariable() = default;
513 };
514
515 struct DestroyNRVOVariableCXX final
516 : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
Marco Antognini88559632019-07-22 09:39:13 +0000517 DestroyNRVOVariableCXX(Address addr, QualType type,
518 const CXXDestructorDecl *Dtor, llvm::Value *NRVOFlag)
519 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, NRVOFlag),
520 Dtor(Dtor) {}
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000521
522 const CXXDestructorDecl *Dtor;
523
524 void emitDestructorCall(CodeGenFunction &CGF) {
525 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
526 /*ForVirtualBase=*/false,
Marco Antognini88559632019-07-22 09:39:13 +0000527 /*Delegating=*/false, Loc, Ty);
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000528 }
529 };
530
531 struct DestroyNRVOVariableC final
532 : DestroyNRVOVariable<DestroyNRVOVariableC> {
533 DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
Marco Antognini88559632019-07-22 09:39:13 +0000534 : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, Ty, NRVOFlag) {}
Akira Hatanaka673af7a2018-03-29 17:56:24 +0000535
536 void emitDestructorCall(CodeGenFunction &CGF) {
537 CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
538 }
John McCall2b7fc382010-07-13 20:32:21 +0000539 };
John McCall2b7fc382010-07-13 20:32:21 +0000540
David Blaikie7e70d682015-08-18 22:40:54 +0000541 struct CallStackRestore final : EHScopeStack::Cleanup {
John McCall7f416cc2015-09-08 08:05:57 +0000542 Address Stack;
543 CallStackRestore(Address Stack) : Stack(Stack) {}
Craig Topper4f12f102014-03-12 06:41:41 +0000544 void Emit(CodeGenFunction &CGF, Flags flags) override {
Benjamin Kramer76399eb2011-09-27 21:06:10 +0000545 llvm::Value *V = CGF.Builder.CreateLoad(Stack);
James Y Knight8799cae2019-02-03 21:53:49 +0000546 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
John McCalla464ff92010-07-21 06:13:08 +0000547 CGF.Builder.CreateCall(F, V);
548 }
549 };
550
David Blaikie7e70d682015-08-18 22:40:54 +0000551 struct ExtendGCLifetime final : EHScopeStack::Cleanup {
John McCall1bd25562011-06-24 23:21:27 +0000552 const VarDecl &Var;
553 ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
554
Craig Topper4f12f102014-03-12 06:41:41 +0000555 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1bd25562011-06-24 23:21:27 +0000556 // Compute the address of the local variable, in case it's a
557 // byref or something.
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000558 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
John McCall113bee02012-03-10 09:33:50 +0000559 Var.getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000560 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
561 SourceLocation());
John McCall1bd25562011-06-24 23:21:27 +0000562 CGF.EmitExtendGCLifetime(value);
563 }
564 };
565
David Blaikie7e70d682015-08-18 22:40:54 +0000566 struct CallCleanupFunction final : EHScopeStack::Cleanup {
John McCalla464ff92010-07-21 06:13:08 +0000567 llvm::Constant *CleanupFn;
568 const CGFunctionInfo &FnInfo;
John McCalla464ff92010-07-21 06:13:08 +0000569 const VarDecl &Var;
Eric Christopher31ab1302011-08-23 22:38:00 +0000570
John McCalla464ff92010-07-21 06:13:08 +0000571 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
John McCallc533cb72011-02-22 06:44:22 +0000572 const VarDecl *Var)
573 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
John McCalla464ff92010-07-21 06:13:08 +0000574
Craig Topper4f12f102014-03-12 06:41:41 +0000575 void Emit(CodeGenFunction &CGF, Flags flags) override {
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000576 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
John McCall113bee02012-03-10 09:33:50 +0000577 Var.getType(), VK_LValue, SourceLocation());
John McCallc533cb72011-02-22 06:44:22 +0000578 // Compute the address of the local variable, in case it's a byref
579 // or something.
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800580 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(CGF);
John McCallc533cb72011-02-22 06:44:22 +0000581
John McCalla464ff92010-07-21 06:13:08 +0000582 // In some cases, the type of the function argument will be different from
583 // the type of the pointer. An example of this is
584 // void f(void* arg);
585 // __attribute__((cleanup(f))) void *g;
586 //
587 // To fix this we insert a bitcast here.
588 QualType ArgTy = FnInfo.arg_begin()->type;
589 llvm::Value *Arg =
590 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
591
592 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +0000593 Args.add(RValue::get(Arg),
594 CGF.getContext().getPointerType(Var.getType()));
John McCallb92ab1a2016-10-26 23:46:34 +0000595 auto Callee = CGCallee::forDirect(CleanupFn);
596 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
John McCalla464ff92010-07-21 06:13:08 +0000597 }
598 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000599} // end anonymous namespace
John McCalla464ff92010-07-21 06:13:08 +0000600
John McCall31168b02011-06-15 23:02:42 +0000601/// EmitAutoVarWithLifetime - Does the setup required for an automatic
602/// variable with lifetime.
603static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
John McCall7f416cc2015-09-08 08:05:57 +0000604 Address addr,
John McCall31168b02011-06-15 23:02:42 +0000605 Qualifiers::ObjCLifetime lifetime) {
606 switch (lifetime) {
607 case Qualifiers::OCL_None:
608 llvm_unreachable("present but none");
609
610 case Qualifiers::OCL_ExplicitNone:
611 // nothing to do
612 break;
613
614 case Qualifiers::OCL_Strong: {
Peter Collingbourne1425b452012-01-26 03:33:36 +0000615 CodeGenFunction::Destroyer *destroyer =
John McCall4bd0fb12011-07-12 16:41:08 +0000616 (var.hasAttr<ObjCPreciseLifetimeAttr>()
617 ? CodeGenFunction::destroyARCStrongPrecise
618 : CodeGenFunction::destroyARCStrongImprecise);
619
620 CleanupKind cleanupKind = CGF.getARCCleanupKind();
621 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
622 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000623 break;
624 }
625 case Qualifiers::OCL_Autoreleasing:
626 // nothing to do
627 break;
Eric Christopher31ab1302011-08-23 22:38:00 +0000628
John McCall31168b02011-06-15 23:02:42 +0000629 case Qualifiers::OCL_Weak:
630 // __weak objects always get EH cleanups; otherwise, exceptions
631 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000632 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
633 CodeGenFunction::destroyARCWeak,
634 /*useEHCleanup*/ true);
John McCall31168b02011-06-15 23:02:42 +0000635 break;
636 }
637}
638
639static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
640 if (const Expr *e = dyn_cast<Expr>(s)) {
641 // Skip the most common kinds of expressions that make
642 // hierarchy-walking expensive.
643 s = e = e->IgnoreParenCasts();
644
645 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
646 return (ref->getDecl() == &var);
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000647 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
648 const BlockDecl *block = be->getBlockDecl();
Aaron Ballman9371dd22014-03-14 18:34:04 +0000649 for (const auto &I : block->captures()) {
650 if (I.getVariable() == &var)
Fariborz Jahaniana36cbeb2012-06-19 20:53:26 +0000651 return true;
652 }
653 }
John McCall31168b02011-06-15 23:02:42 +0000654 }
655
Benjamin Kramer642f1732015-07-02 21:03:14 +0000656 for (const Stmt *SubStmt : s->children())
657 // SubStmt might be null; as in missing decl or conditional of an if-stmt.
658 if (SubStmt && isAccessedBy(var, SubStmt))
John McCall31168b02011-06-15 23:02:42 +0000659 return true;
660
661 return false;
662}
663
664static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
665 if (!decl) return false;
666 if (!isa<VarDecl>(decl)) return false;
667 const VarDecl *var = cast<VarDecl>(decl);
668 return isAccessedBy(*var, e);
669}
670
John McCallf8a9b662015-10-21 18:06:31 +0000671static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
672 const LValue &destLV, const Expr *init) {
John McCall0204e342015-11-16 22:11:41 +0000673 bool needsCast = false;
674
John McCallf8a9b662015-10-21 18:06:31 +0000675 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
676 switch (castExpr->getCastKind()) {
677 // Look through casts that don't require representation changes.
678 case CK_NoOp:
679 case CK_BitCast:
680 case CK_BlockPointerToObjCPointerCast:
John McCall0204e342015-11-16 22:11:41 +0000681 needsCast = true;
John McCallf8a9b662015-10-21 18:06:31 +0000682 break;
683
684 // If we find an l-value to r-value cast from a __weak variable,
685 // emit this operation as a copy or move.
686 case CK_LValueToRValue: {
687 const Expr *srcExpr = castExpr->getSubExpr();
688 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
689 return false;
690
691 // Emit the source l-value.
692 LValue srcLV = CGF.EmitLValue(srcExpr);
693
John McCall0204e342015-11-16 22:11:41 +0000694 // Handle a formal type change to avoid asserting.
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800695 auto srcAddr = srcLV.getAddress(CGF);
John McCall0204e342015-11-16 22:11:41 +0000696 if (needsCast) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800697 srcAddr = CGF.Builder.CreateElementBitCast(
698 srcAddr, destLV.getAddress(CGF).getElementType());
John McCall0204e342015-11-16 22:11:41 +0000699 }
700
John McCallf8a9b662015-10-21 18:06:31 +0000701 // If it was an l-value, use objc_copyWeak.
702 if (srcExpr->getValueKind() == VK_LValue) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800703 CGF.EmitARCCopyWeak(destLV.getAddress(CGF), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000704 } else {
705 assert(srcExpr->getValueKind() == VK_XValue);
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800706 CGF.EmitARCMoveWeak(destLV.getAddress(CGF), srcAddr);
John McCallf8a9b662015-10-21 18:06:31 +0000707 }
708 return true;
709 }
710
711 // Stop at anything else.
712 default:
713 return false;
714 }
715
716 init = castExpr->getSubExpr();
John McCallf8a9b662015-10-21 18:06:31 +0000717 }
718 return false;
719}
720
John McCall1553b192011-06-16 04:16:24 +0000721static void drillIntoBlockVariable(CodeGenFunction &CGF,
722 LValue &lvalue,
723 const VarDecl *var) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800724 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(CGF), var));
John McCall1553b192011-06-16 04:16:24 +0000725}
726
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000727void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
728 SourceLocation Loc) {
729 if (!SanOpts.has(SanitizerKind::NullabilityAssign))
730 return;
731
732 auto Nullability = LHS.getType()->getNullability(getContext());
733 if (!Nullability || *Nullability != NullabilityKind::NonNull)
734 return;
735
736 // Check if the right hand side of the assignment is nonnull, if the left
737 // hand side must be nonnull.
738 SanitizerScope SanScope(this);
739 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000740 llvm::Constant *StaticData[] = {
741 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
Simon Pilgrim2df19982017-03-14 21:43:52 +0000742 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
Vedant Kumar2b9f48a2017-03-14 16:48:29 +0000743 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000744 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
745 SanitizerHandler::TypeMismatch, StaticData, RHS);
746}
747
David Blaikie73ca5692014-12-09 00:32:22 +0000748void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +0000749 LValue lvalue, bool capturedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000750 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +0000751 if (!lifetime) {
752 llvm::Value *value = EmitScalarExpr(init);
John McCall1553b192011-06-16 04:16:24 +0000753 if (capturedByInit)
754 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000755 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
David Blaikie66e41972015-01-14 07:38:27 +0000756 EmitStoreThroughLValue(RValue::get(value), lvalue, true);
John McCall31168b02011-06-15 23:02:42 +0000757 return;
758 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000759
Fariborz Jahaniana5a469e2014-03-14 15:40:54 +0000760 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
761 init = DIE->getExpr();
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000762
John McCall31168b02011-06-15 23:02:42 +0000763 // If we're emitting a value with lifetime, we have to do the
764 // initialization *before* we leave the cleanup scopes.
Bill Wendling7c44da22018-10-31 03:48:47 +0000765 if (const FullExpr *fe = dyn_cast<FullExpr>(init)) {
766 enterFullExpression(fe);
767 init = fe->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +0000768 }
769 CodeGenFunction::RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000770
771 // We have to maintain the illusion that the variable is
772 // zero-initialized. If the variable might be accessed in its
773 // initializer, zero-initialize before running the initializer, then
774 // actually perform the initialization with an assign.
775 bool accessedByInit = false;
776 if (lifetime != Qualifiers::OCL_ExplicitNone)
John McCallb726a552011-07-28 07:23:35 +0000777 accessedByInit = (capturedByInit || isAccessedBy(D, init));
John McCall31168b02011-06-15 23:02:42 +0000778 if (accessedByInit) {
John McCall1553b192011-06-16 04:16:24 +0000779 LValue tempLV = lvalue;
John McCall31168b02011-06-15 23:02:42 +0000780 // Drill down to the __block object if necessary.
John McCall31168b02011-06-15 23:02:42 +0000781 if (capturedByInit) {
782 // We can use a simple GEP for this because it can't have been
783 // moved yet.
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800784 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(*this),
John McCall7f416cc2015-09-08 08:05:57 +0000785 cast<VarDecl>(D),
786 /*follow*/ false));
John McCall31168b02011-06-15 23:02:42 +0000787 }
788
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800789 auto ty =
790 cast<llvm::PointerType>(tempLV.getAddress(*this).getElementType());
Yaxun Liu402804b2016-12-15 08:09:08 +0000791 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
Eric Christopher31ab1302011-08-23 22:38:00 +0000792
John McCall31168b02011-06-15 23:02:42 +0000793 // If __weak, we want to use a barrier under certain conditions.
794 if (lifetime == Qualifiers::OCL_Weak)
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800795 EmitARCInitWeak(tempLV.getAddress(*this), zero);
John McCall31168b02011-06-15 23:02:42 +0000796
797 // Otherwise just do a simple store.
798 else
David Chisnallfa35df62012-01-16 17:27:18 +0000799 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000800 }
801
802 // Emit the initializer.
Craig Topper8a13c412014-05-21 05:09:00 +0000803 llvm::Value *value = nullptr;
John McCall31168b02011-06-15 23:02:42 +0000804
805 switch (lifetime) {
806 case Qualifiers::OCL_None:
807 llvm_unreachable("present but none");
808
Erik Pilkington1e368822019-01-04 18:33:06 +0000809 case Qualifiers::OCL_Strong: {
810 if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
811 value = EmitARCRetainScalarExpr(init);
812 break;
813 }
814 // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
815 // that we omit the retain, and causes non-autoreleased return values to be
816 // immediately released.
817 LLVM_FALLTHROUGH;
818 }
819
John McCall31168b02011-06-15 23:02:42 +0000820 case Qualifiers::OCL_ExplicitNone:
John McCalle399e5b2016-01-27 18:32:30 +0000821 value = EmitARCUnsafeUnretainedScalarExpr(init);
John McCall31168b02011-06-15 23:02:42 +0000822 break;
823
John McCall31168b02011-06-15 23:02:42 +0000824 case Qualifiers::OCL_Weak: {
John McCallf8a9b662015-10-21 18:06:31 +0000825 // If it's not accessed by the initializer, try to emit the
826 // initialization with a copy or move.
827 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
828 return;
829 }
830
John McCall31168b02011-06-15 23:02:42 +0000831 // No way to optimize a producing initializer into this. It's not
832 // worth optimizing for, because the value will immediately
833 // disappear in the common case.
834 value = EmitScalarExpr(init);
835
John McCall1553b192011-06-16 04:16:24 +0000836 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000837 if (accessedByInit)
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800838 EmitARCStoreWeak(lvalue.getAddress(*this), value, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +0000839 else
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800840 EmitARCInitWeak(lvalue.getAddress(*this), value);
John McCall31168b02011-06-15 23:02:42 +0000841 return;
842 }
843
844 case Qualifiers::OCL_Autoreleasing:
845 value = EmitARCRetainAutoreleaseScalarExpr(init);
846 break;
847 }
848
John McCall1553b192011-06-16 04:16:24 +0000849 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
John McCall31168b02011-06-15 23:02:42 +0000850
Vedant Kumar42c17ec2017-03-14 01:56:34 +0000851 EmitNullabilityCheck(lvalue, value, init->getExprLoc());
852
John McCall31168b02011-06-15 23:02:42 +0000853 // If the variable might have been accessed by its initializer, we
854 // might have to initialize with a barrier. We have to do this for
855 // both __weak and __strong, but __weak got filtered out above.
856 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000857 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
David Chisnallfa35df62012-01-16 17:27:18 +0000858 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCallcdda29c2013-03-13 03:10:54 +0000859 EmitARCRelease(oldValue, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +0000860 return;
861 }
862
David Chisnallfa35df62012-01-16 17:27:18 +0000863 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
John McCall31168b02011-06-15 23:02:42 +0000864}
Chris Lattnerb85025f2010-12-01 02:05:19 +0000865
JF Bastiened92f602018-07-20 23:37:12 +0000866/// Decide whether we can emit the non-zero parts of the specified initializer
867/// with equal or fewer than NumStores scalar stores.
868static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
869 unsigned &NumStores) {
Chris Lattnere6af8862010-12-02 01:58:41 +0000870 // Zero and Undef never requires any extra stores.
871 if (isa<llvm::ConstantAggregateZero>(Init) ||
872 isa<llvm::ConstantPointerNull>(Init) ||
873 isa<llvm::UndefValue>(Init))
874 return true;
875 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
876 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
877 isa<llvm::ConstantExpr>(Init))
878 return Init->isNullValue() || NumStores--;
879
880 // See if we can emit each element.
881 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
882 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
883 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
JF Bastiened92f602018-07-20 23:37:12 +0000884 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
Chris Lattnere6af8862010-12-02 01:58:41 +0000885 return false;
886 }
887 return true;
888 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000889
Chris Lattner236b3572012-01-31 04:36:19 +0000890 if (llvm::ConstantDataSequential *CDS =
891 dyn_cast<llvm::ConstantDataSequential>(Init)) {
892 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
893 llvm::Constant *Elt = CDS->getElementAsConstant(i);
JF Bastiened92f602018-07-20 23:37:12 +0000894 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
Chris Lattner236b3572012-01-31 04:36:19 +0000895 return false;
896 }
897 return true;
898 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000899
Chris Lattnerb85025f2010-12-01 02:05:19 +0000900 // Anything else is hard and scary.
901 return false;
902}
903
JF Bastiened92f602018-07-20 23:37:12 +0000904/// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
905/// the scalar stores that would be required.
906static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
907 llvm::Constant *Init, Address Loc,
908 bool isVolatile, CGBuilderTy &Builder) {
Benjamin Kramer29f9a002012-08-27 22:07:02 +0000909 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
JF Bastiened92f602018-07-20 23:37:12 +0000910 "called emitStoresForInitAfterBZero for zero or undef value.");
Eric Christopher31ab1302011-08-23 22:38:00 +0000911
Chris Lattnere6af8862010-12-02 01:58:41 +0000912 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
913 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
914 isa<llvm::ConstantExpr>(Init)) {
JF Bastien9aab85a2018-07-13 20:33:23 +0000915 Builder.CreateStore(Init, Loc, isVolatile);
Chris Lattner236b3572012-01-31 04:36:19 +0000916 return;
917 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000918
919 if (llvm::ConstantDataSequential *CDS =
920 dyn_cast<llvm::ConstantDataSequential>(Init)) {
Chris Lattner236b3572012-01-31 04:36:19 +0000921 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
922 llvm::Constant *Elt = CDS->getElementAsConstant(i);
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000923
924 // If necessary, get a pointer to the element and emit it.
925 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
JF Bastiened92f602018-07-20 23:37:12 +0000926 emitStoresForInitAfterBZero(
James Y Knight751fe282019-02-09 22:22:28 +0000927 CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,
928 Builder);
Chris Lattner236b3572012-01-31 04:36:19 +0000929 }
Chris Lattnere6af8862010-12-02 01:58:41 +0000930 return;
931 }
Eric Christopher31ab1302011-08-23 22:38:00 +0000932
Chris Lattnere6af8862010-12-02 01:58:41 +0000933 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
934 "Unknown value type!");
Eric Christopher31ab1302011-08-23 22:38:00 +0000935
Chris Lattnere6af8862010-12-02 01:58:41 +0000936 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
937 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
Benjamin Kramer46cbe772012-08-27 21:35:58 +0000938
939 // If necessary, get a pointer to the element and emit it.
940 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
James Y Knight751fe282019-02-09 22:22:28 +0000941 emitStoresForInitAfterBZero(CGM, Elt,
942 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),
943 isVolatile, Builder);
Chris Lattnere6af8862010-12-02 01:58:41 +0000944 }
Chris Lattnerb85025f2010-12-01 02:05:19 +0000945}
946
JF Bastiened92f602018-07-20 23:37:12 +0000947/// Decide whether we should use bzero plus some stores to initialize a local
948/// variable instead of using a memcpy from a constant global. It is beneficial
949/// to use bzero if the global is all zeros, or mostly zeros and large.
950static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
951 uint64_t GlobalSize) {
952 // If a global is all zeros, always use a bzero.
Chris Lattnerb85025f2010-12-01 02:05:19 +0000953 if (isa<llvm::ConstantAggregateZero>(Init)) return true;
954
Chris Lattnerb85025f2010-12-01 02:05:19 +0000955 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large,
956 // do it if it will require 6 or fewer scalar stores.
957 // TODO: Should budget depends on the size? Avoiding a large global warrants
958 // plopping in more stores.
959 unsigned StoreBudget = 6;
960 uint64_t SizeLimit = 32;
Eric Christopher31ab1302011-08-23 22:38:00 +0000961
962 return GlobalSize > SizeLimit &&
JF Bastiened92f602018-07-20 23:37:12 +0000963 canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
Chris Lattnerb85025f2010-12-01 02:05:19 +0000964}
965
JF Bastien65089292018-07-25 04:29:03 +0000966/// Decide whether we should use memset to initialize a local variable instead
967/// of using a memcpy from a constant global. Assumes we've already decided to
968/// not user bzero.
969/// FIXME We could be more clever, as we are for bzero above, and generate
970/// memset followed by stores. It's unclear that's worth the effort.
JF Bastien2f0582f2018-09-21 13:54:09 +0000971static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
Vitaly Bukad03bd1d2019-07-10 22:53:52 +0000972 uint64_t GlobalSize,
973 const llvm::DataLayout &DL) {
JF Bastien65089292018-07-25 04:29:03 +0000974 uint64_t SizeLimit = 32;
975 if (GlobalSize <= SizeLimit)
JF Bastien2f0582f2018-09-21 13:54:09 +0000976 return nullptr;
Vitaly Bukad03bd1d2019-07-10 22:53:52 +0000977 return llvm::isBytewiseValue(Init, DL);
JF Bastien65089292018-07-25 04:29:03 +0000978}
979
JF Bastienb5e5bc72019-03-08 01:26:49 +0000980/// Decide whether we want to split a constant structure or array store into a
981/// sequence of its fields' stores. This may cost us code size and compilation
982/// speed, but plays better with store optimizations.
983static bool shouldSplitConstantStore(CodeGenModule &CGM,
984 uint64_t GlobalByteSize) {
985 // Don't break things that occupy more than one cacheline.
Alexander Potapenkofa61ddd2019-03-01 09:00:41 +0000986 uint64_t ByteSizeLimit = 64;
987 if (CGM.getCodeGenOpts().OptimizationLevel == 0)
988 return false;
989 if (GlobalByteSize <= ByteSizeLimit)
990 return true;
991 return false;
992}
993
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +0000994enum class IsPattern { No, Yes };
995
996/// Generate a constant filled with either a pattern or zeroes.
997static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
998 llvm::Type *Ty) {
999 if (isPattern == IsPattern::Yes)
JF Bastienef202c32019-04-12 00:11:27 +00001000 return initializationPatternFor(CGM, Ty);
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001001 else
1002 return llvm::Constant::getNullValue(Ty);
1003}
1004
1005static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1006 llvm::Constant *constant);
1007
1008/// Helper function for constWithPadding() to deal with padding in structures.
1009static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
1010 IsPattern isPattern,
1011 llvm::StructType *STy,
1012 llvm::Constant *constant) {
1013 const llvm::DataLayout &DL = CGM.getDataLayout();
1014 const llvm::StructLayout *Layout = DL.getStructLayout(STy);
1015 llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1016 unsigned SizeSoFar = 0;
1017 SmallVector<llvm::Constant *, 8> Values;
1018 bool NestedIntact = true;
1019 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1020 unsigned CurOff = Layout->getElementOffset(i);
1021 if (SizeSoFar < CurOff) {
1022 assert(!STy->isPacked());
1023 auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);
1024 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1025 }
1026 llvm::Constant *CurOp;
1027 if (constant->isZeroValue())
1028 CurOp = llvm::Constant::getNullValue(STy->getElementType(i));
1029 else
1030 CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));
1031 auto *NewOp = constWithPadding(CGM, isPattern, CurOp);
1032 if (CurOp != NewOp)
1033 NestedIntact = false;
1034 Values.push_back(NewOp);
1035 SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());
1036 }
1037 unsigned TotalSize = Layout->getSizeInBytes();
1038 if (SizeSoFar < TotalSize) {
1039 auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);
1040 Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1041 }
1042 if (NestedIntact && Values.size() == STy->getNumElements())
1043 return constant;
Peter Collingbourne68b46732019-03-16 19:25:39 +00001044 return llvm::ConstantStruct::getAnon(Values, STy->isPacked());
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001045}
1046
1047/// Replace all padding bytes in a given constant with either a pattern byte or
1048/// 0x00.
1049static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1050 llvm::Constant *constant) {
1051 llvm::Type *OrigTy = constant->getType();
1052 if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))
1053 return constStructWithPadding(CGM, isPattern, STy, constant);
Eli Friedman3f1defa2020-03-20 14:18:04 -07001054 if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(OrigTy)) {
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001055 llvm::SmallVector<llvm::Constant *, 8> Values;
Eli Friedman3f1defa2020-03-20 14:18:04 -07001056 uint64_t Size = ArrayTy->getNumElements();
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001057 if (!Size)
1058 return constant;
Eli Friedman3f1defa2020-03-20 14:18:04 -07001059 llvm::Type *ElemTy = ArrayTy->getElementType();
1060 bool ZeroInitializer = constant->isNullValue();
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001061 llvm::Constant *OpValue, *PaddedOp;
1062 if (ZeroInitializer) {
1063 OpValue = llvm::Constant::getNullValue(ElemTy);
1064 PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1065 }
1066 for (unsigned Op = 0; Op != Size; ++Op) {
1067 if (!ZeroInitializer) {
1068 OpValue = constant->getAggregateElement(Op);
1069 PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1070 }
1071 Values.push_back(PaddedOp);
1072 }
1073 auto *NewElemTy = Values[0]->getType();
1074 if (NewElemTy == ElemTy)
1075 return constant;
Eli Friedman3f1defa2020-03-20 14:18:04 -07001076 auto *NewArrayTy = llvm::ArrayType::get(NewElemTy, Size);
1077 return llvm::ConstantArray::get(NewArrayTy, Values);
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001078 }
Eli Friedmanc46a0c02020-03-25 10:56:48 -07001079 // FIXME: Add handling for tail padding in vectors. Vectors don't
1080 // have padding between or inside elements, but the total amount of
1081 // data can be less than the allocated size.
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001082 return constant;
1083}
1084
Richard Smith24cdcad2019-06-14 17:46:37 +00001085Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D,
1086 llvm::Constant *Constant,
1087 CharUnits Align) {
JF Bastien3a881e62018-11-15 00:19:18 +00001088 auto FunctionName = [&](const DeclContext *DC) -> std::string {
1089 if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1090 if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
1091 return CC->getNameAsString();
1092 if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
1093 return CD->getNameAsString();
Benjamin Krameradcd0262020-01-28 20:23:46 +01001094 return std::string(getMangledName(FD));
JF Bastien3a881e62018-11-15 00:19:18 +00001095 } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
1096 return OM->getNameAsString();
Mikael Holmenee846762018-11-15 13:01:54 +00001097 } else if (isa<BlockDecl>(DC)) {
JF Bastien3a881e62018-11-15 00:19:18 +00001098 return "<block>";
Mikael Holmenee846762018-11-15 13:01:54 +00001099 } else if (isa<CapturedDecl>(DC)) {
JF Bastien3a881e62018-11-15 00:19:18 +00001100 return "<captured>";
1101 } else {
Richard Smith24cdcad2019-06-14 17:46:37 +00001102 llvm_unreachable("expected a function or method");
JF Bastien3a881e62018-11-15 00:19:18 +00001103 }
1104 };
1105
Richard Smith24cdcad2019-06-14 17:46:37 +00001106 // Form a simple per-variable cache of these values in case we find we
1107 // want to reuse them.
1108 llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];
1109 if (!CacheEntry || CacheEntry->getInitializer() != Constant) {
1110 auto *Ty = Constant->getType();
1111 bool isConstant = true;
1112 llvm::GlobalVariable *InsertBefore = nullptr;
1113 unsigned AS =
1114 getContext().getTargetAddressSpace(getStringLiteralAddressSpace());
1115 std::string Name;
1116 if (D.hasGlobalStorage())
1117 Name = getMangledName(&D).str() + ".const";
1118 else if (const DeclContext *DC = D.getParentFunctionOrMethod())
1119 Name = ("__const." + FunctionName(DC) + "." + D.getName()).str();
1120 else
1121 llvm_unreachable("local variable has no parent function or method");
1122 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1123 getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
1124 Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001125 GV->setAlignment(Align.getAsAlign());
Richard Smith24cdcad2019-06-14 17:46:37 +00001126 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1127 CacheEntry = GV;
1128 } else if (CacheEntry->getAlignment() < Align.getQuantity()) {
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001129 CacheEntry->setAlignment(Align.getAsAlign());
Richard Smith24cdcad2019-06-14 17:46:37 +00001130 }
JF Bastien3a881e62018-11-15 00:19:18 +00001131
Richard Smith24cdcad2019-06-14 17:46:37 +00001132 return Address(CacheEntry, Align);
1133}
1134
1135static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM,
1136 const VarDecl &D,
1137 CGBuilderTy &Builder,
1138 llvm::Constant *Constant,
1139 CharUnits Align) {
1140 Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);
1141 llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(),
1142 SrcPtr.getAddressSpace());
JF Bastien3a881e62018-11-15 00:19:18 +00001143 if (SrcPtr.getType() != BP)
1144 SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1145 return SrcPtr;
1146}
1147
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001148static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
1149 Address Loc, bool isVolatile,
1150 CGBuilderTy &Builder,
1151 llvm::Constant *constant) {
JF Bastien14daa202018-12-18 05:12:21 +00001152 auto *Ty = constant->getType();
Vitaly Bukaf35a3452019-06-27 02:08:15 +00001153 uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
1154 if (!ConstantSize)
1155 return;
1156
JF Bastienb5e5bc72019-03-08 01:26:49 +00001157 bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
1158 Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
1159 if (canDoSingleStore) {
JF Bastien14daa202018-12-18 05:12:21 +00001160 Builder.CreateStore(constant, Loc, isVolatile);
1161 return;
1162 }
1163
Vitaly Buka96ff25a2019-06-27 01:34:21 +00001164 auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);
JF Bastienb5e5bc72019-03-08 01:26:49 +00001165
1166 // If the initializer is all or mostly the same, codegen with bzero / memset
1167 // then do a few stores afterward.
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001168 if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
Vitaly Buka96ff25a2019-06-27 01:34:21 +00001169 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0), SizeVal,
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001170 isVolatile);
1171
1172 bool valueAlreadyCorrect =
1173 constant->isNullValue() || isa<llvm::UndefValue>(constant);
1174 if (!valueAlreadyCorrect) {
JF Bastien14daa202018-12-18 05:12:21 +00001175 Loc = Builder.CreateBitCast(Loc, Ty->getPointerTo(Loc.getAddressSpace()));
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001176 emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder);
1177 }
1178 return;
1179 }
1180
JF Bastienb5e5bc72019-03-08 01:26:49 +00001181 // If the initializer is a repeated byte pattern, use memset.
Vitaly Bukad03bd1d2019-07-10 22:53:52 +00001182 llvm::Value *Pattern =
1183 shouldUseMemSetToInitialize(constant, ConstantSize, CGM.getDataLayout());
JF Bastien2f0582f2018-09-21 13:54:09 +00001184 if (Pattern) {
1185 uint64_t Value = 0x00;
1186 if (!isa<llvm::UndefValue>(Pattern)) {
1187 const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1188 assert(AP.getBitWidth() <= 8);
1189 Value = AP.getLimitedValue();
1190 }
Vitaly Buka96ff25a2019-06-27 01:34:21 +00001191 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal,
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001192 isVolatile);
1193 return;
1194 }
1195
JF Bastienb5e5bc72019-03-08 01:26:49 +00001196 // If the initializer is small, use a handful of stores.
1197 if (shouldSplitConstantStore(CGM, ConstantSize)) {
1198 if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
1199 // FIXME: handle the case when STy != Loc.getElementType().
1200 if (STy == Loc.getElementType()) {
1201 for (unsigned i = 0; i != constant->getNumOperands(); i++) {
1202 Address EltPtr = Builder.CreateStructGEP(Loc, i);
1203 emitStoresForConstant(
1204 CGM, D, EltPtr, isVolatile, Builder,
1205 cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)));
1206 }
1207 return;
1208 }
1209 } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
1210 // FIXME: handle the case when ATy != Loc.getElementType().
1211 if (ATy == Loc.getElementType()) {
1212 for (unsigned i = 0; i != ATy->getNumElements(); i++) {
1213 Address EltPtr = Builder.CreateConstArrayGEP(Loc, i);
1214 emitStoresForConstant(
1215 CGM, D, EltPtr, isVolatile, Builder,
1216 cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)));
1217 }
1218 return;
1219 }
Alexander Potapenkofa61ddd2019-03-01 09:00:41 +00001220 }
Alexander Potapenkofa61ddd2019-03-01 09:00:41 +00001221 }
1222
JF Bastienb5e5bc72019-03-08 01:26:49 +00001223 // Copy from a global.
Richard Smith24cdcad2019-06-14 17:46:37 +00001224 Builder.CreateMemCpy(Loc,
1225 createUnnamedGlobalForMemcpyFrom(
1226 CGM, D, Builder, constant, Loc.getAlignment()),
1227 SizeVal, isVolatile);
JF Bastienb9cc1fc2018-08-07 21:55:13 +00001228}
1229
JF Bastien14daa202018-12-18 05:12:21 +00001230static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
1231 Address Loc, bool isVolatile,
1232 CGBuilderTy &Builder) {
1233 llvm::Type *ElTy = Loc.getElementType();
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001234 llvm::Constant *constant =
1235 constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
JF Bastien14daa202018-12-18 05:12:21 +00001236 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1237}
1238
1239static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
1240 Address Loc, bool isVolatile,
1241 CGBuilderTy &Builder) {
1242 llvm::Type *ElTy = Loc.getElementType();
JF Bastienef202c32019-04-12 00:11:27 +00001243 llvm::Constant *constant = constWithPadding(
1244 CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
JF Bastien14daa202018-12-18 05:12:21 +00001245 assert(!isa<llvm::UndefValue>(constant));
1246 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1247}
1248
1249static bool containsUndef(llvm::Constant *constant) {
1250 auto *Ty = constant->getType();
1251 if (isa<llvm::UndefValue>(constant))
1252 return true;
1253 if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1254 for (llvm::Use &Op : constant->operands())
1255 if (containsUndef(cast<llvm::Constant>(Op)))
1256 return true;
1257 return false;
1258}
1259
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001260static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
1261 llvm::Constant *constant) {
JF Bastien14daa202018-12-18 05:12:21 +00001262 auto *Ty = constant->getType();
1263 if (isa<llvm::UndefValue>(constant))
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001264 return patternOrZeroFor(CGM, isPattern, Ty);
JF Bastien14daa202018-12-18 05:12:21 +00001265 if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1266 return constant;
1267 if (!containsUndef(constant))
1268 return constant;
1269 llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1270 for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1271 auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001272 Values[Op] = replaceUndef(CGM, isPattern, OpValue);
JF Bastien14daa202018-12-18 05:12:21 +00001273 }
1274 if (Ty->isStructTy())
1275 return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
1276 if (Ty->isArrayTy())
1277 return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
1278 assert(Ty->isVectorTy());
1279 return llvm::ConstantVector::get(Values);
1280}
1281
Nick Lewycky8a7d90b2010-12-30 20:21:55 +00001282/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
Chris Lattner03df1222007-06-02 04:53:11 +00001283/// variable declaration with auto, register, or no storage class specifier.
Chris Lattnerb781dc792008-05-08 05:58:21 +00001284/// These turn into simple stack objects, or GlobalValues depending on target.
John McCallc533cb72011-02-22 06:44:22 +00001285void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1286 AutoVarEmission emission = EmitAutoVarAlloca(D);
1287 EmitAutoVarInit(emission);
1288 EmitAutoVarCleanups(emission);
1289}
Chris Lattner03df1222007-06-02 04:53:11 +00001290
David Majnemerdc012fa2015-04-22 21:38:15 +00001291/// Emit a lifetime.begin marker if some criteria are satisfied.
1292/// \return a pointer to the temporary size Value if a marker was emitted, null
1293/// otherwise
1294llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
1295 llvm::Value *Addr) {
Vitaly Buka1c943322016-10-26 01:59:57 +00001296 if (!ShouldEmitLifetimeMarkers)
Reid Kleckner1ef49212015-04-23 18:07:13 +00001297 return nullptr;
1298
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001299 assert(Addr->getType()->getPointerAddressSpace() ==
1300 CGM.getDataLayout().getAllocaAddrSpace() &&
1301 "Pointer should be in alloca address space");
David Majnemerdc012fa2015-04-22 21:38:15 +00001302 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001303 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +00001304 llvm::CallInst *C =
1305 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +00001306 C->setDoesNotThrow();
1307 return SizeV;
1308}
1309
1310void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001311 assert(Addr->getType()->getPointerAddressSpace() ==
1312 CGM.getDataLayout().getAllocaAddrSpace() &&
1313 "Pointer should be in alloca address space");
Yaxun Liu7f7f3232017-04-17 20:03:11 +00001314 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
Alexey Samsonovd918ff62015-06-12 22:31:32 +00001315 llvm::CallInst *C =
1316 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
David Majnemerdc012fa2015-04-22 21:38:15 +00001317 C->setDoesNotThrow();
1318}
1319
Sander de Smalen891af03a2018-02-03 13:55:59 +00001320void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1321 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1322 // For each dimension stores its QualType and corresponding
1323 // size-expression Value.
1324 SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
Adrian Prantla40cce82018-11-09 19:17:56 +00001325 SmallVector<IdentifierInfo *, 4> VLAExprNames;
Sander de Smalen891af03a2018-02-03 13:55:59 +00001326
1327 // Break down the array into individual dimensions.
1328 QualType Type1D = D.getType();
1329 while (getContext().getAsVariableArrayType(Type1D)) {
1330 auto VlaSize = getVLAElements1D(Type1D);
1331 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1332 Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1333 else {
Adrian Prantla40cce82018-11-09 19:17:56 +00001334 // Generate a locally unique name for the size expression.
1335 Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1336 SmallString<12> Buffer;
1337 StringRef NameRef = Name.toStringRef(Buffer);
1338 auto &Ident = getContext().Idents.getOwn(NameRef);
1339 VLAExprNames.push_back(&Ident);
1340 auto SizeExprAddr =
1341 CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
Sander de Smalen891af03a2018-02-03 13:55:59 +00001342 Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1343 Dimensions.emplace_back(SizeExprAddr.getPointer(),
1344 Type1D.getUnqualifiedType());
1345 }
1346 Type1D = VlaSize.Type;
1347 }
1348
1349 if (!EmitDebugInfo)
1350 return;
1351
1352 // Register each dimension's size-expression with a DILocalVariable,
1353 // so that it can be used by CGDebugInfo when instantiating a DISubrange
1354 // to describe this array.
Adrian Prantla40cce82018-11-09 19:17:56 +00001355 unsigned NameIdx = 0;
Sander de Smalen891af03a2018-02-03 13:55:59 +00001356 for (auto &VlaSize : Dimensions) {
1357 llvm::Metadata *MD;
1358 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1359 MD = llvm::ConstantAsMetadata::get(C);
1360 else {
1361 // Create an artificial VarDecl to generate debug info for.
Adrian Prantla40cce82018-11-09 19:17:56 +00001362 IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
Sander de Smalen891af03a2018-02-03 13:55:59 +00001363 auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
1364 auto QT = getContext().getIntTypeForBitwidth(
1365 VlaExprTy->getScalarSizeInBits(), false);
1366 auto *ArtificialDecl = VarDecl::Create(
1367 getContext(), const_cast<DeclContext *>(D.getDeclContext()),
Adrian Prantla40cce82018-11-09 19:17:56 +00001368 D.getLocation(), D.getLocation(), NameIdent, QT,
Sander de Smalen891af03a2018-02-03 13:55:59 +00001369 getContext().CreateTypeSourceInfo(QT), SC_Auto);
Sander de Smalen9084a3b2018-02-13 07:49:34 +00001370 ArtificialDecl->setImplicit();
Sander de Smalen891af03a2018-02-03 13:55:59 +00001371
1372 MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1373 Builder);
1374 }
1375 assert(MD && "No Size expression debug node created");
1376 DI->registerVLASizeExpression(VlaSize.Type, MD);
1377 }
1378}
1379
John McCallc533cb72011-02-22 06:44:22 +00001380/// EmitAutoVarAlloca - Emit the alloca and debug information for a
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001381/// local variable. Does not emit initialization or destruction.
John McCallc533cb72011-02-22 06:44:22 +00001382CodeGenFunction::AutoVarEmission
1383CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1384 QualType Ty = D.getType();
Yaxun Liub7318e02017-10-13 03:37:48 +00001385 assert(
1386 Ty.getAddressSpace() == LangAS::Default ||
1387 (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
John McCallc533cb72011-02-22 06:44:22 +00001388
1389 AutoVarEmission emission(D);
1390
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001391 bool isEscapingByRef = D.isEscapingByref();
1392 emission.IsEscapingByRef = isEscapingByRef;
John McCallc533cb72011-02-22 06:44:22 +00001393
1394 CharUnits alignment = getContext().getDeclAlign(&D);
John McCallc533cb72011-02-22 06:44:22 +00001395
John McCall23c29fe2011-06-24 21:55:10 +00001396 // If the type is variably-modified, emit all the VLA sizes for it.
1397 if (Ty->isVariablyModifiedType())
1398 EmitVariablyModifiedType(Ty);
1399
Sander de Smalen891af03a2018-02-03 13:55:59 +00001400 auto *DI = getDebugInfo();
Amy Huang53539bb2020-01-13 15:54:54 -08001401 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();
Sander de Smalen891af03a2018-02-03 13:55:59 +00001402
John McCall7f416cc2015-09-08 08:05:57 +00001403 Address address = Address::invalid();
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001404 Address AllocaAddr = Address::invalid();
Alexey Bataev9c397812019-04-03 17:57:06 +00001405 Address OpenMPLocalAddr =
1406 getLangOpts().OpenMP
1407 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
1408 : Address::invalid();
Amy Huang7fac5c82019-06-20 17:15:21 +00001409 bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();
1410
Alexey Bataev9c397812019-04-03 17:57:06 +00001411 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1412 address = OpenMPLocalAddr;
1413 } else if (Ty->isConstantSizeType()) {
Richard Smith2bcde3a2013-06-02 00:09:52 +00001414 // If this value is an array or struct with a statically determinable
1415 // constant initializer, there are optimizations we can do.
Rafael Espindola609f5d92013-03-26 18:41:47 +00001416 //
1417 // TODO: We should constant-evaluate the initializer of any variable,
1418 // as long as it is initialized by a constant expression. Currently,
1419 // isConstantInitializer produces wrong answers for structs with
1420 // reference or bitfield members, and a few other cases, and checking
1421 // for POD-ness protects us from some of these.
Richard Smith2bcde3a2013-06-02 00:09:52 +00001422 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1423 (D.isConstexpr() ||
1424 ((Ty.isPODType(getContext()) ||
1425 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1426 D.getInit()->isConstantInitializer(getContext(), false)))) {
John McCallc533cb72011-02-22 06:44:22 +00001427
Rafael Espindola609f5d92013-03-26 18:41:47 +00001428 // If the variable's a const type, and it's neither an NRVO
1429 // candidate nor a __block variable and has no mutable members,
1430 // emit it as a global instead.
Anastasia Stulovae4a1c382016-11-29 17:01:19 +00001431 // Exception is if a variable is located in non-constant address space
1432 // in OpenCL.
1433 if ((!getLangOpts().OpenCL ||
1434 Ty.getAddressSpace() == LangAS::opencl_constant) &&
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001435 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1436 !isEscapingByRef && CGM.isTypeConstant(Ty, true))) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001437 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
John McCallc533cb72011-02-22 06:44:22 +00001438
John McCall7f416cc2015-09-08 08:05:57 +00001439 // Signal this condition to later callbacks.
1440 emission.Addr = Address::invalid();
Rafael Espindola609f5d92013-03-26 18:41:47 +00001441 assert(emission.wasEmittedAsGlobal());
1442 return emission;
Tanya Lattnerf9d41df2009-11-04 01:18:09 +00001443 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001444
Rafael Espindola609f5d92013-03-26 18:41:47 +00001445 // Otherwise, tell the initialization code that we're in this case.
1446 emission.IsConstantAggregate = true;
1447 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001448
Rafael Espindola609f5d92013-03-26 18:41:47 +00001449 // A normal fixed sized variable becomes an alloca in the entry block,
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00001450 // unless:
1451 // - it's an NRVO variable.
1452 // - we are compiling OpenMP and it's an OpenMP local variable.
Alexey Bataev9c397812019-04-03 17:57:06 +00001453 if (NRVO) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001454 // The named return value optimization: allocate this variable in the
1455 // return slot, so that we can elide the copy when returning this
1456 // variable (C++0x [class.copy]p34).
John McCall7f416cc2015-09-08 08:05:57 +00001457 address = ReturnValue;
Eric Christopher31ab1302011-08-23 22:38:00 +00001458
Rafael Espindola609f5d92013-03-26 18:41:47 +00001459 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001460 const auto *RD = RecordTy->getDecl();
1461 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1462 if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1463 RD->isNonTrivialToPrimitiveDestroy()) {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001464 // Create a flag that is used to indicate when the NRVO was applied
1465 // to this variable. Set it to zero to indicate that NRVO was not
1466 // applied.
1467 llvm::Value *Zero = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +00001468 Address NRVOFlag =
1469 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
Rafael Espindola609f5d92013-03-26 18:41:47 +00001470 EnsureInsertPoint();
1471 Builder.CreateStore(Zero, NRVOFlag);
Eric Christopher31ab1302011-08-23 22:38:00 +00001472
Rafael Espindola609f5d92013-03-26 18:41:47 +00001473 // Record the NRVO flag for this variable.
John McCall7f416cc2015-09-08 08:05:57 +00001474 NRVOFlags[&D] = NRVOFlag.getPointer();
1475 emission.NRVOFlag = NRVOFlag.getPointer();
Nadav Rotem1da30942013-03-23 06:43:35 +00001476 }
Douglas Gregor290c93e2010-05-15 06:46:45 +00001477 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001478 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001479 CharUnits allocaAlignment;
1480 llvm::Type *allocaTy;
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001481 if (isEscapingByRef) {
John McCall7f416cc2015-09-08 08:05:57 +00001482 auto &byrefInfo = getBlockByrefInfo(&D);
1483 allocaTy = byrefInfo.Type;
1484 allocaAlignment = byrefInfo.ByrefAlignment;
1485 } else {
1486 allocaTy = ConvertTypeForMem(Ty);
1487 allocaAlignment = alignment;
1488 }
Rafael Espindola609f5d92013-03-26 18:41:47 +00001489
John McCall999110f2015-09-08 09:18:30 +00001490 // Create the alloca. Note that we set the name separately from
1491 // building the instruction so that it's there even in no-asserts
1492 // builds.
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001493 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1494 /*ArraySize=*/nullptr, &AllocaAddr);
Rafael Espindola609f5d92013-03-26 18:41:47 +00001495
Reid Kleckner1f88e932015-10-07 21:03:41 +00001496 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1497 // the catch parameter starts in the catchpad instruction, and we can't
1498 // insert code in those basic blocks.
1499 bool IsMSCatchParam =
1500 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1501
Vitaly Buka64c80b42016-10-26 05:42:30 +00001502 // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1503 // if we don't have a valid insertion point (?).
Reid Kleckner1f88e932015-10-07 21:03:41 +00001504 if (HaveInsertPoint() && !IsMSCatchParam) {
Akira Hatanakafdcd18b2017-01-25 22:55:13 +00001505 // If there's a jump into the lifetime of this variable, its lifetime
1506 // gets broken up into several regions in IR, which requires more work
1507 // to handle correctly. For now, just omit the intrinsics; this is a
1508 // rare case, and it's better to just be conservatively correct.
1509 // PR28267.
1510 //
1511 // We have to do this in all language modes if there's a jump past the
1512 // declaration. We also have to do it in C if there's a jump to an
1513 // earlier point in the current block because non-VLA lifetimes begin as
1514 // soon as the containing block is entered, not when its variables
1515 // actually come into scope; suppressing the lifetime annotations
1516 // completely in this case is unnecessarily pessimistic, but again, this
1517 // is rare.
1518 if (!Bypasses.IsBypassed(&D) &&
1519 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
Sander de Smalen49b307e2020-02-19 10:44:56 +00001520 llvm::TypeSize size =
1521 CGM.getDataLayout().getTypeAllocSize(allocaTy);
Vitaly Buka64c80b42016-10-26 05:42:30 +00001522 emission.SizeForLifetimeMarkers =
Sander de Smalen49b307e2020-02-19 10:44:56 +00001523 size.isScalable() ? EmitLifetimeStart(-1, AllocaAddr.getPointer())
1524 : EmitLifetimeStart(size.getFixedSize(),
1525 AllocaAddr.getPointer());
Vitaly Buka64c80b42016-10-26 05:42:30 +00001526 }
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001527 } else {
Rafael Espindola609f5d92013-03-26 18:41:47 +00001528 assert(!emission.useLifetimeMarkers());
Arnaud A. de Grandmaisone69ec552014-10-08 14:04:26 +00001529 }
Chris Lattnerb781dc792008-05-08 05:58:21 +00001530 }
Chris Lattner03df1222007-06-02 04:53:11 +00001531 } else {
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001532 EnsureInsertPoint();
1533
Anders Carlsson15949b32009-02-09 20:41:50 +00001534 if (!DidCallStackSave) {
Anders Carlsson30032882008-12-12 07:38:43 +00001535 // Save the stack.
John McCall7f416cc2015-09-08 08:05:57 +00001536 Address Stack =
1537 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
Mike Stump11289f42009-09-09 15:08:12 +00001538
James Y Knight8799cae2019-02-03 21:53:49 +00001539 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
David Blaikie4ba525b2015-07-14 17:27:39 +00001540 llvm::Value *V = Builder.CreateCall(F);
Anders Carlsson30032882008-12-12 07:38:43 +00001541 Builder.CreateStore(V, Stack);
Anders Carlsson15949b32009-02-09 20:41:50 +00001542
1543 DidCallStackSave = true;
Mike Stump11289f42009-09-09 15:08:12 +00001544
John McCalla464ff92010-07-21 06:13:08 +00001545 // Push a cleanup block and restore the stack there.
John McCalle4df6c82011-01-28 08:37:24 +00001546 // FIXME: in general circumstances, this should be an EH cleanup.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001547 pushStackRestore(NormalCleanup, Stack);
Anders Carlsson30032882008-12-12 07:38:43 +00001548 }
Mike Stump11289f42009-09-09 15:08:12 +00001549
Sander de Smalen891af03a2018-02-03 13:55:59 +00001550 auto VlaSize = getVLASize(Ty);
1551 llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
Anders Carlsson30032882008-12-12 07:38:43 +00001552
1553 // Allocate memory for the array.
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001554 address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1555 &AllocaAddr);
Sander de Smalen891af03a2018-02-03 13:55:59 +00001556
1557 // If we have debug info enabled, properly describe the VLA dimensions for
1558 // this type by registering the vla size expression for each of the
1559 // dimensions.
1560 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
Chris Lattner03df1222007-06-02 04:53:11 +00001561 }
Eli Friedmanf4084702008-12-20 23:11:59 +00001562
John McCall7f416cc2015-09-08 08:05:57 +00001563 setAddrOfLocalVar(&D, address);
1564 emission.Addr = address;
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001565 emission.AllocaAddr = AllocaAddr;
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001566
1567 // Emit debug info for local var declaration.
Sander de Smalen891af03a2018-02-03 13:55:59 +00001568 if (EmitDebugInfo && HaveInsertPoint()) {
Amy Huang7fac5c82019-06-20 17:15:21 +00001569 Address DebugAddr = address;
1570 bool UsePointerValue = NRVO && ReturnValuePointer.isValid();
Sander de Smalen891af03a2018-02-03 13:55:59 +00001571 DI->setLocation(D.getLocation());
Amy Huang7fac5c82019-06-20 17:15:21 +00001572
1573 // If NRVO, use a pointer to the return address.
1574 if (UsePointerValue)
1575 DebugAddr = ReturnValuePointer;
1576
1577 (void)DI->EmitDeclareOfAutoVariable(&D, DebugAddr.getPointer(), Builder,
1578 UsePointerValue);
Sander de Smalen891af03a2018-02-03 13:55:59 +00001579 }
Sanjiv Gupta18de6242008-05-30 10:30:31 +00001580
Volodymyr Sapsai93317d82019-03-01 02:15:39 +00001581 if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
John McCall7f416cc2015-09-08 08:05:57 +00001582 EmitVarAnnotations(&D, address.getPointer());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001583
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001584 // Make sure we call @llvm.lifetime.end.
1585 if (emission.useLifetimeMarkers())
1586 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
Yaxun Liua2a9cfa2018-05-17 11:16:35 +00001587 emission.getOriginalAllocatedAddress(),
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001588 emission.getSizeForLifetimeMarkers());
1589
John McCallc533cb72011-02-22 06:44:22 +00001590 return emission;
1591}
1592
JF Bastien6b239722018-05-19 04:21:26 +00001593static bool isCapturedBy(const VarDecl &, const Expr *);
1594
1595/// Determines whether the given __block variable is potentially
1596/// captured by the given statement.
1597static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1598 if (const Expr *E = dyn_cast<Expr>(S))
1599 return isCapturedBy(Var, E);
1600 for (const Stmt *SubStmt : S->children())
1601 if (isCapturedBy(Var, SubStmt))
1602 return true;
1603 return false;
1604}
1605
John McCallc533cb72011-02-22 06:44:22 +00001606/// Determines whether the given __block variable is potentially
1607/// captured by the given expression.
JF Bastien6b239722018-05-19 04:21:26 +00001608static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
John McCallc533cb72011-02-22 06:44:22 +00001609 // Skip the most common kinds of expressions that make
1610 // hierarchy-walking expensive.
JF Bastien6b239722018-05-19 04:21:26 +00001611 E = E->IgnoreParenCasts();
John McCallc533cb72011-02-22 06:44:22 +00001612
JF Bastien6b239722018-05-19 04:21:26 +00001613 if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1614 const BlockDecl *Block = BE->getBlockDecl();
1615 for (const auto &I : Block->captures()) {
1616 if (I.getVariable() == &Var)
John McCallc533cb72011-02-22 06:44:22 +00001617 return true;
1618 }
1619
1620 // No need to walk into the subexpressions.
1621 return false;
1622 }
1623
JF Bastien6b239722018-05-19 04:21:26 +00001624 if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001625 const CompoundStmt *CS = SE->getSubStmt();
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001626 for (const auto *BI : CS->body())
JF Bastien6b239722018-05-19 04:21:26 +00001627 if (const auto *BIE = dyn_cast<Expr>(BI)) {
1628 if (isCapturedBy(Var, BIE))
1629 return true;
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001630 }
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001631 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001632 // special case declarations
Aaron Ballman535bbcc2014-03-14 17:01:24 +00001633 for (const auto *I : DS->decls()) {
1634 if (const auto *VD = dyn_cast<VarDecl>((I))) {
1635 const Expr *Init = VD->getInit();
JF Bastien6b239722018-05-19 04:21:26 +00001636 if (Init && isCapturedBy(Var, Init))
Fariborz Jahanian5c4b2ca2011-08-25 00:06:26 +00001637 return true;
1638 }
1639 }
1640 }
1641 else
1642 // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1643 // Later, provide code to poke into statements for capture analysis.
1644 return true;
Fariborz Jahanian797f1e22011-08-23 16:47:15 +00001645 return false;
1646 }
Eric Christopher31ab1302011-08-23 22:38:00 +00001647
JF Bastien6b239722018-05-19 04:21:26 +00001648 for (const Stmt *SubStmt : E->children())
1649 if (isCapturedBy(Var, SubStmt))
John McCallc533cb72011-02-22 06:44:22 +00001650 return true;
1651
1652 return false;
1653}
1654
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001655/// Determine whether the given initializer is trivial in the sense
Douglas Gregor82e1af22011-07-01 21:08:19 +00001656/// that it requires no code to be generated.
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001657bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
Douglas Gregor82e1af22011-07-01 21:08:19 +00001658 if (!Init)
1659 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001660
Douglas Gregor82e1af22011-07-01 21:08:19 +00001661 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1662 if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1663 if (Constructor->isTrivial() &&
1664 Constructor->isDefaultConstructor() &&
1665 !Construct->requiresZeroInitialization())
1666 return true;
Eric Christopher31ab1302011-08-23 22:38:00 +00001667
Douglas Gregor82e1af22011-07-01 21:08:19 +00001668 return false;
1669}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001670
Vitaly Bukae7267662019-07-10 22:53:50 +00001671void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
1672 const VarDecl &D,
1673 Address Loc) {
1674 auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
1675 CharUnits Size = getContext().getTypeSizeInChars(type);
1676 bool isVolatile = type.isVolatileQualified();
1677 if (!Size.isZero()) {
1678 switch (trivialAutoVarInit) {
1679 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1680 llvm_unreachable("Uninitialized handled by caller");
1681 case LangOptions::TrivialAutoVarInitKind::Zero:
1682 emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
1683 break;
1684 case LangOptions::TrivialAutoVarInitKind::Pattern:
1685 emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
1686 break;
1687 }
1688 return;
1689 }
1690
1691 // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1692 // them, so emit a memcpy with the VLA size to initialize each element.
1693 // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1694 // will catch that code, but there exists code which generates zero-sized
1695 // VLAs. Be nice and initialize whatever they requested.
1696 const auto *VlaType = getContext().getAsVariableArrayType(type);
1697 if (!VlaType)
1698 return;
1699 auto VlaSize = getVLASize(VlaType);
1700 auto SizeVal = VlaSize.NumElts;
1701 CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1702 switch (trivialAutoVarInit) {
1703 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1704 llvm_unreachable("Uninitialized handled by caller");
1705
1706 case LangOptions::TrivialAutoVarInitKind::Zero:
1707 if (!EltSize.isOne())
1708 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1709 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1710 isVolatile);
1711 break;
1712
1713 case LangOptions::TrivialAutoVarInitKind::Pattern: {
1714 llvm::Type *ElTy = Loc.getElementType();
1715 llvm::Constant *Constant = constWithPadding(
1716 CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1717 CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
1718 llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
1719 llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
1720 llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
1721 llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1722 SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
1723 "vla.iszerosized");
1724 Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
1725 EmitBlock(SetupBB);
1726 if (!EltSize.isOne())
1727 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1728 llvm::Value *BaseSizeInChars =
1729 llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
1730 Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
1731 llvm::Value *End =
1732 Builder.CreateInBoundsGEP(Begin.getPointer(), SizeVal, "vla.end");
1733 llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1734 EmitBlock(LoopBB);
1735 llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
1736 Cur->addIncoming(Begin.getPointer(), OriginBB);
1737 CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
1738 Builder.CreateMemCpy(Address(Cur, CurAlign),
1739 createUnnamedGlobalForMemcpyFrom(
1740 CGM, D, Builder, Constant, ConstantAlign),
1741 BaseSizeInChars, isVolatile);
1742 llvm::Value *Next =
1743 Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
1744 llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
1745 Builder.CreateCondBr(Done, ContBB, LoopBB);
1746 Cur->addIncoming(Next, LoopBB);
1747 EmitBlock(ContBB);
1748 } break;
1749 }
1750}
1751
John McCallc533cb72011-02-22 06:44:22 +00001752void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001753 assert(emission.Variable && "emission was not valid!");
1754
John McCallc533cb72011-02-22 06:44:22 +00001755 // If this was emitted as a global constant, we're done.
1756 if (emission.wasEmittedAsGlobal()) return;
1757
John McCall9e2e22f2011-02-22 07:16:58 +00001758 const VarDecl &D = *emission.Variable;
Adrian Prantl95b24e92015-02-03 20:00:54 +00001759 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
John McCallc533cb72011-02-22 06:44:22 +00001760 QualType type = D.getType();
1761
Chris Lattner07eb7332007-07-12 00:39:48 +00001762 // If this local has an initializer, emit it now.
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001763 const Expr *Init = D.getInit();
1764
1765 // If we are at an unreachable point, we don't need to emit the initializer
1766 // unless it contains a label.
1767 if (!HaveInsertPoint()) {
John McCallc533cb72011-02-22 06:44:22 +00001768 if (!Init || !ContainsLabel(Init)) return;
1769 EnsureInsertPoint();
Daniel Dunbarb6adc432009-07-19 06:58:07 +00001770 }
1771
John McCall73064872011-03-31 01:59:53 +00001772 // Initialize the structure of a __block variable.
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001773 if (emission.IsEscapingByRef)
John McCall73064872011-03-31 01:59:53 +00001774 emitByrefStructureInit(emission);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00001775
Akira Hatanaka7275da02018-02-28 07:15:55 +00001776 // Initialize the variable here if it doesn't have a initializer and it is a
1777 // C struct that is non-trivial to initialize or an array containing such a
1778 // struct.
1779 if (!Init &&
1780 type.isNonTrivialToPrimitiveDefaultInitialize() ==
1781 QualType::PDIK_Struct) {
1782 LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
Akira Hatanaka8e57b072018-10-01 21:51:28 +00001783 if (emission.IsEscapingByRef)
Akira Hatanaka7275da02018-02-28 07:15:55 +00001784 drillIntoBlockVariable(*this, Dst, &D);
1785 defaultInitNonTrivialCStructVar(Dst);
1786 return;
1787 }
1788
John McCallc533cb72011-02-22 06:44:22 +00001789 // Check whether this is a byref variable that's potentially
1790 // captured and moved by its own initializer. If so, we'll need to
1791 // emit the initializer first, then copy into the variable.
JF Bastien14daa202018-12-18 05:12:21 +00001792 bool capturedByInit =
1793 Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
John McCallc533cb72011-02-22 06:44:22 +00001794
JF Bastien0bae08a2019-02-15 17:26:29 +00001795 bool locIsByrefHeader = !capturedByInit;
1796 const Address Loc =
1797 locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
JF Bastien14daa202018-12-18 05:12:21 +00001798
1799 // Note: constexpr already initializes everything correctly.
1800 LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
1801 (D.isConstexpr()
1802 ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1803 : (D.getAttr<UninitializedAttr>()
1804 ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1805 : getContext().getLangOpts().getTrivialAutoVarInit()));
1806
JF Bastienb347e752019-02-08 01:29:17 +00001807 auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
JF Bastien14daa202018-12-18 05:12:21 +00001808 if (trivialAutoVarInit ==
1809 LangOptions::TrivialAutoVarInitKind::Uninitialized)
1810 return;
1811
JF Bastienb347e752019-02-08 01:29:17 +00001812 // Only initialize a __block's storage: we always initialize the header.
JF Bastien0bae08a2019-02-15 17:26:29 +00001813 if (emission.IsEscapingByRef && !locIsByrefHeader)
JF Bastienb347e752019-02-08 01:29:17 +00001814 Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
1815
Vitaly Bukae7267662019-07-10 22:53:50 +00001816 return emitZeroOrPatternForAutoVarInit(type, D, Loc);
JF Bastien14daa202018-12-18 05:12:21 +00001817 };
1818
Vitaly Bukae7267662019-07-10 22:53:50 +00001819 if (isTrivialInitializer(Init))
1820 return initializeWhatIsTechnicallyUninitialized(Loc);
John McCallc533cb72011-02-22 06:44:22 +00001821
Craig Topper8a13c412014-05-21 05:09:00 +00001822 llvm::Constant *constant = nullptr;
Richard Smith715f7a12019-06-11 17:50:32 +00001823 if (emission.IsConstantAggregate ||
1824 D.mightBeUsableInConstantExpressions(getContext())) {
Richard Smithfddd3842011-12-30 21:15:51 +00001825 assert(!capturedByInit && "constant init contains a capturing block?");
John McCallde0fe072017-08-15 21:42:52 +00001826 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
JF Bastiend39fbc72019-04-30 22:56:53 +00001827 if (constant && !constant->isZeroValue() &&
1828 (trivialAutoVarInit !=
1829 LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001830 IsPattern isPattern =
1831 (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
1832 ? IsPattern::Yes
1833 : IsPattern::No;
JF Bastiend39fbc72019-04-30 22:56:53 +00001834 // C guarantees that brace-init with fewer initializers than members in
1835 // the aggregate will initialize the rest of the aggregate as-if it were
1836 // static initialization. In turn static initialization guarantees that
1837 // padding is initialized to zero bits. We could instead pattern-init if D
1838 // has any ImplicitValueInitExpr, but that seems to be unintuitive
1839 // behavior.
1840 constant = constWithPadding(CGM, IsPattern::No,
Alexander Potapenko4f7bc0e2019-02-26 10:46:21 +00001841 replaceUndef(CGM, isPattern, constant));
1842 }
Richard Smithfddd3842011-12-30 21:15:51 +00001843 }
1844
1845 if (!constant) {
JF Bastienb347e752019-02-08 01:29:17 +00001846 initializeWhatIsTechnicallyUninitialized(Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001847 LValue lv = MakeAddrLValue(Loc, type);
John McCall1553b192011-06-16 04:16:24 +00001848 lv.setNonGC(true);
David Blaikie66e41972015-01-14 07:38:27 +00001849 return EmitExprAsInit(Init, &D, lv, capturedByInit);
John McCall1553b192011-06-16 04:16:24 +00001850 }
John McCall91ca10f2011-03-08 09:11:50 +00001851
Richard Smith2bcde3a2013-06-02 00:09:52 +00001852 if (!emission.IsConstantAggregate) {
1853 // For simple scalar/complex initialization, store the value directly.
John McCall7f416cc2015-09-08 08:05:57 +00001854 LValue lv = MakeAddrLValue(Loc, type);
Richard Smith2bcde3a2013-06-02 00:09:52 +00001855 lv.setNonGC(true);
1856 return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1857 }
1858
Yaxun Liudaceb1e2018-05-14 19:20:12 +00001859 llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
JF Bastien0bae08a2019-02-15 17:26:29 +00001860 emitStoresForConstant(
1861 CGM, D, (Loc.getType() == BP) ? Loc : Builder.CreateBitCast(Loc, BP),
Vitaly Buka96ff25a2019-06-27 01:34:21 +00001862 type.isVolatileQualified(), Builder, constant);
John McCall91ca10f2011-03-08 09:11:50 +00001863}
1864
Richard Smithe78fac52018-04-05 20:52:58 +00001865/// Emit an expression as an initializer for an object (variable, field, etc.)
1866/// at the given location. The expression is not necessarily the normal
1867/// initializer for the object, and the address is not necessarily
John McCall91ca10f2011-03-08 09:11:50 +00001868/// its normal location.
1869///
1870/// \param init the initializing expression
Richard Smithe78fac52018-04-05 20:52:58 +00001871/// \param D the object to act as if we're initializing
John McCall91ca10f2011-03-08 09:11:50 +00001872/// \param loc the address to initialize; its type is a pointer
Richard Smithe78fac52018-04-05 20:52:58 +00001873/// to the LLVM mapping of the object's type
John McCall91ca10f2011-03-08 09:11:50 +00001874/// \param alignment the alignment of the address
Richard Smithe78fac52018-04-05 20:52:58 +00001875/// \param capturedByInit true if \p D is a __block variable
John McCall91ca10f2011-03-08 09:11:50 +00001876/// whose address is potentially changed by the initializer
David Blaikie73ca5692014-12-09 00:32:22 +00001877void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
David Blaikie66e41972015-01-14 07:38:27 +00001878 LValue lvalue, bool capturedByInit) {
John McCall31168b02011-06-15 23:02:42 +00001879 QualType type = D->getType();
John McCall91ca10f2011-03-08 09:11:50 +00001880
1881 if (type->isReferenceType()) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +00001882 RValue rvalue = EmitReferenceBindingToExpr(init);
Eric Christopher31ab1302011-08-23 22:38:00 +00001883 if (capturedByInit)
John McCall1553b192011-06-16 04:16:24 +00001884 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001885 EmitStoreThroughLValue(rvalue, lvalue, true);
John McCall47fb9502013-03-07 21:37:08 +00001886 return;
1887 }
1888 switch (getEvaluationKind(type)) {
1889 case TEK_Scalar:
David Blaikie66e41972015-01-14 07:38:27 +00001890 EmitScalarInit(init, D, lvalue, capturedByInit);
John McCall47fb9502013-03-07 21:37:08 +00001891 return;
1892 case TEK_Complex: {
John McCall91ca10f2011-03-08 09:11:50 +00001893 ComplexPairTy complex = EmitComplexExpr(init);
John McCall1553b192011-06-16 04:16:24 +00001894 if (capturedByInit)
1895 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
David Blaikie66e41972015-01-14 07:38:27 +00001896 EmitStoreOfComplex(complex, lvalue, /*init*/ true);
John McCall47fb9502013-03-07 21:37:08 +00001897 return;
1898 }
1899 case TEK_Aggregate:
John McCalla8ec7eb2013-03-07 21:37:17 +00001900 if (type->isAtomicType()) {
1901 EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1902 } else {
Richard Smithe78fac52018-04-05 20:52:58 +00001903 AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
1904 if (isa<VarDecl>(D))
1905 Overlap = AggValueSlot::DoesNotOverlap;
1906 else if (auto *FD = dyn_cast<FieldDecl>(D))
Richard Smith8cca3a52019-06-20 20:56:20 +00001907 Overlap = getOverlapForFieldInit(FD);
John McCalla8ec7eb2013-03-07 21:37:17 +00001908 // TODO: how can we delay here if D is captured by its initializer?
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001909 EmitAggExpr(init, AggValueSlot::forLValue(
1910 lvalue, *this, AggValueSlot::IsDestructed,
1911 AggValueSlot::DoesNotNeedGCBarriers,
1912 AggValueSlot::IsNotAliased, Overlap));
John McCalla8ec7eb2013-03-07 21:37:17 +00001913 }
John McCall47fb9502013-03-07 21:37:08 +00001914 return;
Fariborz Jahanianc6140732010-03-12 21:40:43 +00001915 }
John McCall47fb9502013-03-07 21:37:08 +00001916 llvm_unreachable("bad evaluation kind");
John McCallc533cb72011-02-22 06:44:22 +00001917}
John McCallbd309292010-07-06 01:34:17 +00001918
John McCall82fe67b2011-07-09 01:37:26 +00001919/// Enter a destroy cleanup for the given local variable.
1920void CodeGenFunction::emitAutoVarTypeCleanup(
1921 const CodeGenFunction::AutoVarEmission &emission,
1922 QualType::DestructionKind dtorKind) {
1923 assert(dtorKind != QualType::DK_none);
1924
1925 // Note that for __block variables, we want to destroy the
1926 // original stack object, not the possibly forwarded object.
John McCall7f416cc2015-09-08 08:05:57 +00001927 Address addr = emission.getObjectAddress(*this);
John McCall82fe67b2011-07-09 01:37:26 +00001928
1929 const VarDecl *var = emission.Variable;
1930 QualType type = var->getType();
1931
1932 CleanupKind cleanupKind = NormalAndEHCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001933 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall82fe67b2011-07-09 01:37:26 +00001934
1935 switch (dtorKind) {
1936 case QualType::DK_none:
1937 llvm_unreachable("no cleanup for trivially-destructible variable");
1938
1939 case QualType::DK_cxx_destructor:
1940 // If there's an NRVO flag on the emission, we need a different
1941 // cleanup.
1942 if (emission.NRVOFlag) {
1943 assert(!type->isArrayType());
1944 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
Marco Antognini88559632019-07-22 09:39:13 +00001945 EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001946 emission.NRVOFlag);
John McCall82fe67b2011-07-09 01:37:26 +00001947 return;
1948 }
1949 break;
1950
1951 case QualType::DK_objc_strong_lifetime:
1952 // Suppress cleanups for pseudo-strong variables.
1953 if (var->isARCPseudoStrong()) return;
Eric Christopher31ab1302011-08-23 22:38:00 +00001954
John McCall82fe67b2011-07-09 01:37:26 +00001955 // Otherwise, consider whether to use an EH cleanup or not.
1956 cleanupKind = getARCCleanupKind();
1957
1958 // Use the imprecise destroyer by default.
1959 if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1960 destroyer = CodeGenFunction::destroyARCStrongImprecise;
1961 break;
1962
1963 case QualType::DK_objc_weak_lifetime:
1964 break;
Akira Hatanaka7275da02018-02-28 07:15:55 +00001965
1966 case QualType::DK_nontrivial_c_struct:
1967 destroyer = CodeGenFunction::destroyNonTrivialCStruct;
Akira Hatanaka673af7a2018-03-29 17:56:24 +00001968 if (emission.NRVOFlag) {
1969 assert(!type->isArrayType());
1970 EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
1971 emission.NRVOFlag, type);
1972 return;
1973 }
Akira Hatanaka7275da02018-02-28 07:15:55 +00001974 break;
John McCall82fe67b2011-07-09 01:37:26 +00001975 }
1976
1977 // If we haven't chosen a more specific destroyer, use the default.
Peter Collingbourne1425b452012-01-26 03:33:36 +00001978 if (!destroyer) destroyer = getDestroyer(dtorKind);
John McCall178360e2011-07-11 08:38:19 +00001979
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001980 // Use an EH cleanup in array destructors iff the destructor itself
John McCall178360e2011-07-11 08:38:19 +00001981 // is being pushed as an EH cleanup.
1982 bool useEHCleanup = (cleanupKind & EHCleanup);
1983 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1984 useEHCleanup);
John McCall82fe67b2011-07-09 01:37:26 +00001985}
1986
John McCallc533cb72011-02-22 06:44:22 +00001987void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
John McCall9e2e22f2011-02-22 07:16:58 +00001988 assert(emission.Variable && "emission was not valid!");
1989
John McCallc533cb72011-02-22 06:44:22 +00001990 // If this was emitted as a global constant, we're done.
1991 if (emission.wasEmittedAsGlobal()) return;
1992
John McCall8c38d352012-04-13 18:44:05 +00001993 // If we don't have an insertion point, we're done. Sema prevents
1994 // us from jumping into any of these scopes anyway.
1995 if (!HaveInsertPoint()) return;
1996
John McCall9e2e22f2011-02-22 07:16:58 +00001997 const VarDecl &D = *emission.Variable;
John McCallc533cb72011-02-22 06:44:22 +00001998
John McCall82fe67b2011-07-09 01:37:26 +00001999 // Check the type for a cleanup.
Richard Smith2b4fa532019-09-29 05:08:46 +00002000 if (QualType::DestructionKind dtorKind = D.needsDestruction(getContext()))
John McCall82fe67b2011-07-09 01:37:26 +00002001 emitAutoVarTypeCleanup(emission, dtorKind);
John McCall31168b02011-06-15 23:02:42 +00002002
John McCall1bd25562011-06-24 23:21:27 +00002003 // In GC mode, honor objc_precise_lifetime.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002004 if (getLangOpts().getGC() != LangOptions::NonGC &&
John McCall1bd25562011-06-24 23:21:27 +00002005 D.hasAttr<ObjCPreciseLifetimeAttr>()) {
2006 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
2007 }
2008
John McCallc533cb72011-02-22 06:44:22 +00002009 // Handle the cleanup attribute.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002010 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
Anders Carlssoncadb9a62009-02-07 23:51:38 +00002011 const FunctionDecl *FD = CA->getFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002012
John McCallc533cb72011-02-22 06:44:22 +00002013 llvm::Constant *F = CGM.GetAddrOfFunction(FD);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00002014 assert(F && "Could not find function!");
Mike Stump11289f42009-09-09 15:08:12 +00002015
John McCalla729c622012-02-17 03:33:10 +00002016 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
John McCallc533cb72011-02-22 06:44:22 +00002017 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
Anders Carlssoncadb9a62009-02-07 23:51:38 +00002018 }
Mike Stump626aecc2009-03-05 01:23:13 +00002019
John McCallc533cb72011-02-22 06:44:22 +00002020 // If this is a block variable, call _Block_object_destroy
Akira Hatanakacb6a9332018-07-26 16:51:21 +00002021 // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
2022 // mode.
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002023 if (emission.IsEscapingByRef &&
2024 CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
Akira Hatanakacb6a9332018-07-26 16:51:21 +00002025 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2026 if (emission.Variable->getType().isObjCGCWeak())
2027 Flags |= BLOCK_FIELD_IS_WEAK;
2028 enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
Akira Hatanaka9978da32018-08-10 15:09:24 +00002029 /*LoadBlockVarAddr*/ false,
2030 cxxDestructorCanThrow(emission.Variable->getType()));
Akira Hatanakacb6a9332018-07-26 16:51:21 +00002031 }
Chris Lattner03df1222007-06-02 04:53:11 +00002032}
Chris Lattner53621a52007-06-13 20:44:40 +00002033
Peter Collingbourne1425b452012-01-26 03:33:36 +00002034CodeGenFunction::Destroyer *
John McCall82fe67b2011-07-09 01:37:26 +00002035CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
2036 switch (kind) {
2037 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
John McCallc2f00012011-07-09 09:09:00 +00002038 case QualType::DK_cxx_destructor:
Peter Collingbourne1425b452012-01-26 03:33:36 +00002039 return destroyCXXObject;
John McCallc2f00012011-07-09 09:09:00 +00002040 case QualType::DK_objc_strong_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00002041 return destroyARCStrongPrecise;
John McCallc2f00012011-07-09 09:09:00 +00002042 case QualType::DK_objc_weak_lifetime:
Peter Collingbourne1425b452012-01-26 03:33:36 +00002043 return destroyARCWeak;
Akira Hatanaka7275da02018-02-28 07:15:55 +00002044 case QualType::DK_nontrivial_c_struct:
2045 return destroyNonTrivialCStruct;
John McCall82fe67b2011-07-09 01:37:26 +00002046 }
Matt Beaumont-Gay934bbf52012-01-27 00:46:27 +00002047 llvm_unreachable("Unknown DestructionKind");
John McCall82fe67b2011-07-09 01:37:26 +00002048}
2049
John McCall12cc42a2013-02-01 05:11:40 +00002050/// pushEHDestroy - Push the standard destructor for the given type as
2051/// an EH-only cleanup.
2052void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00002053 Address addr, QualType type) {
John McCall12cc42a2013-02-01 05:11:40 +00002054 assert(dtorKind && "cannot push destructor for trivial type");
2055 assert(needsEHCleanup(dtorKind));
2056
2057 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
2058}
2059
2060/// pushDestroy - Push the standard destructor for the given type as
2061/// at least a normal cleanup.
John McCall4bd0fb12011-07-12 16:41:08 +00002062void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
John McCall7f416cc2015-09-08 08:05:57 +00002063 Address addr, QualType type) {
John McCall4bd0fb12011-07-12 16:41:08 +00002064 assert(dtorKind && "cannot push destructor for trivial type");
2065
2066 CleanupKind cleanupKind = getCleanupKind(dtorKind);
2067 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
2068 cleanupKind & EHCleanup);
2069}
2070
John McCall7f416cc2015-09-08 08:05:57 +00002071void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002072 QualType type, Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00002073 bool useEHCleanupForArray) {
John McCall4bd0fb12011-07-12 16:41:08 +00002074 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
2075 destroyer, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00002076}
2077
John McCall7f416cc2015-09-08 08:05:57 +00002078void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002079 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
2080}
2081
Richard Smith736a9472013-06-12 20:42:33 +00002082void CodeGenFunction::pushLifetimeExtendedDestroy(
John McCall7f416cc2015-09-08 08:05:57 +00002083 CleanupKind cleanupKind, Address addr, QualType type,
Richard Smith736a9472013-06-12 20:42:33 +00002084 Destroyer *destroyer, bool useEHCleanupForArray) {
Richard Smith736a9472013-06-12 20:42:33 +00002085 // Push an EH-only cleanup for the object now.
2086 // FIXME: When popping normal cleanups, we need to keep this EH cleanup
2087 // around in case a temporary's destructor throws an exception.
2088 if (cleanupKind & EHCleanup)
2089 EHStack.pushCleanup<DestroyObject>(
2090 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
2091 destroyer, useEHCleanupForArray);
2092
2093 // Remember that we need to push a full cleanup for the object at the
2094 // end of the full-expression.
2095 pushCleanupAfterFullExpr<DestroyObject>(
2096 cleanupKind, addr, type, destroyer, useEHCleanupForArray);
2097}
2098
John McCall178360e2011-07-11 08:38:19 +00002099/// emitDestroy - Immediately perform the destruction of the given
2100/// object.
2101///
2102/// \param addr - the address of the object; a type*
2103/// \param type - the type of the object; if an array type, all
2104/// objects are destroyed in reverse order
2105/// \param destroyer - the function to call to destroy individual
2106/// elements
2107/// \param useEHCleanupForArray - whether an EH cleanup should be
2108/// used when destroying array elements, in case one of the
2109/// destructions throws an exception
John McCall7f416cc2015-09-08 08:05:57 +00002110void CodeGenFunction::emitDestroy(Address addr, QualType type,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002111 Destroyer *destroyer,
John McCall178360e2011-07-11 08:38:19 +00002112 bool useEHCleanupForArray) {
John McCall82fe67b2011-07-09 01:37:26 +00002113 const ArrayType *arrayType = getContext().getAsArrayType(type);
2114 if (!arrayType)
2115 return destroyer(*this, addr, type);
2116
John McCall7f416cc2015-09-08 08:05:57 +00002117 llvm::Value *length = emitArrayLength(arrayType, type, addr);
2118
2119 CharUnits elementAlign =
2120 addr.getAlignment()
2121 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
John McCall97eab0a2011-07-13 08:09:46 +00002122
2123 // Normally we have to check whether the array is zero-length.
2124 bool checkZeroLength = true;
2125
2126 // But if the array length is constant, we can suppress that.
2127 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
2128 // ...and if it's constant zero, we can just skip the entire thing.
2129 if (constLength->isZero()) return;
2130 checkZeroLength = false;
2131 }
2132
John McCall7f416cc2015-09-08 08:05:57 +00002133 llvm::Value *begin = addr.getPointer();
John McCall82fe67b2011-07-09 01:37:26 +00002134 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
John McCall7f416cc2015-09-08 08:05:57 +00002135 emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00002136 checkZeroLength, useEHCleanupForArray);
John McCall82fe67b2011-07-09 01:37:26 +00002137}
2138
John McCall178360e2011-07-11 08:38:19 +00002139/// emitArrayDestroy - Destroys all the elements of the given array,
2140/// beginning from last to first. The array cannot be zero-length.
2141///
2142/// \param begin - a type* denoting the first element of the array
2143/// \param end - a type* denoting one past the end of the array
NAKAMURA Takumiff7a9252015-09-08 09:42:41 +00002144/// \param elementType - the element type of the array
John McCall178360e2011-07-11 08:38:19 +00002145/// \param destroyer - the function to call to destroy elements
2146/// \param useEHCleanup - whether to push an EH cleanup to destroy
2147/// the remaining elements in case the destruction of a single
2148/// element throws
John McCall82fe67b2011-07-09 01:37:26 +00002149void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2150 llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00002151 QualType elementType,
2152 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002153 Destroyer *destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00002154 bool checkZeroLength,
John McCall178360e2011-07-11 08:38:19 +00002155 bool useEHCleanup) {
John McCall7f416cc2015-09-08 08:05:57 +00002156 assert(!elementType->isArrayType());
John McCall82fe67b2011-07-09 01:37:26 +00002157
2158 // The basic structure here is a do-while loop, because we don't
2159 // need to check for the zero-element case.
2160 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
2161 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
2162
John McCall97eab0a2011-07-13 08:09:46 +00002163 if (checkZeroLength) {
2164 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
2165 "arraydestroy.isempty");
2166 Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
2167 }
2168
John McCall82fe67b2011-07-09 01:37:26 +00002169 // Enter the loop body, making that address the current address.
2170 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2171 EmitBlock(bodyBB);
2172 llvm::PHINode *elementPast =
2173 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
2174 elementPast->addIncoming(end, entryBB);
2175
2176 // Shift the address back by one element.
2177 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
2178 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
2179 "arraydestroy.element");
2180
John McCall178360e2011-07-11 08:38:19 +00002181 if (useEHCleanup)
John McCall7f416cc2015-09-08 08:05:57 +00002182 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
2183 destroyer);
John McCall178360e2011-07-11 08:38:19 +00002184
John McCall82fe67b2011-07-09 01:37:26 +00002185 // Perform the actual destruction there.
John McCall7f416cc2015-09-08 08:05:57 +00002186 destroyer(*this, Address(element, elementAlign), elementType);
John McCall82fe67b2011-07-09 01:37:26 +00002187
John McCall178360e2011-07-11 08:38:19 +00002188 if (useEHCleanup)
2189 PopCleanupBlock();
2190
John McCall82fe67b2011-07-09 01:37:26 +00002191 // Check whether we've reached the end.
2192 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
2193 Builder.CreateCondBr(done, doneBB, bodyBB);
2194 elementPast->addIncoming(element, Builder.GetInsertBlock());
2195
2196 // Done.
2197 EmitBlock(doneBB);
2198}
2199
John McCall178360e2011-07-11 08:38:19 +00002200/// Perform partial array destruction as if in an EH cleanup. Unlike
2201/// emitArrayDestroy, the element type here may still be an array type.
John McCall178360e2011-07-11 08:38:19 +00002202static void emitPartialArrayDestroy(CodeGenFunction &CGF,
2203 llvm::Value *begin, llvm::Value *end,
John McCall7f416cc2015-09-08 08:05:57 +00002204 QualType type, CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002205 CodeGenFunction::Destroyer *destroyer) {
John McCall178360e2011-07-11 08:38:19 +00002206 // If the element type is itself an array, drill down.
John McCall97eab0a2011-07-13 08:09:46 +00002207 unsigned arrayDepth = 0;
John McCall178360e2011-07-11 08:38:19 +00002208 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
2209 // VLAs don't require a GEP index to walk into.
2210 if (!isa<VariableArrayType>(arrayType))
John McCall97eab0a2011-07-13 08:09:46 +00002211 arrayDepth++;
John McCall178360e2011-07-11 08:38:19 +00002212 type = arrayType->getElementType();
2213 }
John McCall97eab0a2011-07-13 08:09:46 +00002214
2215 if (arrayDepth) {
John McCallf0f0b7a2015-09-14 18:57:08 +00002216 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
John McCall97eab0a2011-07-13 08:09:46 +00002217
John McCallf0f0b7a2015-09-14 18:57:08 +00002218 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
Jay Foad040dd822011-07-22 08:16:57 +00002219 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
2220 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
John McCall178360e2011-07-11 08:38:19 +00002221 }
2222
John McCall97eab0a2011-07-13 08:09:46 +00002223 // Destroy the array. We don't ever need an EH cleanup because we
2224 // assume that we're in an EH cleanup ourselves, so a throwing
2225 // destructor causes an immediate terminate.
John McCall7f416cc2015-09-08 08:05:57 +00002226 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
John McCall97eab0a2011-07-13 08:09:46 +00002227 /*checkZeroLength*/ true, /*useEHCleanup*/ false);
John McCall178360e2011-07-11 08:38:19 +00002228}
2229
John McCall82fe67b2011-07-09 01:37:26 +00002230namespace {
John McCall178360e2011-07-11 08:38:19 +00002231 /// RegularPartialArrayDestroy - a cleanup which performs a partial
2232 /// array destroy where the end pointer is regularly determined and
2233 /// does not need to be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00002234 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall178360e2011-07-11 08:38:19 +00002235 llvm::Value *ArrayBegin;
2236 llvm::Value *ArrayEnd;
2237 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00002238 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00002239 CharUnits ElementAlign;
John McCall178360e2011-07-11 08:38:19 +00002240 public:
2241 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002242 QualType elementType, CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00002243 CodeGenFunction::Destroyer *destroyer)
2244 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
John McCall7f416cc2015-09-08 08:05:57 +00002245 ElementType(elementType), Destroyer(destroyer),
2246 ElementAlign(elementAlign) {}
John McCall178360e2011-07-11 08:38:19 +00002247
Craig Topper4f12f102014-03-12 06:41:41 +00002248 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall178360e2011-07-11 08:38:19 +00002249 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002250 ElementType, ElementAlign, Destroyer);
John McCall178360e2011-07-11 08:38:19 +00002251 }
2252 };
2253
2254 /// IrregularPartialArrayDestroy - a cleanup which performs a
2255 /// partial array destroy where the end pointer is irregularly
2256 /// determined and must be loaded from a local.
David Blaikie7e70d682015-08-18 22:40:54 +00002257 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
John McCall82fe67b2011-07-09 01:37:26 +00002258 llvm::Value *ArrayBegin;
John McCall7f416cc2015-09-08 08:05:57 +00002259 Address ArrayEndPointer;
John McCall82fe67b2011-07-09 01:37:26 +00002260 QualType ElementType;
Peter Collingbourne1425b452012-01-26 03:33:36 +00002261 CodeGenFunction::Destroyer *Destroyer;
John McCall7f416cc2015-09-08 08:05:57 +00002262 CharUnits ElementAlign;
John McCall82fe67b2011-07-09 01:37:26 +00002263 public:
John McCall178360e2011-07-11 08:38:19 +00002264 IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00002265 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00002266 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00002267 CharUnits elementAlign,
John McCall178360e2011-07-11 08:38:19 +00002268 CodeGenFunction::Destroyer *destroyer)
John McCall82fe67b2011-07-09 01:37:26 +00002269 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
John McCall7f416cc2015-09-08 08:05:57 +00002270 ElementType(elementType), Destroyer(destroyer),
2271 ElementAlign(elementAlign) {}
John McCall82fe67b2011-07-09 01:37:26 +00002272
Craig Topper4f12f102014-03-12 06:41:41 +00002273 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall82fe67b2011-07-09 01:37:26 +00002274 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
John McCall178360e2011-07-11 08:38:19 +00002275 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002276 ElementType, ElementAlign, Destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00002277 }
2278 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002279} // end anonymous namespace
John McCall82fe67b2011-07-09 01:37:26 +00002280
John McCall178360e2011-07-11 08:38:19 +00002281/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
John McCall82fe67b2011-07-09 01:37:26 +00002282/// already-constructed elements of the given array. The cleanup
John McCall178360e2011-07-11 08:38:19 +00002283/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00002284///
John McCall82fe67b2011-07-09 01:37:26 +00002285/// \param elementType - the immediate element type of the array;
2286/// possibly still an array type
John McCall4bd0fb12011-07-12 16:41:08 +00002287void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
John McCall7f416cc2015-09-08 08:05:57 +00002288 Address arrayEndPointer,
John McCall178360e2011-07-11 08:38:19 +00002289 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00002290 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002291 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00002292 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
2293 arrayBegin, arrayEndPointer,
John McCall7f416cc2015-09-08 08:05:57 +00002294 elementType, elementAlign,
2295 destroyer);
John McCall178360e2011-07-11 08:38:19 +00002296}
2297
2298/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2299/// already-constructed elements of the given array. The cleanup
2300/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
Eric Christopher31ab1302011-08-23 22:38:00 +00002301///
John McCall178360e2011-07-11 08:38:19 +00002302/// \param elementType - the immediate element type of the array;
2303/// possibly still an array type
John McCall178360e2011-07-11 08:38:19 +00002304void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2305 llvm::Value *arrayEnd,
2306 QualType elementType,
John McCall7f416cc2015-09-08 08:05:57 +00002307 CharUnits elementAlign,
Peter Collingbourne1425b452012-01-26 03:33:36 +00002308 Destroyer *destroyer) {
John McCall4bd0fb12011-07-12 16:41:08 +00002309 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
John McCall178360e2011-07-11 08:38:19 +00002310 arrayBegin, arrayEnd,
John McCall7f416cc2015-09-08 08:05:57 +00002311 elementType, elementAlign,
2312 destroyer);
John McCall82fe67b2011-07-09 01:37:26 +00002313}
2314
Nadav Rotem1da30942013-03-23 06:43:35 +00002315/// Lazily declare the @llvm.lifetime.start intrinsic.
James Y Knight76f78742019-02-05 19:17:50 +00002316llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00002317 if (LifetimeStartFn)
2318 return LifetimeStartFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00002319 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00002320 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00002321 return LifetimeStartFn;
2322}
2323
2324/// Lazily declare the @llvm.lifetime.end intrinsic.
James Y Knight76f78742019-02-05 19:17:50 +00002325llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
Matt Arsenaultd9729492017-04-10 20:18:45 +00002326 if (LifetimeEndFn)
2327 return LifetimeEndFn;
Nadav Rotem1da30942013-03-23 06:43:35 +00002328 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
Yaxun Liu7f7f3232017-04-17 20:03:11 +00002329 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
Nadav Rotem1da30942013-03-23 06:43:35 +00002330 return LifetimeEndFn;
2331}
2332
John McCall31168b02011-06-15 23:02:42 +00002333namespace {
2334 /// A cleanup to perform a release of an object at the end of a
2335 /// function. This is used to balance out the incoming +1 of a
2336 /// ns_consumed argument when we can't reasonably do that just by
2337 /// not doing the initial retain for a __block argument.
David Blaikie7e70d682015-08-18 22:40:54 +00002338 struct ConsumeARCParameter final : EHScopeStack::Cleanup {
John McCallcdda29c2013-03-13 03:10:54 +00002339 ConsumeARCParameter(llvm::Value *param,
2340 ARCPreciseLifetime_t precise)
2341 : Param(param), Precise(precise) {}
John McCall31168b02011-06-15 23:02:42 +00002342
2343 llvm::Value *Param;
John McCallcdda29c2013-03-13 03:10:54 +00002344 ARCPreciseLifetime_t Precise;
John McCall31168b02011-06-15 23:02:42 +00002345
Craig Topper4f12f102014-03-12 06:41:41 +00002346 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00002347 CGF.EmitARCRelease(Param, Precise);
John McCall31168b02011-06-15 23:02:42 +00002348 }
2349 };
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002350} // end anonymous namespace
John McCall31168b02011-06-15 23:02:42 +00002351
Mike Stump11289f42009-09-09 15:08:12 +00002352/// Emit an alloca (or GlobalValue depending on target)
Chris Lattnerb781dc792008-05-08 05:58:21 +00002353/// for the specified parameter and set up LocalDeclMap.
John McCall7f416cc2015-09-08 08:05:57 +00002354void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2355 unsigned ArgNo) {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00002356 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
Sanjiv Guptad7959242008-10-31 09:52:39 +00002357 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
Daniel Dunbara94ecd22008-08-16 03:19:19 +00002358 "Invalid argument to EmitParmDecl");
John McCall147d0212011-02-22 22:38:33 +00002359
John McCall7f416cc2015-09-08 08:05:57 +00002360 Arg.getAnyValue()->setName(D.getName());
John McCall147d0212011-02-22 22:38:33 +00002361
Adrian Prantl51936dd2013-03-14 17:53:33 +00002362 QualType Ty = D.getType();
2363
John McCall147d0212011-02-22 22:38:33 +00002364 // Use better IR generation for certain implicit parameters.
John McCall7f416cc2015-09-08 08:05:57 +00002365 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
John McCall147d0212011-02-22 22:38:33 +00002366 // The only implicit argument a block has is its literal.
Saleem Abdulrasoolc1b46382018-02-21 21:47:51 +00002367 // This may be passed as an inalloca'ed value on Windows x86.
John McCall147d0212011-02-22 22:38:33 +00002368 if (BlockInfo) {
Saleem Abdulrasoolc1b46382018-02-21 21:47:51 +00002369 llvm::Value *V = Arg.isIndirect()
2370 ? Builder.CreateLoad(Arg.getIndirectAddress())
2371 : Arg.getDirectValue();
2372 setBlockContextParameter(IPD, ArgNo, V);
John McCall147d0212011-02-22 22:38:33 +00002373 return;
2374 }
2375 }
2376
John McCall7f416cc2015-09-08 08:05:57 +00002377 Address DeclPtr = Address::invalid();
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002378 bool DoStore = false;
2379 bool IsScalar = hasScalarEvaluationKind(Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002380 // If we already have a pointer to the argument, reuse the input pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002381 if (Arg.isIndirect()) {
2382 DeclPtr = Arg.getIndirectAddress();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00002383 // If we have a prettier pointer type at this point, bitcast to that.
John McCall7f416cc2015-09-08 08:05:57 +00002384 unsigned AS = DeclPtr.getType()->getAddressSpace();
Reid Kleckner5e8edba2014-04-02 00:16:53 +00002385 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
John McCall7f416cc2015-09-08 08:05:57 +00002386 if (DeclPtr.getType() != IRTy)
2387 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
Yaxun Liu5b330e82018-03-15 15:25:19 +00002388 // Indirect argument is in alloca address space, which may be different
2389 // from the default address space.
2390 auto AllocaAS = CGM.getASTAllocaAddressSpace();
2391 auto *V = DeclPtr.getPointer();
2392 auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2393 auto DestLangAS =
2394 getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
2395 if (SrcLangAS != DestLangAS) {
2396 assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2397 CGM.getDataLayout().getAllocaAddrSpace());
2398 auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2399 auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
2400 DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
2401 *this, V, SrcLangAS, DestLangAS, T, true),
2402 DeclPtr.getAlignment());
2403 }
John McCall7f416cc2015-09-08 08:05:57 +00002404
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002405 // Push a destructor cleanup for this parameter if the ABI requires it.
Reid Kleckner19819442014-07-25 21:39:46 +00002406 // Don't push a cleanup in a thunk for a method that will also emit a
2407 // cleanup.
Akira Hatanaka85282972018-05-15 21:00:30 +00002408 if (hasAggregateEvaluationKind(Ty) && !CurFuncIsThunk &&
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00002409 Ty->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
Richard Smith2b4fa532019-09-29 05:08:46 +00002410 if (QualType::DestructionKind DtorKind =
2411 D.needsDestruction(getContext())) {
Akira Hatanaka7275da02018-02-28 07:15:55 +00002412 assert((DtorKind == QualType::DK_cxx_destructor ||
2413 DtorKind == QualType::DK_nontrivial_c_struct) &&
2414 "unexpected destructor type");
2415 pushDestroy(DtorKind, DeclPtr, Ty);
Akira Hatanakaccda3d22018-04-27 06:57:00 +00002416 CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2417 EHStack.stable_begin();
Akira Hatanaka7275da02018-02-28 07:15:55 +00002418 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00002419 }
Chris Lattner53621a52007-06-13 20:44:40 +00002420 } else {
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00002421 // Check if the parameter address is controlled by OpenMP runtime.
2422 Address OpenMPLocalAddr =
2423 getLangOpts().OpenMP
2424 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
2425 : Address::invalid();
2426 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2427 DeclPtr = OpenMPLocalAddr;
2428 } else {
2429 // Otherwise, create a temporary to hold the value.
2430 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2431 D.getName() + ".addr");
2432 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002433 DoStore = true;
2434 }
Mike Stump11289f42009-09-09 15:08:12 +00002435
John McCall7f416cc2015-09-08 08:05:57 +00002436 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2437
2438 LValue lv = MakeAddrLValue(DeclPtr, Ty);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002439 if (IsScalar) {
John McCall31168b02011-06-15 23:02:42 +00002440 Qualifiers qs = Ty.getQualifiers();
John McCall31168b02011-06-15 23:02:42 +00002441 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2442 // We honor __attribute__((ns_consumed)) for types with lifetime.
2443 // For __strong, it's handled by just skipping the initial retain;
2444 // otherwise we have to balance out the initial +1 with an extra
2445 // cleanup to do the release at the end of the function.
2446 bool isConsumed = D.hasAttr<NSConsumedAttr>();
2447
Erik Pilkington1e368822019-01-04 18:33:06 +00002448 // If a parameter is pseudo-strong then we can omit the implicit retain.
John McCalld4631322011-06-17 06:42:21 +00002449 if (D.isARCPseudoStrong()) {
Erik Pilkington1e368822019-01-04 18:33:06 +00002450 assert(lt == Qualifiers::OCL_Strong &&
2451 "pseudo-strong variable isn't strong?");
2452 assert(qs.hasConst() && "pseudo-strong variable should be const!");
John McCall31168b02011-06-15 23:02:42 +00002453 lt = Qualifiers::OCL_ExplicitNone;
2454 }
2455
Saleem Abdulrasoolda6784e2017-06-27 18:37:51 +00002456 // Load objects passed indirectly.
2457 if (Arg.isIndirect() && !ArgVal)
2458 ArgVal = Builder.CreateLoad(DeclPtr);
2459
John McCall31168b02011-06-15 23:02:42 +00002460 if (lt == Qualifiers::OCL_Strong) {
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002461 if (!isConsumed) {
2462 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2463 // use objc_storeStrong(&dest, value) for retaining the
2464 // object. But first, store a null into 'dest' because
2465 // objc_storeStrong attempts to release its old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002466 llvm::Value *Null = CGM.EmitNullConstant(D.getType());
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002467 EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002468 EmitARCStoreStrongCall(lv.getAddress(*this), ArgVal, true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002469 DoStore = false;
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002470 }
2471 else
John McCall31168b02011-06-15 23:02:42 +00002472 // Don't use objc_retainBlock for block pointers, because we
2473 // don't want to Block_copy something just because we got it
2474 // as a parameter.
John McCall7f416cc2015-09-08 08:05:57 +00002475 ArgVal = EmitARCRetainNonBlock(ArgVal);
Fariborz Jahanian134cec62013-02-21 00:40:10 +00002476 }
John McCall31168b02011-06-15 23:02:42 +00002477 } else {
2478 // Push the cleanup for a consumed parameter.
John McCallcdda29c2013-03-13 03:10:54 +00002479 if (isConsumed) {
2480 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2481 ? ARCPreciseLifetime : ARCImpreciseLifetime);
John McCall7f416cc2015-09-08 08:05:57 +00002482 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
John McCallcdda29c2013-03-13 03:10:54 +00002483 precise);
2484 }
John McCall31168b02011-06-15 23:02:42 +00002485
2486 if (lt == Qualifiers::OCL_Weak) {
John McCall7f416cc2015-09-08 08:05:57 +00002487 EmitARCInitWeak(DeclPtr, ArgVal);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002488 DoStore = false; // The weak init is a store, no need to do two.
John McCall31168b02011-06-15 23:02:42 +00002489 }
2490 }
2491
2492 // Enter the cleanup scope.
2493 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2494 }
Chris Lattner53621a52007-06-13 20:44:40 +00002495 }
2496
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002497 // Store the initial value into the alloca.
2498 if (DoStore)
John McCall7f416cc2015-09-08 08:05:57 +00002499 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00002500
John McCall7f416cc2015-09-08 08:05:57 +00002501 setAddrOfLocalVar(&D, DeclPtr);
Sanjiv Gupta18de6242008-05-30 10:30:31 +00002502
Vedant Kumar04818d82019-07-29 22:49:55 +00002503 // Emit debug info for param declarations in non-thunk functions.
Alexey Samsonov74a38682012-05-04 07:39:27 +00002504 if (CGDebugInfo *DI = getDebugInfo()) {
Amy Huang53539bb2020-01-13 15:54:54 -08002505 if (CGM.getCodeGenOpts().hasReducedDebugInfo() && !CurFuncIsThunk) {
John McCall7f416cc2015-09-08 08:05:57 +00002506 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
Alexey Samsonov74a38682012-05-04 07:39:27 +00002507 }
2508 }
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002509
2510 if (D.hasAttr<AnnotateAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002511 EmitVarAnnotations(&D, DeclPtr.getPointer());
Vedant Kumar42c17ec2017-03-14 01:56:34 +00002512
2513 // We can only check return value nullability if all arguments to the
2514 // function satisfy their nullability preconditions. This makes it necessary
2515 // to emit null checks for args in the function body itself.
2516 if (requiresReturnValueNullabilityCheck()) {
2517 auto Nullability = Ty->getNullability(getContext());
2518 if (Nullability && *Nullability == NullabilityKind::NonNull) {
2519 SanitizerScope SanScope(this);
2520 RetValNullabilityPrecondition =
2521 Builder.CreateAnd(RetValNullabilityPrecondition,
2522 Builder.CreateIsNotNull(Arg.getAnyValue()));
2523 }
2524 }
Chris Lattner53621a52007-06-13 20:44:40 +00002525}
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002526
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002527void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2528 CodeGenFunction *CGF) {
2529 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2530 return;
2531 getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2532}
Kelvin Li1408f912018-09-26 04:28:39 +00002533
Michael Kruse251e1482019-02-01 20:25:04 +00002534void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
Michael Krused47b9432019-08-05 18:43:21 +00002535 CodeGenFunction *CGF) {
2536 if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
2537 (!LangOpts.EmitAllDecls && !D->isUsed()))
Michael Kruse251e1482019-02-01 20:25:04 +00002538 return;
Michael Krused47b9432019-08-05 18:43:21 +00002539 getOpenMPRuntime().emitUserDefinedMapper(D, CGF);
Michael Kruse251e1482019-02-01 20:25:04 +00002540}
2541
Kelvin Li1408f912018-09-26 04:28:39 +00002542void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
Alexey Bataev2d4f80f2020-02-11 15:15:21 -05002543 getOpenMPRuntime().processRequiresDirective(D);
Kelvin Li1408f912018-09-26 04:28:39 +00002544}