blob: 3751ef116a89dfa4a33c6e51b86138f5d6a6e12f [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlssoncc52f652009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Devang Patel91bbb552010-09-30 19:05:55 +000017#include "CGDebugInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGObjCRuntime.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000020#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000021#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000022#include "llvm/IR/Intrinsics.h"
Anders Carlssonbbe277c2011-04-13 02:35:36 +000023
Anders Carlssoncc52f652009-09-22 22:53:17 +000024using namespace clang;
25using namespace CodeGen;
26
Alexey Samsonovefa956c2016-03-10 00:20:33 +000027static RequiredArgs
28commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
29 llvm::Value *This, llvm::Value *ImplicitParam,
30 QualType ImplicitParamTy, const CallExpr *CE,
Richard Smith762672a2016-09-28 19:09:10 +000031 CallArgList &Args, CallArgList *RtlArgs) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000032 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
33 isa<CXXOperatorCallExpr>(CE));
Anders Carlsson27da15b2010-01-01 20:29:01 +000034 assert(MD->isInstance() &&
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000035 "Trying to emit a member or operator call expr on a static method!");
Reid Kleckner034e7272016-09-07 15:15:51 +000036 ASTContext &C = CGF.getContext();
Anders Carlsson27da15b2010-01-01 20:29:01 +000037
Anders Carlsson27da15b2010-01-01 20:29:01 +000038 // Push the this ptr.
Reid Kleckner034e7272016-09-07 15:15:51 +000039 const CXXRecordDecl *RD =
40 CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
41 Args.add(RValue::get(This),
42 RD ? C.getPointerType(C.getTypeDeclType(RD)) : C.VoidPtrTy);
Anders Carlsson27da15b2010-01-01 20:29:01 +000043
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +000044 // If there is an implicit parameter (e.g. VTT), emit it.
45 if (ImplicitParam) {
46 Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
Anders Carlssone36a6b32010-01-02 01:01:18 +000047 }
John McCalla729c622012-02-17 03:33:10 +000048
49 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
George Burgess IV419996c2016-06-16 23:06:04 +000050 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size(), MD);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000051
John McCalla729c622012-02-17 03:33:10 +000052 // And the rest of the call args.
Richard Smith762672a2016-09-28 19:09:10 +000053 if (RtlArgs) {
54 // Special case: if the caller emitted the arguments right-to-left already
55 // (prior to emitting the *this argument), we're done. This happens for
56 // assignment operators.
57 Args.addFrom(*RtlArgs);
58 } else if (CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000059 // Special case: skip first argument of CXXOperatorCall (it is "this").
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000060 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
David Blaikief05779e2015-07-21 18:37:18 +000061 CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
David Majnemer0c0b6d92014-10-31 20:09:12 +000062 CE->getDirectCallee());
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000063 } else {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000064 assert(
65 FPT->getNumParams() == 0 &&
66 "No CallExpr specified for function with non-zero number of arguments");
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000067 }
David Majnemer0c0b6d92014-10-31 20:09:12 +000068 return required;
69}
Anders Carlsson27da15b2010-01-01 20:29:01 +000070
David Majnemer0c0b6d92014-10-31 20:09:12 +000071RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
John McCallb92ab1a2016-10-26 23:46:34 +000072 const CXXMethodDecl *MD, const CGCallee &Callee,
73 ReturnValueSlot ReturnValue,
David Majnemer0c0b6d92014-10-31 20:09:12 +000074 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
Richard Smith762672a2016-09-28 19:09:10 +000075 const CallExpr *CE, CallArgList *RtlArgs) {
David Majnemer0c0b6d92014-10-31 20:09:12 +000076 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
77 CallArgList Args;
78 RequiredArgs required = commonEmitCXXMemberOrOperatorCall(
Richard Smith762672a2016-09-28 19:09:10 +000079 *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
John McCallb92ab1a2016-10-26 23:46:34 +000080 auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required);
81 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +000082}
83
Alexey Samsonovae81bbb2016-03-10 00:20:37 +000084RValue CodeGenFunction::EmitCXXDestructorCall(
John McCallb92ab1a2016-10-26 23:46:34 +000085 const CXXDestructorDecl *DD, const CGCallee &Callee, llvm::Value *This,
Alexey Samsonovae81bbb2016-03-10 00:20:37 +000086 llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE,
87 StructorType Type) {
David Majnemer0c0b6d92014-10-31 20:09:12 +000088 CallArgList Args;
Alexey Samsonovae81bbb2016-03-10 00:20:37 +000089 commonEmitCXXMemberOrOperatorCall(*this, DD, This, ImplicitParam,
Richard Smith762672a2016-09-28 19:09:10 +000090 ImplicitParamTy, CE, Args, nullptr);
Alexey Samsonovae81bbb2016-03-10 00:20:37 +000091 return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(DD, Type),
John McCallb92ab1a2016-10-26 23:46:34 +000092 Callee, ReturnValueSlot(), Args);
93}
94
95RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
96 const CXXPseudoDestructorExpr *E) {
97 QualType DestroyedType = E->getDestroyedType();
98 if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
99 // Automatic Reference Counting:
100 // If the pseudo-expression names a retainable object with weak or
101 // strong lifetime, the object shall be released.
102 Expr *BaseExpr = E->getBase();
103 Address BaseValue = Address::invalid();
104 Qualifiers BaseQuals;
105
106 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
107 if (E->isArrow()) {
108 BaseValue = EmitPointerWithAlignment(BaseExpr);
109 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
110 BaseQuals = PTy->getPointeeType().getQualifiers();
111 } else {
112 LValue BaseLV = EmitLValue(BaseExpr);
113 BaseValue = BaseLV.getAddress();
114 QualType BaseTy = BaseExpr->getType();
115 BaseQuals = BaseTy.getQualifiers();
116 }
117
118 switch (DestroyedType.getObjCLifetime()) {
119 case Qualifiers::OCL_None:
120 case Qualifiers::OCL_ExplicitNone:
121 case Qualifiers::OCL_Autoreleasing:
122 break;
123
124 case Qualifiers::OCL_Strong:
125 EmitARCRelease(Builder.CreateLoad(BaseValue,
126 DestroyedType.isVolatileQualified()),
127 ARCPreciseLifetime);
128 break;
129
130 case Qualifiers::OCL_Weak:
131 EmitARCDestroyWeak(BaseValue);
132 break;
133 }
134 } else {
135 // C++ [expr.pseudo]p1:
136 // The result shall only be used as the operand for the function call
137 // operator (), and the result of such a call has type void. The only
138 // effect is the evaluation of the postfix-expression before the dot or
139 // arrow.
140 EmitIgnoredExpr(E->getBase());
141 }
142
143 return RValue::get(nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000144}
145
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000146static CXXRecordDecl *getCXXRecord(const Expr *E) {
147 QualType T = E->getType();
148 if (const PointerType *PTy = T->getAs<PointerType>())
149 T = PTy->getPointeeType();
150 const RecordType *Ty = T->castAs<RecordType>();
151 return cast<CXXRecordDecl>(Ty->getDecl());
152}
153
Francois Pichet64225792011-01-18 05:04:39 +0000154// Note: This function also emit constructor calls to support a MSVC
155// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000156RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
157 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +0000158 const Expr *callee = CE->getCallee()->IgnoreParens();
159
160 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000161 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +0000162
163 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000164 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
165
166 if (MD->isStatic()) {
167 // The method is static, emit it as we would a regular call.
John McCallb92ab1a2016-10-26 23:46:34 +0000168 CGCallee callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD), MD);
169 return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000170 ReturnValue);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000171 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000172
Nico Weberaad4af62014-12-03 01:21:41 +0000173 bool HasQualifier = ME->hasQualifier();
174 NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
175 bool IsArrow = ME->isArrow();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000176 const Expr *Base = ME->getBase();
Nico Weberaad4af62014-12-03 01:21:41 +0000177
178 return EmitCXXMemberOrOperatorMemberCallExpr(
179 CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
180}
181
182RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
183 const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
184 bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
185 const Expr *Base) {
186 assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
187
188 // Compute the object pointer.
189 bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000190
Craig Topper8a13c412014-05-21 05:09:00 +0000191 const CXXMethodDecl *DevirtualizedMethod = nullptr;
Benjamin Kramer7463ed72013-08-25 22:46:27 +0000192 if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000193 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
194 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
195 assert(DevirtualizedMethod);
196 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
197 const Expr *Inner = Base->ignoreParenBaseCasts();
Alexey Bataev5bd68792014-09-29 10:32:21 +0000198 if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
199 MD->getReturnType().getCanonicalType())
200 // If the return types are not the same, this might be a case where more
201 // code needs to run to compensate for it. For example, the derived
202 // method might return a type that inherits form from the return
203 // type of MD and has a prefix.
204 // For now we just avoid devirtualizing these covariant cases.
205 DevirtualizedMethod = nullptr;
206 else if (getCXXRecord(Inner) == DevirtualizedClass)
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000207 // If the class of the Inner expression is where the dynamic method
208 // is defined, build the this pointer from it.
209 Base = Inner;
210 else if (getCXXRecord(Base) != DevirtualizedClass) {
211 // If the method is defined in a class that is not the best dynamic
212 // one or the one of the full expression, we would have to build
213 // a derived-to-base cast to compute the correct this pointer, but
214 // we don't have support for that yet, so do a virtual call.
Craig Topper8a13c412014-05-21 05:09:00 +0000215 DevirtualizedMethod = nullptr;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000216 }
217 }
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000218
Richard Smith762672a2016-09-28 19:09:10 +0000219 // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
220 // operator before the LHS.
221 CallArgList RtlArgStorage;
222 CallArgList *RtlArgs = nullptr;
223 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
224 if (OCE->isAssignmentOp()) {
225 RtlArgs = &RtlArgStorage;
226 EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
227 drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
Richard Smitha560ccf2016-09-29 21:30:12 +0000228 /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
Richard Smith762672a2016-09-28 19:09:10 +0000229 }
230 }
231
John McCall7f416cc2015-09-08 08:05:57 +0000232 Address This = Address::invalid();
Nico Weberaad4af62014-12-03 01:21:41 +0000233 if (IsArrow)
John McCall7f416cc2015-09-08 08:05:57 +0000234 This = EmitPointerWithAlignment(Base);
John McCalle26a8722010-12-04 08:14:53 +0000235 else
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000236 This = EmitLValue(Base).getAddress();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000237
Anders Carlsson27da15b2010-01-01 20:29:01 +0000238
Richard Smith419bd092015-04-29 19:26:57 +0000239 if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
Craig Topper8a13c412014-05-21 05:09:00 +0000240 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
Francois Pichet64225792011-01-18 05:04:39 +0000241 if (isa<CXXConstructorDecl>(MD) &&
242 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
Craig Topper8a13c412014-05-21 05:09:00 +0000243 return RValue::get(nullptr);
John McCall0d635f52010-09-03 01:26:39 +0000244
Nico Weberaad4af62014-12-03 01:21:41 +0000245 if (!MD->getParent()->mayInsertExtraPadding()) {
246 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
247 // We don't like to generate the trivial copy/move assignment operator
248 // when it isn't necessary; just produce the proper effect here.
Richard Smith762672a2016-09-28 19:09:10 +0000249 LValue RHS = isa<CXXOperatorCallExpr>(CE)
250 ? MakeNaturalAlignAddrLValue(
251 (*RtlArgs)[0].RV.getScalarVal(),
252 (*(CE->arg_begin() + 1))->getType())
253 : EmitLValue(*CE->arg_begin());
254 EmitAggregateAssign(This, RHS.getAddress(), CE->getType());
John McCall7f416cc2015-09-08 08:05:57 +0000255 return RValue::get(This.getPointer());
Nico Weberaad4af62014-12-03 01:21:41 +0000256 }
Alexey Samsonov525bf652014-08-25 21:58:56 +0000257
Nico Weberaad4af62014-12-03 01:21:41 +0000258 if (isa<CXXConstructorDecl>(MD) &&
259 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
260 // Trivial move and copy ctor are the same.
261 assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
John McCall7f416cc2015-09-08 08:05:57 +0000262 Address RHS = EmitLValue(*CE->arg_begin()).getAddress();
Benjamin Kramerf48ee442015-07-18 14:35:53 +0000263 EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType());
John McCall7f416cc2015-09-08 08:05:57 +0000264 return RValue::get(This.getPointer());
Nico Weberaad4af62014-12-03 01:21:41 +0000265 }
266 llvm_unreachable("unknown trivial member function");
Francois Pichet64225792011-01-18 05:04:39 +0000267 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000268 }
269
John McCall0d635f52010-09-03 01:26:39 +0000270 // Compute the function type we're calling.
Nico Weber3abfe952014-12-02 20:41:18 +0000271 const CXXMethodDecl *CalleeDecl =
272 DevirtualizedMethod ? DevirtualizedMethod : MD;
Craig Topper8a13c412014-05-21 05:09:00 +0000273 const CGFunctionInfo *FInfo = nullptr;
Nico Weber3abfe952014-12-02 20:41:18 +0000274 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000275 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
276 Dtor, StructorType::Complete);
Nico Weber3abfe952014-12-02 20:41:18 +0000277 else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000278 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
279 Ctor, StructorType::Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000280 else
Eli Friedmanade60972012-10-25 00:12:49 +0000281 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCall0d635f52010-09-03 01:26:39 +0000282
Reid Klecknere7de47e2013-07-22 13:51:44 +0000283 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000284
Ivan Krasind98f5d72016-11-17 00:39:48 +0000285 // C++11 [class.mfct.non-static]p2:
286 // If a non-static member function of a class X is called for an object that
287 // is not of type X, or of a type derived from X, the behavior is undefined.
288 SourceLocation CallLoc;
289 ASTContext &C = getContext();
290 if (CE)
291 CallLoc = CE->getExprLoc();
292
Vedant Kumar34b1fd62017-02-17 23:22:59 +0000293 SanitizerSet SkippedChecks;
294 if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE))
295 if (CanElideObjectPointerNullCheck(CMCE->getImplicitObjectArgument()))
296 SkippedChecks.set(SanitizerKind::Null, true);
297 EmitTypeCheck(
298 isa<CXXConstructorDecl>(CalleeDecl) ? CodeGenFunction::TCK_ConstructorCall
299 : CodeGenFunction::TCK_MemberCall,
300 CallLoc, This.getPointer(), C.getRecordType(CalleeDecl->getParent()),
301 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
Ivan Krasind98f5d72016-11-17 00:39:48 +0000302
Vedant Kumar018f2662016-10-19 20:21:16 +0000303 // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
304 // 'CalleeDecl' instead.
305
Anders Carlsson27da15b2010-01-01 20:29:01 +0000306 // C++ [class.virtual]p12:
307 // Explicit qualification with the scope operator (5.1) suppresses the
308 // virtual call mechanism.
309 //
310 // We also don't emit a virtual call if the base expression has a record type
311 // because then we know what the type is.
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000312 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
John McCallb92ab1a2016-10-26 23:46:34 +0000313
John McCall0d635f52010-09-03 01:26:39 +0000314 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000315 assert(CE->arg_begin() == CE->arg_end() &&
316 "Destructor shouldn't have explicit parameters");
317 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
John McCall0d635f52010-09-03 01:26:39 +0000318 if (UseVirtualCall) {
Nico Weberaad4af62014-12-03 01:21:41 +0000319 CGM.getCXXABI().EmitVirtualDestructorCall(
320 *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
Anders Carlsson27da15b2010-01-01 20:29:01 +0000321 } else {
John McCallb92ab1a2016-10-26 23:46:34 +0000322 CGCallee Callee;
Nico Weberaad4af62014-12-03 01:21:41 +0000323 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
324 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000325 else if (!DevirtualizedMethod)
John McCallb92ab1a2016-10-26 23:46:34 +0000326 Callee = CGCallee::forDirect(
327 CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty),
328 Dtor);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000329 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000330 const CXXDestructorDecl *DDtor =
331 cast<CXXDestructorDecl>(DevirtualizedMethod);
John McCallb92ab1a2016-10-26 23:46:34 +0000332 Callee = CGCallee::forDirect(
333 CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty),
334 DDtor);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000335 }
Vedant Kumar018f2662016-10-19 20:21:16 +0000336 EmitCXXMemberOrOperatorCall(
337 CalleeDecl, Callee, ReturnValue, This.getPointer(),
338 /*ImplicitParam=*/nullptr, QualType(), CE, nullptr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000339 }
Craig Topper8a13c412014-05-21 05:09:00 +0000340 return RValue::get(nullptr);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000341 }
342
John McCallb92ab1a2016-10-26 23:46:34 +0000343 CGCallee Callee;
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000344 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
John McCallb92ab1a2016-10-26 23:46:34 +0000345 Callee = CGCallee::forDirect(
346 CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty),
347 Ctor);
John McCall0d635f52010-09-03 01:26:39 +0000348 } else if (UseVirtualCall) {
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000349 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty,
350 CE->getLocStart());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000351 } else {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +0000352 if (SanOpts.has(SanitizerKind::CFINVCall) &&
353 MD->getParent()->isDynamicClass()) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000354 llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy, MD->getParent());
Peter Collingbournefb532b92016-02-24 20:46:36 +0000355 EmitVTablePtrCheckForCall(MD->getParent(), VTable, CFITCK_NVCall,
356 CE->getLocStart());
Peter Collingbourne1a7488a2015-04-02 00:23:30 +0000357 }
358
Nico Weberaad4af62014-12-03 01:21:41 +0000359 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
360 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000361 else if (!DevirtualizedMethod)
John McCallb92ab1a2016-10-26 23:46:34 +0000362 Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), MD);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000363 else {
John McCallb92ab1a2016-10-26 23:46:34 +0000364 Callee = CGCallee::forDirect(
365 CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
366 DevirtualizedMethod);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000367 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000368 }
369
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000370 if (MD->isVirtual()) {
371 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
Reid Kleckner4b60f302016-05-03 18:44:29 +0000372 *this, CalleeDecl, This, UseVirtualCall);
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000373 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000374
Vedant Kumar018f2662016-10-19 20:21:16 +0000375 return EmitCXXMemberOrOperatorCall(
376 CalleeDecl, Callee, ReturnValue, This.getPointer(),
377 /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000378}
379
380RValue
381CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
382 ReturnValueSlot ReturnValue) {
383 const BinaryOperator *BO =
384 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
385 const Expr *BaseExpr = BO->getLHS();
386 const Expr *MemFnExpr = BO->getRHS();
387
388 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000389 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000390
Anders Carlsson27da15b2010-01-01 20:29:01 +0000391 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000392 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000393 const CXXRecordDecl *RD =
394 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
395
Anders Carlsson27da15b2010-01-01 20:29:01 +0000396 // Emit the 'this' pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000397 Address This = Address::invalid();
John McCalle3027922010-08-25 11:45:40 +0000398 if (BO->getOpcode() == BO_PtrMemI)
John McCall7f416cc2015-09-08 08:05:57 +0000399 This = EmitPointerWithAlignment(BaseExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000400 else
401 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000402
John McCall7f416cc2015-09-08 08:05:57 +0000403 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
Richard Smithe30752c2012-10-09 19:52:38 +0000404 QualType(MPT->getClass(), 0));
Richard Smith69d0d262012-08-24 00:54:33 +0000405
Richard Smithbde62d72016-09-26 23:56:57 +0000406 // Get the member function pointer.
407 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
408
John McCall475999d2010-08-22 00:05:51 +0000409 // Ask the ABI to load the callee. Note that This is modified.
John McCall7f416cc2015-09-08 08:05:57 +0000410 llvm::Value *ThisPtrForCall = nullptr;
John McCallb92ab1a2016-10-26 23:46:34 +0000411 CGCallee Callee =
John McCall7f416cc2015-09-08 08:05:57 +0000412 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
413 ThisPtrForCall, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000414
Anders Carlsson27da15b2010-01-01 20:29:01 +0000415 CallArgList Args;
416
417 QualType ThisType =
418 getContext().getPointerType(getContext().getTagDeclType(RD));
419
420 // Push the this ptr.
John McCall7f416cc2015-09-08 08:05:57 +0000421 Args.add(RValue::get(ThisPtrForCall), ThisType);
John McCall8dda7b22012-07-07 06:41:13 +0000422
George Burgess IV419996c2016-06-16 23:06:04 +0000423 RequiredArgs required =
424 RequiredArgs::forPrototypePlus(FPT, 1, /*FD=*/nullptr);
425
Anders Carlsson27da15b2010-01-01 20:29:01 +0000426 // And the rest of the call args
George Burgess IV419996c2016-06-16 23:06:04 +0000427 EmitCallArgs(Args, FPT, E->arguments());
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000428 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
429 Callee, ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000430}
431
432RValue
433CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
434 const CXXMethodDecl *MD,
435 ReturnValueSlot ReturnValue) {
436 assert(MD->isInstance() &&
437 "Trying to emit a member call expr on a static method!");
Nico Weberaad4af62014-12-03 01:21:41 +0000438 return EmitCXXMemberOrOperatorMemberCallExpr(
439 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
440 /*IsArrow=*/false, E->getArg(0));
Anders Carlsson27da15b2010-01-01 20:29:01 +0000441}
442
Peter Collingbournefe883422011-10-06 18:29:37 +0000443RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
444 ReturnValueSlot ReturnValue) {
445 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
446}
447
Eli Friedmanfde961d2011-10-14 02:27:24 +0000448static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000449 Address DestPtr,
Eli Friedmanfde961d2011-10-14 02:27:24 +0000450 const CXXRecordDecl *Base) {
451 if (Base->isEmpty())
452 return;
453
John McCall7f416cc2015-09-08 08:05:57 +0000454 DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
Eli Friedmanfde961d2011-10-14 02:27:24 +0000455
456 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
David Majnemer8671c6e2015-11-02 09:01:44 +0000457 CharUnits NVSize = Layout.getNonVirtualSize();
458
459 // We cannot simply zero-initialize the entire base sub-object if vbptrs are
460 // present, they are initialized by the most derived class before calling the
461 // constructor.
462 SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
463 Stores.emplace_back(CharUnits::Zero(), NVSize);
464
465 // Each store is split by the existence of a vbptr.
466 CharUnits VBPtrWidth = CGF.getPointerSize();
467 std::vector<CharUnits> VBPtrOffsets =
468 CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
469 for (CharUnits VBPtrOffset : VBPtrOffsets) {
David Majnemer7f980d82016-05-12 03:51:52 +0000470 // Stop before we hit any virtual base pointers located in virtual bases.
471 if (VBPtrOffset >= NVSize)
472 break;
David Majnemer8671c6e2015-11-02 09:01:44 +0000473 std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
474 CharUnits LastStoreOffset = LastStore.first;
475 CharUnits LastStoreSize = LastStore.second;
476
477 CharUnits SplitBeforeOffset = LastStoreOffset;
478 CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
479 assert(!SplitBeforeSize.isNegative() && "negative store size!");
480 if (!SplitBeforeSize.isZero())
481 Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
482
483 CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
484 CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
485 assert(!SplitAfterSize.isNegative() && "negative store size!");
486 if (!SplitAfterSize.isZero())
487 Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
488 }
Eli Friedmanfde961d2011-10-14 02:27:24 +0000489
490 // If the type contains a pointer to data member we can't memset it to zero.
491 // Instead, create a null constant and copy it to the destination.
492 // TODO: there are other patterns besides zero that we can usefully memset,
493 // like -1, which happens to be the pattern used by member-pointers.
494 // TODO: isZeroInitializable can be over-conservative in the case where a
495 // virtual base contains a member pointer.
David Majnemer8671c6e2015-11-02 09:01:44 +0000496 llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
497 if (!NullConstantForBase->isNullValue()) {
498 llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
499 CGF.CGM.getModule(), NullConstantForBase->getType(),
500 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
501 NullConstantForBase, Twine());
John McCall7f416cc2015-09-08 08:05:57 +0000502
503 CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
504 DestPtr.getAlignment());
Eli Friedmanfde961d2011-10-14 02:27:24 +0000505 NullVariable->setAlignment(Align.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +0000506
507 Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
Eli Friedmanfde961d2011-10-14 02:27:24 +0000508
509 // Get and call the appropriate llvm.memcpy overload.
David Majnemer8671c6e2015-11-02 09:01:44 +0000510 for (std::pair<CharUnits, CharUnits> Store : Stores) {
511 CharUnits StoreOffset = Store.first;
512 CharUnits StoreSize = Store.second;
513 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
514 CGF.Builder.CreateMemCpy(
515 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
516 CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
517 StoreSizeVal);
518 }
519
Eli Friedmanfde961d2011-10-14 02:27:24 +0000520 // Otherwise, just memset the whole thing to zero. This is legal
521 // because in LLVM, all default initializers (other than the ones we just
522 // handled above) are guaranteed to have a bit pattern of all zeros.
David Majnemer8671c6e2015-11-02 09:01:44 +0000523 } else {
524 for (std::pair<CharUnits, CharUnits> Store : Stores) {
525 CharUnits StoreOffset = Store.first;
526 CharUnits StoreSize = Store.second;
527 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
528 CGF.Builder.CreateMemSet(
529 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
530 CGF.Builder.getInt8(0), StoreSizeVal);
531 }
532 }
Eli Friedmanfde961d2011-10-14 02:27:24 +0000533}
534
Anders Carlsson27da15b2010-01-01 20:29:01 +0000535void
John McCall7a626f62010-09-15 10:14:12 +0000536CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
537 AggValueSlot Dest) {
538 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000539 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000540
541 // If we require zero initialization before (or instead of) calling the
542 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000543 // constructor, emit the zero initialization now, unless destination is
544 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000545 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
546 switch (E->getConstructionKind()) {
547 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000548 case CXXConstructExpr::CK_Complete:
John McCall7f416cc2015-09-08 08:05:57 +0000549 EmitNullInitialization(Dest.getAddress(), E->getType());
Eli Friedmanfde961d2011-10-14 02:27:24 +0000550 break;
551 case CXXConstructExpr::CK_VirtualBase:
552 case CXXConstructExpr::CK_NonVirtualBase:
John McCall7f416cc2015-09-08 08:05:57 +0000553 EmitNullBaseClassInitialization(*this, Dest.getAddress(),
554 CD->getParent());
Eli Friedmanfde961d2011-10-14 02:27:24 +0000555 break;
556 }
557 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000558
559 // If this is a call to a trivial default constructor, do nothing.
560 if (CD->isTrivial() && CD->isDefaultConstructor())
561 return;
562
John McCall8ea46b62010-09-18 00:58:34 +0000563 // Elide the constructor if we're constructing from a temporary.
564 // The temporary check is required because Sema sets this on NRVO
565 // returns.
Richard Smith9c6890a2012-11-01 22:30:59 +0000566 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000567 assert(getContext().hasSameUnqualifiedType(E->getType(),
568 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000569 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
570 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000571 return;
572 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000573 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000574
Alexey Bataeve7545b32016-04-29 09:39:50 +0000575 if (const ArrayType *arrayType
576 = getContext().getAsArrayType(E->getType())) {
John McCall7f416cc2015-09-08 08:05:57 +0000577 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E);
John McCallf677a8e2011-07-13 06:10:41 +0000578 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000579 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000580 bool ForVirtualBase = false;
Douglas Gregor61535002013-01-31 05:50:40 +0000581 bool Delegating = false;
582
Alexis Hunt271c3682011-05-03 20:19:28 +0000583 switch (E->getConstructionKind()) {
584 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000585 // We should be emitting a constructor; GlobalDecl will assert this
586 Type = CurGD.getCtorType();
Douglas Gregor61535002013-01-31 05:50:40 +0000587 Delegating = true;
Alexis Hunt271c3682011-05-03 20:19:28 +0000588 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000589
Alexis Hunt271c3682011-05-03 20:19:28 +0000590 case CXXConstructExpr::CK_Complete:
591 Type = Ctor_Complete;
592 break;
593
594 case CXXConstructExpr::CK_VirtualBase:
595 ForVirtualBase = true;
596 // fall-through
597
598 case CXXConstructExpr::CK_NonVirtualBase:
599 Type = Ctor_Base;
600 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000601
Anders Carlsson27da15b2010-01-01 20:29:01 +0000602 // Call the constructor.
John McCall7f416cc2015-09-08 08:05:57 +0000603 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
604 Dest.getAddress(), E);
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000605 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000606}
607
John McCall7f416cc2015-09-08 08:05:57 +0000608void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
609 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000610 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000611 Exp = E->getSubExpr();
612 assert(isa<CXXConstructExpr>(Exp) &&
613 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
614 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
615 const CXXConstructorDecl *CD = E->getConstructor();
616 RunCleanupsScope Scope(*this);
617
618 // If we require zero initialization before (or instead of) calling the
619 // constructor, as can be the case with a non-user-provided default
620 // constructor, emit the zero initialization now.
621 // FIXME. Do I still need this for a copy ctor synthesis?
622 if (E->requiresZeroInitialization())
623 EmitNullInitialization(Dest, E->getType());
624
Chandler Carruth99da11c2010-11-15 13:54:43 +0000625 assert(!getContext().getAsConstantArrayType(E->getType())
626 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Alexey Samsonov525bf652014-08-25 21:58:56 +0000627 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000628}
629
John McCall8ed55a52010-09-02 09:58:18 +0000630static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
631 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000632 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000633 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000634
John McCall7ec4b432011-05-16 01:05:12 +0000635 // No cookie is required if the operator new[] being used is the
636 // reserved placement operator new[].
637 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000638 return CharUnits::Zero();
639
John McCall284c48f2011-01-27 09:37:56 +0000640 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000641}
642
John McCall036f2f62011-05-15 07:14:44 +0000643static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
644 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000645 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000646 llvm::Value *&numElements,
647 llvm::Value *&sizeWithoutCookie) {
648 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000649
John McCall036f2f62011-05-15 07:14:44 +0000650 if (!e->isArray()) {
651 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
652 sizeWithoutCookie
653 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
654 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000655 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000656
John McCall036f2f62011-05-15 07:14:44 +0000657 // The width of size_t.
658 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
659
John McCall8ed55a52010-09-02 09:58:18 +0000660 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000661 llvm::APInt cookieSize(sizeWidth,
662 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000663
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000664 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000665 // We multiply the size of all dimensions for NumElements.
666 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
Nick Lewycky07527622017-02-13 23:49:55 +0000667 numElements = CGF.CGM.EmitConstantExpr(e->getArraySize(),
668 CGF.getContext().getSizeType(), &CGF);
669 if (!numElements)
670 numElements = CGF.EmitScalarExpr(e->getArraySize());
John McCall036f2f62011-05-15 07:14:44 +0000671 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000672
John McCall036f2f62011-05-15 07:14:44 +0000673 // The number of elements can be have an arbitrary integer type;
674 // essentially, we need to multiply it by a constant factor, add a
675 // cookie size, and verify that the result is representable as a
676 // size_t. That's just a gloss, though, and it's wrong in one
677 // important way: if the count is negative, it's an error even if
678 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000679 bool isSigned
680 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000681 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000682 = cast<llvm::IntegerType>(numElements->getType());
683 unsigned numElementsWidth = numElementsType->getBitWidth();
684
685 // Compute the constant factor.
686 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000687 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000688 = CGF.getContext().getAsConstantArrayType(type)) {
689 type = CAT->getElementType();
690 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000691 }
692
John McCall036f2f62011-05-15 07:14:44 +0000693 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
694 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
695 typeSizeMultiplier *= arraySizeMultiplier;
696
697 // This will be a size_t.
698 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000699
Chris Lattner32ac5832010-07-20 21:55:52 +0000700 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
701 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000702 if (llvm::ConstantInt *numElementsC =
703 dyn_cast<llvm::ConstantInt>(numElements)) {
704 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000705
John McCall036f2f62011-05-15 07:14:44 +0000706 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000707
John McCall036f2f62011-05-15 07:14:44 +0000708 // If 'count' was a negative number, it's an overflow.
709 if (isSigned && count.isNegative())
710 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000711
John McCall036f2f62011-05-15 07:14:44 +0000712 // We want to do all this arithmetic in size_t. If numElements is
713 // wider than that, check whether it's already too big, and if so,
714 // overflow.
715 else if (numElementsWidth > sizeWidth &&
716 numElementsWidth - sizeWidth > count.countLeadingZeros())
717 hasAnyOverflow = true;
718
719 // Okay, compute a count at the right width.
720 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
721
Sebastian Redlf862eb62012-02-22 17:37:52 +0000722 // If there is a brace-initializer, we cannot allocate fewer elements than
723 // there are initializers. If we do, that's treated like an overflow.
724 if (adjustedCount.ult(minElements))
725 hasAnyOverflow = true;
726
John McCall036f2f62011-05-15 07:14:44 +0000727 // Scale numElements by that. This might overflow, but we don't
728 // care because it only overflows if allocationSize does, too, and
729 // if that overflows then we shouldn't use this.
730 numElements = llvm::ConstantInt::get(CGF.SizeTy,
731 adjustedCount * arraySizeMultiplier);
732
733 // Compute the size before cookie, and track whether it overflowed.
734 bool overflow;
735 llvm::APInt allocationSize
736 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
737 hasAnyOverflow |= overflow;
738
739 // Add in the cookie, and check whether it's overflowed.
740 if (cookieSize != 0) {
741 // Save the current size without a cookie. This shouldn't be
742 // used if there was overflow.
743 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
744
745 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
746 hasAnyOverflow |= overflow;
747 }
748
749 // On overflow, produce a -1 so operator new will fail.
Aaron Ballman455f42c2014-08-28 17:24:14 +0000750 if (hasAnyOverflow) {
751 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
752 } else {
John McCall036f2f62011-05-15 07:14:44 +0000753 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
Aaron Ballman455f42c2014-08-28 17:24:14 +0000754 }
John McCall036f2f62011-05-15 07:14:44 +0000755
756 // Otherwise, we might need to use the overflow intrinsics.
757 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000758 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000759 // 1) if isSigned, we need to check whether numElements is negative;
760 // 2) if numElementsWidth > sizeWidth, we need to check whether
761 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000762 // 3) if minElements > 0, we need to check whether numElements is smaller
763 // than that.
764 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000765 // sizeWithoutCookie := numElements * typeSizeMultiplier
766 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000767 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000768 // size := sizeWithoutCookie + cookieSize
769 // and check whether it overflows.
770
Craig Topper8a13c412014-05-21 05:09:00 +0000771 llvm::Value *hasOverflow = nullptr;
John McCall036f2f62011-05-15 07:14:44 +0000772
773 // If numElementsWidth > sizeWidth, then one way or another, we're
774 // going to have to do a comparison for (2), and this happens to
775 // take care of (1), too.
776 if (numElementsWidth > sizeWidth) {
777 llvm::APInt threshold(numElementsWidth, 1);
778 threshold <<= sizeWidth;
779
780 llvm::Value *thresholdV
781 = llvm::ConstantInt::get(numElementsType, threshold);
782
783 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
784 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
785
786 // Otherwise, if we're signed, we want to sext up to size_t.
787 } else if (isSigned) {
788 if (numElementsWidth < sizeWidth)
789 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
790
791 // If there's a non-1 type size multiplier, then we can do the
792 // signedness check at the same time as we do the multiply
793 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000794 // unsigned overflow. Otherwise, we have to do it here. But at least
795 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000796 if (typeSizeMultiplier == 1)
797 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000798 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000799
800 // Otherwise, zext up to size_t if necessary.
801 } else if (numElementsWidth < sizeWidth) {
802 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
803 }
804
805 assert(numElements->getType() == CGF.SizeTy);
806
Sebastian Redlf862eb62012-02-22 17:37:52 +0000807 if (minElements) {
808 // Don't allow allocation of fewer elements than we have initializers.
809 if (!hasOverflow) {
810 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
811 llvm::ConstantInt::get(CGF.SizeTy, minElements));
812 } else if (numElementsWidth > sizeWidth) {
813 // The other existing overflow subsumes this check.
814 // We do an unsigned comparison, since any signed value < -1 is
815 // taken care of either above or below.
816 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
817 CGF.Builder.CreateICmpULT(numElements,
818 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
819 }
820 }
821
John McCall036f2f62011-05-15 07:14:44 +0000822 size = numElements;
823
824 // Multiply by the type size if necessary. This multiplier
825 // includes all the factors for nested arrays.
826 //
827 // This step also causes numElements to be scaled up by the
828 // nested-array factor if necessary. Overflow on this computation
829 // can be ignored because the result shouldn't be used if
830 // allocation fails.
831 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000832 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000833 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000834
835 llvm::Value *tsmV =
836 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
837 llvm::Value *result =
David Blaikie43f9bb72015-05-18 22:14:03 +0000838 CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
John McCall036f2f62011-05-15 07:14:44 +0000839
840 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
841 if (hasOverflow)
842 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
843 else
844 hasOverflow = overflowed;
845
846 size = CGF.Builder.CreateExtractValue(result, 0);
847
848 // Also scale up numElements by the array size multiplier.
849 if (arraySizeMultiplier != 1) {
850 // If the base element type size is 1, then we can re-use the
851 // multiply we just did.
852 if (typeSize.isOne()) {
853 assert(arraySizeMultiplier == typeSizeMultiplier);
854 numElements = size;
855
856 // Otherwise we need a separate multiply.
857 } else {
858 llvm::Value *asmV =
859 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
860 numElements = CGF.Builder.CreateMul(numElements, asmV);
861 }
862 }
863 } else {
864 // numElements doesn't need to be scaled.
865 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000866 }
867
John McCall036f2f62011-05-15 07:14:44 +0000868 // Add in the cookie size if necessary.
869 if (cookieSize != 0) {
870 sizeWithoutCookie = size;
871
John McCall036f2f62011-05-15 07:14:44 +0000872 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000873 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000874
875 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
876 llvm::Value *result =
David Blaikie43f9bb72015-05-18 22:14:03 +0000877 CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
John McCall036f2f62011-05-15 07:14:44 +0000878
879 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
880 if (hasOverflow)
881 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
882 else
883 hasOverflow = overflowed;
884
885 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000886 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000887
John McCall036f2f62011-05-15 07:14:44 +0000888 // If we had any possibility of dynamic overflow, make a select to
889 // overwrite 'size' with an all-ones value, which should cause
890 // operator new to throw.
891 if (hasOverflow)
Aaron Ballman455f42c2014-08-28 17:24:14 +0000892 size = CGF.Builder.CreateSelect(hasOverflow,
893 llvm::Constant::getAllOnesValue(CGF.SizeTy),
894 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000895 }
John McCall8ed55a52010-09-02 09:58:18 +0000896
John McCall036f2f62011-05-15 07:14:44 +0000897 if (cookieSize == 0)
898 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000899 else
John McCall036f2f62011-05-15 07:14:44 +0000900 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000901
John McCall036f2f62011-05-15 07:14:44 +0000902 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000903}
904
Sebastian Redlf862eb62012-02-22 17:37:52 +0000905static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
John McCall7f416cc2015-09-08 08:05:57 +0000906 QualType AllocType, Address NewPtr) {
Richard Smith1c96bc52013-12-11 01:40:16 +0000907 // FIXME: Refactor with EmitExprAsInit.
John McCall47fb9502013-03-07 21:37:08 +0000908 switch (CGF.getEvaluationKind(AllocType)) {
909 case TEK_Scalar:
David Blaikiea2c11242014-12-10 19:04:09 +0000910 CGF.EmitScalarInit(Init, nullptr,
John McCall7f416cc2015-09-08 08:05:57 +0000911 CGF.MakeAddrLValue(NewPtr, AllocType), false);
John McCall47fb9502013-03-07 21:37:08 +0000912 return;
913 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000914 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
John McCall47fb9502013-03-07 21:37:08 +0000915 /*isInit*/ true);
916 return;
917 case TEK_Aggregate: {
John McCall7a626f62010-09-15 10:14:12 +0000918 AggValueSlot Slot
John McCall7f416cc2015-09-08 08:05:57 +0000919 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000920 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000921 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000922 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000923 CGF.EmitAggExpr(Init, Slot);
John McCall47fb9502013-03-07 21:37:08 +0000924 return;
John McCall7a626f62010-09-15 10:14:12 +0000925 }
John McCall47fb9502013-03-07 21:37:08 +0000926 }
927 llvm_unreachable("bad evaluation kind");
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000928}
929
David Blaikiefb901c7a2015-04-04 15:12:29 +0000930void CodeGenFunction::EmitNewArrayInitializer(
931 const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
John McCall7f416cc2015-09-08 08:05:57 +0000932 Address BeginPtr, llvm::Value *NumElements,
David Blaikiefb901c7a2015-04-04 15:12:29 +0000933 llvm::Value *AllocSizeWithoutCookie) {
Richard Smith06a67e22014-06-03 06:58:52 +0000934 // If we have a type with trivial initialization and no initializer,
935 // there's nothing to do.
Sebastian Redl6047f072012-02-16 12:22:20 +0000936 if (!E->hasInitializer())
Richard Smith06a67e22014-06-03 06:58:52 +0000937 return;
John McCall99210dc2011-09-15 06:49:18 +0000938
John McCall7f416cc2015-09-08 08:05:57 +0000939 Address CurPtr = BeginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000940
Richard Smith06a67e22014-06-03 06:58:52 +0000941 unsigned InitListElements = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000942
943 const Expr *Init = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +0000944 Address EndOfInit = Address::invalid();
Richard Smith06a67e22014-06-03 06:58:52 +0000945 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
946 EHScopeStack::stable_iterator Cleanup;
947 llvm::Instruction *CleanupDominator = nullptr;
Richard Smith1c96bc52013-12-11 01:40:16 +0000948
John McCall7f416cc2015-09-08 08:05:57 +0000949 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
950 CharUnits ElementAlign =
951 BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
952
Richard Smith0511d232016-10-05 22:41:02 +0000953 // Attempt to perform zero-initialization using memset.
954 auto TryMemsetInitialization = [&]() -> bool {
955 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
956 // we can initialize with a memset to -1.
957 if (!CGM.getTypes().isZeroInitializable(ElementType))
958 return false;
959
960 // Optimization: since zero initialization will just set the memory
961 // to all zeroes, generate a single memset to do it in one shot.
962
963 // Subtract out the size of any elements we've already initialized.
964 auto *RemainingSize = AllocSizeWithoutCookie;
965 if (InitListElements) {
966 // We know this can't overflow; we check this when doing the allocation.
967 auto *InitializedSize = llvm::ConstantInt::get(
968 RemainingSize->getType(),
969 getContext().getTypeSizeInChars(ElementType).getQuantity() *
970 InitListElements);
971 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
972 }
973
974 // Create the memset.
975 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
976 return true;
977 };
978
Sebastian Redlf862eb62012-02-22 17:37:52 +0000979 // If the initializer is an initializer list, first do the explicit elements.
980 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith0511d232016-10-05 22:41:02 +0000981 // Initializing from a (braced) string literal is a special case; the init
982 // list element does not initialize a (single) array element.
983 if (ILE->isStringLiteralInit()) {
984 // Initialize the initial portion of length equal to that of the string
985 // literal. The allocation must be for at least this much; we emitted a
986 // check for that earlier.
987 AggValueSlot Slot =
988 AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
989 AggValueSlot::IsDestructed,
990 AggValueSlot::DoesNotNeedGCBarriers,
991 AggValueSlot::IsNotAliased);
992 EmitAggExpr(ILE->getInit(0), Slot);
993
994 // Move past these elements.
995 InitListElements =
996 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
997 ->getSize().getZExtValue();
998 CurPtr =
999 Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1000 Builder.getSize(InitListElements),
1001 "string.init.end"),
1002 CurPtr.getAlignment().alignmentAtOffset(InitListElements *
1003 ElementSize));
1004
1005 // Zero out the rest, if any remain.
1006 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1007 if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
1008 bool OK = TryMemsetInitialization();
1009 (void)OK;
1010 assert(OK && "couldn't memset character type?");
1011 }
1012 return;
1013 }
1014
Richard Smith06a67e22014-06-03 06:58:52 +00001015 InitListElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +00001016
Richard Smith1c96bc52013-12-11 01:40:16 +00001017 // If this is a multi-dimensional array new, we will initialize multiple
1018 // elements with each init list element.
1019 QualType AllocType = E->getAllocatedType();
1020 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
1021 AllocType->getAsArrayTypeUnsafe())) {
David Blaikiefb901c7a2015-04-04 15:12:29 +00001022 ElementTy = ConvertTypeForMem(AllocType);
John McCall7f416cc2015-09-08 08:05:57 +00001023 CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
Richard Smith06a67e22014-06-03 06:58:52 +00001024 InitListElements *= getContext().getConstantArrayElementCount(CAT);
Richard Smith1c96bc52013-12-11 01:40:16 +00001025 }
1026
Richard Smith06a67e22014-06-03 06:58:52 +00001027 // Enter a partial-destruction Cleanup if necessary.
1028 if (needsEHCleanup(DtorKind)) {
1029 // In principle we could tell the Cleanup where we are more
Chad Rosierf62290a2012-02-24 00:13:55 +00001030 // directly, but the control flow can get so varied here that it
1031 // would actually be quite complex. Therefore we go through an
1032 // alloca.
John McCall7f416cc2015-09-08 08:05:57 +00001033 EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
1034 "array.init.end");
1035 CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
1036 pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
1037 ElementType, ElementAlign,
Richard Smith06a67e22014-06-03 06:58:52 +00001038 getDestroyer(DtorKind));
1039 Cleanup = EHStack.stable_begin();
Chad Rosierf62290a2012-02-24 00:13:55 +00001040 }
1041
John McCall7f416cc2015-09-08 08:05:57 +00001042 CharUnits StartAlign = CurPtr.getAlignment();
Sebastian Redlf862eb62012-02-22 17:37:52 +00001043 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +00001044 // Tell the cleanup that it needs to destroy up to this
1045 // element. TODO: some of these stores can be trivially
1046 // observed to be unnecessary.
John McCall7f416cc2015-09-08 08:05:57 +00001047 if (EndOfInit.isValid()) {
1048 auto FinishedPtr =
1049 Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
1050 Builder.CreateStore(FinishedPtr, EndOfInit);
1051 }
Richard Smith06a67e22014-06-03 06:58:52 +00001052 // FIXME: If the last initializer is an incomplete initializer list for
1053 // an array, and we have an array filler, we can fold together the two
1054 // initialization loops.
Richard Smith1c96bc52013-12-11 01:40:16 +00001055 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
Richard Smith06a67e22014-06-03 06:58:52 +00001056 ILE->getInit(i)->getType(), CurPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001057 CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1058 Builder.getSize(1),
1059 "array.exp.next"),
1060 StartAlign.alignmentAtOffset((i + 1) * ElementSize));
Sebastian Redlf862eb62012-02-22 17:37:52 +00001061 }
1062
1063 // The remaining elements are filled with the array filler expression.
1064 Init = ILE->getArrayFiller();
Richard Smith1c96bc52013-12-11 01:40:16 +00001065
Richard Smith06a67e22014-06-03 06:58:52 +00001066 // Extract the initializer for the individual array elements by pulling
1067 // out the array filler from all the nested initializer lists. This avoids
1068 // generating a nested loop for the initialization.
1069 while (Init && Init->getType()->isConstantArrayType()) {
1070 auto *SubILE = dyn_cast<InitListExpr>(Init);
1071 if (!SubILE)
1072 break;
1073 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
1074 Init = SubILE->getArrayFiller();
1075 }
1076
1077 // Switch back to initializing one base element at a time.
John McCall7f416cc2015-09-08 08:05:57 +00001078 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
Sebastian Redlf862eb62012-02-22 17:37:52 +00001079 }
1080
Richard Smith454a7cd2014-06-03 08:26:00 +00001081 // If all elements have already been initialized, skip any further
1082 // initialization.
1083 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1084 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1085 // If there was a Cleanup, deactivate it.
1086 if (CleanupDominator)
1087 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1088 return;
1089 }
1090
1091 assert(Init && "have trailing elements to initialize but no initializer");
1092
Richard Smith06a67e22014-06-03 06:58:52 +00001093 // If this is a constructor call, try to optimize it out, and failing that
1094 // emit a single loop to initialize all remaining elements.
Richard Smith454a7cd2014-06-03 08:26:00 +00001095 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +00001096 CXXConstructorDecl *Ctor = CCE->getConstructor();
1097 if (Ctor->isTrivial()) {
1098 // If new expression did not specify value-initialization, then there
1099 // is no initialization.
1100 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
1101 return;
1102
1103 if (TryMemsetInitialization())
1104 return;
1105 }
1106
1107 // Store the new Cleanup position for irregular Cleanups.
1108 //
1109 // FIXME: Share this cleanup with the constructor call emission rather than
1110 // having it create a cleanup of its own.
John McCall7f416cc2015-09-08 08:05:57 +00001111 if (EndOfInit.isValid())
1112 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
Richard Smith06a67e22014-06-03 06:58:52 +00001113
1114 // Emit a constructor call loop to initialize the remaining elements.
1115 if (InitListElements)
1116 NumElements = Builder.CreateSub(
1117 NumElements,
1118 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001119 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
Richard Smith06a67e22014-06-03 06:58:52 +00001120 CCE->requiresZeroInitialization());
Chandler Carruthe6c980c2014-05-03 09:16:57 +00001121 return;
1122 }
1123
Richard Smith06a67e22014-06-03 06:58:52 +00001124 // If this is value-initialization, we can usually use memset.
1125 ImplicitValueInitExpr IVIE(ElementType);
Richard Smith454a7cd2014-06-03 08:26:00 +00001126 if (isa<ImplicitValueInitExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +00001127 if (TryMemsetInitialization())
1128 return;
1129
1130 // Switch to an ImplicitValueInitExpr for the element type. This handles
1131 // only one case: multidimensional array new of pointers to members. In
1132 // all other cases, we already have an initializer for the array element.
1133 Init = &IVIE;
1134 }
1135
1136 // At this point we should have found an initializer for the individual
1137 // elements of the array.
1138 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
1139 "got wrong type of element to initialize");
1140
Richard Smith454a7cd2014-06-03 08:26:00 +00001141 // If we have an empty initializer list, we can usually use memset.
1142 if (auto *ILE = dyn_cast<InitListExpr>(Init))
1143 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1144 return;
Richard Smith06a67e22014-06-03 06:58:52 +00001145
Yunzhong Gaocb779302015-06-10 00:27:52 +00001146 // If we have a struct whose every field is value-initialized, we can
1147 // usually use memset.
1148 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1149 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1150 if (RType->getDecl()->isStruct()) {
Richard Smith872307e2016-03-08 22:17:41 +00001151 unsigned NumElements = 0;
1152 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1153 NumElements = CXXRD->getNumBases();
Yunzhong Gaocb779302015-06-10 00:27:52 +00001154 for (auto *Field : RType->getDecl()->fields())
1155 if (!Field->isUnnamedBitfield())
Richard Smith872307e2016-03-08 22:17:41 +00001156 ++NumElements;
1157 // FIXME: Recurse into nested InitListExprs.
1158 if (ILE->getNumInits() == NumElements)
Yunzhong Gaocb779302015-06-10 00:27:52 +00001159 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1160 if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
Richard Smith872307e2016-03-08 22:17:41 +00001161 --NumElements;
1162 if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
Yunzhong Gaocb779302015-06-10 00:27:52 +00001163 return;
1164 }
1165 }
1166 }
1167
Richard Smith06a67e22014-06-03 06:58:52 +00001168 // Create the loop blocks.
1169 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1170 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
1171 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
1172
1173 // Find the end of the array, hoisted out of the loop.
1174 llvm::Value *EndPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001175 Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
John McCall99210dc2011-09-15 06:49:18 +00001176
Sebastian Redlf862eb62012-02-22 17:37:52 +00001177 // If the number of elements isn't constant, we have to now check if there is
1178 // anything left to initialize.
Richard Smith06a67e22014-06-03 06:58:52 +00001179 if (!ConstNum) {
John McCall7f416cc2015-09-08 08:05:57 +00001180 llvm::Value *IsEmpty =
1181 Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
Richard Smith06a67e22014-06-03 06:58:52 +00001182 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
John McCall99210dc2011-09-15 06:49:18 +00001183 }
1184
1185 // Enter the loop.
Richard Smith06a67e22014-06-03 06:58:52 +00001186 EmitBlock(LoopBB);
John McCall99210dc2011-09-15 06:49:18 +00001187
1188 // Set up the current-element phi.
Richard Smith06a67e22014-06-03 06:58:52 +00001189 llvm::PHINode *CurPtrPhi =
John McCall7f416cc2015-09-08 08:05:57 +00001190 Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1191 CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
1192
1193 CurPtr = Address(CurPtrPhi, ElementAlign);
John McCall99210dc2011-09-15 06:49:18 +00001194
Richard Smith06a67e22014-06-03 06:58:52 +00001195 // Store the new Cleanup position for irregular Cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00001196 if (EndOfInit.isValid())
1197 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
Chad Rosierf62290a2012-02-24 00:13:55 +00001198
Richard Smith06a67e22014-06-03 06:58:52 +00001199 // Enter a partial-destruction Cleanup if necessary.
1200 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
John McCall7f416cc2015-09-08 08:05:57 +00001201 pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
1202 ElementType, ElementAlign,
Richard Smith06a67e22014-06-03 06:58:52 +00001203 getDestroyer(DtorKind));
1204 Cleanup = EHStack.stable_begin();
1205 CleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +00001206 }
1207
1208 // Emit the initializer into this element.
Richard Smith06a67e22014-06-03 06:58:52 +00001209 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
John McCall99210dc2011-09-15 06:49:18 +00001210
Richard Smith06a67e22014-06-03 06:58:52 +00001211 // Leave the Cleanup if we entered one.
1212 if (CleanupDominator) {
1213 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1214 CleanupDominator->eraseFromParent();
John McCallf4beacd2011-11-10 10:43:54 +00001215 }
John McCall99210dc2011-09-15 06:49:18 +00001216
Faisal Vali57ae0562013-12-14 00:40:05 +00001217 // Advance to the next element by adjusting the pointer type as necessary.
Richard Smith06a67e22014-06-03 06:58:52 +00001218 llvm::Value *NextPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001219 Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
1220 "array.next");
Richard Smith06a67e22014-06-03 06:58:52 +00001221
John McCall99210dc2011-09-15 06:49:18 +00001222 // Check whether we've gotten to the end of the array and, if so,
1223 // exit the loop.
Richard Smith06a67e22014-06-03 06:58:52 +00001224 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1225 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1226 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
John McCall99210dc2011-09-15 06:49:18 +00001227
Richard Smith06a67e22014-06-03 06:58:52 +00001228 EmitBlock(ContBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +00001229}
1230
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001231static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
David Blaikiefb901c7a2015-04-04 15:12:29 +00001232 QualType ElementType, llvm::Type *ElementTy,
John McCall7f416cc2015-09-08 08:05:57 +00001233 Address NewPtr, llvm::Value *NumElements,
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001234 llvm::Value *AllocSizeWithoutCookie) {
David Blaikie9b479662015-01-25 01:19:10 +00001235 ApplyDebugLocation DL(CGF, E);
Richard Smith06a67e22014-06-03 06:58:52 +00001236 if (E->isArray())
David Blaikiefb901c7a2015-04-04 15:12:29 +00001237 CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
Richard Smith06a67e22014-06-03 06:58:52 +00001238 AllocSizeWithoutCookie);
1239 else if (const Expr *Init = E->getInitializer())
David Blaikie66e41972015-01-14 07:38:27 +00001240 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001241}
1242
Richard Smith8d0dc312013-07-21 23:12:18 +00001243/// Emit a call to an operator new or operator delete function, as implicitly
1244/// created by new-expressions and delete-expressions.
1245static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
John McCallb92ab1a2016-10-26 23:46:34 +00001246 const FunctionDecl *CalleeDecl,
Richard Smith8d0dc312013-07-21 23:12:18 +00001247 const FunctionProtoType *CalleeType,
1248 const CallArgList &Args) {
1249 llvm::Instruction *CallOrInvoke;
John McCallb92ab1a2016-10-26 23:46:34 +00001250 llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
1251 CGCallee Callee = CGCallee::forDirect(CalleePtr, CalleeDecl);
Richard Smith8d0dc312013-07-21 23:12:18 +00001252 RValue RV =
Peter Collingbournef7706832014-12-12 23:41:25 +00001253 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1254 Args, CalleeType, /*chainCall=*/false),
John McCallb92ab1a2016-10-26 23:46:34 +00001255 Callee, ReturnValueSlot(), Args, &CallOrInvoke);
Richard Smith8d0dc312013-07-21 23:12:18 +00001256
1257 /// C++1y [expr.new]p10:
1258 /// [In a new-expression,] an implementation is allowed to omit a call
1259 /// to a replaceable global allocation function.
1260 ///
1261 /// We model such elidable calls with the 'builtin' attribute.
John McCallb92ab1a2016-10-26 23:46:34 +00001262 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1263 if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola6956d582013-10-22 14:23:09 +00001264 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smith8d0dc312013-07-21 23:12:18 +00001265 // FIXME: Add addAttribute to CallSite.
1266 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1267 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1268 llvm::Attribute::Builtin);
1269 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1270 II->addAttribute(llvm::AttributeSet::FunctionIndex,
1271 llvm::Attribute::Builtin);
1272 else
1273 llvm_unreachable("unexpected kind of call instruction");
1274 }
1275
1276 return RV;
1277}
1278
Richard Smith760520b2014-06-03 23:27:44 +00001279RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1280 const Expr *Arg,
1281 bool IsDelete) {
1282 CallArgList Args;
1283 const Stmt *ArgS = Arg;
David Blaikief05779e2015-07-21 18:37:18 +00001284 EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS));
Richard Smith760520b2014-06-03 23:27:44 +00001285 // Find the allocation or deallocation function that we're calling.
1286 ASTContext &Ctx = getContext();
1287 DeclarationName Name = Ctx.DeclarationNames
1288 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1289 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
Richard Smith599bed72014-06-05 00:43:02 +00001290 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1291 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1292 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
Richard Smith760520b2014-06-03 23:27:44 +00001293 llvm_unreachable("predeclared global operator new/delete is missing");
1294}
1295
Richard Smithb2f0f052016-10-10 18:54:32 +00001296static std::pair<bool, bool>
1297shouldPassSizeAndAlignToUsualDelete(const FunctionProtoType *FPT) {
1298 auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
Richard Smith189e52f2016-10-10 06:42:31 +00001299
Richard Smithb2f0f052016-10-10 18:54:32 +00001300 // The first argument is always a void*.
1301 ++AI;
1302
1303 // Figure out what other parameters we should be implicitly passing.
1304 bool PassSize = false;
1305 bool PassAlignment = false;
1306
1307 if (AI != AE && (*AI)->isIntegerType()) {
1308 PassSize = true;
1309 ++AI;
1310 }
1311
1312 if (AI != AE && (*AI)->isAlignValT()) {
1313 PassAlignment = true;
1314 ++AI;
1315 }
1316
1317 assert(AI == AE && "unexpected usual deallocation function parameter");
1318 return {PassSize, PassAlignment};
1319}
1320
1321namespace {
1322 /// A cleanup to call the given 'operator delete' function upon abnormal
1323 /// exit from a new expression. Templated on a traits type that deals with
1324 /// ensuring that the arguments dominate the cleanup if necessary.
1325 template<typename Traits>
1326 class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1327 /// Type used to hold llvm::Value*s.
1328 typedef typename Traits::ValueTy ValueTy;
1329 /// Type used to hold RValues.
1330 typedef typename Traits::RValueTy RValueTy;
1331 struct PlacementArg {
1332 RValueTy ArgValue;
1333 QualType ArgType;
1334 };
1335
1336 unsigned NumPlacementArgs : 31;
1337 unsigned PassAlignmentToPlacementDelete : 1;
1338 const FunctionDecl *OperatorDelete;
1339 ValueTy Ptr;
1340 ValueTy AllocSize;
1341 CharUnits AllocAlign;
1342
1343 PlacementArg *getPlacementArgs() {
1344 return reinterpret_cast<PlacementArg *>(this + 1);
1345 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00001346
1347 public:
1348 static size_t getExtraSize(size_t NumPlacementArgs) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001349 return NumPlacementArgs * sizeof(PlacementArg);
Daniel Jaspere9abe642016-10-10 14:13:55 +00001350 }
1351
1352 CallDeleteDuringNew(size_t NumPlacementArgs,
Richard Smithb2f0f052016-10-10 18:54:32 +00001353 const FunctionDecl *OperatorDelete, ValueTy Ptr,
1354 ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1355 CharUnits AllocAlign)
1356 : NumPlacementArgs(NumPlacementArgs),
1357 PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1358 OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1359 AllocAlign(AllocAlign) {}
Daniel Jaspere9abe642016-10-10 14:13:55 +00001360
Richard Smithb2f0f052016-10-10 18:54:32 +00001361 void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
Daniel Jaspere9abe642016-10-10 14:13:55 +00001362 assert(I < NumPlacementArgs && "index out of range");
Richard Smithb2f0f052016-10-10 18:54:32 +00001363 getPlacementArgs()[I] = {Arg, Type};
Daniel Jaspere9abe642016-10-10 14:13:55 +00001364 }
1365
1366 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smithb2f0f052016-10-10 18:54:32 +00001367 const FunctionProtoType *FPT =
1368 OperatorDelete->getType()->getAs<FunctionProtoType>();
Daniel Jaspere9abe642016-10-10 14:13:55 +00001369 CallArgList DeleteArgs;
1370
1371 // The first argument is always a void*.
Richard Smithb2f0f052016-10-10 18:54:32 +00001372 DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
Daniel Jaspere9abe642016-10-10 14:13:55 +00001373
Richard Smithb2f0f052016-10-10 18:54:32 +00001374 // Figure out what other parameters we should be implicitly passing.
1375 bool PassSize = false;
1376 bool PassAlignment = false;
1377 if (NumPlacementArgs) {
1378 // A placement deallocation function is implicitly passed an alignment
1379 // if the placement allocation function was, but is never passed a size.
1380 PassAlignment = PassAlignmentToPlacementDelete;
1381 } else {
1382 // For a non-placement new-expression, 'operator delete' can take a
1383 // size and/or an alignment if it has the right parameters.
1384 std::tie(PassSize, PassAlignment) =
1385 shouldPassSizeAndAlignToUsualDelete(FPT);
John McCall7f9c92a2010-09-17 00:50:28 +00001386 }
1387
Richard Smithb2f0f052016-10-10 18:54:32 +00001388 // The second argument can be a std::size_t (for non-placement delete).
1389 if (PassSize)
1390 DeleteArgs.add(Traits::get(CGF, AllocSize),
1391 CGF.getContext().getSizeType());
1392
1393 // The next (second or third) argument can be a std::align_val_t, which
1394 // is an enum whose underlying type is std::size_t.
1395 // FIXME: Use the right type as the parameter type. Note that in a call
1396 // to operator delete(size_t, ...), we may not have it available.
1397 if (PassAlignment)
1398 DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1399 CGF.SizeTy, AllocAlign.getQuantity())),
1400 CGF.getContext().getSizeType());
1401
John McCall7f9c92a2010-09-17 00:50:28 +00001402 // Pass the rest of the arguments, which must match exactly.
1403 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001404 auto Arg = getPlacementArgs()[I];
1405 DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
John McCall7f9c92a2010-09-17 00:50:28 +00001406 }
1407
1408 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001409 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7f9c92a2010-09-17 00:50:28 +00001410 }
1411 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001412}
John McCall7f9c92a2010-09-17 00:50:28 +00001413
1414/// Enter a cleanup to call 'operator delete' if the initializer in a
1415/// new-expression throws.
1416static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1417 const CXXNewExpr *E,
John McCall7f416cc2015-09-08 08:05:57 +00001418 Address NewPtr,
John McCall7f9c92a2010-09-17 00:50:28 +00001419 llvm::Value *AllocSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00001420 CharUnits AllocAlign,
John McCall7f9c92a2010-09-17 00:50:28 +00001421 const CallArgList &NewArgs) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001422 unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1423
John McCall7f9c92a2010-09-17 00:50:28 +00001424 // If we're not inside a conditional branch, then the cleanup will
1425 // dominate and we can do the easier (and more efficient) thing.
1426 if (!CGF.isInConditionalBranch()) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001427 struct DirectCleanupTraits {
1428 typedef llvm::Value *ValueTy;
1429 typedef RValue RValueTy;
1430 static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1431 static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1432 };
1433
1434 typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1435
1436 DirectCleanup *Cleanup = CGF.EHStack
1437 .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
1438 E->getNumPlacementArgs(),
1439 E->getOperatorDelete(),
1440 NewPtr.getPointer(),
1441 AllocSize,
1442 E->passAlignment(),
1443 AllocAlign);
1444 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1445 auto &Arg = NewArgs[I + NumNonPlacementArgs];
1446 Cleanup->setPlacementArg(I, Arg.RV, Arg.Ty);
1447 }
John McCall7f9c92a2010-09-17 00:50:28 +00001448
1449 return;
1450 }
1451
1452 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001453 DominatingValue<RValue>::saved_type SavedNewPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001454 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
John McCallcb5f77f2011-01-28 10:53:53 +00001455 DominatingValue<RValue>::saved_type SavedAllocSize =
1456 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001457
Richard Smithb2f0f052016-10-10 18:54:32 +00001458 struct ConditionalCleanupTraits {
1459 typedef DominatingValue<RValue>::saved_type ValueTy;
1460 typedef DominatingValue<RValue>::saved_type RValueTy;
1461 static RValue get(CodeGenFunction &CGF, ValueTy V) {
1462 return V.restore(CGF);
1463 }
1464 };
1465 typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1466
1467 ConditionalCleanup *Cleanup = CGF.EHStack
1468 .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
1469 E->getNumPlacementArgs(),
1470 E->getOperatorDelete(),
1471 SavedNewPtr,
1472 SavedAllocSize,
1473 E->passAlignment(),
1474 AllocAlign);
1475 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1476 auto &Arg = NewArgs[I + NumNonPlacementArgs];
1477 Cleanup->setPlacementArg(I, DominatingValue<RValue>::save(CGF, Arg.RV),
1478 Arg.Ty);
1479 }
John McCall7f9c92a2010-09-17 00:50:28 +00001480
John McCallf4beacd2011-11-10 10:43:54 +00001481 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001482}
1483
Anders Carlssoncc52f652009-09-22 22:53:17 +00001484llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001485 // The element type being allocated.
1486 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001487
John McCall75f94982011-03-07 03:12:35 +00001488 // 1. Build a call to the allocation function.
1489 FunctionDecl *allocator = E->getOperatorNew();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001490
Sebastian Redlf862eb62012-02-22 17:37:52 +00001491 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1492 unsigned minElements = 0;
1493 if (E->isArray() && E->hasInitializer()) {
Richard Smith0511d232016-10-05 22:41:02 +00001494 const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
1495 if (ILE && ILE->isStringLiteralInit())
1496 minElements =
1497 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1498 ->getSize().getZExtValue();
1499 else if (ILE)
Sebastian Redlf862eb62012-02-22 17:37:52 +00001500 minElements = ILE->getNumInits();
1501 }
1502
Craig Topper8a13c412014-05-21 05:09:00 +00001503 llvm::Value *numElements = nullptr;
1504 llvm::Value *allocSizeWithoutCookie = nullptr;
John McCall75f94982011-03-07 03:12:35 +00001505 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001506 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1507 allocSizeWithoutCookie);
Richard Smithb2f0f052016-10-10 18:54:32 +00001508 CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00001509
John McCall7ec4b432011-05-16 01:05:12 +00001510 // Emit the allocation call. If the allocator is a global placement
1511 // operator, just "inline" it directly.
John McCall7f416cc2015-09-08 08:05:57 +00001512 Address allocation = Address::invalid();
1513 CallArgList allocatorArgs;
John McCall7ec4b432011-05-16 01:05:12 +00001514 if (allocator->isReservedGlobalPlacementOperator()) {
John McCall53dcf942015-09-29 23:55:17 +00001515 assert(E->getNumPlacementArgs() == 1);
1516 const Expr *arg = *E->placement_arguments().begin();
1517
John McCall7f416cc2015-09-08 08:05:57 +00001518 AlignmentSource alignSource;
John McCall53dcf942015-09-29 23:55:17 +00001519 allocation = EmitPointerWithAlignment(arg, &alignSource);
John McCall7f416cc2015-09-08 08:05:57 +00001520
1521 // The pointer expression will, in many cases, be an opaque void*.
1522 // In these cases, discard the computed alignment and use the
1523 // formal alignment of the allocated type.
Richard Smithb2f0f052016-10-10 18:54:32 +00001524 if (alignSource != AlignmentSource::Decl)
1525 allocation = Address(allocation.getPointer(), allocAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001526
John McCall53dcf942015-09-29 23:55:17 +00001527 // Set up allocatorArgs for the call to operator delete if it's not
1528 // the reserved global operator.
1529 if (E->getOperatorDelete() &&
1530 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1531 allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1532 allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
1533 }
1534
John McCall7ec4b432011-05-16 01:05:12 +00001535 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001536 const FunctionProtoType *allocatorType =
1537 allocator->getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00001538 unsigned ParamsToSkip = 0;
John McCall7f416cc2015-09-08 08:05:57 +00001539
1540 // The allocation size is the first argument.
1541 QualType sizeType = getContext().getSizeType();
1542 allocatorArgs.add(RValue::get(allocSize), sizeType);
Richard Smithb2f0f052016-10-10 18:54:32 +00001543 ++ParamsToSkip;
John McCall7f416cc2015-09-08 08:05:57 +00001544
Richard Smithb2f0f052016-10-10 18:54:32 +00001545 if (allocSize != allocSizeWithoutCookie) {
1546 CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1547 allocAlign = std::max(allocAlign, cookieAlign);
1548 }
1549
1550 // The allocation alignment may be passed as the second argument.
1551 if (E->passAlignment()) {
1552 QualType AlignValT = sizeType;
1553 if (allocatorType->getNumParams() > 1) {
1554 AlignValT = allocatorType->getParamType(1);
1555 assert(getContext().hasSameUnqualifiedType(
1556 AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
1557 sizeType) &&
1558 "wrong type for alignment parameter");
1559 ++ParamsToSkip;
1560 } else {
1561 // Corner case, passing alignment to 'operator new(size_t, ...)'.
1562 assert(allocator->isVariadic() && "can't pass alignment to allocator");
1563 }
1564 allocatorArgs.add(
1565 RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1566 AlignValT);
1567 }
1568
1569 // FIXME: Why do we not pass a CalleeDecl here?
John McCall7f416cc2015-09-08 08:05:57 +00001570 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
Richard Smithb2f0f052016-10-10 18:54:32 +00001571 /*CalleeDecl*/nullptr, /*ParamsToSkip*/ParamsToSkip);
John McCall7f416cc2015-09-08 08:05:57 +00001572
1573 RValue RV =
1574 EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1575
Richard Smithb2f0f052016-10-10 18:54:32 +00001576 // If this was a call to a global replaceable allocation function that does
1577 // not take an alignment argument, the allocator is known to produce
1578 // storage that's suitably aligned for any object that fits, up to a known
1579 // threshold. Otherwise assume it's suitably aligned for the allocated type.
1580 CharUnits allocationAlign = allocAlign;
1581 if (!E->passAlignment() &&
1582 allocator->isReplaceableGlobalAllocationFunction()) {
1583 unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1584 Target.getNewAlign(), getContext().getTypeSize(allocType)));
1585 allocationAlign = std::max(
1586 allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
John McCall7f416cc2015-09-08 08:05:57 +00001587 }
1588
1589 allocation = Address(RV.getScalarVal(), allocationAlign);
John McCall7ec4b432011-05-16 01:05:12 +00001590 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001591
John McCall75f94982011-03-07 03:12:35 +00001592 // Emit a null check on the allocation result if the allocation
1593 // function is allowed to return null (because it has a non-throwing
Richard Smith902a0232015-02-14 01:52:20 +00001594 // exception spec or is the reserved placement new) and we have an
John McCall75f94982011-03-07 03:12:35 +00001595 // interesting initializer.
Richard Smith902a0232015-02-14 01:52:20 +00001596 bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001597 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001598
Craig Topper8a13c412014-05-21 05:09:00 +00001599 llvm::BasicBlock *nullCheckBB = nullptr;
1600 llvm::BasicBlock *contBB = nullptr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001601
John McCallf7dcf322011-03-07 01:52:56 +00001602 // The null-check means that the initializer is conditionally
1603 // evaluated.
1604 ConditionalEvaluation conditional(*this);
1605
John McCall75f94982011-03-07 03:12:35 +00001606 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001607 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001608
1609 nullCheckBB = Builder.GetInsertBlock();
1610 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1611 contBB = createBasicBlock("new.cont");
1612
John McCall7f416cc2015-09-08 08:05:57 +00001613 llvm::Value *isNull =
1614 Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
John McCall75f94982011-03-07 03:12:35 +00001615 Builder.CreateCondBr(isNull, contBB, notNullBB);
1616 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001617 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001618
John McCall824c2f52010-09-14 07:57:04 +00001619 // If there's an operator delete, enter a cleanup to call it if an
1620 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001621 EHScopeStack::stable_iterator operatorDeleteCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001622 llvm::Instruction *cleanupDominator = nullptr;
John McCall7ec4b432011-05-16 01:05:12 +00001623 if (E->getOperatorDelete() &&
1624 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001625 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1626 allocatorArgs);
John McCall75f94982011-03-07 03:12:35 +00001627 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001628 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001629 }
1630
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001631 assert((allocSize == allocSizeWithoutCookie) ==
1632 CalculateCookiePadding(*this, E).isZero());
1633 if (allocSize != allocSizeWithoutCookie) {
1634 assert(E->isArray());
1635 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1636 numElements,
1637 E, allocType);
1638 }
1639
David Blaikiefb901c7a2015-04-04 15:12:29 +00001640 llvm::Type *elementTy = ConvertTypeForMem(allocType);
John McCall7f416cc2015-09-08 08:05:57 +00001641 Address result = Builder.CreateElementBitCast(allocation, elementTy);
John McCall824c2f52010-09-14 07:57:04 +00001642
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001643 // Passing pointer through invariant.group.barrier to avoid propagation of
1644 // vptrs information which may be included in previous type.
1645 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1646 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1647 allocator->isReservedGlobalPlacementOperator())
1648 result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()),
1649 result.getAlignment());
1650
David Blaikiefb901c7a2015-04-04 15:12:29 +00001651 EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
John McCall99210dc2011-09-15 06:49:18 +00001652 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001653 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001654 // NewPtr is a pointer to the base element type. If we're
1655 // allocating an array of arrays, we'll need to cast back to the
1656 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001657 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall7f416cc2015-09-08 08:05:57 +00001658 if (result.getType() != resultType)
John McCall75f94982011-03-07 03:12:35 +00001659 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001660 }
John McCall824c2f52010-09-14 07:57:04 +00001661
1662 // Deactivate the 'operator delete' cleanup if we finished
1663 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001664 if (operatorDeleteCleanup.isValid()) {
1665 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1666 cleanupDominator->eraseFromParent();
1667 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001668
John McCall7f416cc2015-09-08 08:05:57 +00001669 llvm::Value *resultPtr = result.getPointer();
John McCall75f94982011-03-07 03:12:35 +00001670 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001671 conditional.end(*this);
1672
John McCall75f94982011-03-07 03:12:35 +00001673 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1674 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001675
John McCall7f416cc2015-09-08 08:05:57 +00001676 llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
1677 PHI->addIncoming(resultPtr, notNullBB);
1678 PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
John McCall75f94982011-03-07 03:12:35 +00001679 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001680
John McCall7f416cc2015-09-08 08:05:57 +00001681 resultPtr = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001682 }
John McCall8ed55a52010-09-02 09:58:18 +00001683
John McCall7f416cc2015-09-08 08:05:57 +00001684 return resultPtr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001685}
1686
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001687void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
Richard Smithb2f0f052016-10-10 18:54:32 +00001688 llvm::Value *Ptr, QualType DeleteTy,
1689 llvm::Value *NumElements,
1690 CharUnits CookieSize) {
1691 assert((!NumElements && CookieSize.isZero()) ||
1692 DeleteFD->getOverloadedOperator() == OO_Array_Delete);
John McCall8ed55a52010-09-02 09:58:18 +00001693
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001694 const FunctionProtoType *DeleteFTy =
1695 DeleteFD->getType()->getAs<FunctionProtoType>();
1696
1697 CallArgList DeleteArgs;
1698
Richard Smithb2f0f052016-10-10 18:54:32 +00001699 std::pair<bool, bool> PassSizeAndAlign =
1700 shouldPassSizeAndAlignToUsualDelete(DeleteFTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00001701
Richard Smithb2f0f052016-10-10 18:54:32 +00001702 auto ParamTypeIt = DeleteFTy->param_type_begin();
1703
1704 // Pass the pointer itself.
1705 QualType ArgTy = *ParamTypeIt++;
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001706 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001707 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001708
Richard Smithb2f0f052016-10-10 18:54:32 +00001709 // Pass the size if the delete function has a size_t parameter.
1710 if (PassSizeAndAlign.first) {
1711 QualType SizeType = *ParamTypeIt++;
1712 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1713 llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1714 DeleteTypeSize.getQuantity());
1715
1716 // For array new, multiply by the number of elements.
1717 if (NumElements)
1718 Size = Builder.CreateMul(Size, NumElements);
1719
1720 // If there is a cookie, add the cookie size.
1721 if (!CookieSize.isZero())
1722 Size = Builder.CreateAdd(
1723 Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1724
1725 DeleteArgs.add(RValue::get(Size), SizeType);
1726 }
1727
1728 // Pass the alignment if the delete function has an align_val_t parameter.
1729 if (PassSizeAndAlign.second) {
1730 QualType AlignValType = *ParamTypeIt++;
1731 CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits(
1732 getContext().getTypeAlignIfKnown(DeleteTy));
1733 llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1734 DeleteTypeAlign.getQuantity());
1735 DeleteArgs.add(RValue::get(Align), AlignValType);
1736 }
1737
1738 assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1739 "unknown parameter to usual delete function");
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001740
1741 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001742 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001743}
1744
John McCall8ed55a52010-09-02 09:58:18 +00001745namespace {
1746 /// Calls the given 'operator delete' on a single object.
David Blaikie7e70d682015-08-18 22:40:54 +00001747 struct CallObjectDelete final : EHScopeStack::Cleanup {
John McCall8ed55a52010-09-02 09:58:18 +00001748 llvm::Value *Ptr;
1749 const FunctionDecl *OperatorDelete;
1750 QualType ElementType;
1751
1752 CallObjectDelete(llvm::Value *Ptr,
1753 const FunctionDecl *OperatorDelete,
1754 QualType ElementType)
1755 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1756
Craig Topper4f12f102014-03-12 06:41:41 +00001757 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001758 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1759 }
1760 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001761}
John McCall8ed55a52010-09-02 09:58:18 +00001762
David Majnemer0c0b6d92014-10-31 20:09:12 +00001763void
1764CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1765 llvm::Value *CompletePtr,
1766 QualType ElementType) {
1767 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1768 OperatorDelete, ElementType);
1769}
1770
John McCall8ed55a52010-09-02 09:58:18 +00001771/// Emit the code for deleting a single object.
1772static void EmitObjectDelete(CodeGenFunction &CGF,
David Majnemer08681372014-11-01 07:37:17 +00001773 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001774 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001775 QualType ElementType) {
Ivan Krasind98f5d72016-11-17 00:39:48 +00001776 // C++11 [expr.delete]p3:
1777 // If the static type of the object to be deleted is different from its
1778 // dynamic type, the static type shall be a base class of the dynamic type
1779 // of the object to be deleted and the static type shall have a virtual
1780 // destructor or the behavior is undefined.
1781 CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall,
1782 DE->getExprLoc(), Ptr.getPointer(),
1783 ElementType);
1784
John McCall8ed55a52010-09-02 09:58:18 +00001785 // Find the destructor for the type, if applicable. If the
1786 // destructor is virtual, we'll just emit the vcall and return.
Craig Topper8a13c412014-05-21 05:09:00 +00001787 const CXXDestructorDecl *Dtor = nullptr;
John McCall8ed55a52010-09-02 09:58:18 +00001788 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1789 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001790 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001791 Dtor = RD->getDestructor();
1792
1793 if (Dtor->isVirtual()) {
David Majnemer08681372014-11-01 07:37:17 +00001794 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1795 Dtor);
John McCall8ed55a52010-09-02 09:58:18 +00001796 return;
1797 }
1798 }
1799 }
1800
1801 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001802 // This doesn't have to a conditional cleanup because we're going
1803 // to pop it off in a second.
David Majnemer08681372014-11-01 07:37:17 +00001804 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001805 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
John McCall7f416cc2015-09-08 08:05:57 +00001806 Ptr.getPointer(),
1807 OperatorDelete, ElementType);
John McCall8ed55a52010-09-02 09:58:18 +00001808
1809 if (Dtor)
1810 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001811 /*ForVirtualBase=*/false,
1812 /*Delegating=*/false,
1813 Ptr);
John McCall460ce582015-10-22 18:38:17 +00001814 else if (auto Lifetime = ElementType.getObjCLifetime()) {
1815 switch (Lifetime) {
John McCall31168b02011-06-15 23:02:42 +00001816 case Qualifiers::OCL_None:
1817 case Qualifiers::OCL_ExplicitNone:
1818 case Qualifiers::OCL_Autoreleasing:
1819 break;
John McCall8ed55a52010-09-02 09:58:18 +00001820
John McCall7f416cc2015-09-08 08:05:57 +00001821 case Qualifiers::OCL_Strong:
1822 CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001823 break;
John McCall31168b02011-06-15 23:02:42 +00001824
1825 case Qualifiers::OCL_Weak:
1826 CGF.EmitARCDestroyWeak(Ptr);
1827 break;
1828 }
1829 }
1830
John McCall8ed55a52010-09-02 09:58:18 +00001831 CGF.PopCleanupBlock();
1832}
1833
1834namespace {
1835 /// Calls the given 'operator delete' on an array of objects.
David Blaikie7e70d682015-08-18 22:40:54 +00001836 struct CallArrayDelete final : EHScopeStack::Cleanup {
John McCall8ed55a52010-09-02 09:58:18 +00001837 llvm::Value *Ptr;
1838 const FunctionDecl *OperatorDelete;
1839 llvm::Value *NumElements;
1840 QualType ElementType;
1841 CharUnits CookieSize;
1842
1843 CallArrayDelete(llvm::Value *Ptr,
1844 const FunctionDecl *OperatorDelete,
1845 llvm::Value *NumElements,
1846 QualType ElementType,
1847 CharUnits CookieSize)
1848 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1849 ElementType(ElementType), CookieSize(CookieSize) {}
1850
Craig Topper4f12f102014-03-12 06:41:41 +00001851 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smithb2f0f052016-10-10 18:54:32 +00001852 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
1853 CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001854 }
1855 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001856}
John McCall8ed55a52010-09-02 09:58:18 +00001857
1858/// Emit the code for deleting an array of objects.
1859static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001860 const CXXDeleteExpr *E,
John McCall7f416cc2015-09-08 08:05:57 +00001861 Address deletedPtr,
John McCallca2c56f2011-07-13 01:41:37 +00001862 QualType elementType) {
Craig Topper8a13c412014-05-21 05:09:00 +00001863 llvm::Value *numElements = nullptr;
1864 llvm::Value *allocatedPtr = nullptr;
John McCallca2c56f2011-07-13 01:41:37 +00001865 CharUnits cookieSize;
1866 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1867 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001868
John McCallca2c56f2011-07-13 01:41:37 +00001869 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001870
1871 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001872 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001873 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001874 allocatedPtr, operatorDelete,
1875 numElements, elementType,
1876 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001877
John McCallca2c56f2011-07-13 01:41:37 +00001878 // Destroy the elements.
1879 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1880 assert(numElements && "no element count for a type with a destructor!");
1881
John McCall7f416cc2015-09-08 08:05:57 +00001882 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1883 CharUnits elementAlign =
1884 deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
1885
1886 llvm::Value *arrayBegin = deletedPtr.getPointer();
John McCallca2c56f2011-07-13 01:41:37 +00001887 llvm::Value *arrayEnd =
John McCall7f416cc2015-09-08 08:05:57 +00001888 CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001889
1890 // Note that it is legal to allocate a zero-length array, and we
1891 // can never fold the check away because the length should always
1892 // come from a cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001893 CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
John McCallca2c56f2011-07-13 01:41:37 +00001894 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001895 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001896 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001897 }
1898
John McCallca2c56f2011-07-13 01:41:37 +00001899 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001900 CGF.PopCleanupBlock();
1901}
1902
Anders Carlssoncc52f652009-09-22 22:53:17 +00001903void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001904 const Expr *Arg = E->getArgument();
John McCall7f416cc2015-09-08 08:05:57 +00001905 Address Ptr = EmitPointerWithAlignment(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001906
1907 // Null check the pointer.
1908 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1909 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1910
John McCall7f416cc2015-09-08 08:05:57 +00001911 llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001912
1913 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1914 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001915
John McCall8ed55a52010-09-02 09:58:18 +00001916 // We might be deleting a pointer to array. If so, GEP down to the
1917 // first non-array element.
1918 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1919 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1920 if (DeleteTy->isConstantArrayType()) {
1921 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001922 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001923
1924 GEP.push_back(Zero); // point at the outermost array
1925
1926 // For each layer of array type we're pointing at:
1927 while (const ConstantArrayType *Arr
1928 = getContext().getAsConstantArrayType(DeleteTy)) {
1929 // 1. Unpeel the array type.
1930 DeleteTy = Arr->getElementType();
1931
1932 // 2. GEP to the first element of the array.
1933 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001934 }
John McCall8ed55a52010-09-02 09:58:18 +00001935
John McCall7f416cc2015-09-08 08:05:57 +00001936 Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
1937 Ptr.getAlignment());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001938 }
1939
John McCall7f416cc2015-09-08 08:05:57 +00001940 assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001941
Reid Kleckner7270ef52015-03-19 17:03:58 +00001942 if (E->isArrayForm()) {
1943 EmitArrayDelete(*this, E, Ptr, DeleteTy);
1944 } else {
1945 EmitObjectDelete(*this, E, Ptr, DeleteTy);
1946 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001947
Anders Carlssoncc52f652009-09-22 22:53:17 +00001948 EmitBlock(DeleteEnd);
1949}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001950
David Majnemer1c3d95e2014-07-19 00:17:06 +00001951static bool isGLValueFromPointerDeref(const Expr *E) {
1952 E = E->IgnoreParens();
1953
1954 if (const auto *CE = dyn_cast<CastExpr>(E)) {
1955 if (!CE->getSubExpr()->isGLValue())
1956 return false;
1957 return isGLValueFromPointerDeref(CE->getSubExpr());
1958 }
1959
1960 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
1961 return isGLValueFromPointerDeref(OVE->getSourceExpr());
1962
1963 if (const auto *BO = dyn_cast<BinaryOperator>(E))
1964 if (BO->getOpcode() == BO_Comma)
1965 return isGLValueFromPointerDeref(BO->getRHS());
1966
1967 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
1968 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
1969 isGLValueFromPointerDeref(ACO->getFalseExpr());
1970
1971 // C++11 [expr.sub]p1:
1972 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
1973 if (isa<ArraySubscriptExpr>(E))
1974 return true;
1975
1976 if (const auto *UO = dyn_cast<UnaryOperator>(E))
1977 if (UO->getOpcode() == UO_Deref)
1978 return true;
1979
1980 return false;
1981}
1982
Warren Hunt747e3012014-06-18 21:15:55 +00001983static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001984 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001985 // Get the vtable pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001986 Address ThisPtr = CGF.EmitLValue(E).getAddress();
Anders Carlsson940f02d2011-04-18 00:57:03 +00001987
1988 // C++ [expr.typeid]p2:
1989 // If the glvalue expression is obtained by applying the unary * operator to
1990 // a pointer and the pointer is a null pointer value, the typeid expression
1991 // throws the std::bad_typeid exception.
David Majnemer1c3d95e2014-07-19 00:17:06 +00001992 //
1993 // However, this paragraph's intent is not clear. We choose a very generous
1994 // interpretation which implores us to consider comma operators, conditional
1995 // operators, parentheses and other such constructs.
David Majnemer1162d252014-06-22 19:05:33 +00001996 QualType SrcRecordTy = E->getType();
David Majnemer1c3d95e2014-07-19 00:17:06 +00001997 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
1998 isGLValueFromPointerDeref(E), SrcRecordTy)) {
David Majnemer1162d252014-06-22 19:05:33 +00001999 llvm::BasicBlock *BadTypeidBlock =
Anders Carlsson940f02d2011-04-18 00:57:03 +00002000 CGF.createBasicBlock("typeid.bad_typeid");
David Majnemer1162d252014-06-22 19:05:33 +00002001 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
Anders Carlsson940f02d2011-04-18 00:57:03 +00002002
John McCall7f416cc2015-09-08 08:05:57 +00002003 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
David Majnemer1162d252014-06-22 19:05:33 +00002004 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002005
David Majnemer1162d252014-06-22 19:05:33 +00002006 CGF.EmitBlock(BadTypeidBlock);
2007 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2008 CGF.EmitBlock(EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002009 }
2010
David Majnemer1162d252014-06-22 19:05:33 +00002011 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
2012 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002013}
2014
John McCalle4df6c82011-01-28 08:37:24 +00002015llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002016 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00002017 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00002018
Anders Carlsson3f4336c2009-12-17 07:09:17 +00002019 if (E->isTypeOperand()) {
David Majnemer143c55e2013-09-27 07:04:31 +00002020 llvm::Constant *TypeInfo =
2021 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson940f02d2011-04-18 00:57:03 +00002022 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00002023 }
Anders Carlsson0c633502011-04-11 14:13:40 +00002024
Anders Carlsson940f02d2011-04-18 00:57:03 +00002025 // C++ [expr.typeid]p2:
2026 // When typeid is applied to a glvalue expression whose type is a
2027 // polymorphic class type, the result refers to a std::type_info object
2028 // representing the type of the most derived object (that is, the dynamic
2029 // type) to which the glvalue refers.
Richard Smithef8bf432012-08-13 20:08:14 +00002030 if (E->isPotentiallyEvaluated())
2031 return EmitTypeidFromVTable(*this, E->getExprOperand(),
2032 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002033
2034 QualType OperandTy = E->getExprOperand()->getType();
2035 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
2036 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00002037}
Mike Stump65511702009-11-16 06:50:58 +00002038
Anders Carlssonc1c99712011-04-11 01:45:29 +00002039static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
2040 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002041 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00002042 if (DestTy->isPointerType())
2043 return llvm::Constant::getNullValue(DestLTy);
2044
2045 /// C++ [expr.dynamic.cast]p9:
2046 /// A failed cast to reference type throws std::bad_cast
David Majnemer1162d252014-06-22 19:05:33 +00002047 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
2048 return nullptr;
Anders Carlssonc1c99712011-04-11 01:45:29 +00002049
2050 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
2051 return llvm::UndefValue::get(DestLTy);
2052}
2053
John McCall7f416cc2015-09-08 08:05:57 +00002054llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
Mike Stump65511702009-11-16 06:50:58 +00002055 const CXXDynamicCastExpr *DCE) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00002056 CGM.EmitExplicitCastExprType(DCE, this);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00002057 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00002058
Anders Carlssonc1c99712011-04-11 01:45:29 +00002059 if (DCE->isAlwaysNull())
David Majnemer1162d252014-06-22 19:05:33 +00002060 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
2061 return T;
Anders Carlssonc1c99712011-04-11 01:45:29 +00002062
2063 QualType SrcTy = DCE->getSubExpr()->getType();
2064
David Majnemer1162d252014-06-22 19:05:33 +00002065 // C++ [expr.dynamic.cast]p7:
2066 // If T is "pointer to cv void," then the result is a pointer to the most
2067 // derived object pointed to by v.
2068 const PointerType *DestPTy = DestTy->getAs<PointerType>();
2069
2070 bool isDynamicCastToVoid;
2071 QualType SrcRecordTy;
2072 QualType DestRecordTy;
2073 if (DestPTy) {
2074 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
2075 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
2076 DestRecordTy = DestPTy->getPointeeType();
2077 } else {
2078 isDynamicCastToVoid = false;
2079 SrcRecordTy = SrcTy;
2080 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
2081 }
2082
2083 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
2084
Anders Carlsson882d7902011-04-11 00:46:40 +00002085 // C++ [expr.dynamic.cast]p4:
2086 // If the value of v is a null pointer value in the pointer case, the result
2087 // is the null pointer value of type T.
David Majnemer1162d252014-06-22 19:05:33 +00002088 bool ShouldNullCheckSrcValue =
2089 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
2090 SrcRecordTy);
Craig Topper8a13c412014-05-21 05:09:00 +00002091
2092 llvm::BasicBlock *CastNull = nullptr;
2093 llvm::BasicBlock *CastNotNull = nullptr;
Anders Carlsson882d7902011-04-11 00:46:40 +00002094 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00002095
Anders Carlsson882d7902011-04-11 00:46:40 +00002096 if (ShouldNullCheckSrcValue) {
2097 CastNull = createBasicBlock("dynamic_cast.null");
2098 CastNotNull = createBasicBlock("dynamic_cast.notnull");
2099
John McCall7f416cc2015-09-08 08:05:57 +00002100 llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
Anders Carlsson882d7902011-04-11 00:46:40 +00002101 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2102 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00002103 }
2104
John McCall7f416cc2015-09-08 08:05:57 +00002105 llvm::Value *Value;
David Majnemer1162d252014-06-22 19:05:33 +00002106 if (isDynamicCastToVoid) {
John McCall7f416cc2015-09-08 08:05:57 +00002107 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00002108 DestTy);
2109 } else {
2110 assert(DestRecordTy->isRecordType() &&
2111 "destination type must be a record type!");
John McCall7f416cc2015-09-08 08:05:57 +00002112 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00002113 DestTy, DestRecordTy, CastEnd);
David Majnemer67528ea2015-11-23 03:01:14 +00002114 CastNotNull = Builder.GetInsertBlock();
David Majnemer1162d252014-06-22 19:05:33 +00002115 }
Anders Carlsson882d7902011-04-11 00:46:40 +00002116
2117 if (ShouldNullCheckSrcValue) {
2118 EmitBranch(CastEnd);
2119
2120 EmitBlock(CastNull);
2121 EmitBranch(CastEnd);
2122 }
2123
2124 EmitBlock(CastEnd);
2125
2126 if (ShouldNullCheckSrcValue) {
2127 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2128 PHI->addIncoming(Value, CastNotNull);
2129 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
2130
2131 Value = PHI;
2132 }
2133
2134 return Value;
Mike Stump65511702009-11-16 06:50:58 +00002135}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002136
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002137void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00002138 RunCleanupsScope Scope(*this);
John McCall7f416cc2015-09-08 08:05:57 +00002139 LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType());
Eli Friedman8631f3e82012-02-09 03:47:20 +00002140
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002141 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
James Y Knight53c76162015-07-17 18:21:37 +00002142 for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
2143 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00002144 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002145 // Emit initialization
David Blaikie40ed2972012-06-06 20:45:41 +00002146 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Alexey Bataev39c81e22014-08-28 04:28:19 +00002147 if (CurField->hasCapturedVLAType()) {
2148 auto VAT = CurField->getCapturedVLAType();
2149 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2150 } else {
Richard Smith30e304e2016-12-14 00:03:17 +00002151 EmitInitializerForField(*CurField, LV, *i);
Alexey Bataev39c81e22014-08-28 04:28:19 +00002152 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002153 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002154}