blob: 39c77eb8b6dcd4ccbfd1a49286495ce7ea3dc635 [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlsson16d81b82009-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 Collingbourne6c0aa5f2011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Devang Patelc69e1cf2010-09-30 19:05:55 +000017#include "CGDebugInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "CGObjCRuntime.h"
Mark Lacey8b549992013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/Frontend/CodeGenOptions.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070021#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000022#include "llvm/IR/Intrinsics.h"
Anders Carlssonad3692bb2011-04-13 02:35:36 +000023
Anders Carlsson16d81b82009-09-22 22:53:17 +000024using namespace clang;
25using namespace CodeGen;
26
Stephen Hines176edba2014-12-01 14:53:08 -080027static RequiredArgs commonEmitCXXMemberOrOperatorCall(
28 CodeGenFunction &CGF, const CXXMethodDecl *MD, llvm::Value *Callee,
29 ReturnValueSlot ReturnValue, llvm::Value *This, llvm::Value *ImplicitParam,
30 QualType ImplicitParamTy, const CallExpr *CE, CallArgList &Args) {
31 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
32 isa<CXXOperatorCallExpr>(CE));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000033 assert(MD->isInstance() &&
Stephen Hines176edba2014-12-01 14:53:08 -080034 "Trying to emit a member or operator call expr on a static method!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +000035
Richard Smith2c9f87c2012-08-24 00:54:33 +000036 // C++11 [class.mfct.non-static]p2:
37 // If a non-static member function of a class X is called for an object that
38 // is not of type X, or of a type derived from X, the behavior is undefined.
Stephen Hines176edba2014-12-01 14:53:08 -080039 SourceLocation CallLoc;
40 if (CE)
41 CallLoc = CE->getExprLoc();
42 CGF.EmitTypeCheck(
43 isa<CXXConstructorDecl>(MD) ? CodeGenFunction::TCK_ConstructorCall
44 : CodeGenFunction::TCK_MemberCall,
45 CallLoc, This, CGF.getContext().getRecordType(MD->getParent()));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000046
47 // Push the this ptr.
Stephen Hines176edba2014-12-01 14:53:08 -080048 Args.add(RValue::get(This), MD->getThisType(CGF.getContext()));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000049
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +000050 // If there is an implicit parameter (e.g. VTT), emit it.
51 if (ImplicitParam) {
52 Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
Anders Carlssonc997d422010-01-02 01:01:18 +000053 }
John McCallde5d3c72012-02-17 03:33:10 +000054
55 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
56 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Anders Carlsson3b5ad222010-01-01 20:29:01 +000057
Stephen Hines176edba2014-12-01 14:53:08 -080058 // And the rest of the call args.
59 if (CE) {
60 // Special case: skip first argument of CXXOperatorCall (it is "this").
61 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
62 CGF.EmitCallArgs(Args, FPT, CE->arg_begin() + ArgsToSkip, CE->arg_end(),
63 CE->getDirectCallee());
64 } else {
65 assert(
66 FPT->getNumParams() == 0 &&
67 "No CallExpr specified for function with non-zero number of arguments");
68 }
69 return required;
70}
71
72RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
73 const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
74 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
75 const CallExpr *CE) {
76 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
77 CallArgList Args;
78 RequiredArgs required = commonEmitCXXMemberOrOperatorCall(
79 *this, MD, Callee, ReturnValue, This, ImplicitParam, ImplicitParamTy, CE,
80 Args);
John McCall0f3d0972012-07-07 06:41:13 +000081 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
Rafael Espindola264ba482010-03-30 20:24:48 +000082 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000083}
84
Stephen Hines176edba2014-12-01 14:53:08 -080085RValue CodeGenFunction::EmitCXXStructorCall(
86 const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
87 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
88 const CallExpr *CE, StructorType Type) {
89 CallArgList Args;
90 commonEmitCXXMemberOrOperatorCall(*this, MD, Callee, ReturnValue, This,
91 ImplicitParam, ImplicitParamTy, CE, Args);
92 return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(MD, Type),
93 Callee, ReturnValue, Args, MD);
94}
95
Rafael Espindolaea01d762012-06-28 14:28:57 +000096static CXXRecordDecl *getCXXRecord(const Expr *E) {
97 QualType T = E->getType();
98 if (const PointerType *PTy = T->getAs<PointerType>())
99 T = PTy->getPointeeType();
100 const RecordType *Ty = T->castAs<RecordType>();
101 return cast<CXXRecordDecl>(Ty->getDecl());
102}
103
Francois Pichetdbee3412011-01-18 05:04:39 +0000104// Note: This function also emit constructor calls to support a MSVC
105// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000106RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
107 ReturnValueSlot ReturnValue) {
John McCall379b5152011-04-11 07:02:50 +0000108 const Expr *callee = CE->getCallee()->IgnoreParens();
109
110 if (isa<BinaryOperator>(callee))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000111 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall379b5152011-04-11 07:02:50 +0000112
113 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000114 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
115
116 if (MD->isStatic()) {
117 // The method is static, emit it as we would a regular call.
118 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
Stephen Hines176edba2014-12-01 14:53:08 -0800119 return EmitCall(getContext().getPointerType(MD->getType()), Callee, CE,
120 ReturnValue);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000121 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000122
John McCallfc400282010-09-03 01:26:39 +0000123 // Compute the object pointer.
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000124 const Expr *Base = ME->getBase();
125 bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000126
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700127 const CXXMethodDecl *DevirtualizedMethod = nullptr;
Benjamin Kramer9581ed02013-08-25 22:46:27 +0000128 if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000129 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
130 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
131 assert(DevirtualizedMethod);
132 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
133 const Expr *Inner = Base->ignoreParenBaseCasts();
Stephen Hines176edba2014-12-01 14:53:08 -0800134 if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
135 MD->getReturnType().getCanonicalType())
136 // If the return types are not the same, this might be a case where more
137 // code needs to run to compensate for it. For example, the derived
138 // method might return a type that inherits form from the return
139 // type of MD and has a prefix.
140 // For now we just avoid devirtualizing these covariant cases.
141 DevirtualizedMethod = nullptr;
142 else if (getCXXRecord(Inner) == DevirtualizedClass)
Rafael Espindolaea01d762012-06-28 14:28:57 +0000143 // If the class of the Inner expression is where the dynamic method
144 // is defined, build the this pointer from it.
145 Base = Inner;
146 else if (getCXXRecord(Base) != DevirtualizedClass) {
147 // If the method is defined in a class that is not the best dynamic
148 // one or the one of the full expression, we would have to build
149 // a derived-to-base cast to compute the correct this pointer, but
150 // we don't have support for that yet, so do a virtual call.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700151 DevirtualizedMethod = nullptr;
Rafael Espindolaea01d762012-06-28 14:28:57 +0000152 }
153 }
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000154
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000155 llvm::Value *This;
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000156 if (ME->isArrow())
Rafael Espindolaea01d762012-06-28 14:28:57 +0000157 This = EmitScalarExpr(Base);
John McCall0e800c92010-12-04 08:14:53 +0000158 else
Rafael Espindolaea01d762012-06-28 14:28:57 +0000159 This = EmitLValue(Base).getAddress();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000160
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000161
John McCallfc400282010-09-03 01:26:39 +0000162 if (MD->isTrivial()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700163 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
Francois Pichetdbee3412011-01-18 05:04:39 +0000164 if (isa<CXXConstructorDecl>(MD) &&
165 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700166 return RValue::get(nullptr);
John McCallfc400282010-09-03 01:26:39 +0000167
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000168 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
169 // We don't like to generate the trivial copy/move assignment operator
170 // when it isn't necessary; just produce the proper effect here.
Francois Pichetdbee3412011-01-18 05:04:39 +0000171 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
Benjamin Kramer6cacae82012-09-30 12:43:37 +0000172 EmitAggregateAssign(This, RHS, CE->getType());
Francois Pichetdbee3412011-01-18 05:04:39 +0000173 return RValue::get(This);
174 }
Stephen Hines176edba2014-12-01 14:53:08 -0800175
176 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000177 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
178 // Trivial move and copy ctor are the same.
Stephen Hines176edba2014-12-01 14:53:08 -0800179 assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
Francois Pichetdbee3412011-01-18 05:04:39 +0000180 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
Stephen Hines176edba2014-12-01 14:53:08 -0800181 EmitAggregateCopy(This, RHS, CE->arg_begin()->getType());
Francois Pichetdbee3412011-01-18 05:04:39 +0000182 return RValue::get(This);
183 }
184 llvm_unreachable("unknown trivial member function");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000185 }
186
John McCallfc400282010-09-03 01:26:39 +0000187 // Compute the function type we're calling.
Eli Friedman465e89e2012-10-25 00:12:49 +0000188 const CXXMethodDecl *CalleeDecl = DevirtualizedMethod ? DevirtualizedMethod : MD;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700189 const CGFunctionInfo *FInfo = nullptr;
Eli Friedman465e89e2012-10-25 00:12:49 +0000190 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
Stephen Hines176edba2014-12-01 14:53:08 -0800191 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
192 Dtor, StructorType::Complete);
Eli Friedman465e89e2012-10-25 00:12:49 +0000193 else if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
Stephen Hines176edba2014-12-01 14:53:08 -0800194 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
195 Ctor, StructorType::Complete);
Francois Pichetdbee3412011-01-18 05:04:39 +0000196 else
Eli Friedman465e89e2012-10-25 00:12:49 +0000197 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCallfc400282010-09-03 01:26:39 +0000198
Reid Klecknera4130ba2013-07-22 13:51:44 +0000199 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCallfc400282010-09-03 01:26:39 +0000200
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000201 // C++ [class.virtual]p12:
202 // Explicit qualification with the scope operator (5.1) suppresses the
203 // virtual call mechanism.
204 //
205 // We also don't emit a virtual call if the base expression has a record type
206 // because then we know what the type is.
Rafael Espindolaea01d762012-06-28 14:28:57 +0000207 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Stephen Lin3258abc2013-06-19 23:23:19 +0000208 llvm::Value *Callee;
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000209
John McCallfc400282010-09-03 01:26:39 +0000210 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000211 assert(CE->arg_begin() == CE->arg_end() &&
212 "Destructor shouldn't have explicit parameters");
213 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
John McCallfc400282010-09-03 01:26:39 +0000214 if (UseVirtualCall) {
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000215 CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
Stephen Hines176edba2014-12-01 14:53:08 -0800216 This, CE);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000217 } else {
Richard Smith7edf9e32012-11-01 22:30:59 +0000218 if (getLangOpts().AppleKext &&
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000219 MD->isVirtual() &&
220 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000221 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000222 else if (!DevirtualizedMethod)
Stephen Hines176edba2014-12-01 14:53:08 -0800223 Callee =
224 CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000225 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000226 const CXXDestructorDecl *DDtor =
227 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000228 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
229 }
Stephen Hines176edba2014-12-01 14:53:08 -0800230 EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
231 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000232 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700233 return RValue::get(nullptr);
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000234 }
235
236 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Francois Pichetdbee3412011-01-18 05:04:39 +0000237 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000238 } else if (UseVirtualCall) {
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000239 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000240 } else {
Richard Smith7edf9e32012-11-01 22:30:59 +0000241 if (getLangOpts().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000242 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000243 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000244 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000245 else if (!DevirtualizedMethod)
Rafael Espindola12582bd2012-06-26 19:18:25 +0000246 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000247 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000248 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000249 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000250 }
251
Stephen Hines651f13c2014-04-23 16:59:28 -0700252 if (MD->isVirtual()) {
253 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
254 *this, MD, This, UseVirtualCall);
255 }
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +0000256
Stephen Hines176edba2014-12-01 14:53:08 -0800257 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
258 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000259}
260
261RValue
262CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
263 ReturnValueSlot ReturnValue) {
264 const BinaryOperator *BO =
265 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
266 const Expr *BaseExpr = BO->getLHS();
267 const Expr *MemFnExpr = BO->getRHS();
268
269 const MemberPointerType *MPT =
John McCall864c0412011-04-26 20:42:42 +0000270 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000271
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000272 const FunctionProtoType *FPT =
John McCall864c0412011-04-26 20:42:42 +0000273 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000274 const CXXRecordDecl *RD =
275 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
276
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000277 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000278 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000279
280 // Emit the 'this' pointer.
281 llvm::Value *This;
282
John McCall2de56d12010-08-25 11:45:40 +0000283 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000284 This = EmitScalarExpr(BaseExpr);
285 else
286 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000287
Richard Smith4def70d2012-10-09 19:52:38 +0000288 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
289 QualType(MPT->getClass(), 0));
Richard Smith2c9f87c2012-08-24 00:54:33 +0000290
John McCall93d557b2010-08-22 00:05:51 +0000291 // Ask the ABI to load the callee. Note that This is modified.
292 llvm::Value *Callee =
Stephen Hines651f13c2014-04-23 16:59:28 -0700293 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000294
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000295 CallArgList Args;
296
297 QualType ThisType =
298 getContext().getPointerType(getContext().getTagDeclType(RD));
299
300 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +0000301 Args.add(RValue::get(This), ThisType);
John McCall0f3d0972012-07-07 06:41:13 +0000302
303 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000304
305 // And the rest of the call args
Stephen Hines176edba2014-12-01 14:53:08 -0800306 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getDirectCallee());
Nick Lewycky5d4a7552013-10-01 21:51:38 +0000307 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
308 Callee, ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000309}
310
311RValue
312CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
313 const CXXMethodDecl *MD,
314 ReturnValueSlot ReturnValue) {
315 assert(MD->isInstance() &&
316 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000317 LValue LV = EmitLValue(E->getArg(0));
318 llvm::Value *This = LV.getAddress();
319
Douglas Gregorb2b56582011-09-06 16:26:56 +0000320 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
Stephen Hines176edba2014-12-01 14:53:08 -0800321 MD->isTrivial() && !MD->getParent()->mayInsertExtraPadding()) {
Douglas Gregorb2b56582011-09-06 16:26:56 +0000322 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
323 QualType Ty = E->getType();
Benjamin Kramer6cacae82012-09-30 12:43:37 +0000324 EmitAggregateAssign(This, Src, Ty);
Douglas Gregorb2b56582011-09-06 16:26:56 +0000325 return RValue::get(This);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000326 }
327
Anders Carlssona2447e02011-05-08 20:32:23 +0000328 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Stephen Hines176edba2014-12-01 14:53:08 -0800329 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
330 /*ImplicitParam=*/nullptr, QualType(), E);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000331}
332
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000333RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
334 ReturnValueSlot ReturnValue) {
335 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
336}
337
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000338static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
339 llvm::Value *DestPtr,
340 const CXXRecordDecl *Base) {
341 if (Base->isEmpty())
342 return;
343
344 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
345
346 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
347 CharUnits Size = Layout.getNonVirtualSize();
Stephen Hines651f13c2014-04-23 16:59:28 -0700348 CharUnits Align = Layout.getNonVirtualAlignment();
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000349
350 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
351
352 // If the type contains a pointer to data member we can't memset it to zero.
353 // Instead, create a null constant and copy it to the destination.
354 // TODO: there are other patterns besides zero that we can usefully memset,
355 // like -1, which happens to be the pattern used by member-pointers.
356 // TODO: isZeroInitializable can be over-conservative in the case where a
357 // virtual base contains a member pointer.
358 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
359 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
360
361 llvm::GlobalVariable *NullVariable =
362 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
363 /*isConstant=*/true,
364 llvm::GlobalVariable::PrivateLinkage,
365 NullConstant, Twine());
366 NullVariable->setAlignment(Align.getQuantity());
367 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
368
369 // Get and call the appropriate llvm.memcpy overload.
370 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
371 return;
372 }
373
374 // Otherwise, just memset the whole thing to zero. This is legal
375 // because in LLVM, all default initializers (other than the ones we just
376 // handled above) are guaranteed to have a bit pattern of all zeros.
377 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
378 Align.getQuantity());
379}
380
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000381void
John McCall558d2ab2010-09-15 10:14:12 +0000382CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
383 AggValueSlot Dest) {
384 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000385 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000386
387 // If we require zero initialization before (or instead of) calling the
388 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +0000389 // constructor, emit the zero initialization now, unless destination is
390 // already zeroed.
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000391 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
392 switch (E->getConstructionKind()) {
393 case CXXConstructExpr::CK_Delegating:
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000394 case CXXConstructExpr::CK_Complete:
395 EmitNullInitialization(Dest.getAddr(), E->getType());
396 break;
397 case CXXConstructExpr::CK_VirtualBase:
398 case CXXConstructExpr::CK_NonVirtualBase:
399 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
400 break;
401 }
402 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000403
404 // If this is a call to a trivial default constructor, do nothing.
405 if (CD->isTrivial() && CD->isDefaultConstructor())
406 return;
407
John McCallfc1e6c72010-09-18 00:58:34 +0000408 // Elide the constructor if we're constructing from a temporary.
409 // The temporary check is required because Sema sets this on NRVO
410 // returns.
Richard Smith7edf9e32012-11-01 22:30:59 +0000411 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000412 assert(getContext().hasSameUnqualifiedType(E->getType(),
413 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000414 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
415 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000416 return;
417 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000418 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000419
John McCallc3c07662011-07-13 06:10:41 +0000420 if (const ConstantArrayType *arrayType
421 = getContext().getAsConstantArrayType(E->getType())) {
Stephen Hines176edba2014-12-01 14:53:08 -0800422 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(), E);
John McCallc3c07662011-07-13 06:10:41 +0000423 } else {
Cameron Esfahani6bd2f6a2011-05-06 21:28:42 +0000424 CXXCtorType Type = Ctor_Complete;
Sean Huntd49bd552011-05-03 20:19:28 +0000425 bool ForVirtualBase = false;
Douglas Gregor378e1e72013-01-31 05:50:40 +0000426 bool Delegating = false;
427
Sean Huntd49bd552011-05-03 20:19:28 +0000428 switch (E->getConstructionKind()) {
429 case CXXConstructExpr::CK_Delegating:
Sean Hunt059ce0d2011-05-01 07:04:31 +0000430 // We should be emitting a constructor; GlobalDecl will assert this
431 Type = CurGD.getCtorType();
Douglas Gregor378e1e72013-01-31 05:50:40 +0000432 Delegating = true;
Sean Huntd49bd552011-05-03 20:19:28 +0000433 break;
Sean Hunt059ce0d2011-05-01 07:04:31 +0000434
Sean Huntd49bd552011-05-03 20:19:28 +0000435 case CXXConstructExpr::CK_Complete:
436 Type = Ctor_Complete;
437 break;
438
439 case CXXConstructExpr::CK_VirtualBase:
440 ForVirtualBase = true;
441 // fall-through
442
443 case CXXConstructExpr::CK_NonVirtualBase:
444 Type = Ctor_Base;
445 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000446
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000447 // Call the constructor.
Douglas Gregor378e1e72013-01-31 05:50:40 +0000448 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
Stephen Hines176edba2014-12-01 14:53:08 -0800449 E);
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000450 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000451}
452
Fariborz Jahanian34999872010-11-13 21:53:34 +0000453void
454CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
455 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000456 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000457 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000458 Exp = E->getSubExpr();
459 assert(isa<CXXConstructExpr>(Exp) &&
460 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
461 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
462 const CXXConstructorDecl *CD = E->getConstructor();
463 RunCleanupsScope Scope(*this);
464
465 // If we require zero initialization before (or instead of) calling the
466 // constructor, as can be the case with a non-user-provided default
467 // constructor, emit the zero initialization now.
468 // FIXME. Do I still need this for a copy ctor synthesis?
469 if (E->requiresZeroInitialization())
470 EmitNullInitialization(Dest, E->getType());
471
Chandler Carruth858a5462010-11-15 13:54:43 +0000472 assert(!getContext().getAsConstantArrayType(E->getType())
473 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Stephen Hines176edba2014-12-01 14:53:08 -0800474 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
Fariborz Jahanian34999872010-11-13 21:53:34 +0000475}
476
John McCall1e7fe752010-09-02 09:58:18 +0000477static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
478 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000479 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000480 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000481
John McCallb1c98a32011-05-16 01:05:12 +0000482 // No cookie is required if the operator new[] being used is the
483 // reserved placement operator new[].
484 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCall5172ed92010-08-23 01:17:59 +0000485 return CharUnits::Zero();
486
John McCall6ec278d2011-01-27 09:37:56 +0000487 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000488}
489
John McCall7d166272011-05-15 07:14:44 +0000490static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
491 const CXXNewExpr *e,
Sebastian Redl92036472012-02-22 17:37:52 +0000492 unsigned minElements,
John McCall7d166272011-05-15 07:14:44 +0000493 llvm::Value *&numElements,
494 llvm::Value *&sizeWithoutCookie) {
495 QualType type = e->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000496
John McCall7d166272011-05-15 07:14:44 +0000497 if (!e->isArray()) {
498 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
499 sizeWithoutCookie
500 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
501 return sizeWithoutCookie;
Douglas Gregor59174c02010-07-21 01:10:17 +0000502 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000503
John McCall7d166272011-05-15 07:14:44 +0000504 // The width of size_t.
505 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
506
John McCall1e7fe752010-09-02 09:58:18 +0000507 // Figure out the cookie size.
John McCall7d166272011-05-15 07:14:44 +0000508 llvm::APInt cookieSize(sizeWidth,
509 CalculateCookiePadding(CGF, e).getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000510
Anders Carlssona4d4c012009-09-23 16:07:23 +0000511 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000512 // We multiply the size of all dimensions for NumElements.
513 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall7d166272011-05-15 07:14:44 +0000514 numElements = CGF.EmitScalarExpr(e->getArraySize());
515 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall1e7fe752010-09-02 09:58:18 +0000516
John McCall7d166272011-05-15 07:14:44 +0000517 // The number of elements can be have an arbitrary integer type;
518 // essentially, we need to multiply it by a constant factor, add a
519 // cookie size, and verify that the result is representable as a
520 // size_t. That's just a gloss, though, and it's wrong in one
521 // important way: if the count is negative, it's an error even if
522 // the cookie size would bring the total size >= 0.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000523 bool isSigned
524 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000525 llvm::IntegerType *numElementsType
John McCall7d166272011-05-15 07:14:44 +0000526 = cast<llvm::IntegerType>(numElements->getType());
527 unsigned numElementsWidth = numElementsType->getBitWidth();
528
529 // Compute the constant factor.
530 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000531 while (const ConstantArrayType *CAT
John McCall7d166272011-05-15 07:14:44 +0000532 = CGF.getContext().getAsConstantArrayType(type)) {
533 type = CAT->getElementType();
534 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000535 }
536
John McCall7d166272011-05-15 07:14:44 +0000537 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
538 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
539 typeSizeMultiplier *= arraySizeMultiplier;
540
541 // This will be a size_t.
542 llvm::Value *size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000543
Chris Lattner806941e2010-07-20 21:55:52 +0000544 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
545 // Don't bloat the -O0 code.
John McCall7d166272011-05-15 07:14:44 +0000546 if (llvm::ConstantInt *numElementsC =
547 dyn_cast<llvm::ConstantInt>(numElements)) {
548 const llvm::APInt &count = numElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000549
John McCall7d166272011-05-15 07:14:44 +0000550 bool hasAnyOverflow = false;
John McCall1e7fe752010-09-02 09:58:18 +0000551
John McCall7d166272011-05-15 07:14:44 +0000552 // If 'count' was a negative number, it's an overflow.
553 if (isSigned && count.isNegative())
554 hasAnyOverflow = true;
John McCall1e7fe752010-09-02 09:58:18 +0000555
John McCall7d166272011-05-15 07:14:44 +0000556 // We want to do all this arithmetic in size_t. If numElements is
557 // wider than that, check whether it's already too big, and if so,
558 // overflow.
559 else if (numElementsWidth > sizeWidth &&
560 numElementsWidth - sizeWidth > count.countLeadingZeros())
561 hasAnyOverflow = true;
562
563 // Okay, compute a count at the right width.
564 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
565
Sebastian Redl92036472012-02-22 17:37:52 +0000566 // If there is a brace-initializer, we cannot allocate fewer elements than
567 // there are initializers. If we do, that's treated like an overflow.
568 if (adjustedCount.ult(minElements))
569 hasAnyOverflow = true;
570
John McCall7d166272011-05-15 07:14:44 +0000571 // Scale numElements by that. This might overflow, but we don't
572 // care because it only overflows if allocationSize does, too, and
573 // if that overflows then we shouldn't use this.
574 numElements = llvm::ConstantInt::get(CGF.SizeTy,
575 adjustedCount * arraySizeMultiplier);
576
577 // Compute the size before cookie, and track whether it overflowed.
578 bool overflow;
579 llvm::APInt allocationSize
580 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
581 hasAnyOverflow |= overflow;
582
583 // Add in the cookie, and check whether it's overflowed.
584 if (cookieSize != 0) {
585 // Save the current size without a cookie. This shouldn't be
586 // used if there was overflow.
587 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
588
589 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
590 hasAnyOverflow |= overflow;
591 }
592
593 // On overflow, produce a -1 so operator new will fail.
594 if (hasAnyOverflow) {
595 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
596 } else {
597 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
598 }
599
600 // Otherwise, we might need to use the overflow intrinsics.
601 } else {
Sebastian Redl92036472012-02-22 17:37:52 +0000602 // There are up to five conditions we need to test for:
John McCall7d166272011-05-15 07:14:44 +0000603 // 1) if isSigned, we need to check whether numElements is negative;
604 // 2) if numElementsWidth > sizeWidth, we need to check whether
605 // numElements is larger than something representable in size_t;
Sebastian Redl92036472012-02-22 17:37:52 +0000606 // 3) if minElements > 0, we need to check whether numElements is smaller
607 // than that.
608 // 4) we need to compute
John McCall7d166272011-05-15 07:14:44 +0000609 // sizeWithoutCookie := numElements * typeSizeMultiplier
610 // and check whether it overflows; and
Sebastian Redl92036472012-02-22 17:37:52 +0000611 // 5) if we need a cookie, we need to compute
John McCall7d166272011-05-15 07:14:44 +0000612 // size := sizeWithoutCookie + cookieSize
613 // and check whether it overflows.
614
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700615 llvm::Value *hasOverflow = nullptr;
John McCall7d166272011-05-15 07:14:44 +0000616
617 // If numElementsWidth > sizeWidth, then one way or another, we're
618 // going to have to do a comparison for (2), and this happens to
619 // take care of (1), too.
620 if (numElementsWidth > sizeWidth) {
621 llvm::APInt threshold(numElementsWidth, 1);
622 threshold <<= sizeWidth;
623
624 llvm::Value *thresholdV
625 = llvm::ConstantInt::get(numElementsType, threshold);
626
627 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
628 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
629
630 // Otherwise, if we're signed, we want to sext up to size_t.
631 } else if (isSigned) {
632 if (numElementsWidth < sizeWidth)
633 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
634
635 // If there's a non-1 type size multiplier, then we can do the
636 // signedness check at the same time as we do the multiply
637 // because a negative number times anything will cause an
Sebastian Redl92036472012-02-22 17:37:52 +0000638 // unsigned overflow. Otherwise, we have to do it here. But at least
639 // in this case, we can subsume the >= minElements check.
John McCall7d166272011-05-15 07:14:44 +0000640 if (typeSizeMultiplier == 1)
641 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redl92036472012-02-22 17:37:52 +0000642 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall7d166272011-05-15 07:14:44 +0000643
644 // Otherwise, zext up to size_t if necessary.
645 } else if (numElementsWidth < sizeWidth) {
646 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
647 }
648
649 assert(numElements->getType() == CGF.SizeTy);
650
Sebastian Redl92036472012-02-22 17:37:52 +0000651 if (minElements) {
652 // Don't allow allocation of fewer elements than we have initializers.
653 if (!hasOverflow) {
654 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
655 llvm::ConstantInt::get(CGF.SizeTy, minElements));
656 } else if (numElementsWidth > sizeWidth) {
657 // The other existing overflow subsumes this check.
658 // We do an unsigned comparison, since any signed value < -1 is
659 // taken care of either above or below.
660 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
661 CGF.Builder.CreateICmpULT(numElements,
662 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
663 }
664 }
665
John McCall7d166272011-05-15 07:14:44 +0000666 size = numElements;
667
668 // Multiply by the type size if necessary. This multiplier
669 // includes all the factors for nested arrays.
670 //
671 // This step also causes numElements to be scaled up by the
672 // nested-array factor if necessary. Overflow on this computation
673 // can be ignored because the result shouldn't be used if
674 // allocation fails.
675 if (typeSizeMultiplier != 1) {
John McCall7d166272011-05-15 07:14:44 +0000676 llvm::Value *umul_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000677 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000678
679 llvm::Value *tsmV =
680 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
681 llvm::Value *result =
682 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
683
684 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
685 if (hasOverflow)
686 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
687 else
688 hasOverflow = overflowed;
689
690 size = CGF.Builder.CreateExtractValue(result, 0);
691
692 // Also scale up numElements by the array size multiplier.
693 if (arraySizeMultiplier != 1) {
694 // If the base element type size is 1, then we can re-use the
695 // multiply we just did.
696 if (typeSize.isOne()) {
697 assert(arraySizeMultiplier == typeSizeMultiplier);
698 numElements = size;
699
700 // Otherwise we need a separate multiply.
701 } else {
702 llvm::Value *asmV =
703 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
704 numElements = CGF.Builder.CreateMul(numElements, asmV);
705 }
706 }
707 } else {
708 // numElements doesn't need to be scaled.
709 assert(arraySizeMultiplier == 1);
Chris Lattner806941e2010-07-20 21:55:52 +0000710 }
711
John McCall7d166272011-05-15 07:14:44 +0000712 // Add in the cookie size if necessary.
713 if (cookieSize != 0) {
714 sizeWithoutCookie = size;
715
John McCall7d166272011-05-15 07:14:44 +0000716 llvm::Value *uadd_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000717 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000718
719 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
720 llvm::Value *result =
721 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
722
723 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
724 if (hasOverflow)
725 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
726 else
727 hasOverflow = overflowed;
728
729 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall1e7fe752010-09-02 09:58:18 +0000730 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000731
John McCall7d166272011-05-15 07:14:44 +0000732 // If we had any possibility of dynamic overflow, make a select to
733 // overwrite 'size' with an all-ones value, which should cause
734 // operator new to throw.
735 if (hasOverflow)
736 size = CGF.Builder.CreateSelect(hasOverflow,
737 llvm::Constant::getAllOnesValue(CGF.SizeTy),
738 size);
Chris Lattner806941e2010-07-20 21:55:52 +0000739 }
John McCall1e7fe752010-09-02 09:58:18 +0000740
John McCall7d166272011-05-15 07:14:44 +0000741 if (cookieSize == 0)
742 sizeWithoutCookie = size;
John McCall1e7fe752010-09-02 09:58:18 +0000743 else
John McCall7d166272011-05-15 07:14:44 +0000744 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall1e7fe752010-09-02 09:58:18 +0000745
John McCall7d166272011-05-15 07:14:44 +0000746 return size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000747}
748
Sebastian Redl92036472012-02-22 17:37:52 +0000749static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
750 QualType AllocType, llvm::Value *NewPtr) {
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000751 // FIXME: Refactor with EmitExprAsInit.
Eli Friedmand7722d92011-12-03 02:13:40 +0000752 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall9d232c82013-03-07 21:37:08 +0000753 switch (CGF.getEvaluationKind(AllocType)) {
754 case TEK_Scalar:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700755 CGF.EmitScalarInit(Init, nullptr, CGF.MakeAddrLValue(NewPtr, AllocType,
756 Alignment),
John McCalla07398e2011-06-16 04:16:24 +0000757 false);
John McCall9d232c82013-03-07 21:37:08 +0000758 return;
759 case TEK_Complex:
760 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
761 Alignment),
762 /*isInit*/ true);
763 return;
764 case TEK_Aggregate: {
John McCall558d2ab2010-09-15 10:14:12 +0000765 AggValueSlot Slot
Eli Friedmanf3940782011-12-03 00:54:26 +0000766 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000767 AggValueSlot::IsDestructed,
John McCall44184392011-08-26 07:31:35 +0000768 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000769 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000770 CGF.EmitAggExpr(Init, Slot);
John McCall9d232c82013-03-07 21:37:08 +0000771 return;
John McCall558d2ab2010-09-15 10:14:12 +0000772 }
John McCall9d232c82013-03-07 21:37:08 +0000773 }
774 llvm_unreachable("bad evaluation kind");
Fariborz Jahanianef668722010-06-25 18:26:07 +0000775}
776
777void
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700778CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
779 QualType ElementType,
780 llvm::Value *BeginPtr,
781 llvm::Value *NumElements,
782 llvm::Value *AllocSizeWithoutCookie) {
783 // If we have a type with trivial initialization and no initializer,
784 // there's nothing to do.
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000785 if (!E->hasInitializer())
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700786 return;
John McCall19705672011-09-15 06:49:18 +0000787
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700788 llvm::Value *CurPtr = BeginPtr;
John McCall19705672011-09-15 06:49:18 +0000789
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700790 unsigned InitListElements = 0;
Sebastian Redl92036472012-02-22 17:37:52 +0000791
792 const Expr *Init = E->getInitializer();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700793 llvm::AllocaInst *EndOfInit = nullptr;
794 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
795 EHScopeStack::stable_iterator Cleanup;
796 llvm::Instruction *CleanupDominator = nullptr;
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000797
Sebastian Redl92036472012-02-22 17:37:52 +0000798 // If the initializer is an initializer list, first do the explicit elements.
799 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700800 InitListElements = ILE->getNumInits();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000801
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000802 // If this is a multi-dimensional array new, we will initialize multiple
803 // elements with each init list element.
804 QualType AllocType = E->getAllocatedType();
805 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
806 AllocType->getAsArrayTypeUnsafe())) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700807 unsigned AS = CurPtr->getType()->getPointerAddressSpace();
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000808 llvm::Type *AllocPtrTy = ConvertTypeForMem(AllocType)->getPointerTo(AS);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700809 CurPtr = Builder.CreateBitCast(CurPtr, AllocPtrTy);
810 InitListElements *= getContext().getConstantArrayElementCount(CAT);
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000811 }
812
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700813 // Enter a partial-destruction Cleanup if necessary.
814 if (needsEHCleanup(DtorKind)) {
815 // In principle we could tell the Cleanup where we are more
Chad Rosier577fb5b2012-02-24 00:13:55 +0000816 // directly, but the control flow can get so varied here that it
817 // would actually be quite complex. Therefore we go through an
818 // alloca.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700819 EndOfInit = CreateTempAlloca(BeginPtr->getType(), "array.init.end");
820 CleanupDominator = Builder.CreateStore(BeginPtr, EndOfInit);
821 pushIrregularPartialArrayCleanup(BeginPtr, EndOfInit, ElementType,
822 getDestroyer(DtorKind));
823 Cleanup = EHStack.stable_begin();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000824 }
825
Sebastian Redl92036472012-02-22 17:37:52 +0000826 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosier577fb5b2012-02-24 00:13:55 +0000827 // Tell the cleanup that it needs to destroy up to this
828 // element. TODO: some of these stores can be trivially
829 // observed to be unnecessary.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700830 if (EndOfInit)
831 Builder.CreateStore(Builder.CreateBitCast(CurPtr, BeginPtr->getType()),
832 EndOfInit);
833 // FIXME: If the last initializer is an incomplete initializer list for
834 // an array, and we have an array filler, we can fold together the two
835 // initialization loops.
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000836 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700837 ILE->getInit(i)->getType(), CurPtr);
838 CurPtr = Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.exp.next");
Sebastian Redl92036472012-02-22 17:37:52 +0000839 }
840
841 // The remaining elements are filled with the array filler expression.
842 Init = ILE->getArrayFiller();
Bill Wendlingb66a0f42013-12-11 04:25:35 +0000843
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700844 // Extract the initializer for the individual array elements by pulling
845 // out the array filler from all the nested initializer lists. This avoids
846 // generating a nested loop for the initialization.
847 while (Init && Init->getType()->isConstantArrayType()) {
848 auto *SubILE = dyn_cast<InitListExpr>(Init);
849 if (!SubILE)
850 break;
851 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
852 Init = SubILE->getArrayFiller();
853 }
854
855 // Switch back to initializing one base element at a time.
856 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr->getType());
Sebastian Redl92036472012-02-22 17:37:52 +0000857 }
858
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700859 // Attempt to perform zero-initialization using memset.
860 auto TryMemsetInitialization = [&]() -> bool {
861 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
862 // we can initialize with a memset to -1.
863 if (!CGM.getTypes().isZeroInitializable(ElementType))
864 return false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700865
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700866 // Optimization: since zero initialization will just set the memory
867 // to all zeroes, generate a single memset to do it in one shot.
868
869 // Subtract out the size of any elements we've already initialized.
870 auto *RemainingSize = AllocSizeWithoutCookie;
871 if (InitListElements) {
872 // We know this can't overflow; we check this when doing the allocation.
873 auto *InitializedSize = llvm::ConstantInt::get(
874 RemainingSize->getType(),
875 getContext().getTypeSizeInChars(ElementType).getQuantity() *
876 InitListElements);
877 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
878 }
879
880 // Create the memset.
881 CharUnits Alignment = getContext().getTypeAlignInChars(ElementType);
882 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize,
883 Alignment.getQuantity(), false);
884 return true;
885 };
886
887 // If all elements have already been initialized, skip any further
888 // initialization.
889 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
890 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
891 // If there was a Cleanup, deactivate it.
892 if (CleanupDominator)
893 DeactivateCleanupBlock(Cleanup, CleanupDominator);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700894 return;
895 }
896
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700897 assert(Init && "have trailing elements to initialize but no initializer");
898
899 // If this is a constructor call, try to optimize it out, and failing that
900 // emit a single loop to initialize all remaining elements.
901 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
902 CXXConstructorDecl *Ctor = CCE->getConstructor();
903 if (Ctor->isTrivial()) {
904 // If new expression did not specify value-initialization, then there
905 // is no initialization.
906 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
907 return;
908
909 if (TryMemsetInitialization())
910 return;
911 }
912
913 // Store the new Cleanup position for irregular Cleanups.
914 //
915 // FIXME: Share this cleanup with the constructor call emission rather than
916 // having it create a cleanup of its own.
917 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
918
919 // Emit a constructor call loop to initialize the remaining elements.
920 if (InitListElements)
921 NumElements = Builder.CreateSub(
922 NumElements,
923 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
Stephen Hines176edba2014-12-01 14:53:08 -0800924 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700925 CCE->requiresZeroInitialization());
926 return;
927 }
928
929 // If this is value-initialization, we can usually use memset.
930 ImplicitValueInitExpr IVIE(ElementType);
931 if (isa<ImplicitValueInitExpr>(Init)) {
932 if (TryMemsetInitialization())
933 return;
934
935 // Switch to an ImplicitValueInitExpr for the element type. This handles
936 // only one case: multidimensional array new of pointers to members. In
937 // all other cases, we already have an initializer for the array element.
938 Init = &IVIE;
939 }
940
941 // At this point we should have found an initializer for the individual
942 // elements of the array.
943 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
944 "got wrong type of element to initialize");
945
946 // If we have an empty initializer list, we can usually use memset.
947 if (auto *ILE = dyn_cast<InitListExpr>(Init))
948 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
949 return;
950
951 // Create the loop blocks.
952 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
953 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
954 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
955
956 // Find the end of the array, hoisted out of the loop.
957 llvm::Value *EndPtr =
958 Builder.CreateInBoundsGEP(BeginPtr, NumElements, "array.end");
John McCall19705672011-09-15 06:49:18 +0000959
Sebastian Redl92036472012-02-22 17:37:52 +0000960 // If the number of elements isn't constant, we have to now check if there is
961 // anything left to initialize.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700962 if (!ConstNum) {
963 llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr, EndPtr,
John McCall19705672011-09-15 06:49:18 +0000964 "array.isempty");
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700965 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
John McCall19705672011-09-15 06:49:18 +0000966 }
967
968 // Enter the loop.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700969 EmitBlock(LoopBB);
John McCall19705672011-09-15 06:49:18 +0000970
971 // Set up the current-element phi.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700972 llvm::PHINode *CurPtrPhi =
973 Builder.CreatePHI(CurPtr->getType(), 2, "array.cur");
974 CurPtrPhi->addIncoming(CurPtr, EntryBB);
975 CurPtr = CurPtrPhi;
John McCall19705672011-09-15 06:49:18 +0000976
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700977 // Store the new Cleanup position for irregular Cleanups.
978 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
Chad Rosier577fb5b2012-02-24 00:13:55 +0000979
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700980 // Enter a partial-destruction Cleanup if necessary.
981 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
982 pushRegularPartialArrayCleanup(BeginPtr, CurPtr, ElementType,
983 getDestroyer(DtorKind));
984 Cleanup = EHStack.stable_begin();
985 CleanupDominator = Builder.CreateUnreachable();
John McCall19705672011-09-15 06:49:18 +0000986 }
987
988 // Emit the initializer into this element.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700989 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
John McCall19705672011-09-15 06:49:18 +0000990
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700991 // Leave the Cleanup if we entered one.
992 if (CleanupDominator) {
993 DeactivateCleanupBlock(Cleanup, CleanupDominator);
994 CleanupDominator->eraseFromParent();
John McCall6f103ba2011-11-10 10:43:54 +0000995 }
John McCall19705672011-09-15 06:49:18 +0000996
Stephen Hines651f13c2014-04-23 16:59:28 -0700997 // Advance to the next element by adjusting the pointer type as necessary.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700998 llvm::Value *NextPtr =
999 Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.next");
1000
John McCall19705672011-09-15 06:49:18 +00001001 // Check whether we've gotten to the end of the array and, if so,
1002 // exit the loop.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001003 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1004 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1005 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
John McCall19705672011-09-15 06:49:18 +00001006
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001007 EmitBlock(ContBB);
Fariborz Jahanianef668722010-06-25 18:26:07 +00001008}
1009
Anders Carlssona4d4c012009-09-23 16:07:23 +00001010static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +00001011 QualType ElementType,
Anders Carlssona4d4c012009-09-23 16:07:23 +00001012 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +00001013 llvm::Value *NumElements,
1014 llvm::Value *AllocSizeWithoutCookie) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001015 if (E->isArray())
1016 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements,
1017 AllocSizeWithoutCookie);
1018 else if (const Expr *Init = E->getInitializer())
1019 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +00001020}
1021
Richard Smithddcff1b2013-07-21 23:12:18 +00001022/// Emit a call to an operator new or operator delete function, as implicitly
1023/// created by new-expressions and delete-expressions.
1024static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1025 const FunctionDecl *Callee,
1026 const FunctionProtoType *CalleeType,
1027 const CallArgList &Args) {
1028 llvm::Instruction *CallOrInvoke;
Richard Smith060cb4a2013-07-29 20:14:16 +00001029 llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
Richard Smithddcff1b2013-07-21 23:12:18 +00001030 RValue RV =
1031 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(Args, CalleeType),
Richard Smith060cb4a2013-07-29 20:14:16 +00001032 CalleeAddr, ReturnValueSlot(), Args,
Richard Smithddcff1b2013-07-21 23:12:18 +00001033 Callee, &CallOrInvoke);
1034
1035 /// C++1y [expr.new]p10:
1036 /// [In a new-expression,] an implementation is allowed to omit a call
1037 /// to a replaceable global allocation function.
1038 ///
1039 /// We model such elidable calls with the 'builtin' attribute.
Rafael Espindola87017a72013-10-22 14:23:09 +00001040 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
Richard Smith060cb4a2013-07-29 20:14:16 +00001041 if (Callee->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola87017a72013-10-22 14:23:09 +00001042 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smithddcff1b2013-07-21 23:12:18 +00001043 // FIXME: Add addAttribute to CallSite.
1044 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1045 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1046 llvm::Attribute::Builtin);
1047 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1048 II->addAttribute(llvm::AttributeSet::FunctionIndex,
1049 llvm::Attribute::Builtin);
1050 else
1051 llvm_unreachable("unexpected kind of call instruction");
1052 }
1053
1054 return RV;
1055}
1056
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001057RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1058 const Expr *Arg,
1059 bool IsDelete) {
1060 CallArgList Args;
1061 const Stmt *ArgS = Arg;
1062 EmitCallArgs(Args, *Type->param_type_begin(),
1063 ConstExprIterator(&ArgS), ConstExprIterator(&ArgS + 1));
1064 // Find the allocation or deallocation function that we're calling.
1065 ASTContext &Ctx = getContext();
1066 DeclarationName Name = Ctx.DeclarationNames
1067 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1068 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1069 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1070 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1071 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1072 llvm_unreachable("predeclared global operator new/delete is missing");
1073}
1074
John McCall7d8647f2010-09-14 07:57:04 +00001075namespace {
1076 /// A cleanup to call the given 'operator delete' function upon
1077 /// abnormal exit from a new expression.
1078 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1079 size_t NumPlacementArgs;
1080 const FunctionDecl *OperatorDelete;
1081 llvm::Value *Ptr;
1082 llvm::Value *AllocSize;
1083
1084 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1085
1086 public:
1087 static size_t getExtraSize(size_t NumPlacementArgs) {
1088 return NumPlacementArgs * sizeof(RValue);
1089 }
1090
1091 CallDeleteDuringNew(size_t NumPlacementArgs,
1092 const FunctionDecl *OperatorDelete,
1093 llvm::Value *Ptr,
1094 llvm::Value *AllocSize)
1095 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1096 Ptr(Ptr), AllocSize(AllocSize) {}
1097
1098 void setPlacementArg(unsigned I, RValue Arg) {
1099 assert(I < NumPlacementArgs && "index out of range");
1100 getPlacementArgs()[I] = Arg;
1101 }
1102
Stephen Hines651f13c2014-04-23 16:59:28 -07001103 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall7d8647f2010-09-14 07:57:04 +00001104 const FunctionProtoType *FPT
1105 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07001106 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1107 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +00001108
1109 CallArgList DeleteArgs;
1110
1111 // The first argument is always a void*.
Stephen Hines651f13c2014-04-23 16:59:28 -07001112 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001113 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001114
1115 // A member 'operator delete' can take an extra 'size_t' argument.
Stephen Hines651f13c2014-04-23 16:59:28 -07001116 if (FPT->getNumParams() == NumPlacementArgs + 2)
Eli Friedman04c9a492011-05-02 17:57:46 +00001117 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001118
1119 // Pass the rest of the arguments, which must match exactly.
1120 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman04c9a492011-05-02 17:57:46 +00001121 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001122
1123 // Call 'operator delete'.
Richard Smithddcff1b2013-07-21 23:12:18 +00001124 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7d8647f2010-09-14 07:57:04 +00001125 }
1126 };
John McCall3019c442010-09-17 00:50:28 +00001127
1128 /// A cleanup to call the given 'operator delete' function upon
1129 /// abnormal exit from a new expression when the new expression is
1130 /// conditional.
1131 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1132 size_t NumPlacementArgs;
1133 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +00001134 DominatingValue<RValue>::saved_type Ptr;
1135 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +00001136
John McCall804b8072011-01-28 10:53:53 +00001137 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1138 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +00001139 }
1140
1141 public:
1142 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +00001143 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +00001144 }
1145
1146 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1147 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +00001148 DominatingValue<RValue>::saved_type Ptr,
1149 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +00001150 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1151 Ptr(Ptr), AllocSize(AllocSize) {}
1152
John McCall804b8072011-01-28 10:53:53 +00001153 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +00001154 assert(I < NumPlacementArgs && "index out of range");
1155 getPlacementArgs()[I] = Arg;
1156 }
1157
Stephen Hines651f13c2014-04-23 16:59:28 -07001158 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall3019c442010-09-17 00:50:28 +00001159 const FunctionProtoType *FPT
1160 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07001161 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1162 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall3019c442010-09-17 00:50:28 +00001163
1164 CallArgList DeleteArgs;
1165
1166 // The first argument is always a void*.
Stephen Hines651f13c2014-04-23 16:59:28 -07001167 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001168 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall3019c442010-09-17 00:50:28 +00001169
1170 // A member 'operator delete' can take an extra 'size_t' argument.
Stephen Hines651f13c2014-04-23 16:59:28 -07001171 if (FPT->getNumParams() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +00001172 RValue RV = AllocSize.restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001173 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001174 }
1175
1176 // Pass the rest of the arguments, which must match exactly.
1177 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +00001178 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001179 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001180 }
1181
1182 // Call 'operator delete'.
Richard Smithddcff1b2013-07-21 23:12:18 +00001183 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall3019c442010-09-17 00:50:28 +00001184 }
1185 };
1186}
1187
1188/// Enter a cleanup to call 'operator delete' if the initializer in a
1189/// new-expression throws.
1190static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1191 const CXXNewExpr *E,
1192 llvm::Value *NewPtr,
1193 llvm::Value *AllocSize,
1194 const CallArgList &NewArgs) {
1195 // If we're not inside a conditional branch, then the cleanup will
1196 // dominate and we can do the easier (and more efficient) thing.
1197 if (!CGF.isInConditionalBranch()) {
1198 CallDeleteDuringNew *Cleanup = CGF.EHStack
1199 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1200 E->getNumPlacementArgs(),
1201 E->getOperatorDelete(),
1202 NewPtr, AllocSize);
1203 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanc6d07822011-05-02 18:05:27 +00001204 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall3019c442010-09-17 00:50:28 +00001205
1206 return;
1207 }
1208
1209 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +00001210 DominatingValue<RValue>::saved_type SavedNewPtr =
1211 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1212 DominatingValue<RValue>::saved_type SavedAllocSize =
1213 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +00001214
1215 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCall6f103ba2011-11-10 10:43:54 +00001216 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall3019c442010-09-17 00:50:28 +00001217 E->getNumPlacementArgs(),
1218 E->getOperatorDelete(),
1219 SavedNewPtr,
1220 SavedAllocSize);
1221 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +00001222 Cleanup->setPlacementArg(I,
Eli Friedmanc6d07822011-05-02 18:05:27 +00001223 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall3019c442010-09-17 00:50:28 +00001224
John McCall6f103ba2011-11-10 10:43:54 +00001225 CGF.initFullExprCleanup();
John McCall7d8647f2010-09-14 07:57:04 +00001226}
1227
Anders Carlsson16d81b82009-09-22 22:53:17 +00001228llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001229 // The element type being allocated.
1230 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +00001231
John McCallc2f3e7f2011-03-07 03:12:35 +00001232 // 1. Build a call to the allocation function.
1233 FunctionDecl *allocator = E->getOperatorNew();
1234 const FunctionProtoType *allocatorType =
1235 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001236
John McCallc2f3e7f2011-03-07 03:12:35 +00001237 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001238
1239 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001240 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001241
Sebastian Redl92036472012-02-22 17:37:52 +00001242 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1243 unsigned minElements = 0;
1244 if (E->isArray() && E->hasInitializer()) {
1245 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1246 minElements = ILE->getNumInits();
1247 }
1248
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001249 llvm::Value *numElements = nullptr;
1250 llvm::Value *allocSizeWithoutCookie = nullptr;
John McCallc2f3e7f2011-03-07 03:12:35 +00001251 llvm::Value *allocSize =
Sebastian Redl92036472012-02-22 17:37:52 +00001252 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1253 allocSizeWithoutCookie);
Stephen Hines176edba2014-12-01 14:53:08 -08001254
Eli Friedman04c9a492011-05-02 17:57:46 +00001255 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001256
Anders Carlsson16d81b82009-09-22 22:53:17 +00001257 // We start at 1 here because the first argument (the allocation size)
1258 // has already been emitted.
Stephen Hines176edba2014-12-01 14:53:08 -08001259 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arg_begin(),
1260 E->placement_arg_end(), /* CalleeDecl */ nullptr,
1261 /*ParamsToSkip*/ 1);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001262
John McCallb1c98a32011-05-16 01:05:12 +00001263 // Emit the allocation call. If the allocator is a global placement
1264 // operator, just "inline" it directly.
1265 RValue RV;
1266 if (allocator->isReservedGlobalPlacementOperator()) {
1267 assert(allocatorArgs.size() == 2);
1268 RV = allocatorArgs[1].RV;
1269 // TODO: kill any unnecessary computations done for the size
1270 // argument.
1271 } else {
Richard Smithddcff1b2013-07-21 23:12:18 +00001272 RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
John McCallb1c98a32011-05-16 01:05:12 +00001273 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001274
John McCallc2f3e7f2011-03-07 03:12:35 +00001275 // Emit a null check on the allocation result if the allocation
1276 // function is allowed to return null (because it has a non-throwing
1277 // exception spec; for this part, we inline
1278 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1279 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001280 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001281 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001282
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001283 llvm::BasicBlock *nullCheckBB = nullptr;
1284 llvm::BasicBlock *contBB = nullptr;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001285
John McCallc2f3e7f2011-03-07 03:12:35 +00001286 llvm::Value *allocation = RV.getScalarVal();
Micah Villmow956a5a12012-10-25 15:39:14 +00001287 unsigned AS = allocation->getType()->getPointerAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001288
John McCalla7f633f2011-03-07 01:52:56 +00001289 // The null-check means that the initializer is conditionally
1290 // evaluated.
1291 ConditionalEvaluation conditional(*this);
1292
John McCallc2f3e7f2011-03-07 03:12:35 +00001293 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001294 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001295
1296 nullCheckBB = Builder.GetInsertBlock();
1297 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1298 contBB = createBasicBlock("new.cont");
1299
1300 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1301 Builder.CreateCondBr(isNull, contBB, notNullBB);
1302 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001303 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001304
John McCall7d8647f2010-09-14 07:57:04 +00001305 // If there's an operator delete, enter a cleanup to call it if an
1306 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001307 EHScopeStack::stable_iterator operatorDeleteCleanup;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001308 llvm::Instruction *cleanupDominator = nullptr;
John McCallb1c98a32011-05-16 01:05:12 +00001309 if (E->getOperatorDelete() &&
1310 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001311 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1312 operatorDeleteCleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +00001313 cleanupDominator = Builder.CreateUnreachable();
John McCall7d8647f2010-09-14 07:57:04 +00001314 }
1315
Eli Friedman576cf172011-09-06 18:53:03 +00001316 assert((allocSize == allocSizeWithoutCookie) ==
1317 CalculateCookiePadding(*this, E).isZero());
1318 if (allocSize != allocSizeWithoutCookie) {
1319 assert(E->isArray());
1320 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1321 numElements,
1322 E, allocType);
1323 }
1324
Chris Lattner2acc6e32011-07-18 04:24:23 +00001325 llvm::Type *elementPtrTy
John McCallc2f3e7f2011-03-07 03:12:35 +00001326 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1327 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001328
John McCall19705672011-09-15 06:49:18 +00001329 EmitNewInitializer(*this, E, allocType, result, numElements,
1330 allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001331 if (E->isArray()) {
John McCall1e7fe752010-09-02 09:58:18 +00001332 // NewPtr is a pointer to the base element type. If we're
1333 // allocating an array of arrays, we'll need to cast back to the
1334 // array pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001335 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCallc2f3e7f2011-03-07 03:12:35 +00001336 if (result->getType() != resultType)
1337 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001338 }
John McCall7d8647f2010-09-14 07:57:04 +00001339
1340 // Deactivate the 'operator delete' cleanup if we finished
1341 // initialization.
John McCall6f103ba2011-11-10 10:43:54 +00001342 if (operatorDeleteCleanup.isValid()) {
1343 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1344 cleanupDominator->eraseFromParent();
1345 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001346
John McCallc2f3e7f2011-03-07 03:12:35 +00001347 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001348 conditional.end(*this);
1349
John McCallc2f3e7f2011-03-07 03:12:35 +00001350 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1351 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001352
Jay Foadbbf3bac2011-03-30 11:28:58 +00001353 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001354 PHI->addIncoming(result, notNullBB);
1355 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1356 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001357
John McCallc2f3e7f2011-03-07 03:12:35 +00001358 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001359 }
John McCall1e7fe752010-09-02 09:58:18 +00001360
John McCallc2f3e7f2011-03-07 03:12:35 +00001361 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001362}
1363
Eli Friedman5fe05982009-11-18 00:50:08 +00001364void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1365 llvm::Value *Ptr,
1366 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001367 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1368
Eli Friedman5fe05982009-11-18 00:50:08 +00001369 const FunctionProtoType *DeleteFTy =
1370 DeleteFD->getType()->getAs<FunctionProtoType>();
1371
1372 CallArgList DeleteArgs;
1373
Anders Carlsson871d0782009-12-13 20:04:38 +00001374 // Check if we need to pass the size to the delete operator.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001375 llvm::Value *Size = nullptr;
Anders Carlsson871d0782009-12-13 20:04:38 +00001376 QualType SizeTy;
Stephen Hines651f13c2014-04-23 16:59:28 -07001377 if (DeleteFTy->getNumParams() == 2) {
1378 SizeTy = DeleteFTy->getParamType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001379 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1380 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1381 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001382 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001383
1384 QualType ArgTy = DeleteFTy->getParamType(0);
Eli Friedman5fe05982009-11-18 00:50:08 +00001385 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001386 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001387
Anders Carlsson871d0782009-12-13 20:04:38 +00001388 if (Size)
Eli Friedman04c9a492011-05-02 17:57:46 +00001389 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001390
1391 // Emit the call to delete.
Richard Smithddcff1b2013-07-21 23:12:18 +00001392 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedman5fe05982009-11-18 00:50:08 +00001393}
1394
John McCall1e7fe752010-09-02 09:58:18 +00001395namespace {
1396 /// Calls the given 'operator delete' on a single object.
1397 struct CallObjectDelete : EHScopeStack::Cleanup {
1398 llvm::Value *Ptr;
1399 const FunctionDecl *OperatorDelete;
1400 QualType ElementType;
1401
1402 CallObjectDelete(llvm::Value *Ptr,
1403 const FunctionDecl *OperatorDelete,
1404 QualType ElementType)
1405 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1406
Stephen Hines651f13c2014-04-23 16:59:28 -07001407 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e7fe752010-09-02 09:58:18 +00001408 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1409 }
1410 };
1411}
1412
Stephen Hines176edba2014-12-01 14:53:08 -08001413void
1414CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1415 llvm::Value *CompletePtr,
1416 QualType ElementType) {
1417 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1418 OperatorDelete, ElementType);
1419}
1420
John McCall1e7fe752010-09-02 09:58:18 +00001421/// Emit the code for deleting a single object.
1422static void EmitObjectDelete(CodeGenFunction &CGF,
Stephen Hines176edba2014-12-01 14:53:08 -08001423 const CXXDeleteExpr *DE,
John McCall1e7fe752010-09-02 09:58:18 +00001424 llvm::Value *Ptr,
Stephen Hines176edba2014-12-01 14:53:08 -08001425 QualType ElementType) {
John McCall1e7fe752010-09-02 09:58:18 +00001426 // Find the destructor for the type, if applicable. If the
1427 // destructor is virtual, we'll just emit the vcall and return.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001428 const CXXDestructorDecl *Dtor = nullptr;
John McCall1e7fe752010-09-02 09:58:18 +00001429 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1430 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanaebab722011-08-02 18:05:30 +00001431 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall1e7fe752010-09-02 09:58:18 +00001432 Dtor = RD->getDestructor();
1433
1434 if (Dtor->isVirtual()) {
Stephen Hines176edba2014-12-01 14:53:08 -08001435 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1436 Dtor);
John McCall1e7fe752010-09-02 09:58:18 +00001437 return;
1438 }
1439 }
1440 }
1441
1442 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001443 // This doesn't have to a conditional cleanup because we're going
1444 // to pop it off in a second.
Stephen Hines176edba2014-12-01 14:53:08 -08001445 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001446 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1447 Ptr, OperatorDelete, ElementType);
1448
1449 if (Dtor)
1450 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001451 /*ForVirtualBase=*/false,
1452 /*Delegating=*/false,
1453 Ptr);
David Blaikie4e4d0842012-03-11 07:00:24 +00001454 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001455 ElementType->isObjCLifetimeType()) {
1456 switch (ElementType.getObjCLifetime()) {
1457 case Qualifiers::OCL_None:
1458 case Qualifiers::OCL_ExplicitNone:
1459 case Qualifiers::OCL_Autoreleasing:
1460 break;
John McCall1e7fe752010-09-02 09:58:18 +00001461
John McCallf85e1932011-06-15 23:02:42 +00001462 case Qualifiers::OCL_Strong: {
1463 // Load the pointer value.
1464 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1465 ElementType.isVolatileQualified());
1466
John McCall5b07e802013-03-13 03:10:54 +00001467 CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +00001468 break;
1469 }
1470
1471 case Qualifiers::OCL_Weak:
1472 CGF.EmitARCDestroyWeak(Ptr);
1473 break;
1474 }
1475 }
1476
John McCall1e7fe752010-09-02 09:58:18 +00001477 CGF.PopCleanupBlock();
1478}
1479
1480namespace {
1481 /// Calls the given 'operator delete' on an array of objects.
1482 struct CallArrayDelete : EHScopeStack::Cleanup {
1483 llvm::Value *Ptr;
1484 const FunctionDecl *OperatorDelete;
1485 llvm::Value *NumElements;
1486 QualType ElementType;
1487 CharUnits CookieSize;
1488
1489 CallArrayDelete(llvm::Value *Ptr,
1490 const FunctionDecl *OperatorDelete,
1491 llvm::Value *NumElements,
1492 QualType ElementType,
1493 CharUnits CookieSize)
1494 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1495 ElementType(ElementType), CookieSize(CookieSize) {}
1496
Stephen Hines651f13c2014-04-23 16:59:28 -07001497 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall1e7fe752010-09-02 09:58:18 +00001498 const FunctionProtoType *DeleteFTy =
1499 OperatorDelete->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07001500 assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
John McCall1e7fe752010-09-02 09:58:18 +00001501
1502 CallArgList Args;
1503
1504 // Pass the pointer as the first argument.
Stephen Hines651f13c2014-04-23 16:59:28 -07001505 QualType VoidPtrTy = DeleteFTy->getParamType(0);
John McCall1e7fe752010-09-02 09:58:18 +00001506 llvm::Value *DeletePtr
1507 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001508 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall1e7fe752010-09-02 09:58:18 +00001509
1510 // Pass the original requested size as the second argument.
Stephen Hines651f13c2014-04-23 16:59:28 -07001511 if (DeleteFTy->getNumParams() == 2) {
1512 QualType size_t = DeleteFTy->getParamType(1);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001513 llvm::IntegerType *SizeTy
John McCall1e7fe752010-09-02 09:58:18 +00001514 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1515
1516 CharUnits ElementTypeSize =
1517 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1518
1519 // The size of an element, multiplied by the number of elements.
1520 llvm::Value *Size
1521 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1522 Size = CGF.Builder.CreateMul(Size, NumElements);
1523
1524 // Plus the size of the cookie if applicable.
1525 if (!CookieSize.isZero()) {
1526 llvm::Value *CookieSizeV
1527 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1528 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1529 }
1530
Eli Friedman04c9a492011-05-02 17:57:46 +00001531 Args.add(RValue::get(Size), size_t);
John McCall1e7fe752010-09-02 09:58:18 +00001532 }
1533
1534 // Emit the call to delete.
Richard Smithddcff1b2013-07-21 23:12:18 +00001535 EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
John McCall1e7fe752010-09-02 09:58:18 +00001536 }
1537 };
1538}
1539
1540/// Emit the code for deleting an array of objects.
1541static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001542 const CXXDeleteExpr *E,
John McCall7cfd76c2011-07-13 01:41:37 +00001543 llvm::Value *deletedPtr,
1544 QualType elementType) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001545 llvm::Value *numElements = nullptr;
1546 llvm::Value *allocatedPtr = nullptr;
John McCall7cfd76c2011-07-13 01:41:37 +00001547 CharUnits cookieSize;
1548 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1549 numElements, allocatedPtr, cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001550
John McCall7cfd76c2011-07-13 01:41:37 +00001551 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall1e7fe752010-09-02 09:58:18 +00001552
1553 // Make sure that we call delete even if one of the dtors throws.
John McCall7cfd76c2011-07-13 01:41:37 +00001554 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001555 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCall7cfd76c2011-07-13 01:41:37 +00001556 allocatedPtr, operatorDelete,
1557 numElements, elementType,
1558 cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001559
John McCall7cfd76c2011-07-13 01:41:37 +00001560 // Destroy the elements.
1561 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1562 assert(numElements && "no element count for a type with a destructor!");
1563
John McCall7cfd76c2011-07-13 01:41:37 +00001564 llvm::Value *arrayEnd =
1565 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCallfbf780a2011-07-13 08:09:46 +00001566
1567 // Note that it is legal to allocate a zero-length array, and we
1568 // can never fold the check away because the length should always
1569 // come from a cookie.
John McCall7cfd76c2011-07-13 01:41:37 +00001570 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1571 CGF.getDestroyer(dtorKind),
John McCallfbf780a2011-07-13 08:09:46 +00001572 /*checkZeroLength*/ true,
John McCall7cfd76c2011-07-13 01:41:37 +00001573 CGF.needsEHCleanup(dtorKind));
John McCall1e7fe752010-09-02 09:58:18 +00001574 }
1575
John McCall7cfd76c2011-07-13 01:41:37 +00001576 // Pop the cleanup block.
John McCall1e7fe752010-09-02 09:58:18 +00001577 CGF.PopCleanupBlock();
1578}
1579
Anders Carlsson16d81b82009-09-22 22:53:17 +00001580void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregor90916562009-09-29 18:16:17 +00001581 const Expr *Arg = E->getArgument();
Douglas Gregor90916562009-09-29 18:16:17 +00001582 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001583
1584 // Null check the pointer.
1585 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1586 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1587
Anders Carlssonb9241242011-04-11 00:30:07 +00001588 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001589
1590 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1591 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001592
John McCall1e7fe752010-09-02 09:58:18 +00001593 // We might be deleting a pointer to array. If so, GEP down to the
1594 // first non-array element.
1595 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1596 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1597 if (DeleteTy->isConstantArrayType()) {
1598 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001599 SmallVector<llvm::Value*,8> GEP;
John McCall1e7fe752010-09-02 09:58:18 +00001600
1601 GEP.push_back(Zero); // point at the outermost array
1602
1603 // For each layer of array type we're pointing at:
1604 while (const ConstantArrayType *Arr
1605 = getContext().getAsConstantArrayType(DeleteTy)) {
1606 // 1. Unpeel the array type.
1607 DeleteTy = Arr->getElementType();
1608
1609 // 2. GEP to the first element of the array.
1610 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001611 }
John McCall1e7fe752010-09-02 09:58:18 +00001612
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001613 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001614 }
1615
Douglas Gregoreede61a2010-09-02 17:38:50 +00001616 assert(ConvertTypeForMem(DeleteTy) ==
1617 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001618
1619 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001620 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001621 } else {
Stephen Hines176edba2014-12-01 14:53:08 -08001622 EmitObjectDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001623 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001624
Anders Carlsson16d81b82009-09-22 22:53:17 +00001625 EmitBlock(DeleteEnd);
1626}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001627
Stephen Hines176edba2014-12-01 14:53:08 -08001628static bool isGLValueFromPointerDeref(const Expr *E) {
1629 E = E->IgnoreParens();
1630
1631 if (const auto *CE = dyn_cast<CastExpr>(E)) {
1632 if (!CE->getSubExpr()->isGLValue())
1633 return false;
1634 return isGLValueFromPointerDeref(CE->getSubExpr());
1635 }
1636
1637 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
1638 return isGLValueFromPointerDeref(OVE->getSourceExpr());
1639
1640 if (const auto *BO = dyn_cast<BinaryOperator>(E))
1641 if (BO->getOpcode() == BO_Comma)
1642 return isGLValueFromPointerDeref(BO->getRHS());
1643
1644 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
1645 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
1646 isGLValueFromPointerDeref(ACO->getFalseExpr());
1647
1648 // C++11 [expr.sub]p1:
1649 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
1650 if (isa<ArraySubscriptExpr>(E))
1651 return true;
1652
1653 if (const auto *UO = dyn_cast<UnaryOperator>(E))
1654 if (UO->getOpcode() == UO_Deref)
1655 return true;
1656
1657 return false;
1658}
1659
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001660static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001661 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001662 // Get the vtable pointer.
1663 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1664
1665 // C++ [expr.typeid]p2:
1666 // If the glvalue expression is obtained by applying the unary * operator to
1667 // a pointer and the pointer is a null pointer value, the typeid expression
1668 // throws the std::bad_typeid exception.
Stephen Hines176edba2014-12-01 14:53:08 -08001669 //
1670 // However, this paragraph's intent is not clear. We choose a very generous
1671 // interpretation which implores us to consider comma operators, conditional
1672 // operators, parentheses and other such constructs.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001673 QualType SrcRecordTy = E->getType();
Stephen Hines176edba2014-12-01 14:53:08 -08001674 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
1675 isGLValueFromPointerDeref(E), SrcRecordTy)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001676 llvm::BasicBlock *BadTypeidBlock =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001677 CGF.createBasicBlock("typeid.bad_typeid");
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001678 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001679
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001680 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1681 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001682
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001683 CGF.EmitBlock(BadTypeidBlock);
1684 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1685 CGF.EmitBlock(EndBlock);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001686 }
1687
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001688 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
1689 StdTypeInfoPtrTy);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001690}
1691
John McCall3ad32c82011-01-28 08:37:24 +00001692llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001693 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001694 ConvertType(E->getType())->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001695
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001696 if (E->isTypeOperand()) {
David Majnemerfe16aa32013-09-27 07:04:31 +00001697 llvm::Constant *TypeInfo =
1698 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001699 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001700 }
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001701
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001702 // C++ [expr.typeid]p2:
1703 // When typeid is applied to a glvalue expression whose type is a
1704 // polymorphic class type, the result refers to a std::type_info object
1705 // representing the type of the most derived object (that is, the dynamic
1706 // type) to which the glvalue refers.
Richard Smith0d729102012-08-13 20:08:14 +00001707 if (E->isPotentiallyEvaluated())
1708 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1709 StdTypeInfoPtrTy);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001710
1711 QualType OperandTy = E->getExprOperand()->getType();
1712 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1713 StdTypeInfoPtrTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001714}
Mike Stumpc849c052009-11-16 06:50:58 +00001715
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001716static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1717 QualType DestTy) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001718 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001719 if (DestTy->isPointerType())
1720 return llvm::Constant::getNullValue(DestLTy);
1721
1722 /// C++ [expr.dynamic.cast]p9:
1723 /// A failed cast to reference type throws std::bad_cast
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001724 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
1725 return nullptr;
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001726
1727 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1728 return llvm::UndefValue::get(DestLTy);
1729}
1730
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001731llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001732 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001733 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001734
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001735 if (DCE->isAlwaysNull())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001736 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
1737 return T;
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001738
1739 QualType SrcTy = DCE->getSubExpr()->getType();
1740
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001741 // C++ [expr.dynamic.cast]p7:
1742 // If T is "pointer to cv void," then the result is a pointer to the most
1743 // derived object pointed to by v.
1744 const PointerType *DestPTy = DestTy->getAs<PointerType>();
1745
1746 bool isDynamicCastToVoid;
1747 QualType SrcRecordTy;
1748 QualType DestRecordTy;
1749 if (DestPTy) {
1750 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
1751 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1752 DestRecordTy = DestPTy->getPointeeType();
1753 } else {
1754 isDynamicCastToVoid = false;
1755 SrcRecordTy = SrcTy;
1756 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1757 }
1758
1759 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1760
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001761 // C++ [expr.dynamic.cast]p4:
1762 // If the value of v is a null pointer value in the pointer case, the result
1763 // is the null pointer value of type T.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001764 bool ShouldNullCheckSrcValue =
1765 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
1766 SrcRecordTy);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001767
1768 llvm::BasicBlock *CastNull = nullptr;
1769 llvm::BasicBlock *CastNotNull = nullptr;
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001770 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001771
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001772 if (ShouldNullCheckSrcValue) {
1773 CastNull = createBasicBlock("dynamic_cast.null");
1774 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1775
1776 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1777 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1778 EmitBlock(CastNotNull);
Mike Stumpc849c052009-11-16 06:50:58 +00001779 }
1780
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001781 if (isDynamicCastToVoid) {
1782 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, Value, SrcRecordTy,
1783 DestTy);
1784 } else {
1785 assert(DestRecordTy->isRecordType() &&
1786 "destination type must be a record type!");
1787 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, Value, SrcRecordTy,
1788 DestTy, DestRecordTy, CastEnd);
1789 }
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001790
1791 if (ShouldNullCheckSrcValue) {
1792 EmitBranch(CastEnd);
1793
1794 EmitBlock(CastNull);
1795 EmitBranch(CastEnd);
1796 }
1797
1798 EmitBlock(CastEnd);
1799
1800 if (ShouldNullCheckSrcValue) {
1801 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1802 PHI->addIncoming(Value, CastNotNull);
1803 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1804
1805 Value = PHI;
1806 }
1807
1808 return Value;
Mike Stumpc849c052009-11-16 06:50:58 +00001809}
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001810
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001811void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedmanf8823e72012-02-09 03:47:20 +00001812 RunCleanupsScope Scope(*this);
Stephen Hines176edba2014-12-01 14:53:08 -08001813 LValue SlotLV =
1814 MakeAddrLValue(Slot.getAddr(), E->getType(), Slot.getAlignment());
Eli Friedmanf8823e72012-02-09 03:47:20 +00001815
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001816 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1817 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1818 e = E->capture_init_end();
Eric Christopherc07b18e2012-02-29 03:25:18 +00001819 i != e; ++i, ++CurField) {
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001820 // Emit initialization
David Blaikie581deb32012-06-06 20:45:41 +00001821 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Stephen Hines176edba2014-12-01 14:53:08 -08001822 if (CurField->hasCapturedVLAType()) {
1823 auto VAT = CurField->getCapturedVLAType();
1824 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
1825 } else {
1826 ArrayRef<VarDecl *> ArrayIndexes;
1827 if (CurField->getType()->isArrayType())
1828 ArrayIndexes = E->getCaptureInitIndexVars(i);
1829 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
1830 }
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001831 }
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001832}