blob: c32f1e5415da998d73a8443417631c0f0a6ed7d4 [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);
Vedant Kumar09b5bfd2017-12-21 00:10:25 +000092 return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr,
93 CE ? CE->getExprLoc() : SourceLocation());
Anders Carlsson27da15b2010-01-01 20:29:01 +000094}
95
Alexey Samsonovae81bbb2016-03-10 00:20:37 +000096RValue CodeGenFunction::EmitCXXDestructorCall(
John McCallb92ab1a2016-10-26 23:46:34 +000097 const CXXDestructorDecl *DD, const CGCallee &Callee, llvm::Value *This,
Alexey Samsonovae81bbb2016-03-10 00:20:37 +000098 llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE,
99 StructorType Type) {
David Majnemer0c0b6d92014-10-31 20:09:12 +0000100 CallArgList Args;
Alexey Samsonovae81bbb2016-03-10 00:20:37 +0000101 commonEmitCXXMemberOrOperatorCall(*this, DD, This, ImplicitParam,
Richard Smith762672a2016-09-28 19:09:10 +0000102 ImplicitParamTy, CE, Args, nullptr);
Alexey Samsonovae81bbb2016-03-10 00:20:37 +0000103 return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(DD, Type),
John McCallb92ab1a2016-10-26 23:46:34 +0000104 Callee, ReturnValueSlot(), Args);
105}
106
107RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
108 const CXXPseudoDestructorExpr *E) {
109 QualType DestroyedType = E->getDestroyedType();
110 if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
111 // Automatic Reference Counting:
112 // If the pseudo-expression names a retainable object with weak or
113 // strong lifetime, the object shall be released.
114 Expr *BaseExpr = E->getBase();
115 Address BaseValue = Address::invalid();
116 Qualifiers BaseQuals;
117
118 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
119 if (E->isArrow()) {
120 BaseValue = EmitPointerWithAlignment(BaseExpr);
121 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
122 BaseQuals = PTy->getPointeeType().getQualifiers();
123 } else {
124 LValue BaseLV = EmitLValue(BaseExpr);
125 BaseValue = BaseLV.getAddress();
126 QualType BaseTy = BaseExpr->getType();
127 BaseQuals = BaseTy.getQualifiers();
128 }
129
130 switch (DestroyedType.getObjCLifetime()) {
131 case Qualifiers::OCL_None:
132 case Qualifiers::OCL_ExplicitNone:
133 case Qualifiers::OCL_Autoreleasing:
134 break;
135
136 case Qualifiers::OCL_Strong:
137 EmitARCRelease(Builder.CreateLoad(BaseValue,
138 DestroyedType.isVolatileQualified()),
139 ARCPreciseLifetime);
140 break;
141
142 case Qualifiers::OCL_Weak:
143 EmitARCDestroyWeak(BaseValue);
144 break;
145 }
146 } else {
147 // C++ [expr.pseudo]p1:
148 // The result shall only be used as the operand for the function call
149 // operator (), and the result of such a call has type void. The only
150 // effect is the evaluation of the postfix-expression before the dot or
151 // arrow.
152 EmitIgnoredExpr(E->getBase());
153 }
154
155 return RValue::get(nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000156}
157
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000158static CXXRecordDecl *getCXXRecord(const Expr *E) {
159 QualType T = E->getType();
160 if (const PointerType *PTy = T->getAs<PointerType>())
161 T = PTy->getPointeeType();
162 const RecordType *Ty = T->castAs<RecordType>();
163 return cast<CXXRecordDecl>(Ty->getDecl());
164}
165
Francois Pichet64225792011-01-18 05:04:39 +0000166// Note: This function also emit constructor calls to support a MSVC
167// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000168RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
169 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +0000170 const Expr *callee = CE->getCallee()->IgnoreParens();
171
172 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000173 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +0000174
175 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000176 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
177
178 if (MD->isStatic()) {
179 // The method is static, emit it as we would a regular call.
John McCallb92ab1a2016-10-26 23:46:34 +0000180 CGCallee callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD), MD);
181 return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000182 ReturnValue);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000183 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000184
Nico Weberaad4af62014-12-03 01:21:41 +0000185 bool HasQualifier = ME->hasQualifier();
186 NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
187 bool IsArrow = ME->isArrow();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000188 const Expr *Base = ME->getBase();
Nico Weberaad4af62014-12-03 01:21:41 +0000189
190 return EmitCXXMemberOrOperatorMemberCallExpr(
191 CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
192}
193
194RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
195 const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
196 bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
197 const Expr *Base) {
198 assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
199
200 // Compute the object pointer.
201 bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000202
Craig Topper8a13c412014-05-21 05:09:00 +0000203 const CXXMethodDecl *DevirtualizedMethod = nullptr;
Akira Hatanaka22461672017-07-13 06:08:27 +0000204 if (CanUseVirtualCall &&
205 MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000206 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
207 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
208 assert(DevirtualizedMethod);
209 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
210 const Expr *Inner = Base->ignoreParenBaseCasts();
Alexey Bataev5bd68792014-09-29 10:32:21 +0000211 if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
212 MD->getReturnType().getCanonicalType())
213 // If the return types are not the same, this might be a case where more
214 // code needs to run to compensate for it. For example, the derived
215 // method might return a type that inherits form from the return
216 // type of MD and has a prefix.
217 // For now we just avoid devirtualizing these covariant cases.
218 DevirtualizedMethod = nullptr;
219 else if (getCXXRecord(Inner) == DevirtualizedClass)
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000220 // If the class of the Inner expression is where the dynamic method
221 // is defined, build the this pointer from it.
222 Base = Inner;
223 else if (getCXXRecord(Base) != DevirtualizedClass) {
224 // If the method is defined in a class that is not the best dynamic
225 // one or the one of the full expression, we would have to build
226 // a derived-to-base cast to compute the correct this pointer, but
227 // we don't have support for that yet, so do a virtual call.
Craig Topper8a13c412014-05-21 05:09:00 +0000228 DevirtualizedMethod = nullptr;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000229 }
230 }
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000231
Richard Smith762672a2016-09-28 19:09:10 +0000232 // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
233 // operator before the LHS.
234 CallArgList RtlArgStorage;
235 CallArgList *RtlArgs = nullptr;
236 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
237 if (OCE->isAssignmentOp()) {
238 RtlArgs = &RtlArgStorage;
239 EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
240 drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
Richard Smitha560ccf2016-09-29 21:30:12 +0000241 /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
Richard Smith762672a2016-09-28 19:09:10 +0000242 }
243 }
244
John McCall7f416cc2015-09-08 08:05:57 +0000245 Address This = Address::invalid();
Nico Weberaad4af62014-12-03 01:21:41 +0000246 if (IsArrow)
John McCall7f416cc2015-09-08 08:05:57 +0000247 This = EmitPointerWithAlignment(Base);
John McCalle26a8722010-12-04 08:14:53 +0000248 else
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000249 This = EmitLValue(Base).getAddress();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000250
Anders Carlsson27da15b2010-01-01 20:29:01 +0000251
Richard Smith419bd092015-04-29 19:26:57 +0000252 if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
Craig Topper8a13c412014-05-21 05:09:00 +0000253 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
Francois Pichet64225792011-01-18 05:04:39 +0000254 if (isa<CXXConstructorDecl>(MD) &&
255 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
Craig Topper8a13c412014-05-21 05:09:00 +0000256 return RValue::get(nullptr);
John McCall0d635f52010-09-03 01:26:39 +0000257
Nico Weberaad4af62014-12-03 01:21:41 +0000258 if (!MD->getParent()->mayInsertExtraPadding()) {
259 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
260 // We don't like to generate the trivial copy/move assignment operator
261 // when it isn't necessary; just produce the proper effect here.
Richard Smith762672a2016-09-28 19:09:10 +0000262 LValue RHS = isa<CXXOperatorCallExpr>(CE)
263 ? MakeNaturalAlignAddrLValue(
264 (*RtlArgs)[0].RV.getScalarVal(),
265 (*(CE->arg_begin() + 1))->getType())
266 : EmitLValue(*CE->arg_begin());
267 EmitAggregateAssign(This, RHS.getAddress(), CE->getType());
John McCall7f416cc2015-09-08 08:05:57 +0000268 return RValue::get(This.getPointer());
Nico Weberaad4af62014-12-03 01:21:41 +0000269 }
Alexey Samsonov525bf652014-08-25 21:58:56 +0000270
Nico Weberaad4af62014-12-03 01:21:41 +0000271 if (isa<CXXConstructorDecl>(MD) &&
272 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
273 // Trivial move and copy ctor are the same.
274 assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
John McCall7f416cc2015-09-08 08:05:57 +0000275 Address RHS = EmitLValue(*CE->arg_begin()).getAddress();
Benjamin Kramerf48ee442015-07-18 14:35:53 +0000276 EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType());
John McCall7f416cc2015-09-08 08:05:57 +0000277 return RValue::get(This.getPointer());
Nico Weberaad4af62014-12-03 01:21:41 +0000278 }
279 llvm_unreachable("unknown trivial member function");
Francois Pichet64225792011-01-18 05:04:39 +0000280 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000281 }
282
John McCall0d635f52010-09-03 01:26:39 +0000283 // Compute the function type we're calling.
Nico Weber3abfe952014-12-02 20:41:18 +0000284 const CXXMethodDecl *CalleeDecl =
285 DevirtualizedMethod ? DevirtualizedMethod : MD;
Craig Topper8a13c412014-05-21 05:09:00 +0000286 const CGFunctionInfo *FInfo = nullptr;
Nico Weber3abfe952014-12-02 20:41:18 +0000287 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000288 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
289 Dtor, StructorType::Complete);
Nico Weber3abfe952014-12-02 20:41:18 +0000290 else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000291 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
292 Ctor, StructorType::Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000293 else
Eli Friedmanade60972012-10-25 00:12:49 +0000294 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCall0d635f52010-09-03 01:26:39 +0000295
Reid Klecknere7de47e2013-07-22 13:51:44 +0000296 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000297
Ivan Krasind98f5d72016-11-17 00:39:48 +0000298 // C++11 [class.mfct.non-static]p2:
299 // If a non-static member function of a class X is called for an object that
300 // is not of type X, or of a type derived from X, the behavior is undefined.
301 SourceLocation CallLoc;
302 ASTContext &C = getContext();
303 if (CE)
304 CallLoc = CE->getExprLoc();
305
Vedant Kumar34b1fd62017-02-17 23:22:59 +0000306 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +0000307 if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
308 auto *IOA = CMCE->getImplicitObjectArgument();
309 bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);
310 if (IsImplicitObjectCXXThis)
311 SkippedChecks.set(SanitizerKind::Alignment, true);
312 if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA))
Vedant Kumar34b1fd62017-02-17 23:22:59 +0000313 SkippedChecks.set(SanitizerKind::Null, true);
Vedant Kumarffd7c882017-04-14 22:03:34 +0000314 }
Vedant Kumar34b1fd62017-02-17 23:22:59 +0000315 EmitTypeCheck(
316 isa<CXXConstructorDecl>(CalleeDecl) ? CodeGenFunction::TCK_ConstructorCall
317 : CodeGenFunction::TCK_MemberCall,
318 CallLoc, This.getPointer(), C.getRecordType(CalleeDecl->getParent()),
319 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
Ivan Krasind98f5d72016-11-17 00:39:48 +0000320
Vedant Kumar018f2662016-10-19 20:21:16 +0000321 // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
322 // 'CalleeDecl' instead.
323
Anders Carlsson27da15b2010-01-01 20:29:01 +0000324 // C++ [class.virtual]p12:
325 // Explicit qualification with the scope operator (5.1) suppresses the
326 // virtual call mechanism.
327 //
328 // We also don't emit a virtual call if the base expression has a record type
329 // because then we know what the type is.
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000330 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
John McCallb92ab1a2016-10-26 23:46:34 +0000331
John McCall0d635f52010-09-03 01:26:39 +0000332 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000333 assert(CE->arg_begin() == CE->arg_end() &&
334 "Destructor shouldn't have explicit parameters");
335 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
John McCall0d635f52010-09-03 01:26:39 +0000336 if (UseVirtualCall) {
Nico Weberaad4af62014-12-03 01:21:41 +0000337 CGM.getCXXABI().EmitVirtualDestructorCall(
338 *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
Anders Carlsson27da15b2010-01-01 20:29:01 +0000339 } else {
John McCallb92ab1a2016-10-26 23:46:34 +0000340 CGCallee Callee;
Nico Weberaad4af62014-12-03 01:21:41 +0000341 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
342 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000343 else if (!DevirtualizedMethod)
John McCallb92ab1a2016-10-26 23:46:34 +0000344 Callee = CGCallee::forDirect(
345 CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty),
346 Dtor);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000347 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000348 const CXXDestructorDecl *DDtor =
349 cast<CXXDestructorDecl>(DevirtualizedMethod);
John McCallb92ab1a2016-10-26 23:46:34 +0000350 Callee = CGCallee::forDirect(
351 CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty),
352 DDtor);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000353 }
Vedant Kumar018f2662016-10-19 20:21:16 +0000354 EmitCXXMemberOrOperatorCall(
355 CalleeDecl, Callee, ReturnValue, This.getPointer(),
356 /*ImplicitParam=*/nullptr, QualType(), CE, nullptr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000357 }
Craig Topper8a13c412014-05-21 05:09:00 +0000358 return RValue::get(nullptr);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000359 }
360
John McCallb92ab1a2016-10-26 23:46:34 +0000361 CGCallee Callee;
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000362 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
John McCallb92ab1a2016-10-26 23:46:34 +0000363 Callee = CGCallee::forDirect(
364 CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty),
365 Ctor);
John McCall0d635f52010-09-03 01:26:39 +0000366 } else if (UseVirtualCall) {
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000367 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty,
368 CE->getLocStart());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000369 } else {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +0000370 if (SanOpts.has(SanitizerKind::CFINVCall) &&
371 MD->getParent()->isDynamicClass()) {
Peter Collingbourne60108802017-12-13 21:53:04 +0000372 llvm::Value *VTable;
373 const CXXRecordDecl *RD;
374 std::tie(VTable, RD) =
375 CGM.getCXXABI().LoadVTablePtr(*this, This, MD->getParent());
376 EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getLocStart());
Peter Collingbourne1a7488a2015-04-02 00:23:30 +0000377 }
378
Nico Weberaad4af62014-12-03 01:21:41 +0000379 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
380 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000381 else if (!DevirtualizedMethod)
John McCallb92ab1a2016-10-26 23:46:34 +0000382 Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), MD);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000383 else {
John McCallb92ab1a2016-10-26 23:46:34 +0000384 Callee = CGCallee::forDirect(
385 CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
386 DevirtualizedMethod);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000387 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000388 }
389
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000390 if (MD->isVirtual()) {
391 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
Reid Kleckner4b60f302016-05-03 18:44:29 +0000392 *this, CalleeDecl, This, UseVirtualCall);
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000393 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000394
Vedant Kumar018f2662016-10-19 20:21:16 +0000395 return EmitCXXMemberOrOperatorCall(
396 CalleeDecl, Callee, ReturnValue, This.getPointer(),
397 /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000398}
399
400RValue
401CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
402 ReturnValueSlot ReturnValue) {
403 const BinaryOperator *BO =
404 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
405 const Expr *BaseExpr = BO->getLHS();
406 const Expr *MemFnExpr = BO->getRHS();
407
408 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000409 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000410
Anders Carlsson27da15b2010-01-01 20:29:01 +0000411 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000412 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000413 const CXXRecordDecl *RD =
414 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
415
Anders Carlsson27da15b2010-01-01 20:29:01 +0000416 // Emit the 'this' pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000417 Address This = Address::invalid();
John McCalle3027922010-08-25 11:45:40 +0000418 if (BO->getOpcode() == BO_PtrMemI)
John McCall7f416cc2015-09-08 08:05:57 +0000419 This = EmitPointerWithAlignment(BaseExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000420 else
421 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000422
John McCall7f416cc2015-09-08 08:05:57 +0000423 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
Richard Smithe30752c2012-10-09 19:52:38 +0000424 QualType(MPT->getClass(), 0));
Richard Smith69d0d262012-08-24 00:54:33 +0000425
Richard Smithbde62d72016-09-26 23:56:57 +0000426 // Get the member function pointer.
427 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
428
John McCall475999d2010-08-22 00:05:51 +0000429 // Ask the ABI to load the callee. Note that This is modified.
John McCall7f416cc2015-09-08 08:05:57 +0000430 llvm::Value *ThisPtrForCall = nullptr;
John McCallb92ab1a2016-10-26 23:46:34 +0000431 CGCallee Callee =
John McCall7f416cc2015-09-08 08:05:57 +0000432 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
433 ThisPtrForCall, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000434
Anders Carlsson27da15b2010-01-01 20:29:01 +0000435 CallArgList Args;
436
437 QualType ThisType =
438 getContext().getPointerType(getContext().getTagDeclType(RD));
439
440 // Push the this ptr.
John McCall7f416cc2015-09-08 08:05:57 +0000441 Args.add(RValue::get(ThisPtrForCall), ThisType);
John McCall8dda7b22012-07-07 06:41:13 +0000442
George Burgess IV419996c2016-06-16 23:06:04 +0000443 RequiredArgs required =
444 RequiredArgs::forPrototypePlus(FPT, 1, /*FD=*/nullptr);
445
Anders Carlsson27da15b2010-01-01 20:29:01 +0000446 // And the rest of the call args
George Burgess IV419996c2016-06-16 23:06:04 +0000447 EmitCallArgs(Args, FPT, E->arguments());
George Burgess IVd0a9e802017-02-23 22:07:35 +0000448 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
449 /*PrefixSize=*/0),
Vedant Kumar09b5bfd2017-12-21 00:10:25 +0000450 Callee, ReturnValue, Args, nullptr, E->getExprLoc());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000451}
452
453RValue
454CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
455 const CXXMethodDecl *MD,
456 ReturnValueSlot ReturnValue) {
457 assert(MD->isInstance() &&
458 "Trying to emit a member call expr on a static method!");
Nico Weberaad4af62014-12-03 01:21:41 +0000459 return EmitCXXMemberOrOperatorMemberCallExpr(
460 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
461 /*IsArrow=*/false, E->getArg(0));
Anders Carlsson27da15b2010-01-01 20:29:01 +0000462}
463
Peter Collingbournefe883422011-10-06 18:29:37 +0000464RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
465 ReturnValueSlot ReturnValue) {
466 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
467}
468
Eli Friedmanfde961d2011-10-14 02:27:24 +0000469static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000470 Address DestPtr,
Eli Friedmanfde961d2011-10-14 02:27:24 +0000471 const CXXRecordDecl *Base) {
472 if (Base->isEmpty())
473 return;
474
John McCall7f416cc2015-09-08 08:05:57 +0000475 DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
Eli Friedmanfde961d2011-10-14 02:27:24 +0000476
477 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
David Majnemer8671c6e2015-11-02 09:01:44 +0000478 CharUnits NVSize = Layout.getNonVirtualSize();
479
480 // We cannot simply zero-initialize the entire base sub-object if vbptrs are
481 // present, they are initialized by the most derived class before calling the
482 // constructor.
483 SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
484 Stores.emplace_back(CharUnits::Zero(), NVSize);
485
486 // Each store is split by the existence of a vbptr.
487 CharUnits VBPtrWidth = CGF.getPointerSize();
488 std::vector<CharUnits> VBPtrOffsets =
489 CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
490 for (CharUnits VBPtrOffset : VBPtrOffsets) {
David Majnemer7f980d82016-05-12 03:51:52 +0000491 // Stop before we hit any virtual base pointers located in virtual bases.
492 if (VBPtrOffset >= NVSize)
493 break;
David Majnemer8671c6e2015-11-02 09:01:44 +0000494 std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
495 CharUnits LastStoreOffset = LastStore.first;
496 CharUnits LastStoreSize = LastStore.second;
497
498 CharUnits SplitBeforeOffset = LastStoreOffset;
499 CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
500 assert(!SplitBeforeSize.isNegative() && "negative store size!");
501 if (!SplitBeforeSize.isZero())
502 Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
503
504 CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
505 CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
506 assert(!SplitAfterSize.isNegative() && "negative store size!");
507 if (!SplitAfterSize.isZero())
508 Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
509 }
Eli Friedmanfde961d2011-10-14 02:27:24 +0000510
511 // If the type contains a pointer to data member we can't memset it to zero.
512 // Instead, create a null constant and copy it to the destination.
513 // TODO: there are other patterns besides zero that we can usefully memset,
514 // like -1, which happens to be the pattern used by member-pointers.
515 // TODO: isZeroInitializable can be over-conservative in the case where a
516 // virtual base contains a member pointer.
David Majnemer8671c6e2015-11-02 09:01:44 +0000517 llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
518 if (!NullConstantForBase->isNullValue()) {
519 llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
520 CGF.CGM.getModule(), NullConstantForBase->getType(),
521 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
522 NullConstantForBase, Twine());
John McCall7f416cc2015-09-08 08:05:57 +0000523
524 CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
525 DestPtr.getAlignment());
Eli Friedmanfde961d2011-10-14 02:27:24 +0000526 NullVariable->setAlignment(Align.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +0000527
528 Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
Eli Friedmanfde961d2011-10-14 02:27:24 +0000529
530 // Get and call the appropriate llvm.memcpy overload.
David Majnemer8671c6e2015-11-02 09:01:44 +0000531 for (std::pair<CharUnits, CharUnits> Store : Stores) {
532 CharUnits StoreOffset = Store.first;
533 CharUnits StoreSize = Store.second;
534 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
535 CGF.Builder.CreateMemCpy(
536 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
537 CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
538 StoreSizeVal);
539 }
540
Eli Friedmanfde961d2011-10-14 02:27:24 +0000541 // Otherwise, just memset the whole thing to zero. This is legal
542 // because in LLVM, all default initializers (other than the ones we just
543 // handled above) are guaranteed to have a bit pattern of all zeros.
David Majnemer8671c6e2015-11-02 09:01:44 +0000544 } else {
545 for (std::pair<CharUnits, CharUnits> Store : Stores) {
546 CharUnits StoreOffset = Store.first;
547 CharUnits StoreSize = Store.second;
548 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
549 CGF.Builder.CreateMemSet(
550 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
551 CGF.Builder.getInt8(0), StoreSizeVal);
552 }
553 }
Eli Friedmanfde961d2011-10-14 02:27:24 +0000554}
555
Anders Carlsson27da15b2010-01-01 20:29:01 +0000556void
John McCall7a626f62010-09-15 10:14:12 +0000557CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
558 AggValueSlot Dest) {
559 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000560 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000561
562 // If we require zero initialization before (or instead of) calling the
563 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000564 // constructor, emit the zero initialization now, unless destination is
565 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000566 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
567 switch (E->getConstructionKind()) {
568 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000569 case CXXConstructExpr::CK_Complete:
John McCall7f416cc2015-09-08 08:05:57 +0000570 EmitNullInitialization(Dest.getAddress(), E->getType());
Eli Friedmanfde961d2011-10-14 02:27:24 +0000571 break;
572 case CXXConstructExpr::CK_VirtualBase:
573 case CXXConstructExpr::CK_NonVirtualBase:
John McCall7f416cc2015-09-08 08:05:57 +0000574 EmitNullBaseClassInitialization(*this, Dest.getAddress(),
575 CD->getParent());
Eli Friedmanfde961d2011-10-14 02:27:24 +0000576 break;
577 }
578 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000579
580 // If this is a call to a trivial default constructor, do nothing.
581 if (CD->isTrivial() && CD->isDefaultConstructor())
582 return;
583
John McCall8ea46b62010-09-18 00:58:34 +0000584 // Elide the constructor if we're constructing from a temporary.
585 // The temporary check is required because Sema sets this on NRVO
586 // returns.
Richard Smith9c6890a2012-11-01 22:30:59 +0000587 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000588 assert(getContext().hasSameUnqualifiedType(E->getType(),
589 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000590 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
591 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000592 return;
593 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000594 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000595
Alexey Bataeve7545b32016-04-29 09:39:50 +0000596 if (const ArrayType *arrayType
597 = getContext().getAsArrayType(E->getType())) {
John McCall7f416cc2015-09-08 08:05:57 +0000598 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E);
John McCallf677a8e2011-07-13 06:10:41 +0000599 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000600 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000601 bool ForVirtualBase = false;
Douglas Gregor61535002013-01-31 05:50:40 +0000602 bool Delegating = false;
603
Alexis Hunt271c3682011-05-03 20:19:28 +0000604 switch (E->getConstructionKind()) {
605 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000606 // We should be emitting a constructor; GlobalDecl will assert this
607 Type = CurGD.getCtorType();
Douglas Gregor61535002013-01-31 05:50:40 +0000608 Delegating = true;
Alexis Hunt271c3682011-05-03 20:19:28 +0000609 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000610
Alexis Hunt271c3682011-05-03 20:19:28 +0000611 case CXXConstructExpr::CK_Complete:
612 Type = Ctor_Complete;
613 break;
614
615 case CXXConstructExpr::CK_VirtualBase:
616 ForVirtualBase = true;
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000617 LLVM_FALLTHROUGH;
Alexis Hunt271c3682011-05-03 20:19:28 +0000618
619 case CXXConstructExpr::CK_NonVirtualBase:
620 Type = Ctor_Base;
621 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000622
Anders Carlsson27da15b2010-01-01 20:29:01 +0000623 // Call the constructor.
John McCall7f416cc2015-09-08 08:05:57 +0000624 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
625 Dest.getAddress(), E);
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000626 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000627}
628
John McCall7f416cc2015-09-08 08:05:57 +0000629void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
630 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000631 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000632 Exp = E->getSubExpr();
633 assert(isa<CXXConstructExpr>(Exp) &&
634 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
635 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
636 const CXXConstructorDecl *CD = E->getConstructor();
637 RunCleanupsScope Scope(*this);
638
639 // If we require zero initialization before (or instead of) calling the
640 // constructor, as can be the case with a non-user-provided default
641 // constructor, emit the zero initialization now.
642 // FIXME. Do I still need this for a copy ctor synthesis?
643 if (E->requiresZeroInitialization())
644 EmitNullInitialization(Dest, E->getType());
645
Chandler Carruth99da11c2010-11-15 13:54:43 +0000646 assert(!getContext().getAsConstantArrayType(E->getType())
647 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Alexey Samsonov525bf652014-08-25 21:58:56 +0000648 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000649}
650
John McCall8ed55a52010-09-02 09:58:18 +0000651static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
652 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000653 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000654 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000655
John McCall7ec4b432011-05-16 01:05:12 +0000656 // No cookie is required if the operator new[] being used is the
657 // reserved placement operator new[].
658 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000659 return CharUnits::Zero();
660
John McCall284c48f2011-01-27 09:37:56 +0000661 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000662}
663
John McCall036f2f62011-05-15 07:14:44 +0000664static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
665 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000666 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000667 llvm::Value *&numElements,
668 llvm::Value *&sizeWithoutCookie) {
669 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000670
John McCall036f2f62011-05-15 07:14:44 +0000671 if (!e->isArray()) {
672 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
673 sizeWithoutCookie
674 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
675 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000676 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000677
John McCall036f2f62011-05-15 07:14:44 +0000678 // The width of size_t.
679 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
680
John McCall8ed55a52010-09-02 09:58:18 +0000681 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000682 llvm::APInt cookieSize(sizeWidth,
683 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000684
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000685 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000686 // We multiply the size of all dimensions for NumElements.
687 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCallde0fe072017-08-15 21:42:52 +0000688 numElements =
689 ConstantEmitter(CGF).tryEmitAbstract(e->getArraySize(), e->getType());
Nick Lewycky07527622017-02-13 23:49:55 +0000690 if (!numElements)
691 numElements = CGF.EmitScalarExpr(e->getArraySize());
John McCall036f2f62011-05-15 07:14:44 +0000692 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000693
John McCall036f2f62011-05-15 07:14:44 +0000694 // The number of elements can be have an arbitrary integer type;
695 // essentially, we need to multiply it by a constant factor, add a
696 // cookie size, and verify that the result is representable as a
697 // size_t. That's just a gloss, though, and it's wrong in one
698 // important way: if the count is negative, it's an error even if
699 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000700 bool isSigned
701 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000702 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000703 = cast<llvm::IntegerType>(numElements->getType());
704 unsigned numElementsWidth = numElementsType->getBitWidth();
705
706 // Compute the constant factor.
707 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000708 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000709 = CGF.getContext().getAsConstantArrayType(type)) {
710 type = CAT->getElementType();
711 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000712 }
713
John McCall036f2f62011-05-15 07:14:44 +0000714 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
715 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
716 typeSizeMultiplier *= arraySizeMultiplier;
717
718 // This will be a size_t.
719 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000720
Chris Lattner32ac5832010-07-20 21:55:52 +0000721 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
722 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000723 if (llvm::ConstantInt *numElementsC =
724 dyn_cast<llvm::ConstantInt>(numElements)) {
725 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000726
John McCall036f2f62011-05-15 07:14:44 +0000727 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000728
John McCall036f2f62011-05-15 07:14:44 +0000729 // If 'count' was a negative number, it's an overflow.
730 if (isSigned && count.isNegative())
731 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000732
John McCall036f2f62011-05-15 07:14:44 +0000733 // We want to do all this arithmetic in size_t. If numElements is
734 // wider than that, check whether it's already too big, and if so,
735 // overflow.
736 else if (numElementsWidth > sizeWidth &&
737 numElementsWidth - sizeWidth > count.countLeadingZeros())
738 hasAnyOverflow = true;
739
740 // Okay, compute a count at the right width.
741 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
742
Sebastian Redlf862eb62012-02-22 17:37:52 +0000743 // If there is a brace-initializer, we cannot allocate fewer elements than
744 // there are initializers. If we do, that's treated like an overflow.
745 if (adjustedCount.ult(minElements))
746 hasAnyOverflow = true;
747
John McCall036f2f62011-05-15 07:14:44 +0000748 // Scale numElements by that. This might overflow, but we don't
749 // care because it only overflows if allocationSize does, too, and
750 // if that overflows then we shouldn't use this.
751 numElements = llvm::ConstantInt::get(CGF.SizeTy,
752 adjustedCount * arraySizeMultiplier);
753
754 // Compute the size before cookie, and track whether it overflowed.
755 bool overflow;
756 llvm::APInt allocationSize
757 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
758 hasAnyOverflow |= overflow;
759
760 // Add in the cookie, and check whether it's overflowed.
761 if (cookieSize != 0) {
762 // Save the current size without a cookie. This shouldn't be
763 // used if there was overflow.
764 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
765
766 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
767 hasAnyOverflow |= overflow;
768 }
769
770 // On overflow, produce a -1 so operator new will fail.
Aaron Ballman455f42c2014-08-28 17:24:14 +0000771 if (hasAnyOverflow) {
772 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
773 } else {
John McCall036f2f62011-05-15 07:14:44 +0000774 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
Aaron Ballman455f42c2014-08-28 17:24:14 +0000775 }
John McCall036f2f62011-05-15 07:14:44 +0000776
777 // Otherwise, we might need to use the overflow intrinsics.
778 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000779 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000780 // 1) if isSigned, we need to check whether numElements is negative;
781 // 2) if numElementsWidth > sizeWidth, we need to check whether
782 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000783 // 3) if minElements > 0, we need to check whether numElements is smaller
784 // than that.
785 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000786 // sizeWithoutCookie := numElements * typeSizeMultiplier
787 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000788 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000789 // size := sizeWithoutCookie + cookieSize
790 // and check whether it overflows.
791
Craig Topper8a13c412014-05-21 05:09:00 +0000792 llvm::Value *hasOverflow = nullptr;
John McCall036f2f62011-05-15 07:14:44 +0000793
794 // If numElementsWidth > sizeWidth, then one way or another, we're
795 // going to have to do a comparison for (2), and this happens to
796 // take care of (1), too.
797 if (numElementsWidth > sizeWidth) {
798 llvm::APInt threshold(numElementsWidth, 1);
799 threshold <<= sizeWidth;
800
801 llvm::Value *thresholdV
802 = llvm::ConstantInt::get(numElementsType, threshold);
803
804 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
805 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
806
807 // Otherwise, if we're signed, we want to sext up to size_t.
808 } else if (isSigned) {
809 if (numElementsWidth < sizeWidth)
810 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
811
812 // If there's a non-1 type size multiplier, then we can do the
813 // signedness check at the same time as we do the multiply
814 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000815 // unsigned overflow. Otherwise, we have to do it here. But at least
816 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000817 if (typeSizeMultiplier == 1)
818 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000819 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000820
821 // Otherwise, zext up to size_t if necessary.
822 } else if (numElementsWidth < sizeWidth) {
823 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
824 }
825
826 assert(numElements->getType() == CGF.SizeTy);
827
Sebastian Redlf862eb62012-02-22 17:37:52 +0000828 if (minElements) {
829 // Don't allow allocation of fewer elements than we have initializers.
830 if (!hasOverflow) {
831 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
832 llvm::ConstantInt::get(CGF.SizeTy, minElements));
833 } else if (numElementsWidth > sizeWidth) {
834 // The other existing overflow subsumes this check.
835 // We do an unsigned comparison, since any signed value < -1 is
836 // taken care of either above or below.
837 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
838 CGF.Builder.CreateICmpULT(numElements,
839 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
840 }
841 }
842
John McCall036f2f62011-05-15 07:14:44 +0000843 size = numElements;
844
845 // Multiply by the type size if necessary. This multiplier
846 // includes all the factors for nested arrays.
847 //
848 // This step also causes numElements to be scaled up by the
849 // nested-array factor if necessary. Overflow on this computation
850 // can be ignored because the result shouldn't be used if
851 // allocation fails.
852 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000853 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000854 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000855
856 llvm::Value *tsmV =
857 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
858 llvm::Value *result =
David Blaikie43f9bb72015-05-18 22:14:03 +0000859 CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
John McCall036f2f62011-05-15 07:14:44 +0000860
861 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
862 if (hasOverflow)
863 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
864 else
865 hasOverflow = overflowed;
866
867 size = CGF.Builder.CreateExtractValue(result, 0);
868
869 // Also scale up numElements by the array size multiplier.
870 if (arraySizeMultiplier != 1) {
871 // If the base element type size is 1, then we can re-use the
872 // multiply we just did.
873 if (typeSize.isOne()) {
874 assert(arraySizeMultiplier == typeSizeMultiplier);
875 numElements = size;
876
877 // Otherwise we need a separate multiply.
878 } else {
879 llvm::Value *asmV =
880 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
881 numElements = CGF.Builder.CreateMul(numElements, asmV);
882 }
883 }
884 } else {
885 // numElements doesn't need to be scaled.
886 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000887 }
888
John McCall036f2f62011-05-15 07:14:44 +0000889 // Add in the cookie size if necessary.
890 if (cookieSize != 0) {
891 sizeWithoutCookie = size;
892
John McCall036f2f62011-05-15 07:14:44 +0000893 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000894 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000895
896 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
897 llvm::Value *result =
David Blaikie43f9bb72015-05-18 22:14:03 +0000898 CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
John McCall036f2f62011-05-15 07:14:44 +0000899
900 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
901 if (hasOverflow)
902 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
903 else
904 hasOverflow = overflowed;
905
906 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000907 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000908
John McCall036f2f62011-05-15 07:14:44 +0000909 // If we had any possibility of dynamic overflow, make a select to
910 // overwrite 'size' with an all-ones value, which should cause
911 // operator new to throw.
912 if (hasOverflow)
Aaron Ballman455f42c2014-08-28 17:24:14 +0000913 size = CGF.Builder.CreateSelect(hasOverflow,
914 llvm::Constant::getAllOnesValue(CGF.SizeTy),
915 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000916 }
John McCall8ed55a52010-09-02 09:58:18 +0000917
John McCall036f2f62011-05-15 07:14:44 +0000918 if (cookieSize == 0)
919 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000920 else
John McCall036f2f62011-05-15 07:14:44 +0000921 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000922
John McCall036f2f62011-05-15 07:14:44 +0000923 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000924}
925
Sebastian Redlf862eb62012-02-22 17:37:52 +0000926static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
John McCall7f416cc2015-09-08 08:05:57 +0000927 QualType AllocType, Address NewPtr) {
Richard Smith1c96bc52013-12-11 01:40:16 +0000928 // FIXME: Refactor with EmitExprAsInit.
John McCall47fb9502013-03-07 21:37:08 +0000929 switch (CGF.getEvaluationKind(AllocType)) {
930 case TEK_Scalar:
David Blaikiea2c11242014-12-10 19:04:09 +0000931 CGF.EmitScalarInit(Init, nullptr,
John McCall7f416cc2015-09-08 08:05:57 +0000932 CGF.MakeAddrLValue(NewPtr, AllocType), false);
John McCall47fb9502013-03-07 21:37:08 +0000933 return;
934 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000935 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
John McCall47fb9502013-03-07 21:37:08 +0000936 /*isInit*/ true);
937 return;
938 case TEK_Aggregate: {
John McCall7a626f62010-09-15 10:14:12 +0000939 AggValueSlot Slot
John McCall7f416cc2015-09-08 08:05:57 +0000940 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000941 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000942 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000943 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000944 CGF.EmitAggExpr(Init, Slot);
John McCall47fb9502013-03-07 21:37:08 +0000945 return;
John McCall7a626f62010-09-15 10:14:12 +0000946 }
John McCall47fb9502013-03-07 21:37:08 +0000947 }
948 llvm_unreachable("bad evaluation kind");
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000949}
950
David Blaikiefb901c7a2015-04-04 15:12:29 +0000951void CodeGenFunction::EmitNewArrayInitializer(
952 const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
John McCall7f416cc2015-09-08 08:05:57 +0000953 Address BeginPtr, llvm::Value *NumElements,
David Blaikiefb901c7a2015-04-04 15:12:29 +0000954 llvm::Value *AllocSizeWithoutCookie) {
Richard Smith06a67e22014-06-03 06:58:52 +0000955 // If we have a type with trivial initialization and no initializer,
956 // there's nothing to do.
Sebastian Redl6047f072012-02-16 12:22:20 +0000957 if (!E->hasInitializer())
Richard Smith06a67e22014-06-03 06:58:52 +0000958 return;
John McCall99210dc2011-09-15 06:49:18 +0000959
John McCall7f416cc2015-09-08 08:05:57 +0000960 Address CurPtr = BeginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000961
Richard Smith06a67e22014-06-03 06:58:52 +0000962 unsigned InitListElements = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000963
964 const Expr *Init = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +0000965 Address EndOfInit = Address::invalid();
Richard Smith06a67e22014-06-03 06:58:52 +0000966 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
967 EHScopeStack::stable_iterator Cleanup;
968 llvm::Instruction *CleanupDominator = nullptr;
Richard Smith1c96bc52013-12-11 01:40:16 +0000969
John McCall7f416cc2015-09-08 08:05:57 +0000970 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
971 CharUnits ElementAlign =
972 BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
973
Richard Smith0511d232016-10-05 22:41:02 +0000974 // Attempt to perform zero-initialization using memset.
975 auto TryMemsetInitialization = [&]() -> bool {
976 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
977 // we can initialize with a memset to -1.
978 if (!CGM.getTypes().isZeroInitializable(ElementType))
979 return false;
980
981 // Optimization: since zero initialization will just set the memory
982 // to all zeroes, generate a single memset to do it in one shot.
983
984 // Subtract out the size of any elements we've already initialized.
985 auto *RemainingSize = AllocSizeWithoutCookie;
986 if (InitListElements) {
987 // We know this can't overflow; we check this when doing the allocation.
988 auto *InitializedSize = llvm::ConstantInt::get(
989 RemainingSize->getType(),
990 getContext().getTypeSizeInChars(ElementType).getQuantity() *
991 InitListElements);
992 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
993 }
994
995 // Create the memset.
996 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
997 return true;
998 };
999
Sebastian Redlf862eb62012-02-22 17:37:52 +00001000 // If the initializer is an initializer list, first do the explicit elements.
1001 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith0511d232016-10-05 22:41:02 +00001002 // Initializing from a (braced) string literal is a special case; the init
1003 // list element does not initialize a (single) array element.
1004 if (ILE->isStringLiteralInit()) {
1005 // Initialize the initial portion of length equal to that of the string
1006 // literal. The allocation must be for at least this much; we emitted a
1007 // check for that earlier.
1008 AggValueSlot Slot =
1009 AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
1010 AggValueSlot::IsDestructed,
1011 AggValueSlot::DoesNotNeedGCBarriers,
1012 AggValueSlot::IsNotAliased);
1013 EmitAggExpr(ILE->getInit(0), Slot);
1014
1015 // Move past these elements.
1016 InitListElements =
1017 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1018 ->getSize().getZExtValue();
1019 CurPtr =
1020 Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1021 Builder.getSize(InitListElements),
1022 "string.init.end"),
1023 CurPtr.getAlignment().alignmentAtOffset(InitListElements *
1024 ElementSize));
1025
1026 // Zero out the rest, if any remain.
1027 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1028 if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
1029 bool OK = TryMemsetInitialization();
1030 (void)OK;
1031 assert(OK && "couldn't memset character type?");
1032 }
1033 return;
1034 }
1035
Richard Smith06a67e22014-06-03 06:58:52 +00001036 InitListElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +00001037
Richard Smith1c96bc52013-12-11 01:40:16 +00001038 // If this is a multi-dimensional array new, we will initialize multiple
1039 // elements with each init list element.
1040 QualType AllocType = E->getAllocatedType();
1041 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
1042 AllocType->getAsArrayTypeUnsafe())) {
David Blaikiefb901c7a2015-04-04 15:12:29 +00001043 ElementTy = ConvertTypeForMem(AllocType);
John McCall7f416cc2015-09-08 08:05:57 +00001044 CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
Richard Smith06a67e22014-06-03 06:58:52 +00001045 InitListElements *= getContext().getConstantArrayElementCount(CAT);
Richard Smith1c96bc52013-12-11 01:40:16 +00001046 }
1047
Richard Smith06a67e22014-06-03 06:58:52 +00001048 // Enter a partial-destruction Cleanup if necessary.
1049 if (needsEHCleanup(DtorKind)) {
1050 // In principle we could tell the Cleanup where we are more
Chad Rosierf62290a2012-02-24 00:13:55 +00001051 // directly, but the control flow can get so varied here that it
1052 // would actually be quite complex. Therefore we go through an
1053 // alloca.
John McCall7f416cc2015-09-08 08:05:57 +00001054 EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
1055 "array.init.end");
1056 CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
1057 pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
1058 ElementType, ElementAlign,
Richard Smith06a67e22014-06-03 06:58:52 +00001059 getDestroyer(DtorKind));
1060 Cleanup = EHStack.stable_begin();
Chad Rosierf62290a2012-02-24 00:13:55 +00001061 }
1062
John McCall7f416cc2015-09-08 08:05:57 +00001063 CharUnits StartAlign = CurPtr.getAlignment();
Sebastian Redlf862eb62012-02-22 17:37:52 +00001064 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +00001065 // Tell the cleanup that it needs to destroy up to this
1066 // element. TODO: some of these stores can be trivially
1067 // observed to be unnecessary.
John McCall7f416cc2015-09-08 08:05:57 +00001068 if (EndOfInit.isValid()) {
1069 auto FinishedPtr =
1070 Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
1071 Builder.CreateStore(FinishedPtr, EndOfInit);
1072 }
Richard Smith06a67e22014-06-03 06:58:52 +00001073 // FIXME: If the last initializer is an incomplete initializer list for
1074 // an array, and we have an array filler, we can fold together the two
1075 // initialization loops.
Richard Smith1c96bc52013-12-11 01:40:16 +00001076 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
Richard Smith06a67e22014-06-03 06:58:52 +00001077 ILE->getInit(i)->getType(), CurPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001078 CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1079 Builder.getSize(1),
1080 "array.exp.next"),
1081 StartAlign.alignmentAtOffset((i + 1) * ElementSize));
Sebastian Redlf862eb62012-02-22 17:37:52 +00001082 }
1083
1084 // The remaining elements are filled with the array filler expression.
1085 Init = ILE->getArrayFiller();
Richard Smith1c96bc52013-12-11 01:40:16 +00001086
Richard Smith06a67e22014-06-03 06:58:52 +00001087 // Extract the initializer for the individual array elements by pulling
1088 // out the array filler from all the nested initializer lists. This avoids
1089 // generating a nested loop for the initialization.
1090 while (Init && Init->getType()->isConstantArrayType()) {
1091 auto *SubILE = dyn_cast<InitListExpr>(Init);
1092 if (!SubILE)
1093 break;
1094 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
1095 Init = SubILE->getArrayFiller();
1096 }
1097
1098 // Switch back to initializing one base element at a time.
John McCall7f416cc2015-09-08 08:05:57 +00001099 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
Sebastian Redlf862eb62012-02-22 17:37:52 +00001100 }
1101
Richard Smith454a7cd2014-06-03 08:26:00 +00001102 // If all elements have already been initialized, skip any further
1103 // initialization.
1104 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1105 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1106 // If there was a Cleanup, deactivate it.
1107 if (CleanupDominator)
1108 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1109 return;
1110 }
1111
1112 assert(Init && "have trailing elements to initialize but no initializer");
1113
Richard Smith06a67e22014-06-03 06:58:52 +00001114 // If this is a constructor call, try to optimize it out, and failing that
1115 // emit a single loop to initialize all remaining elements.
Richard Smith454a7cd2014-06-03 08:26:00 +00001116 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +00001117 CXXConstructorDecl *Ctor = CCE->getConstructor();
1118 if (Ctor->isTrivial()) {
1119 // If new expression did not specify value-initialization, then there
1120 // is no initialization.
1121 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
1122 return;
1123
1124 if (TryMemsetInitialization())
1125 return;
1126 }
1127
1128 // Store the new Cleanup position for irregular Cleanups.
1129 //
1130 // FIXME: Share this cleanup with the constructor call emission rather than
1131 // having it create a cleanup of its own.
John McCall7f416cc2015-09-08 08:05:57 +00001132 if (EndOfInit.isValid())
1133 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
Richard Smith06a67e22014-06-03 06:58:52 +00001134
1135 // Emit a constructor call loop to initialize the remaining elements.
1136 if (InitListElements)
1137 NumElements = Builder.CreateSub(
1138 NumElements,
1139 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001140 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
Richard Smith06a67e22014-06-03 06:58:52 +00001141 CCE->requiresZeroInitialization());
Chandler Carruthe6c980c2014-05-03 09:16:57 +00001142 return;
1143 }
1144
Richard Smith06a67e22014-06-03 06:58:52 +00001145 // If this is value-initialization, we can usually use memset.
1146 ImplicitValueInitExpr IVIE(ElementType);
Richard Smith454a7cd2014-06-03 08:26:00 +00001147 if (isa<ImplicitValueInitExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +00001148 if (TryMemsetInitialization())
1149 return;
1150
1151 // Switch to an ImplicitValueInitExpr for the element type. This handles
1152 // only one case: multidimensional array new of pointers to members. In
1153 // all other cases, we already have an initializer for the array element.
1154 Init = &IVIE;
1155 }
1156
1157 // At this point we should have found an initializer for the individual
1158 // elements of the array.
1159 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
1160 "got wrong type of element to initialize");
1161
Richard Smith454a7cd2014-06-03 08:26:00 +00001162 // If we have an empty initializer list, we can usually use memset.
1163 if (auto *ILE = dyn_cast<InitListExpr>(Init))
1164 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1165 return;
Richard Smith06a67e22014-06-03 06:58:52 +00001166
Yunzhong Gaocb779302015-06-10 00:27:52 +00001167 // If we have a struct whose every field is value-initialized, we can
1168 // usually use memset.
1169 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1170 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1171 if (RType->getDecl()->isStruct()) {
Richard Smith872307e2016-03-08 22:17:41 +00001172 unsigned NumElements = 0;
1173 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1174 NumElements = CXXRD->getNumBases();
Yunzhong Gaocb779302015-06-10 00:27:52 +00001175 for (auto *Field : RType->getDecl()->fields())
1176 if (!Field->isUnnamedBitfield())
Richard Smith872307e2016-03-08 22:17:41 +00001177 ++NumElements;
1178 // FIXME: Recurse into nested InitListExprs.
1179 if (ILE->getNumInits() == NumElements)
Yunzhong Gaocb779302015-06-10 00:27:52 +00001180 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1181 if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
Richard Smith872307e2016-03-08 22:17:41 +00001182 --NumElements;
1183 if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
Yunzhong Gaocb779302015-06-10 00:27:52 +00001184 return;
1185 }
1186 }
1187 }
1188
Richard Smith06a67e22014-06-03 06:58:52 +00001189 // Create the loop blocks.
1190 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1191 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
1192 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
1193
1194 // Find the end of the array, hoisted out of the loop.
1195 llvm::Value *EndPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001196 Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
John McCall99210dc2011-09-15 06:49:18 +00001197
Sebastian Redlf862eb62012-02-22 17:37:52 +00001198 // If the number of elements isn't constant, we have to now check if there is
1199 // anything left to initialize.
Richard Smith06a67e22014-06-03 06:58:52 +00001200 if (!ConstNum) {
John McCall7f416cc2015-09-08 08:05:57 +00001201 llvm::Value *IsEmpty =
1202 Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
Richard Smith06a67e22014-06-03 06:58:52 +00001203 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
John McCall99210dc2011-09-15 06:49:18 +00001204 }
1205
1206 // Enter the loop.
Richard Smith06a67e22014-06-03 06:58:52 +00001207 EmitBlock(LoopBB);
John McCall99210dc2011-09-15 06:49:18 +00001208
1209 // Set up the current-element phi.
Richard Smith06a67e22014-06-03 06:58:52 +00001210 llvm::PHINode *CurPtrPhi =
John McCall7f416cc2015-09-08 08:05:57 +00001211 Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1212 CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
1213
1214 CurPtr = Address(CurPtrPhi, ElementAlign);
John McCall99210dc2011-09-15 06:49:18 +00001215
Richard Smith06a67e22014-06-03 06:58:52 +00001216 // Store the new Cleanup position for irregular Cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00001217 if (EndOfInit.isValid())
1218 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
Chad Rosierf62290a2012-02-24 00:13:55 +00001219
Richard Smith06a67e22014-06-03 06:58:52 +00001220 // Enter a partial-destruction Cleanup if necessary.
1221 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
John McCall7f416cc2015-09-08 08:05:57 +00001222 pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
1223 ElementType, ElementAlign,
Richard Smith06a67e22014-06-03 06:58:52 +00001224 getDestroyer(DtorKind));
1225 Cleanup = EHStack.stable_begin();
1226 CleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +00001227 }
1228
1229 // Emit the initializer into this element.
Richard Smith06a67e22014-06-03 06:58:52 +00001230 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
John McCall99210dc2011-09-15 06:49:18 +00001231
Richard Smith06a67e22014-06-03 06:58:52 +00001232 // Leave the Cleanup if we entered one.
1233 if (CleanupDominator) {
1234 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1235 CleanupDominator->eraseFromParent();
John McCallf4beacd2011-11-10 10:43:54 +00001236 }
John McCall99210dc2011-09-15 06:49:18 +00001237
Faisal Vali57ae0562013-12-14 00:40:05 +00001238 // Advance to the next element by adjusting the pointer type as necessary.
Richard Smith06a67e22014-06-03 06:58:52 +00001239 llvm::Value *NextPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001240 Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
1241 "array.next");
Richard Smith06a67e22014-06-03 06:58:52 +00001242
John McCall99210dc2011-09-15 06:49:18 +00001243 // Check whether we've gotten to the end of the array and, if so,
1244 // exit the loop.
Richard Smith06a67e22014-06-03 06:58:52 +00001245 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1246 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1247 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
John McCall99210dc2011-09-15 06:49:18 +00001248
Richard Smith06a67e22014-06-03 06:58:52 +00001249 EmitBlock(ContBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +00001250}
1251
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001252static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
David Blaikiefb901c7a2015-04-04 15:12:29 +00001253 QualType ElementType, llvm::Type *ElementTy,
John McCall7f416cc2015-09-08 08:05:57 +00001254 Address NewPtr, llvm::Value *NumElements,
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001255 llvm::Value *AllocSizeWithoutCookie) {
David Blaikie9b479662015-01-25 01:19:10 +00001256 ApplyDebugLocation DL(CGF, E);
Richard Smith06a67e22014-06-03 06:58:52 +00001257 if (E->isArray())
David Blaikiefb901c7a2015-04-04 15:12:29 +00001258 CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
Richard Smith06a67e22014-06-03 06:58:52 +00001259 AllocSizeWithoutCookie);
1260 else if (const Expr *Init = E->getInitializer())
David Blaikie66e41972015-01-14 07:38:27 +00001261 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001262}
1263
Richard Smith8d0dc312013-07-21 23:12:18 +00001264/// Emit a call to an operator new or operator delete function, as implicitly
1265/// created by new-expressions and delete-expressions.
1266static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
John McCallb92ab1a2016-10-26 23:46:34 +00001267 const FunctionDecl *CalleeDecl,
Richard Smith8d0dc312013-07-21 23:12:18 +00001268 const FunctionProtoType *CalleeType,
1269 const CallArgList &Args) {
1270 llvm::Instruction *CallOrInvoke;
John McCallb92ab1a2016-10-26 23:46:34 +00001271 llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
1272 CGCallee Callee = CGCallee::forDirect(CalleePtr, CalleeDecl);
Richard Smith8d0dc312013-07-21 23:12:18 +00001273 RValue RV =
Peter Collingbournef7706832014-12-12 23:41:25 +00001274 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1275 Args, CalleeType, /*chainCall=*/false),
John McCallb92ab1a2016-10-26 23:46:34 +00001276 Callee, ReturnValueSlot(), Args, &CallOrInvoke);
Richard Smith8d0dc312013-07-21 23:12:18 +00001277
1278 /// C++1y [expr.new]p10:
1279 /// [In a new-expression,] an implementation is allowed to omit a call
1280 /// to a replaceable global allocation function.
1281 ///
1282 /// We model such elidable calls with the 'builtin' attribute.
John McCallb92ab1a2016-10-26 23:46:34 +00001283 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1284 if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola6956d582013-10-22 14:23:09 +00001285 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smith8d0dc312013-07-21 23:12:18 +00001286 // FIXME: Add addAttribute to CallSite.
1287 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
Reid Klecknerde864822017-03-21 16:57:30 +00001288 CI->addAttribute(llvm::AttributeList::FunctionIndex,
Richard Smith8d0dc312013-07-21 23:12:18 +00001289 llvm::Attribute::Builtin);
1290 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
Reid Klecknerde864822017-03-21 16:57:30 +00001291 II->addAttribute(llvm::AttributeList::FunctionIndex,
Richard Smith8d0dc312013-07-21 23:12:18 +00001292 llvm::Attribute::Builtin);
1293 else
1294 llvm_unreachable("unexpected kind of call instruction");
1295 }
1296
1297 return RV;
1298}
1299
Richard Smith760520b2014-06-03 23:27:44 +00001300RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1301 const Expr *Arg,
1302 bool IsDelete) {
1303 CallArgList Args;
1304 const Stmt *ArgS = Arg;
David Blaikief05779e2015-07-21 18:37:18 +00001305 EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS));
Richard Smith760520b2014-06-03 23:27:44 +00001306 // Find the allocation or deallocation function that we're calling.
1307 ASTContext &Ctx = getContext();
1308 DeclarationName Name = Ctx.DeclarationNames
1309 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1310 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
Richard Smith599bed72014-06-05 00:43:02 +00001311 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1312 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1313 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
Richard Smith760520b2014-06-03 23:27:44 +00001314 llvm_unreachable("predeclared global operator new/delete is missing");
1315}
1316
Richard Smith5b349582017-10-13 01:55:36 +00001317namespace {
1318/// The parameters to pass to a usual operator delete.
1319struct UsualDeleteParams {
1320 bool DestroyingDelete = false;
1321 bool Size = false;
1322 bool Alignment = false;
1323};
1324}
1325
1326static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {
1327 UsualDeleteParams Params;
1328
1329 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00001330 auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
Richard Smith189e52f2016-10-10 06:42:31 +00001331
Richard Smithb2f0f052016-10-10 18:54:32 +00001332 // The first argument is always a void*.
1333 ++AI;
1334
Richard Smith5b349582017-10-13 01:55:36 +00001335 // The next parameter may be a std::destroying_delete_t.
1336 if (FD->isDestroyingOperatorDelete()) {
1337 Params.DestroyingDelete = true;
1338 assert(AI != AE);
1339 ++AI;
1340 }
Richard Smithb2f0f052016-10-10 18:54:32 +00001341
Richard Smith5b349582017-10-13 01:55:36 +00001342 // Figure out what other parameters we should be implicitly passing.
Richard Smithb2f0f052016-10-10 18:54:32 +00001343 if (AI != AE && (*AI)->isIntegerType()) {
Richard Smith5b349582017-10-13 01:55:36 +00001344 Params.Size = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00001345 ++AI;
1346 }
1347
1348 if (AI != AE && (*AI)->isAlignValT()) {
Richard Smith5b349582017-10-13 01:55:36 +00001349 Params.Alignment = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00001350 ++AI;
1351 }
1352
1353 assert(AI == AE && "unexpected usual deallocation function parameter");
Richard Smith5b349582017-10-13 01:55:36 +00001354 return Params;
Richard Smithb2f0f052016-10-10 18:54:32 +00001355}
1356
1357namespace {
1358 /// A cleanup to call the given 'operator delete' function upon abnormal
1359 /// exit from a new expression. Templated on a traits type that deals with
1360 /// ensuring that the arguments dominate the cleanup if necessary.
1361 template<typename Traits>
1362 class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1363 /// Type used to hold llvm::Value*s.
1364 typedef typename Traits::ValueTy ValueTy;
1365 /// Type used to hold RValues.
1366 typedef typename Traits::RValueTy RValueTy;
1367 struct PlacementArg {
1368 RValueTy ArgValue;
1369 QualType ArgType;
1370 };
1371
1372 unsigned NumPlacementArgs : 31;
1373 unsigned PassAlignmentToPlacementDelete : 1;
1374 const FunctionDecl *OperatorDelete;
1375 ValueTy Ptr;
1376 ValueTy AllocSize;
1377 CharUnits AllocAlign;
1378
1379 PlacementArg *getPlacementArgs() {
1380 return reinterpret_cast<PlacementArg *>(this + 1);
1381 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00001382
1383 public:
1384 static size_t getExtraSize(size_t NumPlacementArgs) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001385 return NumPlacementArgs * sizeof(PlacementArg);
Daniel Jaspere9abe642016-10-10 14:13:55 +00001386 }
1387
1388 CallDeleteDuringNew(size_t NumPlacementArgs,
Richard Smithb2f0f052016-10-10 18:54:32 +00001389 const FunctionDecl *OperatorDelete, ValueTy Ptr,
1390 ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1391 CharUnits AllocAlign)
1392 : NumPlacementArgs(NumPlacementArgs),
1393 PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1394 OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1395 AllocAlign(AllocAlign) {}
Daniel Jaspere9abe642016-10-10 14:13:55 +00001396
Richard Smithb2f0f052016-10-10 18:54:32 +00001397 void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
Daniel Jaspere9abe642016-10-10 14:13:55 +00001398 assert(I < NumPlacementArgs && "index out of range");
Richard Smithb2f0f052016-10-10 18:54:32 +00001399 getPlacementArgs()[I] = {Arg, Type};
Daniel Jaspere9abe642016-10-10 14:13:55 +00001400 }
1401
1402 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smithb2f0f052016-10-10 18:54:32 +00001403 const FunctionProtoType *FPT =
1404 OperatorDelete->getType()->getAs<FunctionProtoType>();
Daniel Jaspere9abe642016-10-10 14:13:55 +00001405 CallArgList DeleteArgs;
1406
Richard Smith5b349582017-10-13 01:55:36 +00001407 // The first argument is always a void* (or C* for a destroying operator
1408 // delete for class type C).
Richard Smithb2f0f052016-10-10 18:54:32 +00001409 DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
Daniel Jaspere9abe642016-10-10 14:13:55 +00001410
Richard Smithb2f0f052016-10-10 18:54:32 +00001411 // Figure out what other parameters we should be implicitly passing.
Richard Smith5b349582017-10-13 01:55:36 +00001412 UsualDeleteParams Params;
Richard Smithb2f0f052016-10-10 18:54:32 +00001413 if (NumPlacementArgs) {
1414 // A placement deallocation function is implicitly passed an alignment
1415 // if the placement allocation function was, but is never passed a size.
Richard Smith5b349582017-10-13 01:55:36 +00001416 Params.Alignment = PassAlignmentToPlacementDelete;
Richard Smithb2f0f052016-10-10 18:54:32 +00001417 } else {
1418 // For a non-placement new-expression, 'operator delete' can take a
1419 // size and/or an alignment if it has the right parameters.
Richard Smith5b349582017-10-13 01:55:36 +00001420 Params = getUsualDeleteParams(OperatorDelete);
John McCall7f9c92a2010-09-17 00:50:28 +00001421 }
1422
Richard Smith5b349582017-10-13 01:55:36 +00001423 assert(!Params.DestroyingDelete &&
1424 "should not call destroying delete in a new-expression");
1425
Richard Smithb2f0f052016-10-10 18:54:32 +00001426 // The second argument can be a std::size_t (for non-placement delete).
Richard Smith5b349582017-10-13 01:55:36 +00001427 if (Params.Size)
Richard Smithb2f0f052016-10-10 18:54:32 +00001428 DeleteArgs.add(Traits::get(CGF, AllocSize),
1429 CGF.getContext().getSizeType());
1430
1431 // The next (second or third) argument can be a std::align_val_t, which
1432 // is an enum whose underlying type is std::size_t.
1433 // FIXME: Use the right type as the parameter type. Note that in a call
1434 // to operator delete(size_t, ...), we may not have it available.
Richard Smith5b349582017-10-13 01:55:36 +00001435 if (Params.Alignment)
Richard Smithb2f0f052016-10-10 18:54:32 +00001436 DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1437 CGF.SizeTy, AllocAlign.getQuantity())),
1438 CGF.getContext().getSizeType());
1439
John McCall7f9c92a2010-09-17 00:50:28 +00001440 // Pass the rest of the arguments, which must match exactly.
1441 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001442 auto Arg = getPlacementArgs()[I];
1443 DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
John McCall7f9c92a2010-09-17 00:50:28 +00001444 }
1445
1446 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001447 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7f9c92a2010-09-17 00:50:28 +00001448 }
1449 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001450}
John McCall7f9c92a2010-09-17 00:50:28 +00001451
1452/// Enter a cleanup to call 'operator delete' if the initializer in a
1453/// new-expression throws.
1454static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1455 const CXXNewExpr *E,
John McCall7f416cc2015-09-08 08:05:57 +00001456 Address NewPtr,
John McCall7f9c92a2010-09-17 00:50:28 +00001457 llvm::Value *AllocSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00001458 CharUnits AllocAlign,
John McCall7f9c92a2010-09-17 00:50:28 +00001459 const CallArgList &NewArgs) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001460 unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1461
John McCall7f9c92a2010-09-17 00:50:28 +00001462 // If we're not inside a conditional branch, then the cleanup will
1463 // dominate and we can do the easier (and more efficient) thing.
1464 if (!CGF.isInConditionalBranch()) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001465 struct DirectCleanupTraits {
1466 typedef llvm::Value *ValueTy;
1467 typedef RValue RValueTy;
1468 static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1469 static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1470 };
1471
1472 typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1473
1474 DirectCleanup *Cleanup = CGF.EHStack
1475 .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
1476 E->getNumPlacementArgs(),
1477 E->getOperatorDelete(),
1478 NewPtr.getPointer(),
1479 AllocSize,
1480 E->passAlignment(),
1481 AllocAlign);
1482 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1483 auto &Arg = NewArgs[I + NumNonPlacementArgs];
1484 Cleanup->setPlacementArg(I, Arg.RV, Arg.Ty);
1485 }
John McCall7f9c92a2010-09-17 00:50:28 +00001486
1487 return;
1488 }
1489
1490 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001491 DominatingValue<RValue>::saved_type SavedNewPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001492 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
John McCallcb5f77f2011-01-28 10:53:53 +00001493 DominatingValue<RValue>::saved_type SavedAllocSize =
1494 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001495
Richard Smithb2f0f052016-10-10 18:54:32 +00001496 struct ConditionalCleanupTraits {
1497 typedef DominatingValue<RValue>::saved_type ValueTy;
1498 typedef DominatingValue<RValue>::saved_type RValueTy;
1499 static RValue get(CodeGenFunction &CGF, ValueTy V) {
1500 return V.restore(CGF);
1501 }
1502 };
1503 typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1504
1505 ConditionalCleanup *Cleanup = CGF.EHStack
1506 .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
1507 E->getNumPlacementArgs(),
1508 E->getOperatorDelete(),
1509 SavedNewPtr,
1510 SavedAllocSize,
1511 E->passAlignment(),
1512 AllocAlign);
1513 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1514 auto &Arg = NewArgs[I + NumNonPlacementArgs];
1515 Cleanup->setPlacementArg(I, DominatingValue<RValue>::save(CGF, Arg.RV),
1516 Arg.Ty);
1517 }
John McCall7f9c92a2010-09-17 00:50:28 +00001518
John McCallf4beacd2011-11-10 10:43:54 +00001519 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001520}
1521
Anders Carlssoncc52f652009-09-22 22:53:17 +00001522llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001523 // The element type being allocated.
1524 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001525
John McCall75f94982011-03-07 03:12:35 +00001526 // 1. Build a call to the allocation function.
1527 FunctionDecl *allocator = E->getOperatorNew();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001528
Sebastian Redlf862eb62012-02-22 17:37:52 +00001529 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1530 unsigned minElements = 0;
1531 if (E->isArray() && E->hasInitializer()) {
Richard Smith0511d232016-10-05 22:41:02 +00001532 const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
1533 if (ILE && ILE->isStringLiteralInit())
1534 minElements =
1535 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1536 ->getSize().getZExtValue();
1537 else if (ILE)
Sebastian Redlf862eb62012-02-22 17:37:52 +00001538 minElements = ILE->getNumInits();
1539 }
1540
Craig Topper8a13c412014-05-21 05:09:00 +00001541 llvm::Value *numElements = nullptr;
1542 llvm::Value *allocSizeWithoutCookie = nullptr;
John McCall75f94982011-03-07 03:12:35 +00001543 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001544 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1545 allocSizeWithoutCookie);
Richard Smithb2f0f052016-10-10 18:54:32 +00001546 CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00001547
John McCall7ec4b432011-05-16 01:05:12 +00001548 // Emit the allocation call. If the allocator is a global placement
1549 // operator, just "inline" it directly.
John McCall7f416cc2015-09-08 08:05:57 +00001550 Address allocation = Address::invalid();
1551 CallArgList allocatorArgs;
John McCall7ec4b432011-05-16 01:05:12 +00001552 if (allocator->isReservedGlobalPlacementOperator()) {
John McCall53dcf942015-09-29 23:55:17 +00001553 assert(E->getNumPlacementArgs() == 1);
1554 const Expr *arg = *E->placement_arguments().begin();
1555
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001556 LValueBaseInfo BaseInfo;
1557 allocation = EmitPointerWithAlignment(arg, &BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +00001558
1559 // The pointer expression will, in many cases, be an opaque void*.
1560 // In these cases, discard the computed alignment and use the
1561 // formal alignment of the allocated type.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001562 if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
Richard Smithb2f0f052016-10-10 18:54:32 +00001563 allocation = Address(allocation.getPointer(), allocAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001564
John McCall53dcf942015-09-29 23:55:17 +00001565 // Set up allocatorArgs for the call to operator delete if it's not
1566 // the reserved global operator.
1567 if (E->getOperatorDelete() &&
1568 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1569 allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1570 allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
1571 }
1572
John McCall7ec4b432011-05-16 01:05:12 +00001573 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001574 const FunctionProtoType *allocatorType =
1575 allocator->getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00001576 unsigned ParamsToSkip = 0;
John McCall7f416cc2015-09-08 08:05:57 +00001577
1578 // The allocation size is the first argument.
1579 QualType sizeType = getContext().getSizeType();
1580 allocatorArgs.add(RValue::get(allocSize), sizeType);
Richard Smithb2f0f052016-10-10 18:54:32 +00001581 ++ParamsToSkip;
John McCall7f416cc2015-09-08 08:05:57 +00001582
Richard Smithb2f0f052016-10-10 18:54:32 +00001583 if (allocSize != allocSizeWithoutCookie) {
1584 CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1585 allocAlign = std::max(allocAlign, cookieAlign);
1586 }
1587
1588 // The allocation alignment may be passed as the second argument.
1589 if (E->passAlignment()) {
1590 QualType AlignValT = sizeType;
1591 if (allocatorType->getNumParams() > 1) {
1592 AlignValT = allocatorType->getParamType(1);
1593 assert(getContext().hasSameUnqualifiedType(
1594 AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
1595 sizeType) &&
1596 "wrong type for alignment parameter");
1597 ++ParamsToSkip;
1598 } else {
1599 // Corner case, passing alignment to 'operator new(size_t, ...)'.
1600 assert(allocator->isVariadic() && "can't pass alignment to allocator");
1601 }
1602 allocatorArgs.add(
1603 RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1604 AlignValT);
1605 }
1606
1607 // FIXME: Why do we not pass a CalleeDecl here?
John McCall7f416cc2015-09-08 08:05:57 +00001608 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
Vedant Kumared00ea02017-03-06 05:28:22 +00001609 /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
John McCall7f416cc2015-09-08 08:05:57 +00001610
1611 RValue RV =
1612 EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1613
Richard Smithb2f0f052016-10-10 18:54:32 +00001614 // If this was a call to a global replaceable allocation function that does
1615 // not take an alignment argument, the allocator is known to produce
1616 // storage that's suitably aligned for any object that fits, up to a known
1617 // threshold. Otherwise assume it's suitably aligned for the allocated type.
1618 CharUnits allocationAlign = allocAlign;
1619 if (!E->passAlignment() &&
1620 allocator->isReplaceableGlobalAllocationFunction()) {
1621 unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1622 Target.getNewAlign(), getContext().getTypeSize(allocType)));
1623 allocationAlign = std::max(
1624 allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
John McCall7f416cc2015-09-08 08:05:57 +00001625 }
1626
1627 allocation = Address(RV.getScalarVal(), allocationAlign);
John McCall7ec4b432011-05-16 01:05:12 +00001628 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001629
John McCall75f94982011-03-07 03:12:35 +00001630 // Emit a null check on the allocation result if the allocation
1631 // function is allowed to return null (because it has a non-throwing
Richard Smith902a0232015-02-14 01:52:20 +00001632 // exception spec or is the reserved placement new) and we have an
John McCall75f94982011-03-07 03:12:35 +00001633 // interesting initializer.
Richard Smith902a0232015-02-14 01:52:20 +00001634 bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001635 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001636
Craig Topper8a13c412014-05-21 05:09:00 +00001637 llvm::BasicBlock *nullCheckBB = nullptr;
1638 llvm::BasicBlock *contBB = nullptr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001639
John McCallf7dcf322011-03-07 01:52:56 +00001640 // The null-check means that the initializer is conditionally
1641 // evaluated.
1642 ConditionalEvaluation conditional(*this);
1643
John McCall75f94982011-03-07 03:12:35 +00001644 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001645 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001646
1647 nullCheckBB = Builder.GetInsertBlock();
1648 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1649 contBB = createBasicBlock("new.cont");
1650
John McCall7f416cc2015-09-08 08:05:57 +00001651 llvm::Value *isNull =
1652 Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
John McCall75f94982011-03-07 03:12:35 +00001653 Builder.CreateCondBr(isNull, contBB, notNullBB);
1654 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001655 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001656
John McCall824c2f52010-09-14 07:57:04 +00001657 // If there's an operator delete, enter a cleanup to call it if an
1658 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001659 EHScopeStack::stable_iterator operatorDeleteCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001660 llvm::Instruction *cleanupDominator = nullptr;
John McCall7ec4b432011-05-16 01:05:12 +00001661 if (E->getOperatorDelete() &&
1662 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001663 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1664 allocatorArgs);
John McCall75f94982011-03-07 03:12:35 +00001665 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001666 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001667 }
1668
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001669 assert((allocSize == allocSizeWithoutCookie) ==
1670 CalculateCookiePadding(*this, E).isZero());
1671 if (allocSize != allocSizeWithoutCookie) {
1672 assert(E->isArray());
1673 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1674 numElements,
1675 E, allocType);
1676 }
1677
David Blaikiefb901c7a2015-04-04 15:12:29 +00001678 llvm::Type *elementTy = ConvertTypeForMem(allocType);
John McCall7f416cc2015-09-08 08:05:57 +00001679 Address result = Builder.CreateElementBitCast(allocation, elementTy);
John McCall824c2f52010-09-14 07:57:04 +00001680
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001681 // Passing pointer through invariant.group.barrier to avoid propagation of
1682 // vptrs information which may be included in previous type.
Piotr Padlewski31fd99c2017-05-20 08:56:18 +00001683 // To not break LTO with different optimizations levels, we do it regardless
1684 // of optimization level.
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001685 if (CGM.getCodeGenOpts().StrictVTablePointers &&
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001686 allocator->isReservedGlobalPlacementOperator())
1687 result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()),
1688 result.getAlignment());
1689
David Blaikiefb901c7a2015-04-04 15:12:29 +00001690 EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
John McCall99210dc2011-09-15 06:49:18 +00001691 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001692 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001693 // NewPtr is a pointer to the base element type. If we're
1694 // allocating an array of arrays, we'll need to cast back to the
1695 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001696 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall7f416cc2015-09-08 08:05:57 +00001697 if (result.getType() != resultType)
John McCall75f94982011-03-07 03:12:35 +00001698 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001699 }
John McCall824c2f52010-09-14 07:57:04 +00001700
1701 // Deactivate the 'operator delete' cleanup if we finished
1702 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001703 if (operatorDeleteCleanup.isValid()) {
1704 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1705 cleanupDominator->eraseFromParent();
1706 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001707
John McCall7f416cc2015-09-08 08:05:57 +00001708 llvm::Value *resultPtr = result.getPointer();
John McCall75f94982011-03-07 03:12:35 +00001709 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001710 conditional.end(*this);
1711
John McCall75f94982011-03-07 03:12:35 +00001712 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1713 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001714
John McCall7f416cc2015-09-08 08:05:57 +00001715 llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
1716 PHI->addIncoming(resultPtr, notNullBB);
1717 PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
John McCall75f94982011-03-07 03:12:35 +00001718 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001719
John McCall7f416cc2015-09-08 08:05:57 +00001720 resultPtr = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001721 }
John McCall8ed55a52010-09-02 09:58:18 +00001722
John McCall7f416cc2015-09-08 08:05:57 +00001723 return resultPtr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001724}
1725
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001726void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
Richard Smithb2f0f052016-10-10 18:54:32 +00001727 llvm::Value *Ptr, QualType DeleteTy,
1728 llvm::Value *NumElements,
1729 CharUnits CookieSize) {
1730 assert((!NumElements && CookieSize.isZero()) ||
1731 DeleteFD->getOverloadedOperator() == OO_Array_Delete);
John McCall8ed55a52010-09-02 09:58:18 +00001732
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001733 const FunctionProtoType *DeleteFTy =
1734 DeleteFD->getType()->getAs<FunctionProtoType>();
1735
1736 CallArgList DeleteArgs;
1737
Richard Smith5b349582017-10-13 01:55:36 +00001738 auto Params = getUsualDeleteParams(DeleteFD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001739 auto ParamTypeIt = DeleteFTy->param_type_begin();
1740
1741 // Pass the pointer itself.
1742 QualType ArgTy = *ParamTypeIt++;
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001743 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001744 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001745
Richard Smith5b349582017-10-13 01:55:36 +00001746 // Pass the std::destroying_delete tag if present.
1747 if (Params.DestroyingDelete) {
1748 QualType DDTag = *ParamTypeIt++;
1749 // Just pass an 'undef'. We expect the tag type to be an empty struct.
1750 auto *V = llvm::UndefValue::get(getTypes().ConvertType(DDTag));
1751 DeleteArgs.add(RValue::get(V), DDTag);
1752 }
1753
Richard Smithb2f0f052016-10-10 18:54:32 +00001754 // Pass the size if the delete function has a size_t parameter.
Richard Smith5b349582017-10-13 01:55:36 +00001755 if (Params.Size) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001756 QualType SizeType = *ParamTypeIt++;
1757 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1758 llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1759 DeleteTypeSize.getQuantity());
1760
1761 // For array new, multiply by the number of elements.
1762 if (NumElements)
1763 Size = Builder.CreateMul(Size, NumElements);
1764
1765 // If there is a cookie, add the cookie size.
1766 if (!CookieSize.isZero())
1767 Size = Builder.CreateAdd(
1768 Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1769
1770 DeleteArgs.add(RValue::get(Size), SizeType);
1771 }
1772
1773 // Pass the alignment if the delete function has an align_val_t parameter.
Richard Smith5b349582017-10-13 01:55:36 +00001774 if (Params.Alignment) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001775 QualType AlignValType = *ParamTypeIt++;
1776 CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits(
1777 getContext().getTypeAlignIfKnown(DeleteTy));
1778 llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1779 DeleteTypeAlign.getQuantity());
1780 DeleteArgs.add(RValue::get(Align), AlignValType);
1781 }
1782
1783 assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1784 "unknown parameter to usual delete function");
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001785
1786 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001787 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001788}
1789
John McCall8ed55a52010-09-02 09:58:18 +00001790namespace {
1791 /// Calls the given 'operator delete' on a single object.
David Blaikie7e70d682015-08-18 22:40:54 +00001792 struct CallObjectDelete final : EHScopeStack::Cleanup {
John McCall8ed55a52010-09-02 09:58:18 +00001793 llvm::Value *Ptr;
1794 const FunctionDecl *OperatorDelete;
1795 QualType ElementType;
1796
1797 CallObjectDelete(llvm::Value *Ptr,
1798 const FunctionDecl *OperatorDelete,
1799 QualType ElementType)
1800 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1801
Craig Topper4f12f102014-03-12 06:41:41 +00001802 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001803 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1804 }
1805 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001806}
John McCall8ed55a52010-09-02 09:58:18 +00001807
David Majnemer0c0b6d92014-10-31 20:09:12 +00001808void
1809CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1810 llvm::Value *CompletePtr,
1811 QualType ElementType) {
1812 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1813 OperatorDelete, ElementType);
1814}
1815
Richard Smith5b349582017-10-13 01:55:36 +00001816/// Emit the code for deleting a single object with a destroying operator
1817/// delete. If the element type has a non-virtual destructor, Ptr has already
1818/// been converted to the type of the parameter of 'operator delete'. Otherwise
1819/// Ptr points to an object of the static type.
1820static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,
1821 const CXXDeleteExpr *DE, Address Ptr,
1822 QualType ElementType) {
1823 auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();
1824 if (Dtor && Dtor->isVirtual())
1825 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1826 Dtor);
1827 else
1828 CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.getPointer(), ElementType);
1829}
1830
John McCall8ed55a52010-09-02 09:58:18 +00001831/// Emit the code for deleting a single object.
1832static void EmitObjectDelete(CodeGenFunction &CGF,
David Majnemer08681372014-11-01 07:37:17 +00001833 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001834 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001835 QualType ElementType) {
Ivan Krasind98f5d72016-11-17 00:39:48 +00001836 // C++11 [expr.delete]p3:
1837 // If the static type of the object to be deleted is different from its
1838 // dynamic type, the static type shall be a base class of the dynamic type
1839 // of the object to be deleted and the static type shall have a virtual
1840 // destructor or the behavior is undefined.
1841 CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall,
1842 DE->getExprLoc(), Ptr.getPointer(),
1843 ElementType);
1844
Richard Smith5b349582017-10-13 01:55:36 +00001845 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1846 assert(!OperatorDelete->isDestroyingOperatorDelete());
1847
John McCall8ed55a52010-09-02 09:58:18 +00001848 // Find the destructor for the type, if applicable. If the
1849 // destructor is virtual, we'll just emit the vcall and return.
Craig Topper8a13c412014-05-21 05:09:00 +00001850 const CXXDestructorDecl *Dtor = nullptr;
John McCall8ed55a52010-09-02 09:58:18 +00001851 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1852 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001853 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001854 Dtor = RD->getDestructor();
1855
1856 if (Dtor->isVirtual()) {
David Majnemer08681372014-11-01 07:37:17 +00001857 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1858 Dtor);
John McCall8ed55a52010-09-02 09:58:18 +00001859 return;
1860 }
1861 }
1862 }
1863
1864 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001865 // This doesn't have to a conditional cleanup because we're going
1866 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001867 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
John McCall7f416cc2015-09-08 08:05:57 +00001868 Ptr.getPointer(),
1869 OperatorDelete, ElementType);
John McCall8ed55a52010-09-02 09:58:18 +00001870
1871 if (Dtor)
1872 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001873 /*ForVirtualBase=*/false,
1874 /*Delegating=*/false,
1875 Ptr);
John McCall460ce582015-10-22 18:38:17 +00001876 else if (auto Lifetime = ElementType.getObjCLifetime()) {
1877 switch (Lifetime) {
John McCall31168b02011-06-15 23:02:42 +00001878 case Qualifiers::OCL_None:
1879 case Qualifiers::OCL_ExplicitNone:
1880 case Qualifiers::OCL_Autoreleasing:
1881 break;
John McCall8ed55a52010-09-02 09:58:18 +00001882
John McCall7f416cc2015-09-08 08:05:57 +00001883 case Qualifiers::OCL_Strong:
1884 CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001885 break;
John McCall31168b02011-06-15 23:02:42 +00001886
1887 case Qualifiers::OCL_Weak:
1888 CGF.EmitARCDestroyWeak(Ptr);
1889 break;
1890 }
1891 }
1892
John McCall8ed55a52010-09-02 09:58:18 +00001893 CGF.PopCleanupBlock();
1894}
1895
1896namespace {
1897 /// Calls the given 'operator delete' on an array of objects.
David Blaikie7e70d682015-08-18 22:40:54 +00001898 struct CallArrayDelete final : EHScopeStack::Cleanup {
John McCall8ed55a52010-09-02 09:58:18 +00001899 llvm::Value *Ptr;
1900 const FunctionDecl *OperatorDelete;
1901 llvm::Value *NumElements;
1902 QualType ElementType;
1903 CharUnits CookieSize;
1904
1905 CallArrayDelete(llvm::Value *Ptr,
1906 const FunctionDecl *OperatorDelete,
1907 llvm::Value *NumElements,
1908 QualType ElementType,
1909 CharUnits CookieSize)
1910 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1911 ElementType(ElementType), CookieSize(CookieSize) {}
1912
Craig Topper4f12f102014-03-12 06:41:41 +00001913 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smithb2f0f052016-10-10 18:54:32 +00001914 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
1915 CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001916 }
1917 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001918}
John McCall8ed55a52010-09-02 09:58:18 +00001919
1920/// Emit the code for deleting an array of objects.
1921static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001922 const CXXDeleteExpr *E,
John McCall7f416cc2015-09-08 08:05:57 +00001923 Address deletedPtr,
John McCallca2c56f2011-07-13 01:41:37 +00001924 QualType elementType) {
Craig Topper8a13c412014-05-21 05:09:00 +00001925 llvm::Value *numElements = nullptr;
1926 llvm::Value *allocatedPtr = nullptr;
John McCallca2c56f2011-07-13 01:41:37 +00001927 CharUnits cookieSize;
1928 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1929 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001930
John McCallca2c56f2011-07-13 01:41:37 +00001931 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001932
1933 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001934 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001935 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001936 allocatedPtr, operatorDelete,
1937 numElements, elementType,
1938 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001939
John McCallca2c56f2011-07-13 01:41:37 +00001940 // Destroy the elements.
1941 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1942 assert(numElements && "no element count for a type with a destructor!");
1943
John McCall7f416cc2015-09-08 08:05:57 +00001944 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1945 CharUnits elementAlign =
1946 deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
1947
1948 llvm::Value *arrayBegin = deletedPtr.getPointer();
John McCallca2c56f2011-07-13 01:41:37 +00001949 llvm::Value *arrayEnd =
John McCall7f416cc2015-09-08 08:05:57 +00001950 CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001951
1952 // Note that it is legal to allocate a zero-length array, and we
1953 // can never fold the check away because the length should always
1954 // come from a cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001955 CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
John McCallca2c56f2011-07-13 01:41:37 +00001956 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001957 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001958 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001959 }
1960
John McCallca2c56f2011-07-13 01:41:37 +00001961 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001962 CGF.PopCleanupBlock();
1963}
1964
Anders Carlssoncc52f652009-09-22 22:53:17 +00001965void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001966 const Expr *Arg = E->getArgument();
John McCall7f416cc2015-09-08 08:05:57 +00001967 Address Ptr = EmitPointerWithAlignment(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001968
1969 // Null check the pointer.
1970 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1971 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1972
John McCall7f416cc2015-09-08 08:05:57 +00001973 llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001974
1975 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1976 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001977
Richard Smith5b349582017-10-13 01:55:36 +00001978 QualType DeleteTy = E->getDestroyedType();
1979
1980 // A destroying operator delete overrides the entire operation of the
1981 // delete expression.
1982 if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {
1983 EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy);
1984 EmitBlock(DeleteEnd);
1985 return;
1986 }
1987
John McCall8ed55a52010-09-02 09:58:18 +00001988 // We might be deleting a pointer to array. If so, GEP down to the
1989 // first non-array element.
1990 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
John McCall8ed55a52010-09-02 09:58:18 +00001991 if (DeleteTy->isConstantArrayType()) {
1992 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001993 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001994
1995 GEP.push_back(Zero); // point at the outermost array
1996
1997 // For each layer of array type we're pointing at:
1998 while (const ConstantArrayType *Arr
1999 = getContext().getAsConstantArrayType(DeleteTy)) {
2000 // 1. Unpeel the array type.
2001 DeleteTy = Arr->getElementType();
2002
2003 // 2. GEP to the first element of the array.
2004 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00002005 }
John McCall8ed55a52010-09-02 09:58:18 +00002006
John McCall7f416cc2015-09-08 08:05:57 +00002007 Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
2008 Ptr.getAlignment());
Anders Carlssoncc52f652009-09-22 22:53:17 +00002009 }
2010
John McCall7f416cc2015-09-08 08:05:57 +00002011 assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00002012
Reid Kleckner7270ef52015-03-19 17:03:58 +00002013 if (E->isArrayForm()) {
2014 EmitArrayDelete(*this, E, Ptr, DeleteTy);
2015 } else {
2016 EmitObjectDelete(*this, E, Ptr, DeleteTy);
2017 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00002018
Anders Carlssoncc52f652009-09-22 22:53:17 +00002019 EmitBlock(DeleteEnd);
2020}
Mike Stumpc9b231c2009-11-15 08:09:41 +00002021
David Majnemer1c3d95e2014-07-19 00:17:06 +00002022static bool isGLValueFromPointerDeref(const Expr *E) {
2023 E = E->IgnoreParens();
2024
2025 if (const auto *CE = dyn_cast<CastExpr>(E)) {
2026 if (!CE->getSubExpr()->isGLValue())
2027 return false;
2028 return isGLValueFromPointerDeref(CE->getSubExpr());
2029 }
2030
2031 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
2032 return isGLValueFromPointerDeref(OVE->getSourceExpr());
2033
2034 if (const auto *BO = dyn_cast<BinaryOperator>(E))
2035 if (BO->getOpcode() == BO_Comma)
2036 return isGLValueFromPointerDeref(BO->getRHS());
2037
2038 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
2039 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
2040 isGLValueFromPointerDeref(ACO->getFalseExpr());
2041
2042 // C++11 [expr.sub]p1:
2043 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
2044 if (isa<ArraySubscriptExpr>(E))
2045 return true;
2046
2047 if (const auto *UO = dyn_cast<UnaryOperator>(E))
2048 if (UO->getOpcode() == UO_Deref)
2049 return true;
2050
2051 return false;
2052}
2053
Warren Hunt747e3012014-06-18 21:15:55 +00002054static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00002055 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00002056 // Get the vtable pointer.
John McCall7f416cc2015-09-08 08:05:57 +00002057 Address ThisPtr = CGF.EmitLValue(E).getAddress();
Anders Carlsson940f02d2011-04-18 00:57:03 +00002058
Stephan Bergmannd71ad172017-12-28 12:45:41 +00002059 QualType SrcRecordTy = E->getType();
2060
2061 // C++ [class.cdtor]p4:
2062 // If the operand of typeid refers to the object under construction or
2063 // destruction and the static type of the operand is neither the constructor
2064 // or destructor’s class nor one of its bases, the behavior is undefined.
2065 CGF.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation, E->getExprLoc(),
2066 ThisPtr.getPointer(), SrcRecordTy);
2067
Anders Carlsson940f02d2011-04-18 00:57:03 +00002068 // C++ [expr.typeid]p2:
2069 // If the glvalue expression is obtained by applying the unary * operator to
2070 // a pointer and the pointer is a null pointer value, the typeid expression
2071 // throws the std::bad_typeid exception.
David Majnemer1c3d95e2014-07-19 00:17:06 +00002072 //
2073 // However, this paragraph's intent is not clear. We choose a very generous
2074 // interpretation which implores us to consider comma operators, conditional
2075 // operators, parentheses and other such constructs.
David Majnemer1c3d95e2014-07-19 00:17:06 +00002076 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
2077 isGLValueFromPointerDeref(E), SrcRecordTy)) {
David Majnemer1162d252014-06-22 19:05:33 +00002078 llvm::BasicBlock *BadTypeidBlock =
Anders Carlsson940f02d2011-04-18 00:57:03 +00002079 CGF.createBasicBlock("typeid.bad_typeid");
David Majnemer1162d252014-06-22 19:05:33 +00002080 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
Anders Carlsson940f02d2011-04-18 00:57:03 +00002081
John McCall7f416cc2015-09-08 08:05:57 +00002082 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
David Majnemer1162d252014-06-22 19:05:33 +00002083 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002084
David Majnemer1162d252014-06-22 19:05:33 +00002085 CGF.EmitBlock(BadTypeidBlock);
2086 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2087 CGF.EmitBlock(EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002088 }
2089
David Majnemer1162d252014-06-22 19:05:33 +00002090 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
2091 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002092}
2093
John McCalle4df6c82011-01-28 08:37:24 +00002094llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002095 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00002096 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00002097
Anders Carlsson3f4336c2009-12-17 07:09:17 +00002098 if (E->isTypeOperand()) {
David Majnemer143c55e2013-09-27 07:04:31 +00002099 llvm::Constant *TypeInfo =
2100 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson940f02d2011-04-18 00:57:03 +00002101 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00002102 }
Anders Carlsson0c633502011-04-11 14:13:40 +00002103
Anders Carlsson940f02d2011-04-18 00:57:03 +00002104 // C++ [expr.typeid]p2:
2105 // When typeid is applied to a glvalue expression whose type is a
2106 // polymorphic class type, the result refers to a std::type_info object
2107 // representing the type of the most derived object (that is, the dynamic
2108 // type) to which the glvalue refers.
Richard Smithef8bf432012-08-13 20:08:14 +00002109 if (E->isPotentiallyEvaluated())
2110 return EmitTypeidFromVTable(*this, E->getExprOperand(),
2111 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002112
2113 QualType OperandTy = E->getExprOperand()->getType();
2114 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
2115 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00002116}
Mike Stump65511702009-11-16 06:50:58 +00002117
Anders Carlssonc1c99712011-04-11 01:45:29 +00002118static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
2119 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002120 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00002121 if (DestTy->isPointerType())
2122 return llvm::Constant::getNullValue(DestLTy);
2123
2124 /// C++ [expr.dynamic.cast]p9:
2125 /// A failed cast to reference type throws std::bad_cast
David Majnemer1162d252014-06-22 19:05:33 +00002126 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
2127 return nullptr;
Anders Carlssonc1c99712011-04-11 01:45:29 +00002128
2129 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
2130 return llvm::UndefValue::get(DestLTy);
2131}
2132
John McCall7f416cc2015-09-08 08:05:57 +00002133llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
Mike Stump65511702009-11-16 06:50:58 +00002134 const CXXDynamicCastExpr *DCE) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00002135 CGM.EmitExplicitCastExprType(DCE, this);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00002136 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00002137
Anders Carlssonc1c99712011-04-11 01:45:29 +00002138 QualType SrcTy = DCE->getSubExpr()->getType();
2139
David Majnemer1162d252014-06-22 19:05:33 +00002140 // C++ [expr.dynamic.cast]p7:
2141 // If T is "pointer to cv void," then the result is a pointer to the most
2142 // derived object pointed to by v.
2143 const PointerType *DestPTy = DestTy->getAs<PointerType>();
2144
2145 bool isDynamicCastToVoid;
2146 QualType SrcRecordTy;
2147 QualType DestRecordTy;
2148 if (DestPTy) {
2149 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
2150 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
2151 DestRecordTy = DestPTy->getPointeeType();
2152 } else {
2153 isDynamicCastToVoid = false;
2154 SrcRecordTy = SrcTy;
2155 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
2156 }
2157
Stephan Bergmannd71ad172017-12-28 12:45:41 +00002158 // C++ [class.cdtor]p5:
2159 // If the operand of the dynamic_cast refers to the object under
2160 // construction or destruction and the static type of the operand is not a
2161 // pointer to or object of the constructor or destructor’s own class or one
2162 // of its bases, the dynamic_cast results in undefined behavior.
2163 EmitTypeCheck(TCK_DynamicOperation, DCE->getExprLoc(), ThisAddr.getPointer(),
2164 SrcRecordTy);
2165
2166 if (DCE->isAlwaysNull())
2167 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
2168 return T;
2169
David Majnemer1162d252014-06-22 19:05:33 +00002170 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
2171
Anders Carlsson882d7902011-04-11 00:46:40 +00002172 // C++ [expr.dynamic.cast]p4:
2173 // If the value of v is a null pointer value in the pointer case, the result
2174 // is the null pointer value of type T.
David Majnemer1162d252014-06-22 19:05:33 +00002175 bool ShouldNullCheckSrcValue =
2176 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
2177 SrcRecordTy);
Craig Topper8a13c412014-05-21 05:09:00 +00002178
2179 llvm::BasicBlock *CastNull = nullptr;
2180 llvm::BasicBlock *CastNotNull = nullptr;
Anders Carlsson882d7902011-04-11 00:46:40 +00002181 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00002182
Anders Carlsson882d7902011-04-11 00:46:40 +00002183 if (ShouldNullCheckSrcValue) {
2184 CastNull = createBasicBlock("dynamic_cast.null");
2185 CastNotNull = createBasicBlock("dynamic_cast.notnull");
2186
John McCall7f416cc2015-09-08 08:05:57 +00002187 llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
Anders Carlsson882d7902011-04-11 00:46:40 +00002188 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2189 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00002190 }
2191
John McCall7f416cc2015-09-08 08:05:57 +00002192 llvm::Value *Value;
David Majnemer1162d252014-06-22 19:05:33 +00002193 if (isDynamicCastToVoid) {
John McCall7f416cc2015-09-08 08:05:57 +00002194 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00002195 DestTy);
2196 } else {
2197 assert(DestRecordTy->isRecordType() &&
2198 "destination type must be a record type!");
John McCall7f416cc2015-09-08 08:05:57 +00002199 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00002200 DestTy, DestRecordTy, CastEnd);
David Majnemer67528ea2015-11-23 03:01:14 +00002201 CastNotNull = Builder.GetInsertBlock();
David Majnemer1162d252014-06-22 19:05:33 +00002202 }
Anders Carlsson882d7902011-04-11 00:46:40 +00002203
2204 if (ShouldNullCheckSrcValue) {
2205 EmitBranch(CastEnd);
2206
2207 EmitBlock(CastNull);
2208 EmitBranch(CastEnd);
2209 }
2210
2211 EmitBlock(CastEnd);
2212
2213 if (ShouldNullCheckSrcValue) {
2214 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2215 PHI->addIncoming(Value, CastNotNull);
2216 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
2217
2218 Value = PHI;
2219 }
2220
2221 return Value;
Mike Stump65511702009-11-16 06:50:58 +00002222}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002223
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002224void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00002225 RunCleanupsScope Scope(*this);
John McCall7f416cc2015-09-08 08:05:57 +00002226 LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType());
Eli Friedman8631f3e82012-02-09 03:47:20 +00002227
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002228 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
James Y Knight53c76162015-07-17 18:21:37 +00002229 for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
2230 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00002231 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002232 // Emit initialization
David Blaikie40ed2972012-06-06 20:45:41 +00002233 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Alexey Bataev39c81e22014-08-28 04:28:19 +00002234 if (CurField->hasCapturedVLAType()) {
2235 auto VAT = CurField->getCapturedVLAType();
2236 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2237 } else {
Richard Smith30e304e2016-12-14 00:03:17 +00002238 EmitInitializerForField(*CurField, LV, *i);
Alexey Bataev39c81e22014-08-28 04:28:19 +00002239 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002240 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002241}