blob: 3eb4bd6b901eb95eb886377fc0bb830e9dac1d46 [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"
John McCallde0fe072017-08-15 21:42:52 +000019#include "ConstantEmitter.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000020#include "clang/CodeGen/CGFunctionInfo.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000021#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000022#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000023#include "llvm/IR/Intrinsics.h"
Anders Carlssonbbe277c2011-04-13 02:35:36 +000024
Anders Carlssoncc52f652009-09-22 22:53:17 +000025using namespace clang;
26using namespace CodeGen;
27
George Burgess IVd0a9e802017-02-23 22:07:35 +000028namespace {
29struct MemberCallInfo {
30 RequiredArgs ReqArgs;
31 // Number of prefix arguments for the call. Ignores the `this` pointer.
32 unsigned PrefixSize;
33};
34}
35
36static MemberCallInfo
Alexey Samsonovefa956c2016-03-10 00:20:33 +000037commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
38 llvm::Value *This, llvm::Value *ImplicitParam,
39 QualType ImplicitParamTy, const CallExpr *CE,
Richard Smith762672a2016-09-28 19:09:10 +000040 CallArgList &Args, CallArgList *RtlArgs) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000041 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
42 isa<CXXOperatorCallExpr>(CE));
Anders Carlsson27da15b2010-01-01 20:29:01 +000043 assert(MD->isInstance() &&
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000044 "Trying to emit a member or operator call expr on a static method!");
Reid Kleckner034e7272016-09-07 15:15:51 +000045 ASTContext &C = CGF.getContext();
Anders Carlsson27da15b2010-01-01 20:29:01 +000046
Anders Carlsson27da15b2010-01-01 20:29:01 +000047 // Push the this ptr.
Reid Kleckner034e7272016-09-07 15:15:51 +000048 const CXXRecordDecl *RD =
49 CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
50 Args.add(RValue::get(This),
51 RD ? C.getPointerType(C.getTypeDeclType(RD)) : C.VoidPtrTy);
Anders Carlsson27da15b2010-01-01 20:29:01 +000052
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +000053 // If there is an implicit parameter (e.g. VTT), emit it.
54 if (ImplicitParam) {
55 Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
Anders Carlssone36a6b32010-01-02 01:01:18 +000056 }
John McCalla729c622012-02-17 03:33:10 +000057
58 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
George Burgess IV419996c2016-06-16 23:06:04 +000059 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size(), MD);
George Burgess IVd0a9e802017-02-23 22:07:35 +000060 unsigned PrefixSize = Args.size() - 1;
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000061
John McCalla729c622012-02-17 03:33:10 +000062 // And the rest of the call args.
Richard Smith762672a2016-09-28 19:09:10 +000063 if (RtlArgs) {
64 // Special case: if the caller emitted the arguments right-to-left already
65 // (prior to emitting the *this argument), we're done. This happens for
66 // assignment operators.
67 Args.addFrom(*RtlArgs);
68 } else if (CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000069 // Special case: skip first argument of CXXOperatorCall (it is "this").
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000070 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
David Blaikief05779e2015-07-21 18:37:18 +000071 CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
David Majnemer0c0b6d92014-10-31 20:09:12 +000072 CE->getDirectCallee());
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000073 } else {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000074 assert(
75 FPT->getNumParams() == 0 &&
76 "No CallExpr specified for function with non-zero number of arguments");
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000077 }
George Burgess IVd0a9e802017-02-23 22:07:35 +000078 return {required, PrefixSize};
David Majnemer0c0b6d92014-10-31 20:09:12 +000079}
Anders Carlsson27da15b2010-01-01 20:29:01 +000080
David Majnemer0c0b6d92014-10-31 20:09:12 +000081RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
John McCallb92ab1a2016-10-26 23:46:34 +000082 const CXXMethodDecl *MD, const CGCallee &Callee,
83 ReturnValueSlot ReturnValue,
David Majnemer0c0b6d92014-10-31 20:09:12 +000084 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
Richard Smith762672a2016-09-28 19:09:10 +000085 const CallExpr *CE, CallArgList *RtlArgs) {
David Majnemer0c0b6d92014-10-31 20:09:12 +000086 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
87 CallArgList Args;
George Burgess IVd0a9e802017-02-23 22:07:35 +000088 MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
Richard Smith762672a2016-09-28 19:09:10 +000089 *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
George Burgess IVd0a9e802017-02-23 22:07:35 +000090 auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
91 Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);
John McCallb92ab1a2016-10-26 23:46:34 +000092 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +000093}
94
Alexey Samsonovae81bbb2016-03-10 00:20:37 +000095RValue CodeGenFunction::EmitCXXDestructorCall(
John McCallb92ab1a2016-10-26 23:46:34 +000096 const CXXDestructorDecl *DD, const CGCallee &Callee, llvm::Value *This,
Alexey Samsonovae81bbb2016-03-10 00:20:37 +000097 llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE,
98 StructorType Type) {
David Majnemer0c0b6d92014-10-31 20:09:12 +000099 CallArgList Args;
Alexey Samsonovae81bbb2016-03-10 00:20:37 +0000100 commonEmitCXXMemberOrOperatorCall(*this, DD, This, ImplicitParam,
Richard Smith762672a2016-09-28 19:09:10 +0000101 ImplicitParamTy, CE, Args, nullptr);
Alexey Samsonovae81bbb2016-03-10 00:20:37 +0000102 return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(DD, Type),
John McCallb92ab1a2016-10-26 23:46:34 +0000103 Callee, ReturnValueSlot(), Args);
104}
105
106RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
107 const CXXPseudoDestructorExpr *E) {
108 QualType DestroyedType = E->getDestroyedType();
109 if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
110 // Automatic Reference Counting:
111 // If the pseudo-expression names a retainable object with weak or
112 // strong lifetime, the object shall be released.
113 Expr *BaseExpr = E->getBase();
114 Address BaseValue = Address::invalid();
115 Qualifiers BaseQuals;
116
117 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
118 if (E->isArrow()) {
119 BaseValue = EmitPointerWithAlignment(BaseExpr);
120 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
121 BaseQuals = PTy->getPointeeType().getQualifiers();
122 } else {
123 LValue BaseLV = EmitLValue(BaseExpr);
124 BaseValue = BaseLV.getAddress();
125 QualType BaseTy = BaseExpr->getType();
126 BaseQuals = BaseTy.getQualifiers();
127 }
128
129 switch (DestroyedType.getObjCLifetime()) {
130 case Qualifiers::OCL_None:
131 case Qualifiers::OCL_ExplicitNone:
132 case Qualifiers::OCL_Autoreleasing:
133 break;
134
135 case Qualifiers::OCL_Strong:
136 EmitARCRelease(Builder.CreateLoad(BaseValue,
137 DestroyedType.isVolatileQualified()),
138 ARCPreciseLifetime);
139 break;
140
141 case Qualifiers::OCL_Weak:
142 EmitARCDestroyWeak(BaseValue);
143 break;
144 }
145 } else {
146 // C++ [expr.pseudo]p1:
147 // The result shall only be used as the operand for the function call
148 // operator (), and the result of such a call has type void. The only
149 // effect is the evaluation of the postfix-expression before the dot or
150 // arrow.
151 EmitIgnoredExpr(E->getBase());
152 }
153
154 return RValue::get(nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000155}
156
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000157static CXXRecordDecl *getCXXRecord(const Expr *E) {
158 QualType T = E->getType();
159 if (const PointerType *PTy = T->getAs<PointerType>())
160 T = PTy->getPointeeType();
161 const RecordType *Ty = T->castAs<RecordType>();
162 return cast<CXXRecordDecl>(Ty->getDecl());
163}
164
Francois Pichet64225792011-01-18 05:04:39 +0000165// Note: This function also emit constructor calls to support a MSVC
166// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000167RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
168 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +0000169 const Expr *callee = CE->getCallee()->IgnoreParens();
170
171 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000172 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +0000173
174 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000175 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
176
177 if (MD->isStatic()) {
178 // The method is static, emit it as we would a regular call.
John McCallb92ab1a2016-10-26 23:46:34 +0000179 CGCallee callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD), MD);
180 return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000181 ReturnValue);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000182 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000183
Nico Weberaad4af62014-12-03 01:21:41 +0000184 bool HasQualifier = ME->hasQualifier();
185 NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
186 bool IsArrow = ME->isArrow();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000187 const Expr *Base = ME->getBase();
Nico Weberaad4af62014-12-03 01:21:41 +0000188
189 return EmitCXXMemberOrOperatorMemberCallExpr(
190 CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
191}
192
193RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
194 const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
195 bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
196 const Expr *Base) {
197 assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
198
199 // Compute the object pointer.
200 bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000201
Craig Topper8a13c412014-05-21 05:09:00 +0000202 const CXXMethodDecl *DevirtualizedMethod = nullptr;
Akira Hatanaka22461672017-07-13 06:08:27 +0000203 if (CanUseVirtualCall &&
204 MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000205 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
206 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
207 assert(DevirtualizedMethod);
208 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
209 const Expr *Inner = Base->ignoreParenBaseCasts();
Alexey Bataev5bd68792014-09-29 10:32:21 +0000210 if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
211 MD->getReturnType().getCanonicalType())
212 // If the return types are not the same, this might be a case where more
213 // code needs to run to compensate for it. For example, the derived
214 // method might return a type that inherits form from the return
215 // type of MD and has a prefix.
216 // For now we just avoid devirtualizing these covariant cases.
217 DevirtualizedMethod = nullptr;
218 else if (getCXXRecord(Inner) == DevirtualizedClass)
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000219 // If the class of the Inner expression is where the dynamic method
220 // is defined, build the this pointer from it.
221 Base = Inner;
222 else if (getCXXRecord(Base) != DevirtualizedClass) {
223 // If the method is defined in a class that is not the best dynamic
224 // one or the one of the full expression, we would have to build
225 // a derived-to-base cast to compute the correct this pointer, but
226 // we don't have support for that yet, so do a virtual call.
Craig Topper8a13c412014-05-21 05:09:00 +0000227 DevirtualizedMethod = nullptr;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000228 }
229 }
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000230
Richard Smith762672a2016-09-28 19:09:10 +0000231 // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
232 // operator before the LHS.
233 CallArgList RtlArgStorage;
234 CallArgList *RtlArgs = nullptr;
235 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
236 if (OCE->isAssignmentOp()) {
237 RtlArgs = &RtlArgStorage;
238 EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
239 drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
Richard Smitha560ccf2016-09-29 21:30:12 +0000240 /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
Richard Smith762672a2016-09-28 19:09:10 +0000241 }
242 }
243
John McCall7f416cc2015-09-08 08:05:57 +0000244 Address This = Address::invalid();
Nico Weberaad4af62014-12-03 01:21:41 +0000245 if (IsArrow)
John McCall7f416cc2015-09-08 08:05:57 +0000246 This = EmitPointerWithAlignment(Base);
John McCalle26a8722010-12-04 08:14:53 +0000247 else
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000248 This = EmitLValue(Base).getAddress();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000249
Anders Carlsson27da15b2010-01-01 20:29:01 +0000250
Richard Smith419bd092015-04-29 19:26:57 +0000251 if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
Craig Topper8a13c412014-05-21 05:09:00 +0000252 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
Francois Pichet64225792011-01-18 05:04:39 +0000253 if (isa<CXXConstructorDecl>(MD) &&
254 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
Craig Topper8a13c412014-05-21 05:09:00 +0000255 return RValue::get(nullptr);
John McCall0d635f52010-09-03 01:26:39 +0000256
Nico Weberaad4af62014-12-03 01:21:41 +0000257 if (!MD->getParent()->mayInsertExtraPadding()) {
258 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
259 // We don't like to generate the trivial copy/move assignment operator
260 // when it isn't necessary; just produce the proper effect here.
Richard Smith762672a2016-09-28 19:09:10 +0000261 LValue RHS = isa<CXXOperatorCallExpr>(CE)
262 ? MakeNaturalAlignAddrLValue(
263 (*RtlArgs)[0].RV.getScalarVal(),
264 (*(CE->arg_begin() + 1))->getType())
265 : EmitLValue(*CE->arg_begin());
266 EmitAggregateAssign(This, RHS.getAddress(), CE->getType());
John McCall7f416cc2015-09-08 08:05:57 +0000267 return RValue::get(This.getPointer());
Nico Weberaad4af62014-12-03 01:21:41 +0000268 }
Alexey Samsonov525bf652014-08-25 21:58:56 +0000269
Nico Weberaad4af62014-12-03 01:21:41 +0000270 if (isa<CXXConstructorDecl>(MD) &&
271 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
272 // Trivial move and copy ctor are the same.
273 assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
John McCall7f416cc2015-09-08 08:05:57 +0000274 Address RHS = EmitLValue(*CE->arg_begin()).getAddress();
Benjamin Kramerf48ee442015-07-18 14:35:53 +0000275 EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType());
John McCall7f416cc2015-09-08 08:05:57 +0000276 return RValue::get(This.getPointer());
Nico Weberaad4af62014-12-03 01:21:41 +0000277 }
278 llvm_unreachable("unknown trivial member function");
Francois Pichet64225792011-01-18 05:04:39 +0000279 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000280 }
281
John McCall0d635f52010-09-03 01:26:39 +0000282 // Compute the function type we're calling.
Nico Weber3abfe952014-12-02 20:41:18 +0000283 const CXXMethodDecl *CalleeDecl =
284 DevirtualizedMethod ? DevirtualizedMethod : MD;
Craig Topper8a13c412014-05-21 05:09:00 +0000285 const CGFunctionInfo *FInfo = nullptr;
Nico Weber3abfe952014-12-02 20:41:18 +0000286 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000287 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
288 Dtor, StructorType::Complete);
Nico Weber3abfe952014-12-02 20:41:18 +0000289 else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000290 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
291 Ctor, StructorType::Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000292 else
Eli Friedmanade60972012-10-25 00:12:49 +0000293 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCall0d635f52010-09-03 01:26:39 +0000294
Reid Klecknere7de47e2013-07-22 13:51:44 +0000295 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000296
Ivan Krasind98f5d72016-11-17 00:39:48 +0000297 // C++11 [class.mfct.non-static]p2:
298 // If a non-static member function of a class X is called for an object that
299 // is not of type X, or of a type derived from X, the behavior is undefined.
300 SourceLocation CallLoc;
301 ASTContext &C = getContext();
302 if (CE)
303 CallLoc = CE->getExprLoc();
304
Vedant Kumar34b1fd62017-02-17 23:22:59 +0000305 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +0000306 if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
307 auto *IOA = CMCE->getImplicitObjectArgument();
308 bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);
309 if (IsImplicitObjectCXXThis)
310 SkippedChecks.set(SanitizerKind::Alignment, true);
311 if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA))
Vedant Kumar34b1fd62017-02-17 23:22:59 +0000312 SkippedChecks.set(SanitizerKind::Null, true);
Vedant Kumarffd7c882017-04-14 22:03:34 +0000313 }
Vedant Kumar34b1fd62017-02-17 23:22:59 +0000314 EmitTypeCheck(
315 isa<CXXConstructorDecl>(CalleeDecl) ? CodeGenFunction::TCK_ConstructorCall
316 : CodeGenFunction::TCK_MemberCall,
317 CallLoc, This.getPointer(), C.getRecordType(CalleeDecl->getParent()),
318 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
Ivan Krasind98f5d72016-11-17 00:39:48 +0000319
Vedant Kumar018f2662016-10-19 20:21:16 +0000320 // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
321 // 'CalleeDecl' instead.
322
Anders Carlsson27da15b2010-01-01 20:29:01 +0000323 // C++ [class.virtual]p12:
324 // Explicit qualification with the scope operator (5.1) suppresses the
325 // virtual call mechanism.
326 //
327 // We also don't emit a virtual call if the base expression has a record type
328 // because then we know what the type is.
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000329 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
John McCallb92ab1a2016-10-26 23:46:34 +0000330
John McCall0d635f52010-09-03 01:26:39 +0000331 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000332 assert(CE->arg_begin() == CE->arg_end() &&
333 "Destructor shouldn't have explicit parameters");
334 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
John McCall0d635f52010-09-03 01:26:39 +0000335 if (UseVirtualCall) {
Nico Weberaad4af62014-12-03 01:21:41 +0000336 CGM.getCXXABI().EmitVirtualDestructorCall(
337 *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
Anders Carlsson27da15b2010-01-01 20:29:01 +0000338 } else {
John McCallb92ab1a2016-10-26 23:46:34 +0000339 CGCallee Callee;
Nico Weberaad4af62014-12-03 01:21:41 +0000340 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
341 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000342 else if (!DevirtualizedMethod)
John McCallb92ab1a2016-10-26 23:46:34 +0000343 Callee = CGCallee::forDirect(
344 CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty),
345 Dtor);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000346 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000347 const CXXDestructorDecl *DDtor =
348 cast<CXXDestructorDecl>(DevirtualizedMethod);
John McCallb92ab1a2016-10-26 23:46:34 +0000349 Callee = CGCallee::forDirect(
350 CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty),
351 DDtor);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000352 }
Vedant Kumar018f2662016-10-19 20:21:16 +0000353 EmitCXXMemberOrOperatorCall(
354 CalleeDecl, Callee, ReturnValue, This.getPointer(),
355 /*ImplicitParam=*/nullptr, QualType(), CE, nullptr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000356 }
Craig Topper8a13c412014-05-21 05:09:00 +0000357 return RValue::get(nullptr);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000358 }
359
John McCallb92ab1a2016-10-26 23:46:34 +0000360 CGCallee Callee;
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000361 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
John McCallb92ab1a2016-10-26 23:46:34 +0000362 Callee = CGCallee::forDirect(
363 CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty),
364 Ctor);
John McCall0d635f52010-09-03 01:26:39 +0000365 } else if (UseVirtualCall) {
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000366 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty,
367 CE->getLocStart());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000368 } else {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +0000369 if (SanOpts.has(SanitizerKind::CFINVCall) &&
370 MD->getParent()->isDynamicClass()) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000371 llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy, MD->getParent());
Peter Collingbournefb532b92016-02-24 20:46:36 +0000372 EmitVTablePtrCheckForCall(MD->getParent(), VTable, CFITCK_NVCall,
373 CE->getLocStart());
Peter Collingbourne1a7488a2015-04-02 00:23:30 +0000374 }
375
Nico Weberaad4af62014-12-03 01:21:41 +0000376 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
377 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000378 else if (!DevirtualizedMethod)
John McCallb92ab1a2016-10-26 23:46:34 +0000379 Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), MD);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000380 else {
John McCallb92ab1a2016-10-26 23:46:34 +0000381 Callee = CGCallee::forDirect(
382 CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
383 DevirtualizedMethod);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000384 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000385 }
386
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000387 if (MD->isVirtual()) {
388 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
Reid Kleckner4b60f302016-05-03 18:44:29 +0000389 *this, CalleeDecl, This, UseVirtualCall);
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000390 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000391
Vedant Kumar018f2662016-10-19 20:21:16 +0000392 return EmitCXXMemberOrOperatorCall(
393 CalleeDecl, Callee, ReturnValue, This.getPointer(),
394 /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000395}
396
397RValue
398CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
399 ReturnValueSlot ReturnValue) {
400 const BinaryOperator *BO =
401 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
402 const Expr *BaseExpr = BO->getLHS();
403 const Expr *MemFnExpr = BO->getRHS();
404
405 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000406 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000407
Anders Carlsson27da15b2010-01-01 20:29:01 +0000408 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000409 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000410 const CXXRecordDecl *RD =
411 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
412
Anders Carlsson27da15b2010-01-01 20:29:01 +0000413 // Emit the 'this' pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000414 Address This = Address::invalid();
John McCalle3027922010-08-25 11:45:40 +0000415 if (BO->getOpcode() == BO_PtrMemI)
John McCall7f416cc2015-09-08 08:05:57 +0000416 This = EmitPointerWithAlignment(BaseExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000417 else
418 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000419
John McCall7f416cc2015-09-08 08:05:57 +0000420 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
Richard Smithe30752c2012-10-09 19:52:38 +0000421 QualType(MPT->getClass(), 0));
Richard Smith69d0d262012-08-24 00:54:33 +0000422
Richard Smithbde62d72016-09-26 23:56:57 +0000423 // Get the member function pointer.
424 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
425
John McCall475999d2010-08-22 00:05:51 +0000426 // Ask the ABI to load the callee. Note that This is modified.
John McCall7f416cc2015-09-08 08:05:57 +0000427 llvm::Value *ThisPtrForCall = nullptr;
John McCallb92ab1a2016-10-26 23:46:34 +0000428 CGCallee Callee =
John McCall7f416cc2015-09-08 08:05:57 +0000429 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
430 ThisPtrForCall, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000431
Anders Carlsson27da15b2010-01-01 20:29:01 +0000432 CallArgList Args;
433
434 QualType ThisType =
435 getContext().getPointerType(getContext().getTagDeclType(RD));
436
437 // Push the this ptr.
John McCall7f416cc2015-09-08 08:05:57 +0000438 Args.add(RValue::get(ThisPtrForCall), ThisType);
John McCall8dda7b22012-07-07 06:41:13 +0000439
George Burgess IV419996c2016-06-16 23:06:04 +0000440 RequiredArgs required =
441 RequiredArgs::forPrototypePlus(FPT, 1, /*FD=*/nullptr);
442
Anders Carlsson27da15b2010-01-01 20:29:01 +0000443 // And the rest of the call args
George Burgess IV419996c2016-06-16 23:06:04 +0000444 EmitCallArgs(Args, FPT, E->arguments());
George Burgess IVd0a9e802017-02-23 22:07:35 +0000445 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
446 /*PrefixSize=*/0),
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000447 Callee, ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000448}
449
450RValue
451CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
452 const CXXMethodDecl *MD,
453 ReturnValueSlot ReturnValue) {
454 assert(MD->isInstance() &&
455 "Trying to emit a member call expr on a static method!");
Nico Weberaad4af62014-12-03 01:21:41 +0000456 return EmitCXXMemberOrOperatorMemberCallExpr(
457 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
458 /*IsArrow=*/false, E->getArg(0));
Anders Carlsson27da15b2010-01-01 20:29:01 +0000459}
460
Peter Collingbournefe883422011-10-06 18:29:37 +0000461RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
462 ReturnValueSlot ReturnValue) {
463 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
464}
465
Eli Friedmanfde961d2011-10-14 02:27:24 +0000466static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000467 Address DestPtr,
Eli Friedmanfde961d2011-10-14 02:27:24 +0000468 const CXXRecordDecl *Base) {
469 if (Base->isEmpty())
470 return;
471
John McCall7f416cc2015-09-08 08:05:57 +0000472 DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
Eli Friedmanfde961d2011-10-14 02:27:24 +0000473
474 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
David Majnemer8671c6e2015-11-02 09:01:44 +0000475 CharUnits NVSize = Layout.getNonVirtualSize();
476
477 // We cannot simply zero-initialize the entire base sub-object if vbptrs are
478 // present, they are initialized by the most derived class before calling the
479 // constructor.
480 SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
481 Stores.emplace_back(CharUnits::Zero(), NVSize);
482
483 // Each store is split by the existence of a vbptr.
484 CharUnits VBPtrWidth = CGF.getPointerSize();
485 std::vector<CharUnits> VBPtrOffsets =
486 CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
487 for (CharUnits VBPtrOffset : VBPtrOffsets) {
David Majnemer7f980d82016-05-12 03:51:52 +0000488 // Stop before we hit any virtual base pointers located in virtual bases.
489 if (VBPtrOffset >= NVSize)
490 break;
David Majnemer8671c6e2015-11-02 09:01:44 +0000491 std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
492 CharUnits LastStoreOffset = LastStore.first;
493 CharUnits LastStoreSize = LastStore.second;
494
495 CharUnits SplitBeforeOffset = LastStoreOffset;
496 CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
497 assert(!SplitBeforeSize.isNegative() && "negative store size!");
498 if (!SplitBeforeSize.isZero())
499 Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
500
501 CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
502 CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
503 assert(!SplitAfterSize.isNegative() && "negative store size!");
504 if (!SplitAfterSize.isZero())
505 Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
506 }
Eli Friedmanfde961d2011-10-14 02:27:24 +0000507
508 // If the type contains a pointer to data member we can't memset it to zero.
509 // Instead, create a null constant and copy it to the destination.
510 // TODO: there are other patterns besides zero that we can usefully memset,
511 // like -1, which happens to be the pattern used by member-pointers.
512 // TODO: isZeroInitializable can be over-conservative in the case where a
513 // virtual base contains a member pointer.
David Majnemer8671c6e2015-11-02 09:01:44 +0000514 llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
515 if (!NullConstantForBase->isNullValue()) {
516 llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
517 CGF.CGM.getModule(), NullConstantForBase->getType(),
518 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
519 NullConstantForBase, Twine());
John McCall7f416cc2015-09-08 08:05:57 +0000520
521 CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
522 DestPtr.getAlignment());
Eli Friedmanfde961d2011-10-14 02:27:24 +0000523 NullVariable->setAlignment(Align.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +0000524
525 Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
Eli Friedmanfde961d2011-10-14 02:27:24 +0000526
527 // Get and call the appropriate llvm.memcpy overload.
David Majnemer8671c6e2015-11-02 09:01:44 +0000528 for (std::pair<CharUnits, CharUnits> Store : Stores) {
529 CharUnits StoreOffset = Store.first;
530 CharUnits StoreSize = Store.second;
531 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
532 CGF.Builder.CreateMemCpy(
533 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
534 CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
535 StoreSizeVal);
536 }
537
Eli Friedmanfde961d2011-10-14 02:27:24 +0000538 // Otherwise, just memset the whole thing to zero. This is legal
539 // because in LLVM, all default initializers (other than the ones we just
540 // handled above) are guaranteed to have a bit pattern of all zeros.
David Majnemer8671c6e2015-11-02 09:01:44 +0000541 } else {
542 for (std::pair<CharUnits, CharUnits> Store : Stores) {
543 CharUnits StoreOffset = Store.first;
544 CharUnits StoreSize = Store.second;
545 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
546 CGF.Builder.CreateMemSet(
547 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
548 CGF.Builder.getInt8(0), StoreSizeVal);
549 }
550 }
Eli Friedmanfde961d2011-10-14 02:27:24 +0000551}
552
Anders Carlsson27da15b2010-01-01 20:29:01 +0000553void
John McCall7a626f62010-09-15 10:14:12 +0000554CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
555 AggValueSlot Dest) {
556 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000557 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000558
559 // If we require zero initialization before (or instead of) calling the
560 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000561 // constructor, emit the zero initialization now, unless destination is
562 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000563 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
564 switch (E->getConstructionKind()) {
565 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000566 case CXXConstructExpr::CK_Complete:
John McCall7f416cc2015-09-08 08:05:57 +0000567 EmitNullInitialization(Dest.getAddress(), E->getType());
Eli Friedmanfde961d2011-10-14 02:27:24 +0000568 break;
569 case CXXConstructExpr::CK_VirtualBase:
570 case CXXConstructExpr::CK_NonVirtualBase:
John McCall7f416cc2015-09-08 08:05:57 +0000571 EmitNullBaseClassInitialization(*this, Dest.getAddress(),
572 CD->getParent());
Eli Friedmanfde961d2011-10-14 02:27:24 +0000573 break;
574 }
575 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000576
577 // If this is a call to a trivial default constructor, do nothing.
578 if (CD->isTrivial() && CD->isDefaultConstructor())
579 return;
580
John McCall8ea46b62010-09-18 00:58:34 +0000581 // Elide the constructor if we're constructing from a temporary.
582 // The temporary check is required because Sema sets this on NRVO
583 // returns.
Richard Smith9c6890a2012-11-01 22:30:59 +0000584 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000585 assert(getContext().hasSameUnqualifiedType(E->getType(),
586 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000587 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
588 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000589 return;
590 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000591 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000592
Alexey Bataeve7545b32016-04-29 09:39:50 +0000593 if (const ArrayType *arrayType
594 = getContext().getAsArrayType(E->getType())) {
John McCall7f416cc2015-09-08 08:05:57 +0000595 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E);
John McCallf677a8e2011-07-13 06:10:41 +0000596 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000597 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000598 bool ForVirtualBase = false;
Douglas Gregor61535002013-01-31 05:50:40 +0000599 bool Delegating = false;
600
Alexis Hunt271c3682011-05-03 20:19:28 +0000601 switch (E->getConstructionKind()) {
602 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000603 // We should be emitting a constructor; GlobalDecl will assert this
604 Type = CurGD.getCtorType();
Douglas Gregor61535002013-01-31 05:50:40 +0000605 Delegating = true;
Alexis Hunt271c3682011-05-03 20:19:28 +0000606 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000607
Alexis Hunt271c3682011-05-03 20:19:28 +0000608 case CXXConstructExpr::CK_Complete:
609 Type = Ctor_Complete;
610 break;
611
612 case CXXConstructExpr::CK_VirtualBase:
613 ForVirtualBase = true;
614 // fall-through
615
616 case CXXConstructExpr::CK_NonVirtualBase:
617 Type = Ctor_Base;
618 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000619
Anders Carlsson27da15b2010-01-01 20:29:01 +0000620 // Call the constructor.
John McCall7f416cc2015-09-08 08:05:57 +0000621 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
622 Dest.getAddress(), E);
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000623 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000624}
625
John McCall7f416cc2015-09-08 08:05:57 +0000626void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
627 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000628 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000629 Exp = E->getSubExpr();
630 assert(isa<CXXConstructExpr>(Exp) &&
631 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
632 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
633 const CXXConstructorDecl *CD = E->getConstructor();
634 RunCleanupsScope Scope(*this);
635
636 // If we require zero initialization before (or instead of) calling the
637 // constructor, as can be the case with a non-user-provided default
638 // constructor, emit the zero initialization now.
639 // FIXME. Do I still need this for a copy ctor synthesis?
640 if (E->requiresZeroInitialization())
641 EmitNullInitialization(Dest, E->getType());
642
Chandler Carruth99da11c2010-11-15 13:54:43 +0000643 assert(!getContext().getAsConstantArrayType(E->getType())
644 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Alexey Samsonov525bf652014-08-25 21:58:56 +0000645 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000646}
647
John McCall8ed55a52010-09-02 09:58:18 +0000648static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
649 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000650 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000651 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000652
John McCall7ec4b432011-05-16 01:05:12 +0000653 // No cookie is required if the operator new[] being used is the
654 // reserved placement operator new[].
655 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000656 return CharUnits::Zero();
657
John McCall284c48f2011-01-27 09:37:56 +0000658 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000659}
660
John McCall036f2f62011-05-15 07:14:44 +0000661static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
662 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000663 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000664 llvm::Value *&numElements,
665 llvm::Value *&sizeWithoutCookie) {
666 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000667
John McCall036f2f62011-05-15 07:14:44 +0000668 if (!e->isArray()) {
669 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
670 sizeWithoutCookie
671 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
672 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000673 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000674
John McCall036f2f62011-05-15 07:14:44 +0000675 // The width of size_t.
676 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
677
John McCall8ed55a52010-09-02 09:58:18 +0000678 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000679 llvm::APInt cookieSize(sizeWidth,
680 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000681
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000682 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000683 // We multiply the size of all dimensions for NumElements.
684 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCallde0fe072017-08-15 21:42:52 +0000685 numElements =
686 ConstantEmitter(CGF).tryEmitAbstract(e->getArraySize(), e->getType());
Nick Lewycky07527622017-02-13 23:49:55 +0000687 if (!numElements)
688 numElements = CGF.EmitScalarExpr(e->getArraySize());
John McCall036f2f62011-05-15 07:14:44 +0000689 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000690
John McCall036f2f62011-05-15 07:14:44 +0000691 // The number of elements can be have an arbitrary integer type;
692 // essentially, we need to multiply it by a constant factor, add a
693 // cookie size, and verify that the result is representable as a
694 // size_t. That's just a gloss, though, and it's wrong in one
695 // important way: if the count is negative, it's an error even if
696 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000697 bool isSigned
698 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000699 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000700 = cast<llvm::IntegerType>(numElements->getType());
701 unsigned numElementsWidth = numElementsType->getBitWidth();
702
703 // Compute the constant factor.
704 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000705 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000706 = CGF.getContext().getAsConstantArrayType(type)) {
707 type = CAT->getElementType();
708 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000709 }
710
John McCall036f2f62011-05-15 07:14:44 +0000711 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
712 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
713 typeSizeMultiplier *= arraySizeMultiplier;
714
715 // This will be a size_t.
716 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000717
Chris Lattner32ac5832010-07-20 21:55:52 +0000718 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
719 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000720 if (llvm::ConstantInt *numElementsC =
721 dyn_cast<llvm::ConstantInt>(numElements)) {
722 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000723
John McCall036f2f62011-05-15 07:14:44 +0000724 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000725
John McCall036f2f62011-05-15 07:14:44 +0000726 // If 'count' was a negative number, it's an overflow.
727 if (isSigned && count.isNegative())
728 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000729
John McCall036f2f62011-05-15 07:14:44 +0000730 // We want to do all this arithmetic in size_t. If numElements is
731 // wider than that, check whether it's already too big, and if so,
732 // overflow.
733 else if (numElementsWidth > sizeWidth &&
734 numElementsWidth - sizeWidth > count.countLeadingZeros())
735 hasAnyOverflow = true;
736
737 // Okay, compute a count at the right width.
738 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
739
Sebastian Redlf862eb62012-02-22 17:37:52 +0000740 // If there is a brace-initializer, we cannot allocate fewer elements than
741 // there are initializers. If we do, that's treated like an overflow.
742 if (adjustedCount.ult(minElements))
743 hasAnyOverflow = true;
744
John McCall036f2f62011-05-15 07:14:44 +0000745 // Scale numElements by that. This might overflow, but we don't
746 // care because it only overflows if allocationSize does, too, and
747 // if that overflows then we shouldn't use this.
748 numElements = llvm::ConstantInt::get(CGF.SizeTy,
749 adjustedCount * arraySizeMultiplier);
750
751 // Compute the size before cookie, and track whether it overflowed.
752 bool overflow;
753 llvm::APInt allocationSize
754 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
755 hasAnyOverflow |= overflow;
756
757 // Add in the cookie, and check whether it's overflowed.
758 if (cookieSize != 0) {
759 // Save the current size without a cookie. This shouldn't be
760 // used if there was overflow.
761 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
762
763 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
764 hasAnyOverflow |= overflow;
765 }
766
767 // On overflow, produce a -1 so operator new will fail.
Aaron Ballman455f42c2014-08-28 17:24:14 +0000768 if (hasAnyOverflow) {
769 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
770 } else {
John McCall036f2f62011-05-15 07:14:44 +0000771 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
Aaron Ballman455f42c2014-08-28 17:24:14 +0000772 }
John McCall036f2f62011-05-15 07:14:44 +0000773
774 // Otherwise, we might need to use the overflow intrinsics.
775 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000776 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000777 // 1) if isSigned, we need to check whether numElements is negative;
778 // 2) if numElementsWidth > sizeWidth, we need to check whether
779 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000780 // 3) if minElements > 0, we need to check whether numElements is smaller
781 // than that.
782 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000783 // sizeWithoutCookie := numElements * typeSizeMultiplier
784 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000785 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000786 // size := sizeWithoutCookie + cookieSize
787 // and check whether it overflows.
788
Craig Topper8a13c412014-05-21 05:09:00 +0000789 llvm::Value *hasOverflow = nullptr;
John McCall036f2f62011-05-15 07:14:44 +0000790
791 // If numElementsWidth > sizeWidth, then one way or another, we're
792 // going to have to do a comparison for (2), and this happens to
793 // take care of (1), too.
794 if (numElementsWidth > sizeWidth) {
795 llvm::APInt threshold(numElementsWidth, 1);
796 threshold <<= sizeWidth;
797
798 llvm::Value *thresholdV
799 = llvm::ConstantInt::get(numElementsType, threshold);
800
801 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
802 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
803
804 // Otherwise, if we're signed, we want to sext up to size_t.
805 } else if (isSigned) {
806 if (numElementsWidth < sizeWidth)
807 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
808
809 // If there's a non-1 type size multiplier, then we can do the
810 // signedness check at the same time as we do the multiply
811 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000812 // unsigned overflow. Otherwise, we have to do it here. But at least
813 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000814 if (typeSizeMultiplier == 1)
815 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000816 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000817
818 // Otherwise, zext up to size_t if necessary.
819 } else if (numElementsWidth < sizeWidth) {
820 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
821 }
822
823 assert(numElements->getType() == CGF.SizeTy);
824
Sebastian Redlf862eb62012-02-22 17:37:52 +0000825 if (minElements) {
826 // Don't allow allocation of fewer elements than we have initializers.
827 if (!hasOverflow) {
828 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
829 llvm::ConstantInt::get(CGF.SizeTy, minElements));
830 } else if (numElementsWidth > sizeWidth) {
831 // The other existing overflow subsumes this check.
832 // We do an unsigned comparison, since any signed value < -1 is
833 // taken care of either above or below.
834 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
835 CGF.Builder.CreateICmpULT(numElements,
836 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
837 }
838 }
839
John McCall036f2f62011-05-15 07:14:44 +0000840 size = numElements;
841
842 // Multiply by the type size if necessary. This multiplier
843 // includes all the factors for nested arrays.
844 //
845 // This step also causes numElements to be scaled up by the
846 // nested-array factor if necessary. Overflow on this computation
847 // can be ignored because the result shouldn't be used if
848 // allocation fails.
849 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000850 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000851 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000852
853 llvm::Value *tsmV =
854 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
855 llvm::Value *result =
David Blaikie43f9bb72015-05-18 22:14:03 +0000856 CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
John McCall036f2f62011-05-15 07:14:44 +0000857
858 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
859 if (hasOverflow)
860 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
861 else
862 hasOverflow = overflowed;
863
864 size = CGF.Builder.CreateExtractValue(result, 0);
865
866 // Also scale up numElements by the array size multiplier.
867 if (arraySizeMultiplier != 1) {
868 // If the base element type size is 1, then we can re-use the
869 // multiply we just did.
870 if (typeSize.isOne()) {
871 assert(arraySizeMultiplier == typeSizeMultiplier);
872 numElements = size;
873
874 // Otherwise we need a separate multiply.
875 } else {
876 llvm::Value *asmV =
877 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
878 numElements = CGF.Builder.CreateMul(numElements, asmV);
879 }
880 }
881 } else {
882 // numElements doesn't need to be scaled.
883 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000884 }
885
John McCall036f2f62011-05-15 07:14:44 +0000886 // Add in the cookie size if necessary.
887 if (cookieSize != 0) {
888 sizeWithoutCookie = size;
889
John McCall036f2f62011-05-15 07:14:44 +0000890 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000891 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000892
893 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
894 llvm::Value *result =
David Blaikie43f9bb72015-05-18 22:14:03 +0000895 CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
John McCall036f2f62011-05-15 07:14:44 +0000896
897 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
898 if (hasOverflow)
899 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
900 else
901 hasOverflow = overflowed;
902
903 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000904 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000905
John McCall036f2f62011-05-15 07:14:44 +0000906 // If we had any possibility of dynamic overflow, make a select to
907 // overwrite 'size' with an all-ones value, which should cause
908 // operator new to throw.
909 if (hasOverflow)
Aaron Ballman455f42c2014-08-28 17:24:14 +0000910 size = CGF.Builder.CreateSelect(hasOverflow,
911 llvm::Constant::getAllOnesValue(CGF.SizeTy),
912 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000913 }
John McCall8ed55a52010-09-02 09:58:18 +0000914
John McCall036f2f62011-05-15 07:14:44 +0000915 if (cookieSize == 0)
916 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000917 else
John McCall036f2f62011-05-15 07:14:44 +0000918 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000919
John McCall036f2f62011-05-15 07:14:44 +0000920 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000921}
922
Sebastian Redlf862eb62012-02-22 17:37:52 +0000923static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
John McCall7f416cc2015-09-08 08:05:57 +0000924 QualType AllocType, Address NewPtr) {
Richard Smith1c96bc52013-12-11 01:40:16 +0000925 // FIXME: Refactor with EmitExprAsInit.
John McCall47fb9502013-03-07 21:37:08 +0000926 switch (CGF.getEvaluationKind(AllocType)) {
927 case TEK_Scalar:
David Blaikiea2c11242014-12-10 19:04:09 +0000928 CGF.EmitScalarInit(Init, nullptr,
John McCall7f416cc2015-09-08 08:05:57 +0000929 CGF.MakeAddrLValue(NewPtr, AllocType), false);
John McCall47fb9502013-03-07 21:37:08 +0000930 return;
931 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000932 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
John McCall47fb9502013-03-07 21:37:08 +0000933 /*isInit*/ true);
934 return;
935 case TEK_Aggregate: {
John McCall7a626f62010-09-15 10:14:12 +0000936 AggValueSlot Slot
John McCall7f416cc2015-09-08 08:05:57 +0000937 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000938 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000939 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000940 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000941 CGF.EmitAggExpr(Init, Slot);
John McCall47fb9502013-03-07 21:37:08 +0000942 return;
John McCall7a626f62010-09-15 10:14:12 +0000943 }
John McCall47fb9502013-03-07 21:37:08 +0000944 }
945 llvm_unreachable("bad evaluation kind");
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000946}
947
David Blaikiefb901c7a2015-04-04 15:12:29 +0000948void CodeGenFunction::EmitNewArrayInitializer(
949 const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
John McCall7f416cc2015-09-08 08:05:57 +0000950 Address BeginPtr, llvm::Value *NumElements,
David Blaikiefb901c7a2015-04-04 15:12:29 +0000951 llvm::Value *AllocSizeWithoutCookie) {
Richard Smith06a67e22014-06-03 06:58:52 +0000952 // If we have a type with trivial initialization and no initializer,
953 // there's nothing to do.
Sebastian Redl6047f072012-02-16 12:22:20 +0000954 if (!E->hasInitializer())
Richard Smith06a67e22014-06-03 06:58:52 +0000955 return;
John McCall99210dc2011-09-15 06:49:18 +0000956
John McCall7f416cc2015-09-08 08:05:57 +0000957 Address CurPtr = BeginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000958
Richard Smith06a67e22014-06-03 06:58:52 +0000959 unsigned InitListElements = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000960
961 const Expr *Init = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +0000962 Address EndOfInit = Address::invalid();
Richard Smith06a67e22014-06-03 06:58:52 +0000963 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
964 EHScopeStack::stable_iterator Cleanup;
965 llvm::Instruction *CleanupDominator = nullptr;
Richard Smith1c96bc52013-12-11 01:40:16 +0000966
John McCall7f416cc2015-09-08 08:05:57 +0000967 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
968 CharUnits ElementAlign =
969 BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
970
Richard Smith0511d232016-10-05 22:41:02 +0000971 // Attempt to perform zero-initialization using memset.
972 auto TryMemsetInitialization = [&]() -> bool {
973 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
974 // we can initialize with a memset to -1.
975 if (!CGM.getTypes().isZeroInitializable(ElementType))
976 return false;
977
978 // Optimization: since zero initialization will just set the memory
979 // to all zeroes, generate a single memset to do it in one shot.
980
981 // Subtract out the size of any elements we've already initialized.
982 auto *RemainingSize = AllocSizeWithoutCookie;
983 if (InitListElements) {
984 // We know this can't overflow; we check this when doing the allocation.
985 auto *InitializedSize = llvm::ConstantInt::get(
986 RemainingSize->getType(),
987 getContext().getTypeSizeInChars(ElementType).getQuantity() *
988 InitListElements);
989 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
990 }
991
992 // Create the memset.
993 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
994 return true;
995 };
996
Sebastian Redlf862eb62012-02-22 17:37:52 +0000997 // If the initializer is an initializer list, first do the explicit elements.
998 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith0511d232016-10-05 22:41:02 +0000999 // Initializing from a (braced) string literal is a special case; the init
1000 // list element does not initialize a (single) array element.
1001 if (ILE->isStringLiteralInit()) {
1002 // Initialize the initial portion of length equal to that of the string
1003 // literal. The allocation must be for at least this much; we emitted a
1004 // check for that earlier.
1005 AggValueSlot Slot =
1006 AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
1007 AggValueSlot::IsDestructed,
1008 AggValueSlot::DoesNotNeedGCBarriers,
1009 AggValueSlot::IsNotAliased);
1010 EmitAggExpr(ILE->getInit(0), Slot);
1011
1012 // Move past these elements.
1013 InitListElements =
1014 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1015 ->getSize().getZExtValue();
1016 CurPtr =
1017 Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1018 Builder.getSize(InitListElements),
1019 "string.init.end"),
1020 CurPtr.getAlignment().alignmentAtOffset(InitListElements *
1021 ElementSize));
1022
1023 // Zero out the rest, if any remain.
1024 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1025 if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
1026 bool OK = TryMemsetInitialization();
1027 (void)OK;
1028 assert(OK && "couldn't memset character type?");
1029 }
1030 return;
1031 }
1032
Richard Smith06a67e22014-06-03 06:58:52 +00001033 InitListElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +00001034
Richard Smith1c96bc52013-12-11 01:40:16 +00001035 // If this is a multi-dimensional array new, we will initialize multiple
1036 // elements with each init list element.
1037 QualType AllocType = E->getAllocatedType();
1038 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
1039 AllocType->getAsArrayTypeUnsafe())) {
David Blaikiefb901c7a2015-04-04 15:12:29 +00001040 ElementTy = ConvertTypeForMem(AllocType);
John McCall7f416cc2015-09-08 08:05:57 +00001041 CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
Richard Smith06a67e22014-06-03 06:58:52 +00001042 InitListElements *= getContext().getConstantArrayElementCount(CAT);
Richard Smith1c96bc52013-12-11 01:40:16 +00001043 }
1044
Richard Smith06a67e22014-06-03 06:58:52 +00001045 // Enter a partial-destruction Cleanup if necessary.
1046 if (needsEHCleanup(DtorKind)) {
1047 // In principle we could tell the Cleanup where we are more
Chad Rosierf62290a2012-02-24 00:13:55 +00001048 // directly, but the control flow can get so varied here that it
1049 // would actually be quite complex. Therefore we go through an
1050 // alloca.
John McCall7f416cc2015-09-08 08:05:57 +00001051 EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
1052 "array.init.end");
1053 CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
1054 pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
1055 ElementType, ElementAlign,
Richard Smith06a67e22014-06-03 06:58:52 +00001056 getDestroyer(DtorKind));
1057 Cleanup = EHStack.stable_begin();
Chad Rosierf62290a2012-02-24 00:13:55 +00001058 }
1059
John McCall7f416cc2015-09-08 08:05:57 +00001060 CharUnits StartAlign = CurPtr.getAlignment();
Sebastian Redlf862eb62012-02-22 17:37:52 +00001061 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +00001062 // Tell the cleanup that it needs to destroy up to this
1063 // element. TODO: some of these stores can be trivially
1064 // observed to be unnecessary.
John McCall7f416cc2015-09-08 08:05:57 +00001065 if (EndOfInit.isValid()) {
1066 auto FinishedPtr =
1067 Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
1068 Builder.CreateStore(FinishedPtr, EndOfInit);
1069 }
Richard Smith06a67e22014-06-03 06:58:52 +00001070 // FIXME: If the last initializer is an incomplete initializer list for
1071 // an array, and we have an array filler, we can fold together the two
1072 // initialization loops.
Richard Smith1c96bc52013-12-11 01:40:16 +00001073 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
Richard Smith06a67e22014-06-03 06:58:52 +00001074 ILE->getInit(i)->getType(), CurPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001075 CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1076 Builder.getSize(1),
1077 "array.exp.next"),
1078 StartAlign.alignmentAtOffset((i + 1) * ElementSize));
Sebastian Redlf862eb62012-02-22 17:37:52 +00001079 }
1080
1081 // The remaining elements are filled with the array filler expression.
1082 Init = ILE->getArrayFiller();
Richard Smith1c96bc52013-12-11 01:40:16 +00001083
Richard Smith06a67e22014-06-03 06:58:52 +00001084 // Extract the initializer for the individual array elements by pulling
1085 // out the array filler from all the nested initializer lists. This avoids
1086 // generating a nested loop for the initialization.
1087 while (Init && Init->getType()->isConstantArrayType()) {
1088 auto *SubILE = dyn_cast<InitListExpr>(Init);
1089 if (!SubILE)
1090 break;
1091 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
1092 Init = SubILE->getArrayFiller();
1093 }
1094
1095 // Switch back to initializing one base element at a time.
John McCall7f416cc2015-09-08 08:05:57 +00001096 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
Sebastian Redlf862eb62012-02-22 17:37:52 +00001097 }
1098
Richard Smith454a7cd2014-06-03 08:26:00 +00001099 // If all elements have already been initialized, skip any further
1100 // initialization.
1101 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1102 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1103 // If there was a Cleanup, deactivate it.
1104 if (CleanupDominator)
1105 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1106 return;
1107 }
1108
1109 assert(Init && "have trailing elements to initialize but no initializer");
1110
Richard Smith06a67e22014-06-03 06:58:52 +00001111 // If this is a constructor call, try to optimize it out, and failing that
1112 // emit a single loop to initialize all remaining elements.
Richard Smith454a7cd2014-06-03 08:26:00 +00001113 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +00001114 CXXConstructorDecl *Ctor = CCE->getConstructor();
1115 if (Ctor->isTrivial()) {
1116 // If new expression did not specify value-initialization, then there
1117 // is no initialization.
1118 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
1119 return;
1120
1121 if (TryMemsetInitialization())
1122 return;
1123 }
1124
1125 // Store the new Cleanup position for irregular Cleanups.
1126 //
1127 // FIXME: Share this cleanup with the constructor call emission rather than
1128 // having it create a cleanup of its own.
John McCall7f416cc2015-09-08 08:05:57 +00001129 if (EndOfInit.isValid())
1130 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
Richard Smith06a67e22014-06-03 06:58:52 +00001131
1132 // Emit a constructor call loop to initialize the remaining elements.
1133 if (InitListElements)
1134 NumElements = Builder.CreateSub(
1135 NumElements,
1136 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001137 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
Richard Smith06a67e22014-06-03 06:58:52 +00001138 CCE->requiresZeroInitialization());
Chandler Carruthe6c980c2014-05-03 09:16:57 +00001139 return;
1140 }
1141
Richard Smith06a67e22014-06-03 06:58:52 +00001142 // If this is value-initialization, we can usually use memset.
1143 ImplicitValueInitExpr IVIE(ElementType);
Richard Smith454a7cd2014-06-03 08:26:00 +00001144 if (isa<ImplicitValueInitExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +00001145 if (TryMemsetInitialization())
1146 return;
1147
1148 // Switch to an ImplicitValueInitExpr for the element type. This handles
1149 // only one case: multidimensional array new of pointers to members. In
1150 // all other cases, we already have an initializer for the array element.
1151 Init = &IVIE;
1152 }
1153
1154 // At this point we should have found an initializer for the individual
1155 // elements of the array.
1156 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
1157 "got wrong type of element to initialize");
1158
Richard Smith454a7cd2014-06-03 08:26:00 +00001159 // If we have an empty initializer list, we can usually use memset.
1160 if (auto *ILE = dyn_cast<InitListExpr>(Init))
1161 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1162 return;
Richard Smith06a67e22014-06-03 06:58:52 +00001163
Yunzhong Gaocb779302015-06-10 00:27:52 +00001164 // If we have a struct whose every field is value-initialized, we can
1165 // usually use memset.
1166 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1167 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1168 if (RType->getDecl()->isStruct()) {
Richard Smith872307e2016-03-08 22:17:41 +00001169 unsigned NumElements = 0;
1170 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1171 NumElements = CXXRD->getNumBases();
Yunzhong Gaocb779302015-06-10 00:27:52 +00001172 for (auto *Field : RType->getDecl()->fields())
1173 if (!Field->isUnnamedBitfield())
Richard Smith872307e2016-03-08 22:17:41 +00001174 ++NumElements;
1175 // FIXME: Recurse into nested InitListExprs.
1176 if (ILE->getNumInits() == NumElements)
Yunzhong Gaocb779302015-06-10 00:27:52 +00001177 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1178 if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
Richard Smith872307e2016-03-08 22:17:41 +00001179 --NumElements;
1180 if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
Yunzhong Gaocb779302015-06-10 00:27:52 +00001181 return;
1182 }
1183 }
1184 }
1185
Richard Smith06a67e22014-06-03 06:58:52 +00001186 // Create the loop blocks.
1187 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1188 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
1189 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
1190
1191 // Find the end of the array, hoisted out of the loop.
1192 llvm::Value *EndPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001193 Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
John McCall99210dc2011-09-15 06:49:18 +00001194
Sebastian Redlf862eb62012-02-22 17:37:52 +00001195 // If the number of elements isn't constant, we have to now check if there is
1196 // anything left to initialize.
Richard Smith06a67e22014-06-03 06:58:52 +00001197 if (!ConstNum) {
John McCall7f416cc2015-09-08 08:05:57 +00001198 llvm::Value *IsEmpty =
1199 Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
Richard Smith06a67e22014-06-03 06:58:52 +00001200 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
John McCall99210dc2011-09-15 06:49:18 +00001201 }
1202
1203 // Enter the loop.
Richard Smith06a67e22014-06-03 06:58:52 +00001204 EmitBlock(LoopBB);
John McCall99210dc2011-09-15 06:49:18 +00001205
1206 // Set up the current-element phi.
Richard Smith06a67e22014-06-03 06:58:52 +00001207 llvm::PHINode *CurPtrPhi =
John McCall7f416cc2015-09-08 08:05:57 +00001208 Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1209 CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
1210
1211 CurPtr = Address(CurPtrPhi, ElementAlign);
John McCall99210dc2011-09-15 06:49:18 +00001212
Richard Smith06a67e22014-06-03 06:58:52 +00001213 // Store the new Cleanup position for irregular Cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00001214 if (EndOfInit.isValid())
1215 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
Chad Rosierf62290a2012-02-24 00:13:55 +00001216
Richard Smith06a67e22014-06-03 06:58:52 +00001217 // Enter a partial-destruction Cleanup if necessary.
1218 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
John McCall7f416cc2015-09-08 08:05:57 +00001219 pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
1220 ElementType, ElementAlign,
Richard Smith06a67e22014-06-03 06:58:52 +00001221 getDestroyer(DtorKind));
1222 Cleanup = EHStack.stable_begin();
1223 CleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +00001224 }
1225
1226 // Emit the initializer into this element.
Richard Smith06a67e22014-06-03 06:58:52 +00001227 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
John McCall99210dc2011-09-15 06:49:18 +00001228
Richard Smith06a67e22014-06-03 06:58:52 +00001229 // Leave the Cleanup if we entered one.
1230 if (CleanupDominator) {
1231 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1232 CleanupDominator->eraseFromParent();
John McCallf4beacd2011-11-10 10:43:54 +00001233 }
John McCall99210dc2011-09-15 06:49:18 +00001234
Faisal Vali57ae0562013-12-14 00:40:05 +00001235 // Advance to the next element by adjusting the pointer type as necessary.
Richard Smith06a67e22014-06-03 06:58:52 +00001236 llvm::Value *NextPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001237 Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
1238 "array.next");
Richard Smith06a67e22014-06-03 06:58:52 +00001239
John McCall99210dc2011-09-15 06:49:18 +00001240 // Check whether we've gotten to the end of the array and, if so,
1241 // exit the loop.
Richard Smith06a67e22014-06-03 06:58:52 +00001242 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1243 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1244 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
John McCall99210dc2011-09-15 06:49:18 +00001245
Richard Smith06a67e22014-06-03 06:58:52 +00001246 EmitBlock(ContBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +00001247}
1248
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001249static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
David Blaikiefb901c7a2015-04-04 15:12:29 +00001250 QualType ElementType, llvm::Type *ElementTy,
John McCall7f416cc2015-09-08 08:05:57 +00001251 Address NewPtr, llvm::Value *NumElements,
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001252 llvm::Value *AllocSizeWithoutCookie) {
David Blaikie9b479662015-01-25 01:19:10 +00001253 ApplyDebugLocation DL(CGF, E);
Richard Smith06a67e22014-06-03 06:58:52 +00001254 if (E->isArray())
David Blaikiefb901c7a2015-04-04 15:12:29 +00001255 CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
Richard Smith06a67e22014-06-03 06:58:52 +00001256 AllocSizeWithoutCookie);
1257 else if (const Expr *Init = E->getInitializer())
David Blaikie66e41972015-01-14 07:38:27 +00001258 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001259}
1260
Richard Smith8d0dc312013-07-21 23:12:18 +00001261/// Emit a call to an operator new or operator delete function, as implicitly
1262/// created by new-expressions and delete-expressions.
1263static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
John McCallb92ab1a2016-10-26 23:46:34 +00001264 const FunctionDecl *CalleeDecl,
Richard Smith8d0dc312013-07-21 23:12:18 +00001265 const FunctionProtoType *CalleeType,
1266 const CallArgList &Args) {
1267 llvm::Instruction *CallOrInvoke;
John McCallb92ab1a2016-10-26 23:46:34 +00001268 llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
1269 CGCallee Callee = CGCallee::forDirect(CalleePtr, CalleeDecl);
Richard Smith8d0dc312013-07-21 23:12:18 +00001270 RValue RV =
Peter Collingbournef7706832014-12-12 23:41:25 +00001271 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1272 Args, CalleeType, /*chainCall=*/false),
John McCallb92ab1a2016-10-26 23:46:34 +00001273 Callee, ReturnValueSlot(), Args, &CallOrInvoke);
Richard Smith8d0dc312013-07-21 23:12:18 +00001274
1275 /// C++1y [expr.new]p10:
1276 /// [In a new-expression,] an implementation is allowed to omit a call
1277 /// to a replaceable global allocation function.
1278 ///
1279 /// We model such elidable calls with the 'builtin' attribute.
John McCallb92ab1a2016-10-26 23:46:34 +00001280 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1281 if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola6956d582013-10-22 14:23:09 +00001282 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smith8d0dc312013-07-21 23:12:18 +00001283 // FIXME: Add addAttribute to CallSite.
1284 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
Reid Klecknerde864822017-03-21 16:57:30 +00001285 CI->addAttribute(llvm::AttributeList::FunctionIndex,
Richard Smith8d0dc312013-07-21 23:12:18 +00001286 llvm::Attribute::Builtin);
1287 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
Reid Klecknerde864822017-03-21 16:57:30 +00001288 II->addAttribute(llvm::AttributeList::FunctionIndex,
Richard Smith8d0dc312013-07-21 23:12:18 +00001289 llvm::Attribute::Builtin);
1290 else
1291 llvm_unreachable("unexpected kind of call instruction");
1292 }
1293
1294 return RV;
1295}
1296
Richard Smith760520b2014-06-03 23:27:44 +00001297RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1298 const Expr *Arg,
1299 bool IsDelete) {
1300 CallArgList Args;
1301 const Stmt *ArgS = Arg;
David Blaikief05779e2015-07-21 18:37:18 +00001302 EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS));
Richard Smith760520b2014-06-03 23:27:44 +00001303 // Find the allocation or deallocation function that we're calling.
1304 ASTContext &Ctx = getContext();
1305 DeclarationName Name = Ctx.DeclarationNames
1306 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1307 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
Richard Smith599bed72014-06-05 00:43:02 +00001308 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1309 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1310 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
Richard Smith760520b2014-06-03 23:27:44 +00001311 llvm_unreachable("predeclared global operator new/delete is missing");
1312}
1313
Richard Smith5b349582017-10-13 01:55:36 +00001314namespace {
1315/// The parameters to pass to a usual operator delete.
1316struct UsualDeleteParams {
1317 bool DestroyingDelete = false;
1318 bool Size = false;
1319 bool Alignment = false;
1320};
1321}
1322
1323static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {
1324 UsualDeleteParams Params;
1325
1326 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00001327 auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
Richard Smith189e52f2016-10-10 06:42:31 +00001328
Richard Smithb2f0f052016-10-10 18:54:32 +00001329 // The first argument is always a void*.
1330 ++AI;
1331
Richard Smith5b349582017-10-13 01:55:36 +00001332 // The next parameter may be a std::destroying_delete_t.
1333 if (FD->isDestroyingOperatorDelete()) {
1334 Params.DestroyingDelete = true;
1335 assert(AI != AE);
1336 ++AI;
1337 }
Richard Smithb2f0f052016-10-10 18:54:32 +00001338
Richard Smith5b349582017-10-13 01:55:36 +00001339 // Figure out what other parameters we should be implicitly passing.
Richard Smithb2f0f052016-10-10 18:54:32 +00001340 if (AI != AE && (*AI)->isIntegerType()) {
Richard Smith5b349582017-10-13 01:55:36 +00001341 Params.Size = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00001342 ++AI;
1343 }
1344
1345 if (AI != AE && (*AI)->isAlignValT()) {
Richard Smith5b349582017-10-13 01:55:36 +00001346 Params.Alignment = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00001347 ++AI;
1348 }
1349
1350 assert(AI == AE && "unexpected usual deallocation function parameter");
Richard Smith5b349582017-10-13 01:55:36 +00001351 return Params;
Richard Smithb2f0f052016-10-10 18:54:32 +00001352}
1353
1354namespace {
1355 /// A cleanup to call the given 'operator delete' function upon abnormal
1356 /// exit from a new expression. Templated on a traits type that deals with
1357 /// ensuring that the arguments dominate the cleanup if necessary.
1358 template<typename Traits>
1359 class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1360 /// Type used to hold llvm::Value*s.
1361 typedef typename Traits::ValueTy ValueTy;
1362 /// Type used to hold RValues.
1363 typedef typename Traits::RValueTy RValueTy;
1364 struct PlacementArg {
1365 RValueTy ArgValue;
1366 QualType ArgType;
1367 };
1368
1369 unsigned NumPlacementArgs : 31;
1370 unsigned PassAlignmentToPlacementDelete : 1;
1371 const FunctionDecl *OperatorDelete;
1372 ValueTy Ptr;
1373 ValueTy AllocSize;
1374 CharUnits AllocAlign;
1375
1376 PlacementArg *getPlacementArgs() {
1377 return reinterpret_cast<PlacementArg *>(this + 1);
1378 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00001379
1380 public:
1381 static size_t getExtraSize(size_t NumPlacementArgs) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001382 return NumPlacementArgs * sizeof(PlacementArg);
Daniel Jaspere9abe642016-10-10 14:13:55 +00001383 }
1384
1385 CallDeleteDuringNew(size_t NumPlacementArgs,
Richard Smithb2f0f052016-10-10 18:54:32 +00001386 const FunctionDecl *OperatorDelete, ValueTy Ptr,
1387 ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1388 CharUnits AllocAlign)
1389 : NumPlacementArgs(NumPlacementArgs),
1390 PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1391 OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1392 AllocAlign(AllocAlign) {}
Daniel Jaspere9abe642016-10-10 14:13:55 +00001393
Richard Smithb2f0f052016-10-10 18:54:32 +00001394 void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
Daniel Jaspere9abe642016-10-10 14:13:55 +00001395 assert(I < NumPlacementArgs && "index out of range");
Richard Smithb2f0f052016-10-10 18:54:32 +00001396 getPlacementArgs()[I] = {Arg, Type};
Daniel Jaspere9abe642016-10-10 14:13:55 +00001397 }
1398
1399 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smithb2f0f052016-10-10 18:54:32 +00001400 const FunctionProtoType *FPT =
1401 OperatorDelete->getType()->getAs<FunctionProtoType>();
Daniel Jaspere9abe642016-10-10 14:13:55 +00001402 CallArgList DeleteArgs;
1403
Richard Smith5b349582017-10-13 01:55:36 +00001404 // The first argument is always a void* (or C* for a destroying operator
1405 // delete for class type C).
Richard Smithb2f0f052016-10-10 18:54:32 +00001406 DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
Daniel Jaspere9abe642016-10-10 14:13:55 +00001407
Richard Smithb2f0f052016-10-10 18:54:32 +00001408 // Figure out what other parameters we should be implicitly passing.
Richard Smith5b349582017-10-13 01:55:36 +00001409 UsualDeleteParams Params;
Richard Smithb2f0f052016-10-10 18:54:32 +00001410 if (NumPlacementArgs) {
1411 // A placement deallocation function is implicitly passed an alignment
1412 // if the placement allocation function was, but is never passed a size.
Richard Smith5b349582017-10-13 01:55:36 +00001413 Params.Alignment = PassAlignmentToPlacementDelete;
Richard Smithb2f0f052016-10-10 18:54:32 +00001414 } else {
1415 // For a non-placement new-expression, 'operator delete' can take a
1416 // size and/or an alignment if it has the right parameters.
Richard Smith5b349582017-10-13 01:55:36 +00001417 Params = getUsualDeleteParams(OperatorDelete);
John McCall7f9c92a2010-09-17 00:50:28 +00001418 }
1419
Richard Smith5b349582017-10-13 01:55:36 +00001420 assert(!Params.DestroyingDelete &&
1421 "should not call destroying delete in a new-expression");
1422
Richard Smithb2f0f052016-10-10 18:54:32 +00001423 // The second argument can be a std::size_t (for non-placement delete).
Richard Smith5b349582017-10-13 01:55:36 +00001424 if (Params.Size)
Richard Smithb2f0f052016-10-10 18:54:32 +00001425 DeleteArgs.add(Traits::get(CGF, AllocSize),
1426 CGF.getContext().getSizeType());
1427
1428 // The next (second or third) argument can be a std::align_val_t, which
1429 // is an enum whose underlying type is std::size_t.
1430 // FIXME: Use the right type as the parameter type. Note that in a call
1431 // to operator delete(size_t, ...), we may not have it available.
Richard Smith5b349582017-10-13 01:55:36 +00001432 if (Params.Alignment)
Richard Smithb2f0f052016-10-10 18:54:32 +00001433 DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1434 CGF.SizeTy, AllocAlign.getQuantity())),
1435 CGF.getContext().getSizeType());
1436
John McCall7f9c92a2010-09-17 00:50:28 +00001437 // Pass the rest of the arguments, which must match exactly.
1438 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001439 auto Arg = getPlacementArgs()[I];
1440 DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
John McCall7f9c92a2010-09-17 00:50:28 +00001441 }
1442
1443 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001444 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7f9c92a2010-09-17 00:50:28 +00001445 }
1446 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001447}
John McCall7f9c92a2010-09-17 00:50:28 +00001448
1449/// Enter a cleanup to call 'operator delete' if the initializer in a
1450/// new-expression throws.
1451static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1452 const CXXNewExpr *E,
John McCall7f416cc2015-09-08 08:05:57 +00001453 Address NewPtr,
John McCall7f9c92a2010-09-17 00:50:28 +00001454 llvm::Value *AllocSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00001455 CharUnits AllocAlign,
John McCall7f9c92a2010-09-17 00:50:28 +00001456 const CallArgList &NewArgs) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001457 unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1458
John McCall7f9c92a2010-09-17 00:50:28 +00001459 // If we're not inside a conditional branch, then the cleanup will
1460 // dominate and we can do the easier (and more efficient) thing.
1461 if (!CGF.isInConditionalBranch()) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001462 struct DirectCleanupTraits {
1463 typedef llvm::Value *ValueTy;
1464 typedef RValue RValueTy;
1465 static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1466 static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1467 };
1468
1469 typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1470
1471 DirectCleanup *Cleanup = CGF.EHStack
1472 .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
1473 E->getNumPlacementArgs(),
1474 E->getOperatorDelete(),
1475 NewPtr.getPointer(),
1476 AllocSize,
1477 E->passAlignment(),
1478 AllocAlign);
1479 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1480 auto &Arg = NewArgs[I + NumNonPlacementArgs];
1481 Cleanup->setPlacementArg(I, Arg.RV, Arg.Ty);
1482 }
John McCall7f9c92a2010-09-17 00:50:28 +00001483
1484 return;
1485 }
1486
1487 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001488 DominatingValue<RValue>::saved_type SavedNewPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001489 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
John McCallcb5f77f2011-01-28 10:53:53 +00001490 DominatingValue<RValue>::saved_type SavedAllocSize =
1491 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001492
Richard Smithb2f0f052016-10-10 18:54:32 +00001493 struct ConditionalCleanupTraits {
1494 typedef DominatingValue<RValue>::saved_type ValueTy;
1495 typedef DominatingValue<RValue>::saved_type RValueTy;
1496 static RValue get(CodeGenFunction &CGF, ValueTy V) {
1497 return V.restore(CGF);
1498 }
1499 };
1500 typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1501
1502 ConditionalCleanup *Cleanup = CGF.EHStack
1503 .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
1504 E->getNumPlacementArgs(),
1505 E->getOperatorDelete(),
1506 SavedNewPtr,
1507 SavedAllocSize,
1508 E->passAlignment(),
1509 AllocAlign);
1510 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1511 auto &Arg = NewArgs[I + NumNonPlacementArgs];
1512 Cleanup->setPlacementArg(I, DominatingValue<RValue>::save(CGF, Arg.RV),
1513 Arg.Ty);
1514 }
John McCall7f9c92a2010-09-17 00:50:28 +00001515
John McCallf4beacd2011-11-10 10:43:54 +00001516 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001517}
1518
Anders Carlssoncc52f652009-09-22 22:53:17 +00001519llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001520 // The element type being allocated.
1521 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001522
John McCall75f94982011-03-07 03:12:35 +00001523 // 1. Build a call to the allocation function.
1524 FunctionDecl *allocator = E->getOperatorNew();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001525
Sebastian Redlf862eb62012-02-22 17:37:52 +00001526 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1527 unsigned minElements = 0;
1528 if (E->isArray() && E->hasInitializer()) {
Richard Smith0511d232016-10-05 22:41:02 +00001529 const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
1530 if (ILE && ILE->isStringLiteralInit())
1531 minElements =
1532 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1533 ->getSize().getZExtValue();
1534 else if (ILE)
Sebastian Redlf862eb62012-02-22 17:37:52 +00001535 minElements = ILE->getNumInits();
1536 }
1537
Craig Topper8a13c412014-05-21 05:09:00 +00001538 llvm::Value *numElements = nullptr;
1539 llvm::Value *allocSizeWithoutCookie = nullptr;
John McCall75f94982011-03-07 03:12:35 +00001540 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001541 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1542 allocSizeWithoutCookie);
Richard Smithb2f0f052016-10-10 18:54:32 +00001543 CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00001544
John McCall7ec4b432011-05-16 01:05:12 +00001545 // Emit the allocation call. If the allocator is a global placement
1546 // operator, just "inline" it directly.
John McCall7f416cc2015-09-08 08:05:57 +00001547 Address allocation = Address::invalid();
1548 CallArgList allocatorArgs;
John McCall7ec4b432011-05-16 01:05:12 +00001549 if (allocator->isReservedGlobalPlacementOperator()) {
John McCall53dcf942015-09-29 23:55:17 +00001550 assert(E->getNumPlacementArgs() == 1);
1551 const Expr *arg = *E->placement_arguments().begin();
1552
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001553 LValueBaseInfo BaseInfo;
1554 allocation = EmitPointerWithAlignment(arg, &BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +00001555
1556 // The pointer expression will, in many cases, be an opaque void*.
1557 // In these cases, discard the computed alignment and use the
1558 // formal alignment of the allocated type.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001559 if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
Richard Smithb2f0f052016-10-10 18:54:32 +00001560 allocation = Address(allocation.getPointer(), allocAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001561
John McCall53dcf942015-09-29 23:55:17 +00001562 // Set up allocatorArgs for the call to operator delete if it's not
1563 // the reserved global operator.
1564 if (E->getOperatorDelete() &&
1565 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1566 allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1567 allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
1568 }
1569
John McCall7ec4b432011-05-16 01:05:12 +00001570 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001571 const FunctionProtoType *allocatorType =
1572 allocator->getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00001573 unsigned ParamsToSkip = 0;
John McCall7f416cc2015-09-08 08:05:57 +00001574
1575 // The allocation size is the first argument.
1576 QualType sizeType = getContext().getSizeType();
1577 allocatorArgs.add(RValue::get(allocSize), sizeType);
Richard Smithb2f0f052016-10-10 18:54:32 +00001578 ++ParamsToSkip;
John McCall7f416cc2015-09-08 08:05:57 +00001579
Richard Smithb2f0f052016-10-10 18:54:32 +00001580 if (allocSize != allocSizeWithoutCookie) {
1581 CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1582 allocAlign = std::max(allocAlign, cookieAlign);
1583 }
1584
1585 // The allocation alignment may be passed as the second argument.
1586 if (E->passAlignment()) {
1587 QualType AlignValT = sizeType;
1588 if (allocatorType->getNumParams() > 1) {
1589 AlignValT = allocatorType->getParamType(1);
1590 assert(getContext().hasSameUnqualifiedType(
1591 AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
1592 sizeType) &&
1593 "wrong type for alignment parameter");
1594 ++ParamsToSkip;
1595 } else {
1596 // Corner case, passing alignment to 'operator new(size_t, ...)'.
1597 assert(allocator->isVariadic() && "can't pass alignment to allocator");
1598 }
1599 allocatorArgs.add(
1600 RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1601 AlignValT);
1602 }
1603
1604 // FIXME: Why do we not pass a CalleeDecl here?
John McCall7f416cc2015-09-08 08:05:57 +00001605 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
Vedant Kumared00ea02017-03-06 05:28:22 +00001606 /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
John McCall7f416cc2015-09-08 08:05:57 +00001607
1608 RValue RV =
1609 EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1610
Richard Smithb2f0f052016-10-10 18:54:32 +00001611 // If this was a call to a global replaceable allocation function that does
1612 // not take an alignment argument, the allocator is known to produce
1613 // storage that's suitably aligned for any object that fits, up to a known
1614 // threshold. Otherwise assume it's suitably aligned for the allocated type.
1615 CharUnits allocationAlign = allocAlign;
1616 if (!E->passAlignment() &&
1617 allocator->isReplaceableGlobalAllocationFunction()) {
1618 unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1619 Target.getNewAlign(), getContext().getTypeSize(allocType)));
1620 allocationAlign = std::max(
1621 allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
John McCall7f416cc2015-09-08 08:05:57 +00001622 }
1623
1624 allocation = Address(RV.getScalarVal(), allocationAlign);
John McCall7ec4b432011-05-16 01:05:12 +00001625 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001626
John McCall75f94982011-03-07 03:12:35 +00001627 // Emit a null check on the allocation result if the allocation
1628 // function is allowed to return null (because it has a non-throwing
Richard Smith902a0232015-02-14 01:52:20 +00001629 // exception spec or is the reserved placement new) and we have an
John McCall75f94982011-03-07 03:12:35 +00001630 // interesting initializer.
Richard Smith902a0232015-02-14 01:52:20 +00001631 bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001632 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001633
Craig Topper8a13c412014-05-21 05:09:00 +00001634 llvm::BasicBlock *nullCheckBB = nullptr;
1635 llvm::BasicBlock *contBB = nullptr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001636
John McCallf7dcf322011-03-07 01:52:56 +00001637 // The null-check means that the initializer is conditionally
1638 // evaluated.
1639 ConditionalEvaluation conditional(*this);
1640
John McCall75f94982011-03-07 03:12:35 +00001641 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001642 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001643
1644 nullCheckBB = Builder.GetInsertBlock();
1645 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1646 contBB = createBasicBlock("new.cont");
1647
John McCall7f416cc2015-09-08 08:05:57 +00001648 llvm::Value *isNull =
1649 Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
John McCall75f94982011-03-07 03:12:35 +00001650 Builder.CreateCondBr(isNull, contBB, notNullBB);
1651 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001652 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001653
John McCall824c2f52010-09-14 07:57:04 +00001654 // If there's an operator delete, enter a cleanup to call it if an
1655 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001656 EHScopeStack::stable_iterator operatorDeleteCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001657 llvm::Instruction *cleanupDominator = nullptr;
John McCall7ec4b432011-05-16 01:05:12 +00001658 if (E->getOperatorDelete() &&
1659 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001660 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1661 allocatorArgs);
John McCall75f94982011-03-07 03:12:35 +00001662 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001663 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001664 }
1665
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001666 assert((allocSize == allocSizeWithoutCookie) ==
1667 CalculateCookiePadding(*this, E).isZero());
1668 if (allocSize != allocSizeWithoutCookie) {
1669 assert(E->isArray());
1670 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1671 numElements,
1672 E, allocType);
1673 }
1674
David Blaikiefb901c7a2015-04-04 15:12:29 +00001675 llvm::Type *elementTy = ConvertTypeForMem(allocType);
John McCall7f416cc2015-09-08 08:05:57 +00001676 Address result = Builder.CreateElementBitCast(allocation, elementTy);
John McCall824c2f52010-09-14 07:57:04 +00001677
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001678 // Passing pointer through invariant.group.barrier to avoid propagation of
1679 // vptrs information which may be included in previous type.
Piotr Padlewski31fd99c2017-05-20 08:56:18 +00001680 // To not break LTO with different optimizations levels, we do it regardless
1681 // of optimization level.
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001682 if (CGM.getCodeGenOpts().StrictVTablePointers &&
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001683 allocator->isReservedGlobalPlacementOperator())
1684 result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()),
1685 result.getAlignment());
1686
David Blaikiefb901c7a2015-04-04 15:12:29 +00001687 EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
John McCall99210dc2011-09-15 06:49:18 +00001688 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001689 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001690 // NewPtr is a pointer to the base element type. If we're
1691 // allocating an array of arrays, we'll need to cast back to the
1692 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001693 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall7f416cc2015-09-08 08:05:57 +00001694 if (result.getType() != resultType)
John McCall75f94982011-03-07 03:12:35 +00001695 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001696 }
John McCall824c2f52010-09-14 07:57:04 +00001697
1698 // Deactivate the 'operator delete' cleanup if we finished
1699 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001700 if (operatorDeleteCleanup.isValid()) {
1701 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1702 cleanupDominator->eraseFromParent();
1703 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001704
John McCall7f416cc2015-09-08 08:05:57 +00001705 llvm::Value *resultPtr = result.getPointer();
John McCall75f94982011-03-07 03:12:35 +00001706 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001707 conditional.end(*this);
1708
John McCall75f94982011-03-07 03:12:35 +00001709 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1710 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001711
John McCall7f416cc2015-09-08 08:05:57 +00001712 llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
1713 PHI->addIncoming(resultPtr, notNullBB);
1714 PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
John McCall75f94982011-03-07 03:12:35 +00001715 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001716
John McCall7f416cc2015-09-08 08:05:57 +00001717 resultPtr = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001718 }
John McCall8ed55a52010-09-02 09:58:18 +00001719
John McCall7f416cc2015-09-08 08:05:57 +00001720 return resultPtr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001721}
1722
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001723void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
Richard Smithb2f0f052016-10-10 18:54:32 +00001724 llvm::Value *Ptr, QualType DeleteTy,
1725 llvm::Value *NumElements,
1726 CharUnits CookieSize) {
1727 assert((!NumElements && CookieSize.isZero()) ||
1728 DeleteFD->getOverloadedOperator() == OO_Array_Delete);
John McCall8ed55a52010-09-02 09:58:18 +00001729
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001730 const FunctionProtoType *DeleteFTy =
1731 DeleteFD->getType()->getAs<FunctionProtoType>();
1732
1733 CallArgList DeleteArgs;
1734
Richard Smith5b349582017-10-13 01:55:36 +00001735 auto Params = getUsualDeleteParams(DeleteFD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001736 auto ParamTypeIt = DeleteFTy->param_type_begin();
1737
1738 // Pass the pointer itself.
1739 QualType ArgTy = *ParamTypeIt++;
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001740 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001741 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001742
Richard Smith5b349582017-10-13 01:55:36 +00001743 // Pass the std::destroying_delete tag if present.
1744 if (Params.DestroyingDelete) {
1745 QualType DDTag = *ParamTypeIt++;
1746 // Just pass an 'undef'. We expect the tag type to be an empty struct.
1747 auto *V = llvm::UndefValue::get(getTypes().ConvertType(DDTag));
1748 DeleteArgs.add(RValue::get(V), DDTag);
1749 }
1750
Richard Smithb2f0f052016-10-10 18:54:32 +00001751 // Pass the size if the delete function has a size_t parameter.
Richard Smith5b349582017-10-13 01:55:36 +00001752 if (Params.Size) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001753 QualType SizeType = *ParamTypeIt++;
1754 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1755 llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1756 DeleteTypeSize.getQuantity());
1757
1758 // For array new, multiply by the number of elements.
1759 if (NumElements)
1760 Size = Builder.CreateMul(Size, NumElements);
1761
1762 // If there is a cookie, add the cookie size.
1763 if (!CookieSize.isZero())
1764 Size = Builder.CreateAdd(
1765 Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1766
1767 DeleteArgs.add(RValue::get(Size), SizeType);
1768 }
1769
1770 // Pass the alignment if the delete function has an align_val_t parameter.
Richard Smith5b349582017-10-13 01:55:36 +00001771 if (Params.Alignment) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001772 QualType AlignValType = *ParamTypeIt++;
1773 CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits(
1774 getContext().getTypeAlignIfKnown(DeleteTy));
1775 llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1776 DeleteTypeAlign.getQuantity());
1777 DeleteArgs.add(RValue::get(Align), AlignValType);
1778 }
1779
1780 assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1781 "unknown parameter to usual delete function");
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001782
1783 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001784 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001785}
1786
John McCall8ed55a52010-09-02 09:58:18 +00001787namespace {
1788 /// Calls the given 'operator delete' on a single object.
David Blaikie7e70d682015-08-18 22:40:54 +00001789 struct CallObjectDelete final : EHScopeStack::Cleanup {
John McCall8ed55a52010-09-02 09:58:18 +00001790 llvm::Value *Ptr;
1791 const FunctionDecl *OperatorDelete;
1792 QualType ElementType;
1793
1794 CallObjectDelete(llvm::Value *Ptr,
1795 const FunctionDecl *OperatorDelete,
1796 QualType ElementType)
1797 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1798
Craig Topper4f12f102014-03-12 06:41:41 +00001799 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001800 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1801 }
1802 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001803}
John McCall8ed55a52010-09-02 09:58:18 +00001804
David Majnemer0c0b6d92014-10-31 20:09:12 +00001805void
1806CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1807 llvm::Value *CompletePtr,
1808 QualType ElementType) {
1809 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1810 OperatorDelete, ElementType);
1811}
1812
Richard Smith5b349582017-10-13 01:55:36 +00001813/// Emit the code for deleting a single object with a destroying operator
1814/// delete. If the element type has a non-virtual destructor, Ptr has already
1815/// been converted to the type of the parameter of 'operator delete'. Otherwise
1816/// Ptr points to an object of the static type.
1817static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,
1818 const CXXDeleteExpr *DE, Address Ptr,
1819 QualType ElementType) {
1820 auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();
1821 if (Dtor && Dtor->isVirtual())
1822 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1823 Dtor);
1824 else
1825 CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.getPointer(), ElementType);
1826}
1827
John McCall8ed55a52010-09-02 09:58:18 +00001828/// Emit the code for deleting a single object.
1829static void EmitObjectDelete(CodeGenFunction &CGF,
David Majnemer08681372014-11-01 07:37:17 +00001830 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001831 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001832 QualType ElementType) {
Ivan Krasind98f5d72016-11-17 00:39:48 +00001833 // C++11 [expr.delete]p3:
1834 // If the static type of the object to be deleted is different from its
1835 // dynamic type, the static type shall be a base class of the dynamic type
1836 // of the object to be deleted and the static type shall have a virtual
1837 // destructor or the behavior is undefined.
1838 CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall,
1839 DE->getExprLoc(), Ptr.getPointer(),
1840 ElementType);
1841
Richard Smith5b349582017-10-13 01:55:36 +00001842 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1843 assert(!OperatorDelete->isDestroyingOperatorDelete());
1844
John McCall8ed55a52010-09-02 09:58:18 +00001845 // Find the destructor for the type, if applicable. If the
1846 // destructor is virtual, we'll just emit the vcall and return.
Craig Topper8a13c412014-05-21 05:09:00 +00001847 const CXXDestructorDecl *Dtor = nullptr;
John McCall8ed55a52010-09-02 09:58:18 +00001848 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1849 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001850 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001851 Dtor = RD->getDestructor();
1852
1853 if (Dtor->isVirtual()) {
David Majnemer08681372014-11-01 07:37:17 +00001854 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1855 Dtor);
John McCall8ed55a52010-09-02 09:58:18 +00001856 return;
1857 }
1858 }
1859 }
1860
1861 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001862 // This doesn't have to a conditional cleanup because we're going
1863 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001864 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
John McCall7f416cc2015-09-08 08:05:57 +00001865 Ptr.getPointer(),
1866 OperatorDelete, ElementType);
John McCall8ed55a52010-09-02 09:58:18 +00001867
1868 if (Dtor)
1869 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001870 /*ForVirtualBase=*/false,
1871 /*Delegating=*/false,
1872 Ptr);
John McCall460ce582015-10-22 18:38:17 +00001873 else if (auto Lifetime = ElementType.getObjCLifetime()) {
1874 switch (Lifetime) {
John McCall31168b02011-06-15 23:02:42 +00001875 case Qualifiers::OCL_None:
1876 case Qualifiers::OCL_ExplicitNone:
1877 case Qualifiers::OCL_Autoreleasing:
1878 break;
John McCall8ed55a52010-09-02 09:58:18 +00001879
John McCall7f416cc2015-09-08 08:05:57 +00001880 case Qualifiers::OCL_Strong:
1881 CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001882 break;
John McCall31168b02011-06-15 23:02:42 +00001883
1884 case Qualifiers::OCL_Weak:
1885 CGF.EmitARCDestroyWeak(Ptr);
1886 break;
1887 }
1888 }
1889
John McCall8ed55a52010-09-02 09:58:18 +00001890 CGF.PopCleanupBlock();
1891}
1892
1893namespace {
1894 /// Calls the given 'operator delete' on an array of objects.
David Blaikie7e70d682015-08-18 22:40:54 +00001895 struct CallArrayDelete final : EHScopeStack::Cleanup {
John McCall8ed55a52010-09-02 09:58:18 +00001896 llvm::Value *Ptr;
1897 const FunctionDecl *OperatorDelete;
1898 llvm::Value *NumElements;
1899 QualType ElementType;
1900 CharUnits CookieSize;
1901
1902 CallArrayDelete(llvm::Value *Ptr,
1903 const FunctionDecl *OperatorDelete,
1904 llvm::Value *NumElements,
1905 QualType ElementType,
1906 CharUnits CookieSize)
1907 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1908 ElementType(ElementType), CookieSize(CookieSize) {}
1909
Craig Topper4f12f102014-03-12 06:41:41 +00001910 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smithb2f0f052016-10-10 18:54:32 +00001911 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
1912 CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001913 }
1914 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001915}
John McCall8ed55a52010-09-02 09:58:18 +00001916
1917/// Emit the code for deleting an array of objects.
1918static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001919 const CXXDeleteExpr *E,
John McCall7f416cc2015-09-08 08:05:57 +00001920 Address deletedPtr,
John McCallca2c56f2011-07-13 01:41:37 +00001921 QualType elementType) {
Craig Topper8a13c412014-05-21 05:09:00 +00001922 llvm::Value *numElements = nullptr;
1923 llvm::Value *allocatedPtr = nullptr;
John McCallca2c56f2011-07-13 01:41:37 +00001924 CharUnits cookieSize;
1925 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1926 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001927
John McCallca2c56f2011-07-13 01:41:37 +00001928 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001929
1930 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001931 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001932 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001933 allocatedPtr, operatorDelete,
1934 numElements, elementType,
1935 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001936
John McCallca2c56f2011-07-13 01:41:37 +00001937 // Destroy the elements.
1938 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1939 assert(numElements && "no element count for a type with a destructor!");
1940
John McCall7f416cc2015-09-08 08:05:57 +00001941 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1942 CharUnits elementAlign =
1943 deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
1944
1945 llvm::Value *arrayBegin = deletedPtr.getPointer();
John McCallca2c56f2011-07-13 01:41:37 +00001946 llvm::Value *arrayEnd =
John McCall7f416cc2015-09-08 08:05:57 +00001947 CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001948
1949 // Note that it is legal to allocate a zero-length array, and we
1950 // can never fold the check away because the length should always
1951 // come from a cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001952 CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
John McCallca2c56f2011-07-13 01:41:37 +00001953 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001954 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001955 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001956 }
1957
John McCallca2c56f2011-07-13 01:41:37 +00001958 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001959 CGF.PopCleanupBlock();
1960}
1961
Anders Carlssoncc52f652009-09-22 22:53:17 +00001962void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001963 const Expr *Arg = E->getArgument();
John McCall7f416cc2015-09-08 08:05:57 +00001964 Address Ptr = EmitPointerWithAlignment(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001965
1966 // Null check the pointer.
1967 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1968 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1969
John McCall7f416cc2015-09-08 08:05:57 +00001970 llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001971
1972 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1973 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001974
Richard Smith5b349582017-10-13 01:55:36 +00001975 QualType DeleteTy = E->getDestroyedType();
1976
1977 // A destroying operator delete overrides the entire operation of the
1978 // delete expression.
1979 if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {
1980 EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy);
1981 EmitBlock(DeleteEnd);
1982 return;
1983 }
1984
John McCall8ed55a52010-09-02 09:58:18 +00001985 // We might be deleting a pointer to array. If so, GEP down to the
1986 // first non-array element.
1987 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
John McCall8ed55a52010-09-02 09:58:18 +00001988 if (DeleteTy->isConstantArrayType()) {
1989 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001990 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001991
1992 GEP.push_back(Zero); // point at the outermost array
1993
1994 // For each layer of array type we're pointing at:
1995 while (const ConstantArrayType *Arr
1996 = getContext().getAsConstantArrayType(DeleteTy)) {
1997 // 1. Unpeel the array type.
1998 DeleteTy = Arr->getElementType();
1999
2000 // 2. GEP to the first element of the array.
2001 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00002002 }
John McCall8ed55a52010-09-02 09:58:18 +00002003
John McCall7f416cc2015-09-08 08:05:57 +00002004 Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
2005 Ptr.getAlignment());
Anders Carlssoncc52f652009-09-22 22:53:17 +00002006 }
2007
John McCall7f416cc2015-09-08 08:05:57 +00002008 assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00002009
Reid Kleckner7270ef52015-03-19 17:03:58 +00002010 if (E->isArrayForm()) {
2011 EmitArrayDelete(*this, E, Ptr, DeleteTy);
2012 } else {
2013 EmitObjectDelete(*this, E, Ptr, DeleteTy);
2014 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00002015
Anders Carlssoncc52f652009-09-22 22:53:17 +00002016 EmitBlock(DeleteEnd);
2017}
Mike Stumpc9b231c2009-11-15 08:09:41 +00002018
David Majnemer1c3d95e2014-07-19 00:17:06 +00002019static bool isGLValueFromPointerDeref(const Expr *E) {
2020 E = E->IgnoreParens();
2021
2022 if (const auto *CE = dyn_cast<CastExpr>(E)) {
2023 if (!CE->getSubExpr()->isGLValue())
2024 return false;
2025 return isGLValueFromPointerDeref(CE->getSubExpr());
2026 }
2027
2028 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
2029 return isGLValueFromPointerDeref(OVE->getSourceExpr());
2030
2031 if (const auto *BO = dyn_cast<BinaryOperator>(E))
2032 if (BO->getOpcode() == BO_Comma)
2033 return isGLValueFromPointerDeref(BO->getRHS());
2034
2035 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
2036 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
2037 isGLValueFromPointerDeref(ACO->getFalseExpr());
2038
2039 // C++11 [expr.sub]p1:
2040 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
2041 if (isa<ArraySubscriptExpr>(E))
2042 return true;
2043
2044 if (const auto *UO = dyn_cast<UnaryOperator>(E))
2045 if (UO->getOpcode() == UO_Deref)
2046 return true;
2047
2048 return false;
2049}
2050
Warren Hunt747e3012014-06-18 21:15:55 +00002051static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00002052 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00002053 // Get the vtable pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002054 Address ThisPtr = CGF.EmitLValue(E).getAddress();
Anders Carlsson940f02d2011-04-18 00:57:03 +00002055
2056 // C++ [expr.typeid]p2:
2057 // If the glvalue expression is obtained by applying the unary * operator to
2058 // a pointer and the pointer is a null pointer value, the typeid expression
2059 // throws the std::bad_typeid exception.
David Majnemer1c3d95e2014-07-19 00:17:06 +00002060 //
2061 // However, this paragraph's intent is not clear. We choose a very generous
2062 // interpretation which implores us to consider comma operators, conditional
2063 // operators, parentheses and other such constructs.
David Majnemer1162d252014-06-22 19:05:33 +00002064 QualType SrcRecordTy = E->getType();
David Majnemer1c3d95e2014-07-19 00:17:06 +00002065 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
2066 isGLValueFromPointerDeref(E), SrcRecordTy)) {
David Majnemer1162d252014-06-22 19:05:33 +00002067 llvm::BasicBlock *BadTypeidBlock =
Anders Carlsson940f02d2011-04-18 00:57:03 +00002068 CGF.createBasicBlock("typeid.bad_typeid");
David Majnemer1162d252014-06-22 19:05:33 +00002069 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
Anders Carlsson940f02d2011-04-18 00:57:03 +00002070
John McCall7f416cc2015-09-08 08:05:57 +00002071 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
David Majnemer1162d252014-06-22 19:05:33 +00002072 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002073
David Majnemer1162d252014-06-22 19:05:33 +00002074 CGF.EmitBlock(BadTypeidBlock);
2075 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2076 CGF.EmitBlock(EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002077 }
2078
David Majnemer1162d252014-06-22 19:05:33 +00002079 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
2080 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002081}
2082
John McCalle4df6c82011-01-28 08:37:24 +00002083llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002084 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00002085 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00002086
Anders Carlsson3f4336c2009-12-17 07:09:17 +00002087 if (E->isTypeOperand()) {
David Majnemer143c55e2013-09-27 07:04:31 +00002088 llvm::Constant *TypeInfo =
2089 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson940f02d2011-04-18 00:57:03 +00002090 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00002091 }
Anders Carlsson0c633502011-04-11 14:13:40 +00002092
Anders Carlsson940f02d2011-04-18 00:57:03 +00002093 // C++ [expr.typeid]p2:
2094 // When typeid is applied to a glvalue expression whose type is a
2095 // polymorphic class type, the result refers to a std::type_info object
2096 // representing the type of the most derived object (that is, the dynamic
2097 // type) to which the glvalue refers.
Richard Smithef8bf432012-08-13 20:08:14 +00002098 if (E->isPotentiallyEvaluated())
2099 return EmitTypeidFromVTable(*this, E->getExprOperand(),
2100 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002101
2102 QualType OperandTy = E->getExprOperand()->getType();
2103 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
2104 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00002105}
Mike Stump65511702009-11-16 06:50:58 +00002106
Anders Carlssonc1c99712011-04-11 01:45:29 +00002107static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
2108 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002109 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00002110 if (DestTy->isPointerType())
2111 return llvm::Constant::getNullValue(DestLTy);
2112
2113 /// C++ [expr.dynamic.cast]p9:
2114 /// A failed cast to reference type throws std::bad_cast
David Majnemer1162d252014-06-22 19:05:33 +00002115 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
2116 return nullptr;
Anders Carlssonc1c99712011-04-11 01:45:29 +00002117
2118 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
2119 return llvm::UndefValue::get(DestLTy);
2120}
2121
John McCall7f416cc2015-09-08 08:05:57 +00002122llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
Mike Stump65511702009-11-16 06:50:58 +00002123 const CXXDynamicCastExpr *DCE) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00002124 CGM.EmitExplicitCastExprType(DCE, this);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00002125 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00002126
Anders Carlssonc1c99712011-04-11 01:45:29 +00002127 if (DCE->isAlwaysNull())
David Majnemer1162d252014-06-22 19:05:33 +00002128 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
2129 return T;
Anders Carlssonc1c99712011-04-11 01:45:29 +00002130
2131 QualType SrcTy = DCE->getSubExpr()->getType();
2132
David Majnemer1162d252014-06-22 19:05:33 +00002133 // C++ [expr.dynamic.cast]p7:
2134 // If T is "pointer to cv void," then the result is a pointer to the most
2135 // derived object pointed to by v.
2136 const PointerType *DestPTy = DestTy->getAs<PointerType>();
2137
2138 bool isDynamicCastToVoid;
2139 QualType SrcRecordTy;
2140 QualType DestRecordTy;
2141 if (DestPTy) {
2142 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
2143 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
2144 DestRecordTy = DestPTy->getPointeeType();
2145 } else {
2146 isDynamicCastToVoid = false;
2147 SrcRecordTy = SrcTy;
2148 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
2149 }
2150
2151 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
2152
Anders Carlsson882d7902011-04-11 00:46:40 +00002153 // C++ [expr.dynamic.cast]p4:
2154 // If the value of v is a null pointer value in the pointer case, the result
2155 // is the null pointer value of type T.
David Majnemer1162d252014-06-22 19:05:33 +00002156 bool ShouldNullCheckSrcValue =
2157 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
2158 SrcRecordTy);
Craig Topper8a13c412014-05-21 05:09:00 +00002159
2160 llvm::BasicBlock *CastNull = nullptr;
2161 llvm::BasicBlock *CastNotNull = nullptr;
Anders Carlsson882d7902011-04-11 00:46:40 +00002162 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00002163
Anders Carlsson882d7902011-04-11 00:46:40 +00002164 if (ShouldNullCheckSrcValue) {
2165 CastNull = createBasicBlock("dynamic_cast.null");
2166 CastNotNull = createBasicBlock("dynamic_cast.notnull");
2167
John McCall7f416cc2015-09-08 08:05:57 +00002168 llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
Anders Carlsson882d7902011-04-11 00:46:40 +00002169 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2170 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00002171 }
2172
John McCall7f416cc2015-09-08 08:05:57 +00002173 llvm::Value *Value;
David Majnemer1162d252014-06-22 19:05:33 +00002174 if (isDynamicCastToVoid) {
John McCall7f416cc2015-09-08 08:05:57 +00002175 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00002176 DestTy);
2177 } else {
2178 assert(DestRecordTy->isRecordType() &&
2179 "destination type must be a record type!");
John McCall7f416cc2015-09-08 08:05:57 +00002180 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00002181 DestTy, DestRecordTy, CastEnd);
David Majnemer67528ea2015-11-23 03:01:14 +00002182 CastNotNull = Builder.GetInsertBlock();
David Majnemer1162d252014-06-22 19:05:33 +00002183 }
Anders Carlsson882d7902011-04-11 00:46:40 +00002184
2185 if (ShouldNullCheckSrcValue) {
2186 EmitBranch(CastEnd);
2187
2188 EmitBlock(CastNull);
2189 EmitBranch(CastEnd);
2190 }
2191
2192 EmitBlock(CastEnd);
2193
2194 if (ShouldNullCheckSrcValue) {
2195 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2196 PHI->addIncoming(Value, CastNotNull);
2197 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
2198
2199 Value = PHI;
2200 }
2201
2202 return Value;
Mike Stump65511702009-11-16 06:50:58 +00002203}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002204
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002205void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00002206 RunCleanupsScope Scope(*this);
John McCall7f416cc2015-09-08 08:05:57 +00002207 LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType());
Eli Friedman8631f3e82012-02-09 03:47:20 +00002208
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002209 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
James Y Knight53c76162015-07-17 18:21:37 +00002210 for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
2211 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00002212 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002213 // Emit initialization
David Blaikie40ed2972012-06-06 20:45:41 +00002214 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Alexey Bataev39c81e22014-08-28 04:28:19 +00002215 if (CurField->hasCapturedVLAType()) {
2216 auto VAT = CurField->getCapturedVLAType();
2217 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2218 } else {
Richard Smith30e304e2016-12-14 00:03:17 +00002219 EmitInitializerForField(*CurField, LV, *i);
Alexey Bataev39c81e22014-08-28 04:28:19 +00002220 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002221 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002222}