blob: 3674facde06edfdf0cca7c41b6aee280b97b9af4 [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"
19#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000020#include "llvm/IR/Intrinsics.h"
Anders Carlssonad3692bb2011-04-13 02:35:36 +000021#include "llvm/Support/CallSite.h"
22
Anders Carlsson16d81b82009-09-22 22:53:17 +000023using namespace clang;
24using namespace CodeGen;
25
Anders Carlsson3b5ad222010-01-01 20:29:01 +000026RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
Richard Smith4def70d2012-10-09 19:52:38 +000027 SourceLocation CallLoc,
Anders Carlsson3b5ad222010-01-01 20:29:01 +000028 llvm::Value *Callee,
29 ReturnValueSlot ReturnValue,
30 llvm::Value *This,
Anders Carlssonc997d422010-01-02 01:01:18 +000031 llvm::Value *VTT,
Anders Carlsson3b5ad222010-01-01 20:29:01 +000032 CallExpr::const_arg_iterator ArgBeg,
33 CallExpr::const_arg_iterator ArgEnd) {
34 assert(MD->isInstance() &&
35 "Trying to emit a member call expr on a static method!");
36
Richard Smith2c9f87c2012-08-24 00:54:33 +000037 // C++11 [class.mfct.non-static]p2:
38 // If a non-static member function of a class X is called for an object that
39 // is not of type X, or of a type derived from X, the behavior is undefined.
Richard Smith8e1cee62012-10-25 02:14:12 +000040 EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall
41 : TCK_MemberCall,
42 CallLoc, This, getContext().getRecordType(MD->getParent()));
Richard Smith2c9f87c2012-08-24 00:54:33 +000043
Anders Carlsson3b5ad222010-01-01 20:29:01 +000044 CallArgList Args;
45
46 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +000047 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000048
Anders Carlssonc997d422010-01-02 01:01:18 +000049 // If there is a VTT parameter, emit it.
50 if (VTT) {
51 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +000052 Args.add(RValue::get(VTT), T);
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 Carlssonc997d422010-01-02 01:01:18 +000057
John McCallde5d3c72012-02-17 03:33:10 +000058 // And the rest of the call args.
Anders Carlsson3b5ad222010-01-01 20:29:01 +000059 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
60
John McCall0f3d0972012-07-07 06:41:13 +000061 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
Rafael Espindola264ba482010-03-30 20:24:48 +000062 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000063}
64
Anders Carlssoncd0b32e2011-04-10 18:20:53 +000065// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
66// quite what we want.
67static const Expr *skipNoOpCastsAndParens(const Expr *E) {
68 while (true) {
69 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
70 E = PE->getSubExpr();
71 continue;
72 }
73
74 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
75 if (CE->getCastKind() == CK_NoOp) {
76 E = CE->getSubExpr();
77 continue;
78 }
79 }
80 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
81 if (UO->getOpcode() == UO_Extension) {
82 E = UO->getSubExpr();
83 continue;
84 }
85 }
86 return E;
87 }
88}
89
Anders Carlsson3b5ad222010-01-01 20:29:01 +000090/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
91/// expr can be devirtualized.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +000092static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
93 const Expr *Base,
Anders Carlssonbd2bfae2010-10-27 13:28:46 +000094 const CXXMethodDecl *MD) {
95
Anders Carlsson1679f5a2011-01-29 03:52:01 +000096 // When building with -fapple-kext, all calls must go through the vtable since
97 // the kernel linker can do runtime patching of vtables.
David Blaikie4e4d0842012-03-11 07:00:24 +000098 if (Context.getLangOpts().AppleKext)
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +000099 return false;
100
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000101 // If the most derived class is marked final, we know that no subclass can
102 // override this member function and so we can devirtualize it. For example:
103 //
104 // struct A { virtual void f(); }
105 // struct B final : A { };
106 //
107 // void f(B *b) {
108 // b->f();
109 // }
110 //
Rafael Espindola8d852e32012-06-27 18:18:05 +0000111 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000112 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
113 return true;
114
Anders Carlssonf89e0422011-01-23 21:07:30 +0000115 // If the member function is marked 'final', we know that it can't be
Anders Carlssond66f4282010-10-27 13:34:43 +0000116 // overridden and can therefore devirtualize it.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000117 if (MD->hasAttr<FinalAttr>())
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000118 return true;
Anders Carlssond66f4282010-10-27 13:34:43 +0000119
Anders Carlssonf89e0422011-01-23 21:07:30 +0000120 // Similarly, if the class itself is marked 'final' it can't be overridden
121 // and we can therefore devirtualize the member function call.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000122 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssond66f4282010-10-27 13:34:43 +0000123 return true;
124
Anders Carlssoncd0b32e2011-04-10 18:20:53 +0000125 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000126 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
127 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
128 // This is a record decl. We know the type and can devirtualize it.
129 return VD->getType()->isRecordType();
130 }
131
132 return false;
133 }
Richard Smithac452932012-08-15 22:59:28 +0000134
135 // We can devirtualize calls on an object accessed by a class member access
136 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
137 // a derived class object constructed in the same location.
138 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
139 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
140 return VD->getType()->isRecordType();
141
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000142 // We can always devirtualize calls on temporary object expressions.
Eli Friedman6997aae2010-01-31 20:58:15 +0000143 if (isa<CXXConstructExpr>(Base))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000144 return true;
145
146 // And calls on bound temporaries.
147 if (isa<CXXBindTemporaryExpr>(Base))
148 return true;
149
150 // Check if this is a call expr that returns a record type.
151 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
152 return CE->getCallReturnType()->isRecordType();
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000153
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000154 // We can't devirtualize the call.
155 return false;
156}
157
Rafael Espindolaea01d762012-06-28 14:28:57 +0000158static CXXRecordDecl *getCXXRecord(const Expr *E) {
159 QualType T = E->getType();
160 if (const PointerType *PTy = T->getAs<PointerType>())
161 T = PTy->getPointeeType();
162 const RecordType *Ty = T->castAs<RecordType>();
163 return cast<CXXRecordDecl>(Ty->getDecl());
164}
165
Francois Pichetdbee3412011-01-18 05:04:39 +0000166// Note: This function also emit constructor calls to support a MSVC
167// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000168RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
169 ReturnValueSlot ReturnValue) {
John McCall379b5152011-04-11 07:02:50 +0000170 const Expr *callee = CE->getCallee()->IgnoreParens();
171
172 if (isa<BinaryOperator>(callee))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000173 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall379b5152011-04-11 07:02:50 +0000174
175 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000176 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
177
Devang Patelc69e1cf2010-09-30 19:05:55 +0000178 CGDebugInfo *DI = getDebugInfo();
Douglas Gregor4cdad312012-10-23 20:05:01 +0000179 if (DI &&
180 CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo &&
181 !isa<CallExpr>(ME->getBase())) {
Devang Patelc69e1cf2010-09-30 19:05:55 +0000182 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
183 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
184 DI->getOrCreateRecordType(PTy->getPointeeType(),
185 MD->getParent()->getLocation());
186 }
187 }
188
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000189 if (MD->isStatic()) {
190 // The method is static, emit it as we would a regular call.
191 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
192 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
193 ReturnValue, CE->arg_begin(), CE->arg_end());
194 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000195
John McCallfc400282010-09-03 01:26:39 +0000196 // Compute the object pointer.
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000197 const Expr *Base = ME->getBase();
198 bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000199
Rafael Espindolaea01d762012-06-28 14:28:57 +0000200 const CXXMethodDecl *DevirtualizedMethod = NULL;
201 if (CanUseVirtualCall &&
202 canDevirtualizeMemberFunctionCalls(getContext(), Base, MD)) {
203 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
204 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
205 assert(DevirtualizedMethod);
206 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
207 const Expr *Inner = Base->ignoreParenBaseCasts();
208 if (getCXXRecord(Inner) == DevirtualizedClass)
209 // If the class of the Inner expression is where the dynamic method
210 // is defined, build the this pointer from it.
211 Base = Inner;
212 else if (getCXXRecord(Base) != DevirtualizedClass) {
213 // If the method is defined in a class that is not the best dynamic
214 // one or the one of the full expression, we would have to build
215 // a derived-to-base cast to compute the correct this pointer, but
216 // we don't have support for that yet, so do a virtual call.
217 DevirtualizedMethod = NULL;
218 }
Rafael Espindola80bc96e2012-06-28 17:57:36 +0000219 // If the return types are not the same, this might be a case where more
220 // code needs to run to compensate for it. For example, the derived
221 // method might return a type that inherits form from the return
222 // type of MD and has a prefix.
223 // For now we just avoid devirtualizing these covariant cases.
224 if (DevirtualizedMethod &&
225 DevirtualizedMethod->getResultType().getCanonicalType() !=
226 MD->getResultType().getCanonicalType())
Rafael Espindola4a889e42012-06-28 15:11:39 +0000227 DevirtualizedMethod = NULL;
Rafael Espindolaea01d762012-06-28 14:28:57 +0000228 }
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000229
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000230 llvm::Value *This;
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000231 if (ME->isArrow())
Rafael Espindolaea01d762012-06-28 14:28:57 +0000232 This = EmitScalarExpr(Base);
John McCall0e800c92010-12-04 08:14:53 +0000233 else
Rafael Espindolaea01d762012-06-28 14:28:57 +0000234 This = EmitLValue(Base).getAddress();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000235
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000236
John McCallfc400282010-09-03 01:26:39 +0000237 if (MD->isTrivial()) {
238 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichetdbee3412011-01-18 05:04:39 +0000239 if (isa<CXXConstructorDecl>(MD) &&
240 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
241 return RValue::get(0);
John McCallfc400282010-09-03 01:26:39 +0000242
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000243 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
244 // We don't like to generate the trivial copy/move assignment operator
245 // when it isn't necessary; just produce the proper effect here.
Francois Pichetdbee3412011-01-18 05:04:39 +0000246 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
Benjamin Kramer6cacae82012-09-30 12:43:37 +0000247 EmitAggregateAssign(This, RHS, CE->getType());
Francois Pichetdbee3412011-01-18 05:04:39 +0000248 return RValue::get(This);
249 }
250
251 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000252 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
253 // Trivial move and copy ctor are the same.
Francois Pichetdbee3412011-01-18 05:04:39 +0000254 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
255 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
256 CE->arg_begin(), CE->arg_end());
257 return RValue::get(This);
258 }
259 llvm_unreachable("unknown trivial member function");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000260 }
261
John McCallfc400282010-09-03 01:26:39 +0000262 // Compute the function type we're calling.
Eli Friedman465e89e2012-10-25 00:12:49 +0000263 const CXXMethodDecl *CalleeDecl = DevirtualizedMethod ? DevirtualizedMethod : MD;
Francois Pichetdbee3412011-01-18 05:04:39 +0000264 const CGFunctionInfo *FInfo = 0;
Eli Friedman465e89e2012-10-25 00:12:49 +0000265 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
266 FInfo = &CGM.getTypes().arrangeCXXDestructor(Dtor,
John McCallde5d3c72012-02-17 03:33:10 +0000267 Dtor_Complete);
Eli Friedman465e89e2012-10-25 00:12:49 +0000268 else if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
269 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor,
270 Ctor_Complete);
Francois Pichetdbee3412011-01-18 05:04:39 +0000271 else
Eli Friedman465e89e2012-10-25 00:12:49 +0000272 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCallfc400282010-09-03 01:26:39 +0000273
John McCallde5d3c72012-02-17 03:33:10 +0000274 llvm::Type *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCallfc400282010-09-03 01:26:39 +0000275
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000276 // C++ [class.virtual]p12:
277 // Explicit qualification with the scope operator (5.1) suppresses the
278 // virtual call mechanism.
279 //
280 // We also don't emit a virtual call if the base expression has a record type
281 // because then we know what the type is.
Rafael Espindolaea01d762012-06-28 14:28:57 +0000282 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000283
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000284 llvm::Value *Callee;
John McCallfc400282010-09-03 01:26:39 +0000285 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
286 if (UseVirtualCall) {
287 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000288 } else {
Richard Smith7edf9e32012-11-01 22:30:59 +0000289 if (getLangOpts().AppleKext &&
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000290 MD->isVirtual() &&
291 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000292 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000293 else if (!DevirtualizedMethod)
Rafael Espindola12582bd2012-06-26 19:18:25 +0000294 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000295 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000296 const CXXDestructorDecl *DDtor =
297 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000298 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
299 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000300 }
Francois Pichetdbee3412011-01-18 05:04:39 +0000301 } else if (const CXXConstructorDecl *Ctor =
302 dyn_cast<CXXConstructorDecl>(MD)) {
303 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000304 } else if (UseVirtualCall) {
Fariborz Jahanian27262672011-01-20 17:19:02 +0000305 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000306 } else {
Richard Smith7edf9e32012-11-01 22:30:59 +0000307 if (getLangOpts().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000308 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000309 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000310 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000311 else if (!DevirtualizedMethod)
Rafael Espindola12582bd2012-06-26 19:18:25 +0000312 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000313 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000314 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000315 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000316 }
317
Richard Smith4def70d2012-10-09 19:52:38 +0000318 return EmitCXXMemberCall(MD, CE->getExprLoc(), Callee, ReturnValue, This,
319 /*VTT=*/0, CE->arg_begin(), CE->arg_end());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000320}
321
322RValue
323CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
324 ReturnValueSlot ReturnValue) {
325 const BinaryOperator *BO =
326 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
327 const Expr *BaseExpr = BO->getLHS();
328 const Expr *MemFnExpr = BO->getRHS();
329
330 const MemberPointerType *MPT =
John McCall864c0412011-04-26 20:42:42 +0000331 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000332
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000333 const FunctionProtoType *FPT =
John McCall864c0412011-04-26 20:42:42 +0000334 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000335 const CXXRecordDecl *RD =
336 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
337
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000338 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000339 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000340
341 // Emit the 'this' pointer.
342 llvm::Value *This;
343
John McCall2de56d12010-08-25 11:45:40 +0000344 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000345 This = EmitScalarExpr(BaseExpr);
346 else
347 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000348
Richard Smith4def70d2012-10-09 19:52:38 +0000349 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
350 QualType(MPT->getClass(), 0));
Richard Smith2c9f87c2012-08-24 00:54:33 +0000351
John McCall93d557b2010-08-22 00:05:51 +0000352 // Ask the ABI to load the callee. Note that This is modified.
353 llvm::Value *Callee =
John McCalld16c2cf2011-02-08 08:22:06 +0000354 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000355
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000356 CallArgList Args;
357
358 QualType ThisType =
359 getContext().getPointerType(getContext().getTagDeclType(RD));
360
361 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +0000362 Args.add(RValue::get(This), ThisType);
John McCall0f3d0972012-07-07 06:41:13 +0000363
364 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000365
366 // And the rest of the call args
367 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall0f3d0972012-07-07 06:41:13 +0000368 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required), Callee,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000369 ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000370}
371
372RValue
373CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
374 const CXXMethodDecl *MD,
375 ReturnValueSlot ReturnValue) {
376 assert(MD->isInstance() &&
377 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000378 LValue LV = EmitLValue(E->getArg(0));
379 llvm::Value *This = LV.getAddress();
380
Douglas Gregorb2b56582011-09-06 16:26:56 +0000381 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
382 MD->isTrivial()) {
383 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
384 QualType Ty = E->getType();
Benjamin Kramer6cacae82012-09-30 12:43:37 +0000385 EmitAggregateAssign(This, Src, Ty);
Douglas Gregorb2b56582011-09-06 16:26:56 +0000386 return RValue::get(This);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000387 }
388
Anders Carlssona2447e02011-05-08 20:32:23 +0000389 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Richard Smith4def70d2012-10-09 19:52:38 +0000390 return EmitCXXMemberCall(MD, E->getExprLoc(), Callee, ReturnValue, This,
391 /*VTT=*/0, E->arg_begin() + 1, E->arg_end());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000392}
393
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000394RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
395 ReturnValueSlot ReturnValue) {
396 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
397}
398
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000399static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
400 llvm::Value *DestPtr,
401 const CXXRecordDecl *Base) {
402 if (Base->isEmpty())
403 return;
404
405 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
406
407 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
408 CharUnits Size = Layout.getNonVirtualSize();
409 CharUnits Align = Layout.getNonVirtualAlign();
410
411 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
412
413 // If the type contains a pointer to data member we can't memset it to zero.
414 // Instead, create a null constant and copy it to the destination.
415 // TODO: there are other patterns besides zero that we can usefully memset,
416 // like -1, which happens to be the pattern used by member-pointers.
417 // TODO: isZeroInitializable can be over-conservative in the case where a
418 // virtual base contains a member pointer.
419 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
420 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
421
422 llvm::GlobalVariable *NullVariable =
423 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
424 /*isConstant=*/true,
425 llvm::GlobalVariable::PrivateLinkage,
426 NullConstant, Twine());
427 NullVariable->setAlignment(Align.getQuantity());
428 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
429
430 // Get and call the appropriate llvm.memcpy overload.
431 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
432 return;
433 }
434
435 // Otherwise, just memset the whole thing to zero. This is legal
436 // because in LLVM, all default initializers (other than the ones we just
437 // handled above) are guaranteed to have a bit pattern of all zeros.
438 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
439 Align.getQuantity());
440}
441
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000442void
John McCall558d2ab2010-09-15 10:14:12 +0000443CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
444 AggValueSlot Dest) {
445 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000446 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000447
448 // If we require zero initialization before (or instead of) calling the
449 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +0000450 // constructor, emit the zero initialization now, unless destination is
451 // already zeroed.
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000452 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
453 switch (E->getConstructionKind()) {
454 case CXXConstructExpr::CK_Delegating:
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000455 case CXXConstructExpr::CK_Complete:
456 EmitNullInitialization(Dest.getAddr(), E->getType());
457 break;
458 case CXXConstructExpr::CK_VirtualBase:
459 case CXXConstructExpr::CK_NonVirtualBase:
460 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
461 break;
462 }
463 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000464
465 // If this is a call to a trivial default constructor, do nothing.
466 if (CD->isTrivial() && CD->isDefaultConstructor())
467 return;
468
John McCallfc1e6c72010-09-18 00:58:34 +0000469 // Elide the constructor if we're constructing from a temporary.
470 // The temporary check is required because Sema sets this on NRVO
471 // returns.
Richard Smith7edf9e32012-11-01 22:30:59 +0000472 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000473 assert(getContext().hasSameUnqualifiedType(E->getType(),
474 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000475 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
476 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000477 return;
478 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000479 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000480
John McCallc3c07662011-07-13 06:10:41 +0000481 if (const ConstantArrayType *arrayType
482 = getContext().getAsConstantArrayType(E->getType())) {
483 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000484 E->arg_begin(), E->arg_end());
John McCallc3c07662011-07-13 06:10:41 +0000485 } else {
Cameron Esfahani6bd2f6a2011-05-06 21:28:42 +0000486 CXXCtorType Type = Ctor_Complete;
Sean Huntd49bd552011-05-03 20:19:28 +0000487 bool ForVirtualBase = false;
488
489 switch (E->getConstructionKind()) {
490 case CXXConstructExpr::CK_Delegating:
Sean Hunt059ce0d2011-05-01 07:04:31 +0000491 // We should be emitting a constructor; GlobalDecl will assert this
492 Type = CurGD.getCtorType();
Sean Huntd49bd552011-05-03 20:19:28 +0000493 break;
Sean Hunt059ce0d2011-05-01 07:04:31 +0000494
Sean Huntd49bd552011-05-03 20:19:28 +0000495 case CXXConstructExpr::CK_Complete:
496 Type = Ctor_Complete;
497 break;
498
499 case CXXConstructExpr::CK_VirtualBase:
500 ForVirtualBase = true;
501 // fall-through
502
503 case CXXConstructExpr::CK_NonVirtualBase:
504 Type = Ctor_Base;
505 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000506
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000507 // Call the constructor.
John McCall558d2ab2010-09-15 10:14:12 +0000508 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000509 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000510 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000511}
512
Fariborz Jahanian34999872010-11-13 21:53:34 +0000513void
514CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
515 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000516 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000517 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000518 Exp = E->getSubExpr();
519 assert(isa<CXXConstructExpr>(Exp) &&
520 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
521 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
522 const CXXConstructorDecl *CD = E->getConstructor();
523 RunCleanupsScope Scope(*this);
524
525 // If we require zero initialization before (or instead of) calling the
526 // constructor, as can be the case with a non-user-provided default
527 // constructor, emit the zero initialization now.
528 // FIXME. Do I still need this for a copy ctor synthesis?
529 if (E->requiresZeroInitialization())
530 EmitNullInitialization(Dest, E->getType());
531
Chandler Carruth858a5462010-11-15 13:54:43 +0000532 assert(!getContext().getAsConstantArrayType(E->getType())
533 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000534 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
535 E->arg_begin(), E->arg_end());
536}
537
John McCall1e7fe752010-09-02 09:58:18 +0000538static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
539 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000540 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000541 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000542
John McCallb1c98a32011-05-16 01:05:12 +0000543 // No cookie is required if the operator new[] being used is the
544 // reserved placement operator new[].
545 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCall5172ed92010-08-23 01:17:59 +0000546 return CharUnits::Zero();
547
John McCall6ec278d2011-01-27 09:37:56 +0000548 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000549}
550
John McCall7d166272011-05-15 07:14:44 +0000551static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
552 const CXXNewExpr *e,
Sebastian Redl92036472012-02-22 17:37:52 +0000553 unsigned minElements,
John McCall7d166272011-05-15 07:14:44 +0000554 llvm::Value *&numElements,
555 llvm::Value *&sizeWithoutCookie) {
556 QualType type = e->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000557
John McCall7d166272011-05-15 07:14:44 +0000558 if (!e->isArray()) {
559 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
560 sizeWithoutCookie
561 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
562 return sizeWithoutCookie;
Douglas Gregor59174c02010-07-21 01:10:17 +0000563 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000564
John McCall7d166272011-05-15 07:14:44 +0000565 // The width of size_t.
566 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
567
John McCall1e7fe752010-09-02 09:58:18 +0000568 // Figure out the cookie size.
John McCall7d166272011-05-15 07:14:44 +0000569 llvm::APInt cookieSize(sizeWidth,
570 CalculateCookiePadding(CGF, e).getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000571
Anders Carlssona4d4c012009-09-23 16:07:23 +0000572 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000573 // We multiply the size of all dimensions for NumElements.
574 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall7d166272011-05-15 07:14:44 +0000575 numElements = CGF.EmitScalarExpr(e->getArraySize());
576 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall1e7fe752010-09-02 09:58:18 +0000577
John McCall7d166272011-05-15 07:14:44 +0000578 // The number of elements can be have an arbitrary integer type;
579 // essentially, we need to multiply it by a constant factor, add a
580 // cookie size, and verify that the result is representable as a
581 // size_t. That's just a gloss, though, and it's wrong in one
582 // important way: if the count is negative, it's an error even if
583 // the cookie size would bring the total size >= 0.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000584 bool isSigned
585 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000586 llvm::IntegerType *numElementsType
John McCall7d166272011-05-15 07:14:44 +0000587 = cast<llvm::IntegerType>(numElements->getType());
588 unsigned numElementsWidth = numElementsType->getBitWidth();
589
590 // Compute the constant factor.
591 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000592 while (const ConstantArrayType *CAT
John McCall7d166272011-05-15 07:14:44 +0000593 = CGF.getContext().getAsConstantArrayType(type)) {
594 type = CAT->getElementType();
595 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000596 }
597
John McCall7d166272011-05-15 07:14:44 +0000598 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
599 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
600 typeSizeMultiplier *= arraySizeMultiplier;
601
602 // This will be a size_t.
603 llvm::Value *size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000604
Chris Lattner806941e2010-07-20 21:55:52 +0000605 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
606 // Don't bloat the -O0 code.
John McCall7d166272011-05-15 07:14:44 +0000607 if (llvm::ConstantInt *numElementsC =
608 dyn_cast<llvm::ConstantInt>(numElements)) {
609 const llvm::APInt &count = numElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000610
John McCall7d166272011-05-15 07:14:44 +0000611 bool hasAnyOverflow = false;
John McCall1e7fe752010-09-02 09:58:18 +0000612
John McCall7d166272011-05-15 07:14:44 +0000613 // If 'count' was a negative number, it's an overflow.
614 if (isSigned && count.isNegative())
615 hasAnyOverflow = true;
John McCall1e7fe752010-09-02 09:58:18 +0000616
John McCall7d166272011-05-15 07:14:44 +0000617 // We want to do all this arithmetic in size_t. If numElements is
618 // wider than that, check whether it's already too big, and if so,
619 // overflow.
620 else if (numElementsWidth > sizeWidth &&
621 numElementsWidth - sizeWidth > count.countLeadingZeros())
622 hasAnyOverflow = true;
623
624 // Okay, compute a count at the right width.
625 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
626
Sebastian Redl92036472012-02-22 17:37:52 +0000627 // If there is a brace-initializer, we cannot allocate fewer elements than
628 // there are initializers. If we do, that's treated like an overflow.
629 if (adjustedCount.ult(minElements))
630 hasAnyOverflow = true;
631
John McCall7d166272011-05-15 07:14:44 +0000632 // Scale numElements by that. This might overflow, but we don't
633 // care because it only overflows if allocationSize does, too, and
634 // if that overflows then we shouldn't use this.
635 numElements = llvm::ConstantInt::get(CGF.SizeTy,
636 adjustedCount * arraySizeMultiplier);
637
638 // Compute the size before cookie, and track whether it overflowed.
639 bool overflow;
640 llvm::APInt allocationSize
641 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
642 hasAnyOverflow |= overflow;
643
644 // Add in the cookie, and check whether it's overflowed.
645 if (cookieSize != 0) {
646 // Save the current size without a cookie. This shouldn't be
647 // used if there was overflow.
648 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
649
650 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
651 hasAnyOverflow |= overflow;
652 }
653
654 // On overflow, produce a -1 so operator new will fail.
655 if (hasAnyOverflow) {
656 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
657 } else {
658 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
659 }
660
661 // Otherwise, we might need to use the overflow intrinsics.
662 } else {
Sebastian Redl92036472012-02-22 17:37:52 +0000663 // There are up to five conditions we need to test for:
John McCall7d166272011-05-15 07:14:44 +0000664 // 1) if isSigned, we need to check whether numElements is negative;
665 // 2) if numElementsWidth > sizeWidth, we need to check whether
666 // numElements is larger than something representable in size_t;
Sebastian Redl92036472012-02-22 17:37:52 +0000667 // 3) if minElements > 0, we need to check whether numElements is smaller
668 // than that.
669 // 4) we need to compute
John McCall7d166272011-05-15 07:14:44 +0000670 // sizeWithoutCookie := numElements * typeSizeMultiplier
671 // and check whether it overflows; and
Sebastian Redl92036472012-02-22 17:37:52 +0000672 // 5) if we need a cookie, we need to compute
John McCall7d166272011-05-15 07:14:44 +0000673 // size := sizeWithoutCookie + cookieSize
674 // and check whether it overflows.
675
676 llvm::Value *hasOverflow = 0;
677
678 // If numElementsWidth > sizeWidth, then one way or another, we're
679 // going to have to do a comparison for (2), and this happens to
680 // take care of (1), too.
681 if (numElementsWidth > sizeWidth) {
682 llvm::APInt threshold(numElementsWidth, 1);
683 threshold <<= sizeWidth;
684
685 llvm::Value *thresholdV
686 = llvm::ConstantInt::get(numElementsType, threshold);
687
688 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
689 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
690
691 // Otherwise, if we're signed, we want to sext up to size_t.
692 } else if (isSigned) {
693 if (numElementsWidth < sizeWidth)
694 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
695
696 // If there's a non-1 type size multiplier, then we can do the
697 // signedness check at the same time as we do the multiply
698 // because a negative number times anything will cause an
Sebastian Redl92036472012-02-22 17:37:52 +0000699 // unsigned overflow. Otherwise, we have to do it here. But at least
700 // in this case, we can subsume the >= minElements check.
John McCall7d166272011-05-15 07:14:44 +0000701 if (typeSizeMultiplier == 1)
702 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redl92036472012-02-22 17:37:52 +0000703 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall7d166272011-05-15 07:14:44 +0000704
705 // Otherwise, zext up to size_t if necessary.
706 } else if (numElementsWidth < sizeWidth) {
707 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
708 }
709
710 assert(numElements->getType() == CGF.SizeTy);
711
Sebastian Redl92036472012-02-22 17:37:52 +0000712 if (minElements) {
713 // Don't allow allocation of fewer elements than we have initializers.
714 if (!hasOverflow) {
715 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
716 llvm::ConstantInt::get(CGF.SizeTy, minElements));
717 } else if (numElementsWidth > sizeWidth) {
718 // The other existing overflow subsumes this check.
719 // We do an unsigned comparison, since any signed value < -1 is
720 // taken care of either above or below.
721 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
722 CGF.Builder.CreateICmpULT(numElements,
723 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
724 }
725 }
726
John McCall7d166272011-05-15 07:14:44 +0000727 size = numElements;
728
729 // Multiply by the type size if necessary. This multiplier
730 // includes all the factors for nested arrays.
731 //
732 // This step also causes numElements to be scaled up by the
733 // nested-array factor if necessary. Overflow on this computation
734 // can be ignored because the result shouldn't be used if
735 // allocation fails.
736 if (typeSizeMultiplier != 1) {
John McCall7d166272011-05-15 07:14:44 +0000737 llvm::Value *umul_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000738 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000739
740 llvm::Value *tsmV =
741 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
742 llvm::Value *result =
743 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
744
745 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
746 if (hasOverflow)
747 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
748 else
749 hasOverflow = overflowed;
750
751 size = CGF.Builder.CreateExtractValue(result, 0);
752
753 // Also scale up numElements by the array size multiplier.
754 if (arraySizeMultiplier != 1) {
755 // If the base element type size is 1, then we can re-use the
756 // multiply we just did.
757 if (typeSize.isOne()) {
758 assert(arraySizeMultiplier == typeSizeMultiplier);
759 numElements = size;
760
761 // Otherwise we need a separate multiply.
762 } else {
763 llvm::Value *asmV =
764 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
765 numElements = CGF.Builder.CreateMul(numElements, asmV);
766 }
767 }
768 } else {
769 // numElements doesn't need to be scaled.
770 assert(arraySizeMultiplier == 1);
Chris Lattner806941e2010-07-20 21:55:52 +0000771 }
772
John McCall7d166272011-05-15 07:14:44 +0000773 // Add in the cookie size if necessary.
774 if (cookieSize != 0) {
775 sizeWithoutCookie = size;
776
John McCall7d166272011-05-15 07:14:44 +0000777 llvm::Value *uadd_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000778 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000779
780 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
781 llvm::Value *result =
782 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
783
784 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
785 if (hasOverflow)
786 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
787 else
788 hasOverflow = overflowed;
789
790 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall1e7fe752010-09-02 09:58:18 +0000791 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000792
John McCall7d166272011-05-15 07:14:44 +0000793 // If we had any possibility of dynamic overflow, make a select to
794 // overwrite 'size' with an all-ones value, which should cause
795 // operator new to throw.
796 if (hasOverflow)
797 size = CGF.Builder.CreateSelect(hasOverflow,
798 llvm::Constant::getAllOnesValue(CGF.SizeTy),
799 size);
Chris Lattner806941e2010-07-20 21:55:52 +0000800 }
John McCall1e7fe752010-09-02 09:58:18 +0000801
John McCall7d166272011-05-15 07:14:44 +0000802 if (cookieSize == 0)
803 sizeWithoutCookie = size;
John McCall1e7fe752010-09-02 09:58:18 +0000804 else
John McCall7d166272011-05-15 07:14:44 +0000805 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall1e7fe752010-09-02 09:58:18 +0000806
John McCall7d166272011-05-15 07:14:44 +0000807 return size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000808}
809
Sebastian Redl92036472012-02-22 17:37:52 +0000810static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
811 QualType AllocType, llvm::Value *NewPtr) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000812
Eli Friedmand7722d92011-12-03 02:13:40 +0000813 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCalla07398e2011-06-16 04:16:24 +0000814 if (!CGF.hasAggregateLLVMType(AllocType))
Eli Friedmand7722d92011-12-03 02:13:40 +0000815 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType,
Eli Friedman6da2c712011-12-03 04:14:32 +0000816 Alignment),
John McCalla07398e2011-06-16 04:16:24 +0000817 false);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000818 else if (AllocType->isAnyComplexType())
819 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
820 AllocType.isVolatileQualified());
John McCall558d2ab2010-09-15 10:14:12 +0000821 else {
822 AggValueSlot Slot
Eli Friedmanf3940782011-12-03 00:54:26 +0000823 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000824 AggValueSlot::IsDestructed,
John McCall44184392011-08-26 07:31:35 +0000825 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000826 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000827 CGF.EmitAggExpr(Init, Slot);
Sebastian Redl972edf02012-02-19 16:03:09 +0000828
829 CGF.MaybeEmitStdInitializerListCleanup(NewPtr, Init);
John McCall558d2ab2010-09-15 10:14:12 +0000830 }
Fariborz Jahanianef668722010-06-25 18:26:07 +0000831}
832
833void
834CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000835 QualType elementType,
836 llvm::Value *beginPtr,
837 llvm::Value *numElements) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000838 if (!E->hasInitializer())
839 return; // We have a POD type.
John McCall19705672011-09-15 06:49:18 +0000840
Sebastian Redl92036472012-02-22 17:37:52 +0000841 llvm::Value *explicitPtr = beginPtr;
John McCall19705672011-09-15 06:49:18 +0000842 // Find the end of the array, hoisted out of the loop.
843 llvm::Value *endPtr =
844 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
845
Sebastian Redl92036472012-02-22 17:37:52 +0000846 unsigned initializerElements = 0;
847
848 const Expr *Init = E->getInitializer();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000849 llvm::AllocaInst *endOfInit = 0;
850 QualType::DestructionKind dtorKind = elementType.isDestructedType();
851 EHScopeStack::stable_iterator cleanup;
852 llvm::Instruction *cleanupDominator = 0;
Sebastian Redl92036472012-02-22 17:37:52 +0000853 // If the initializer is an initializer list, first do the explicit elements.
854 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
855 initializerElements = ILE->getNumInits();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000856
857 // Enter a partial-destruction cleanup if necessary.
858 if (needsEHCleanup(dtorKind)) {
859 // In principle we could tell the cleanup where we are more
860 // directly, but the control flow can get so varied here that it
861 // would actually be quite complex. Therefore we go through an
862 // alloca.
863 endOfInit = CreateTempAlloca(beginPtr->getType(), "array.endOfInit");
864 cleanupDominator = Builder.CreateStore(beginPtr, endOfInit);
865 pushIrregularPartialArrayCleanup(beginPtr, endOfInit, elementType,
866 getDestroyer(dtorKind));
867 cleanup = EHStack.stable_begin();
868 }
869
Sebastian Redl92036472012-02-22 17:37:52 +0000870 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosier577fb5b2012-02-24 00:13:55 +0000871 // Tell the cleanup that it needs to destroy up to this
872 // element. TODO: some of these stores can be trivially
873 // observed to be unnecessary.
874 if (endOfInit) Builder.CreateStore(explicitPtr, endOfInit);
Sebastian Redl92036472012-02-22 17:37:52 +0000875 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), elementType, explicitPtr);
876 explicitPtr =Builder.CreateConstGEP1_32(explicitPtr, 1, "array.exp.next");
877 }
878
879 // The remaining elements are filled with the array filler expression.
880 Init = ILE->getArrayFiller();
881 }
882
John McCall19705672011-09-15 06:49:18 +0000883 // Create the continuation block.
884 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end");
885
Sebastian Redl92036472012-02-22 17:37:52 +0000886 // If the number of elements isn't constant, we have to now check if there is
887 // anything left to initialize.
888 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) {
889 // If all elements have already been initialized, skip the whole loop.
Chad Rosier577fb5b2012-02-24 00:13:55 +0000890 if (constNum->getZExtValue() <= initializerElements) {
891 // If there was a cleanup, deactivate it.
892 if (cleanupDominator)
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +0000893 DeactivateCleanupBlock(cleanup, cleanupDominator);
Chad Rosier577fb5b2012-02-24 00:13:55 +0000894 return;
895 }
Sebastian Redl92036472012-02-22 17:37:52 +0000896 } else {
John McCall19705672011-09-15 06:49:18 +0000897 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty");
Sebastian Redl92036472012-02-22 17:37:52 +0000898 llvm::Value *isEmpty = Builder.CreateICmpEQ(explicitPtr, endPtr,
John McCall19705672011-09-15 06:49:18 +0000899 "array.isempty");
900 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
901 EmitBlock(nonEmptyBB);
902 }
903
904 // Enter the loop.
905 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
906 llvm::BasicBlock *loopBB = createBasicBlock("new.loop");
907
908 EmitBlock(loopBB);
909
910 // Set up the current-element phi.
911 llvm::PHINode *curPtr =
Sebastian Redl92036472012-02-22 17:37:52 +0000912 Builder.CreatePHI(explicitPtr->getType(), 2, "array.cur");
913 curPtr->addIncoming(explicitPtr, entryBB);
John McCall19705672011-09-15 06:49:18 +0000914
Chad Rosier577fb5b2012-02-24 00:13:55 +0000915 // Store the new cleanup position for irregular cleanups.
916 if (endOfInit) Builder.CreateStore(curPtr, endOfInit);
917
John McCall19705672011-09-15 06:49:18 +0000918 // Enter a partial-destruction cleanup if necessary.
Chad Rosier577fb5b2012-02-24 00:13:55 +0000919 if (!cleanupDominator && needsEHCleanup(dtorKind)) {
John McCall19705672011-09-15 06:49:18 +0000920 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
921 getDestroyer(dtorKind));
922 cleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +0000923 cleanupDominator = Builder.CreateUnreachable();
John McCall19705672011-09-15 06:49:18 +0000924 }
925
926 // Emit the initializer into this element.
Sebastian Redl92036472012-02-22 17:37:52 +0000927 StoreAnyExprIntoOneUnit(*this, Init, E->getAllocatedType(), curPtr);
John McCall19705672011-09-15 06:49:18 +0000928
929 // Leave the cleanup if we entered one.
Eli Friedman40563cd2011-12-09 23:05:37 +0000930 if (cleanupDominator) {
John McCall6f103ba2011-11-10 10:43:54 +0000931 DeactivateCleanupBlock(cleanup, cleanupDominator);
932 cleanupDominator->eraseFromParent();
933 }
John McCall19705672011-09-15 06:49:18 +0000934
935 // Advance to the next element.
936 llvm::Value *nextPtr = Builder.CreateConstGEP1_32(curPtr, 1, "array.next");
937
938 // Check whether we've gotten to the end of the array and, if so,
939 // exit the loop.
940 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend");
941 Builder.CreateCondBr(isEnd, contBB, loopBB);
942 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock());
943
944 EmitBlock(contBB);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000945}
946
Douglas Gregor59174c02010-07-21 01:10:17 +0000947static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
948 llvm::Value *NewPtr, llvm::Value *Size) {
John McCalld16c2cf2011-02-08 08:22:06 +0000949 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyckfe710082011-01-19 01:58:38 +0000950 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000951 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000952 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000953}
954
Anders Carlssona4d4c012009-09-23 16:07:23 +0000955static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000956 QualType ElementType,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000957 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000958 llvm::Value *NumElements,
959 llvm::Value *AllocSizeWithoutCookie) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000960 const Expr *Init = E->getInitializer();
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000961 if (E->isArray()) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000962 if (const CXXConstructExpr *CCE = dyn_cast_or_null<CXXConstructExpr>(Init)){
963 CXXConstructorDecl *Ctor = CCE->getConstructor();
Douglas Gregor887ddf32012-02-23 17:07:43 +0000964 if (Ctor->isTrivial()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000965 // If new expression did not specify value-initialization, then there
966 // is no initialization.
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000967 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
Douglas Gregor59174c02010-07-21 01:10:17 +0000968 return;
969
John McCall19705672011-09-15 06:49:18 +0000970 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000971 // Optimization: since zero initialization will just set the memory
972 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +0000973 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
Douglas Gregor59174c02010-07-21 01:10:17 +0000974 return;
975 }
Douglas Gregor59174c02010-07-21 01:10:17 +0000976 }
John McCallc3c07662011-07-13 06:10:41 +0000977
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000978 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
979 CCE->arg_begin(), CCE->arg_end(),
Eli Friedmanb41ba1a2012-08-25 07:11:29 +0000980 CCE->requiresZeroInitialization());
Anders Carlssone99bdb62010-05-03 15:09:17 +0000981 return;
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000982 } else if (Init && isa<ImplicitValueInitExpr>(Init) &&
Eli Friedman40563cd2011-12-09 23:05:37 +0000983 CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000984 // Optimization: since zero initialization will just set the memory
985 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +0000986 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
987 return;
Fariborz Jahanianef668722010-06-25 18:26:07 +0000988 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000989 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
990 return;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000991 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000992
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000993 if (!Init)
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000994 return;
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000995
Sebastian Redl92036472012-02-22 17:37:52 +0000996 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000997}
998
John McCall7d8647f2010-09-14 07:57:04 +0000999namespace {
1000 /// A cleanup to call the given 'operator delete' function upon
1001 /// abnormal exit from a new expression.
1002 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1003 size_t NumPlacementArgs;
1004 const FunctionDecl *OperatorDelete;
1005 llvm::Value *Ptr;
1006 llvm::Value *AllocSize;
1007
1008 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1009
1010 public:
1011 static size_t getExtraSize(size_t NumPlacementArgs) {
1012 return NumPlacementArgs * sizeof(RValue);
1013 }
1014
1015 CallDeleteDuringNew(size_t NumPlacementArgs,
1016 const FunctionDecl *OperatorDelete,
1017 llvm::Value *Ptr,
1018 llvm::Value *AllocSize)
1019 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1020 Ptr(Ptr), AllocSize(AllocSize) {}
1021
1022 void setPlacementArg(unsigned I, RValue Arg) {
1023 assert(I < NumPlacementArgs && "index out of range");
1024 getPlacementArgs()[I] = Arg;
1025 }
1026
John McCallad346f42011-07-12 20:27:29 +00001027 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7d8647f2010-09-14 07:57:04 +00001028 const FunctionProtoType *FPT
1029 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1030 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +00001031 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +00001032
1033 CallArgList DeleteArgs;
1034
1035 // The first argument is always a void*.
1036 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001037 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001038
1039 // A member 'operator delete' can take an extra 'size_t' argument.
1040 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman04c9a492011-05-02 17:57:46 +00001041 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001042
1043 // Pass the rest of the arguments, which must match exactly.
1044 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman04c9a492011-05-02 17:57:46 +00001045 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001046
1047 // Call 'operator delete'.
John McCall0f3d0972012-07-07 06:41:13 +00001048 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, FPT),
John McCall7d8647f2010-09-14 07:57:04 +00001049 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1050 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1051 }
1052 };
John McCall3019c442010-09-17 00:50:28 +00001053
1054 /// A cleanup to call the given 'operator delete' function upon
1055 /// abnormal exit from a new expression when the new expression is
1056 /// conditional.
1057 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1058 size_t NumPlacementArgs;
1059 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +00001060 DominatingValue<RValue>::saved_type Ptr;
1061 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +00001062
John McCall804b8072011-01-28 10:53:53 +00001063 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1064 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +00001065 }
1066
1067 public:
1068 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +00001069 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +00001070 }
1071
1072 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1073 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +00001074 DominatingValue<RValue>::saved_type Ptr,
1075 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +00001076 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1077 Ptr(Ptr), AllocSize(AllocSize) {}
1078
John McCall804b8072011-01-28 10:53:53 +00001079 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +00001080 assert(I < NumPlacementArgs && "index out of range");
1081 getPlacementArgs()[I] = Arg;
1082 }
1083
John McCallad346f42011-07-12 20:27:29 +00001084 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall3019c442010-09-17 00:50:28 +00001085 const FunctionProtoType *FPT
1086 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1087 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
1088 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
1089
1090 CallArgList DeleteArgs;
1091
1092 // The first argument is always a void*.
1093 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001094 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall3019c442010-09-17 00:50:28 +00001095
1096 // A member 'operator delete' can take an extra 'size_t' argument.
1097 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +00001098 RValue RV = AllocSize.restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001099 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001100 }
1101
1102 // Pass the rest of the arguments, which must match exactly.
1103 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +00001104 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001105 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001106 }
1107
1108 // Call 'operator delete'.
John McCall0f3d0972012-07-07 06:41:13 +00001109 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, FPT),
John McCall3019c442010-09-17 00:50:28 +00001110 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1111 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1112 }
1113 };
1114}
1115
1116/// Enter a cleanup to call 'operator delete' if the initializer in a
1117/// new-expression throws.
1118static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1119 const CXXNewExpr *E,
1120 llvm::Value *NewPtr,
1121 llvm::Value *AllocSize,
1122 const CallArgList &NewArgs) {
1123 // If we're not inside a conditional branch, then the cleanup will
1124 // dominate and we can do the easier (and more efficient) thing.
1125 if (!CGF.isInConditionalBranch()) {
1126 CallDeleteDuringNew *Cleanup = CGF.EHStack
1127 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1128 E->getNumPlacementArgs(),
1129 E->getOperatorDelete(),
1130 NewPtr, AllocSize);
1131 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanc6d07822011-05-02 18:05:27 +00001132 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall3019c442010-09-17 00:50:28 +00001133
1134 return;
1135 }
1136
1137 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +00001138 DominatingValue<RValue>::saved_type SavedNewPtr =
1139 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1140 DominatingValue<RValue>::saved_type SavedAllocSize =
1141 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +00001142
1143 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCall6f103ba2011-11-10 10:43:54 +00001144 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall3019c442010-09-17 00:50:28 +00001145 E->getNumPlacementArgs(),
1146 E->getOperatorDelete(),
1147 SavedNewPtr,
1148 SavedAllocSize);
1149 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +00001150 Cleanup->setPlacementArg(I,
Eli Friedmanc6d07822011-05-02 18:05:27 +00001151 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall3019c442010-09-17 00:50:28 +00001152
John McCall6f103ba2011-11-10 10:43:54 +00001153 CGF.initFullExprCleanup();
John McCall7d8647f2010-09-14 07:57:04 +00001154}
1155
Anders Carlsson16d81b82009-09-22 22:53:17 +00001156llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001157 // The element type being allocated.
1158 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +00001159
John McCallc2f3e7f2011-03-07 03:12:35 +00001160 // 1. Build a call to the allocation function.
1161 FunctionDecl *allocator = E->getOperatorNew();
1162 const FunctionProtoType *allocatorType =
1163 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001164
John McCallc2f3e7f2011-03-07 03:12:35 +00001165 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001166
1167 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001168 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001169
Sebastian Redl92036472012-02-22 17:37:52 +00001170 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1171 unsigned minElements = 0;
1172 if (E->isArray() && E->hasInitializer()) {
1173 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1174 minElements = ILE->getNumInits();
1175 }
1176
John McCallc2f3e7f2011-03-07 03:12:35 +00001177 llvm::Value *numElements = 0;
1178 llvm::Value *allocSizeWithoutCookie = 0;
1179 llvm::Value *allocSize =
Sebastian Redl92036472012-02-22 17:37:52 +00001180 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1181 allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +00001182
Eli Friedman04c9a492011-05-02 17:57:46 +00001183 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001184
1185 // Emit the rest of the arguments.
1186 // FIXME: Ideally, this should just use EmitCallArgs.
John McCallc2f3e7f2011-03-07 03:12:35 +00001187 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001188
1189 // First, use the types from the function type.
1190 // We start at 1 here because the first argument (the allocation size)
1191 // has already been emitted.
John McCallc2f3e7f2011-03-07 03:12:35 +00001192 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1193 ++i, ++placementArg) {
1194 QualType argType = allocatorType->getArgType(i);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001195
John McCallc2f3e7f2011-03-07 03:12:35 +00001196 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1197 placementArg->getType()) &&
Anders Carlsson16d81b82009-09-22 22:53:17 +00001198 "type mismatch in call argument!");
1199
John McCall413ebdb2011-03-11 20:59:21 +00001200 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001201 }
1202
1203 // Either we've emitted all the call args, or we have a call to a
1204 // variadic function.
John McCallc2f3e7f2011-03-07 03:12:35 +00001205 assert((placementArg == E->placement_arg_end() ||
1206 allocatorType->isVariadic()) &&
1207 "Extra arguments to non-variadic function!");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001208
1209 // If we still have any arguments, emit them using the type of the argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001210 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1211 placementArg != placementArgsEnd; ++placementArg) {
John McCall413ebdb2011-03-11 20:59:21 +00001212 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001213 }
1214
John McCallb1c98a32011-05-16 01:05:12 +00001215 // Emit the allocation call. If the allocator is a global placement
1216 // operator, just "inline" it directly.
1217 RValue RV;
1218 if (allocator->isReservedGlobalPlacementOperator()) {
1219 assert(allocatorArgs.size() == 2);
1220 RV = allocatorArgs[1].RV;
1221 // TODO: kill any unnecessary computations done for the size
1222 // argument.
1223 } else {
John McCall0f3d0972012-07-07 06:41:13 +00001224 RV = EmitCall(CGM.getTypes().arrangeFreeFunctionCall(allocatorArgs,
1225 allocatorType),
John McCallb1c98a32011-05-16 01:05:12 +00001226 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1227 allocatorArgs, allocator);
1228 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001229
John McCallc2f3e7f2011-03-07 03:12:35 +00001230 // Emit a null check on the allocation result if the allocation
1231 // function is allowed to return null (because it has a non-throwing
1232 // exception spec; for this part, we inline
1233 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1234 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001235 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001236 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001237
John McCallc2f3e7f2011-03-07 03:12:35 +00001238 llvm::BasicBlock *nullCheckBB = 0;
1239 llvm::BasicBlock *contBB = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001240
John McCallc2f3e7f2011-03-07 03:12:35 +00001241 llvm::Value *allocation = RV.getScalarVal();
Micah Villmow956a5a12012-10-25 15:39:14 +00001242 unsigned AS = allocation->getType()->getPointerAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001243
John McCalla7f633f2011-03-07 01:52:56 +00001244 // The null-check means that the initializer is conditionally
1245 // evaluated.
1246 ConditionalEvaluation conditional(*this);
1247
John McCallc2f3e7f2011-03-07 03:12:35 +00001248 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001249 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001250
1251 nullCheckBB = Builder.GetInsertBlock();
1252 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1253 contBB = createBasicBlock("new.cont");
1254
1255 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1256 Builder.CreateCondBr(isNull, contBB, notNullBB);
1257 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001258 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001259
John McCall7d8647f2010-09-14 07:57:04 +00001260 // If there's an operator delete, enter a cleanup to call it if an
1261 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001262 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCall6f103ba2011-11-10 10:43:54 +00001263 llvm::Instruction *cleanupDominator = 0;
John McCallb1c98a32011-05-16 01:05:12 +00001264 if (E->getOperatorDelete() &&
1265 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001266 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1267 operatorDeleteCleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +00001268 cleanupDominator = Builder.CreateUnreachable();
John McCall7d8647f2010-09-14 07:57:04 +00001269 }
1270
Eli Friedman576cf172011-09-06 18:53:03 +00001271 assert((allocSize == allocSizeWithoutCookie) ==
1272 CalculateCookiePadding(*this, E).isZero());
1273 if (allocSize != allocSizeWithoutCookie) {
1274 assert(E->isArray());
1275 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1276 numElements,
1277 E, allocType);
1278 }
1279
Chris Lattner2acc6e32011-07-18 04:24:23 +00001280 llvm::Type *elementPtrTy
John McCallc2f3e7f2011-03-07 03:12:35 +00001281 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1282 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001283
John McCall19705672011-09-15 06:49:18 +00001284 EmitNewInitializer(*this, E, allocType, result, numElements,
1285 allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001286 if (E->isArray()) {
John McCall1e7fe752010-09-02 09:58:18 +00001287 // NewPtr is a pointer to the base element type. If we're
1288 // allocating an array of arrays, we'll need to cast back to the
1289 // array pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001290 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCallc2f3e7f2011-03-07 03:12:35 +00001291 if (result->getType() != resultType)
1292 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001293 }
John McCall7d8647f2010-09-14 07:57:04 +00001294
1295 // Deactivate the 'operator delete' cleanup if we finished
1296 // initialization.
John McCall6f103ba2011-11-10 10:43:54 +00001297 if (operatorDeleteCleanup.isValid()) {
1298 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1299 cleanupDominator->eraseFromParent();
1300 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001301
John McCallc2f3e7f2011-03-07 03:12:35 +00001302 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001303 conditional.end(*this);
1304
John McCallc2f3e7f2011-03-07 03:12:35 +00001305 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1306 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001307
Jay Foadbbf3bac2011-03-30 11:28:58 +00001308 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001309 PHI->addIncoming(result, notNullBB);
1310 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1311 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001312
John McCallc2f3e7f2011-03-07 03:12:35 +00001313 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001314 }
John McCall1e7fe752010-09-02 09:58:18 +00001315
John McCallc2f3e7f2011-03-07 03:12:35 +00001316 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001317}
1318
Eli Friedman5fe05982009-11-18 00:50:08 +00001319void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1320 llvm::Value *Ptr,
1321 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001322 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1323
Eli Friedman5fe05982009-11-18 00:50:08 +00001324 const FunctionProtoType *DeleteFTy =
1325 DeleteFD->getType()->getAs<FunctionProtoType>();
1326
1327 CallArgList DeleteArgs;
1328
Anders Carlsson871d0782009-12-13 20:04:38 +00001329 // Check if we need to pass the size to the delete operator.
1330 llvm::Value *Size = 0;
1331 QualType SizeTy;
1332 if (DeleteFTy->getNumArgs() == 2) {
1333 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001334 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1335 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1336 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001337 }
1338
Eli Friedman5fe05982009-11-18 00:50:08 +00001339 QualType ArgTy = DeleteFTy->getArgType(0);
1340 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001341 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001342
Anders Carlsson871d0782009-12-13 20:04:38 +00001343 if (Size)
Eli Friedman04c9a492011-05-02 17:57:46 +00001344 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001345
1346 // Emit the call to delete.
John McCall0f3d0972012-07-07 06:41:13 +00001347 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001348 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +00001349 DeleteArgs, DeleteFD);
1350}
1351
John McCall1e7fe752010-09-02 09:58:18 +00001352namespace {
1353 /// Calls the given 'operator delete' on a single object.
1354 struct CallObjectDelete : EHScopeStack::Cleanup {
1355 llvm::Value *Ptr;
1356 const FunctionDecl *OperatorDelete;
1357 QualType ElementType;
1358
1359 CallObjectDelete(llvm::Value *Ptr,
1360 const FunctionDecl *OperatorDelete,
1361 QualType ElementType)
1362 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1363
John McCallad346f42011-07-12 20:27:29 +00001364 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001365 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1366 }
1367 };
1368}
1369
1370/// Emit the code for deleting a single object.
1371static void EmitObjectDelete(CodeGenFunction &CGF,
1372 const FunctionDecl *OperatorDelete,
1373 llvm::Value *Ptr,
Douglas Gregora8b20f72011-07-13 00:54:47 +00001374 QualType ElementType,
1375 bool UseGlobalDelete) {
John McCall1e7fe752010-09-02 09:58:18 +00001376 // Find the destructor for the type, if applicable. If the
1377 // destructor is virtual, we'll just emit the vcall and return.
1378 const CXXDestructorDecl *Dtor = 0;
1379 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1380 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanaebab722011-08-02 18:05:30 +00001381 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall1e7fe752010-09-02 09:58:18 +00001382 Dtor = RD->getDestructor();
1383
1384 if (Dtor->isVirtual()) {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001385 if (UseGlobalDelete) {
1386 // If we're supposed to call the global delete, make sure we do so
1387 // even if the destructor throws.
John McCallecd03b42012-09-25 10:10:39 +00001388
1389 // Derive the complete-object pointer, which is what we need
1390 // to pass to the deallocation function.
1391 llvm::Value *completePtr =
1392 CGF.CGM.getCXXABI().adjustToCompleteObject(CGF, Ptr, ElementType);
1393
Douglas Gregora8b20f72011-07-13 00:54:47 +00001394 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
John McCallecd03b42012-09-25 10:10:39 +00001395 completePtr, OperatorDelete,
Douglas Gregora8b20f72011-07-13 00:54:47 +00001396 ElementType);
1397 }
1398
Chris Lattner2acc6e32011-07-18 04:24:23 +00001399 llvm::Type *Ty =
John McCallde5d3c72012-02-17 03:33:10 +00001400 CGF.getTypes().GetFunctionType(
1401 CGF.getTypes().arrangeCXXDestructor(Dtor, Dtor_Complete));
John McCall1e7fe752010-09-02 09:58:18 +00001402
1403 llvm::Value *Callee
Douglas Gregora8b20f72011-07-13 00:54:47 +00001404 = CGF.BuildVirtualCall(Dtor,
1405 UseGlobalDelete? Dtor_Complete : Dtor_Deleting,
1406 Ptr, Ty);
Richard Smith4def70d2012-10-09 19:52:38 +00001407 // FIXME: Provide a source location here.
1408 CGF.EmitCXXMemberCall(Dtor, SourceLocation(), Callee, ReturnValueSlot(),
1409 Ptr, /*VTT=*/0, 0, 0);
John McCall1e7fe752010-09-02 09:58:18 +00001410
Douglas Gregora8b20f72011-07-13 00:54:47 +00001411 if (UseGlobalDelete) {
1412 CGF.PopCleanupBlock();
1413 }
1414
John McCall1e7fe752010-09-02 09:58:18 +00001415 return;
1416 }
1417 }
1418 }
1419
1420 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001421 // This doesn't have to a conditional cleanup because we're going
1422 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001423 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1424 Ptr, OperatorDelete, ElementType);
1425
1426 if (Dtor)
1427 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1428 /*ForVirtualBase=*/false, Ptr);
David Blaikie4e4d0842012-03-11 07:00:24 +00001429 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001430 ElementType->isObjCLifetimeType()) {
1431 switch (ElementType.getObjCLifetime()) {
1432 case Qualifiers::OCL_None:
1433 case Qualifiers::OCL_ExplicitNone:
1434 case Qualifiers::OCL_Autoreleasing:
1435 break;
John McCall1e7fe752010-09-02 09:58:18 +00001436
John McCallf85e1932011-06-15 23:02:42 +00001437 case Qualifiers::OCL_Strong: {
1438 // Load the pointer value.
1439 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1440 ElementType.isVolatileQualified());
1441
1442 CGF.EmitARCRelease(PtrValue, /*precise*/ true);
1443 break;
1444 }
1445
1446 case Qualifiers::OCL_Weak:
1447 CGF.EmitARCDestroyWeak(Ptr);
1448 break;
1449 }
1450 }
1451
John McCall1e7fe752010-09-02 09:58:18 +00001452 CGF.PopCleanupBlock();
1453}
1454
1455namespace {
1456 /// Calls the given 'operator delete' on an array of objects.
1457 struct CallArrayDelete : EHScopeStack::Cleanup {
1458 llvm::Value *Ptr;
1459 const FunctionDecl *OperatorDelete;
1460 llvm::Value *NumElements;
1461 QualType ElementType;
1462 CharUnits CookieSize;
1463
1464 CallArrayDelete(llvm::Value *Ptr,
1465 const FunctionDecl *OperatorDelete,
1466 llvm::Value *NumElements,
1467 QualType ElementType,
1468 CharUnits CookieSize)
1469 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1470 ElementType(ElementType), CookieSize(CookieSize) {}
1471
John McCallad346f42011-07-12 20:27:29 +00001472 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001473 const FunctionProtoType *DeleteFTy =
1474 OperatorDelete->getType()->getAs<FunctionProtoType>();
1475 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1476
1477 CallArgList Args;
1478
1479 // Pass the pointer as the first argument.
1480 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1481 llvm::Value *DeletePtr
1482 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001483 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall1e7fe752010-09-02 09:58:18 +00001484
1485 // Pass the original requested size as the second argument.
1486 if (DeleteFTy->getNumArgs() == 2) {
1487 QualType size_t = DeleteFTy->getArgType(1);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001488 llvm::IntegerType *SizeTy
John McCall1e7fe752010-09-02 09:58:18 +00001489 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1490
1491 CharUnits ElementTypeSize =
1492 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1493
1494 // The size of an element, multiplied by the number of elements.
1495 llvm::Value *Size
1496 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1497 Size = CGF.Builder.CreateMul(Size, NumElements);
1498
1499 // Plus the size of the cookie if applicable.
1500 if (!CookieSize.isZero()) {
1501 llvm::Value *CookieSizeV
1502 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1503 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1504 }
1505
Eli Friedman04c9a492011-05-02 17:57:46 +00001506 Args.add(RValue::get(Size), size_t);
John McCall1e7fe752010-09-02 09:58:18 +00001507 }
1508
1509 // Emit the call to delete.
John McCall0f3d0972012-07-07 06:41:13 +00001510 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Args, DeleteFTy),
John McCall1e7fe752010-09-02 09:58:18 +00001511 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1512 ReturnValueSlot(), Args, OperatorDelete);
1513 }
1514 };
1515}
1516
1517/// Emit the code for deleting an array of objects.
1518static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001519 const CXXDeleteExpr *E,
John McCall7cfd76c2011-07-13 01:41:37 +00001520 llvm::Value *deletedPtr,
1521 QualType elementType) {
1522 llvm::Value *numElements = 0;
1523 llvm::Value *allocatedPtr = 0;
1524 CharUnits cookieSize;
1525 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1526 numElements, allocatedPtr, cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001527
John McCall7cfd76c2011-07-13 01:41:37 +00001528 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall1e7fe752010-09-02 09:58:18 +00001529
1530 // Make sure that we call delete even if one of the dtors throws.
John McCall7cfd76c2011-07-13 01:41:37 +00001531 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001532 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCall7cfd76c2011-07-13 01:41:37 +00001533 allocatedPtr, operatorDelete,
1534 numElements, elementType,
1535 cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001536
John McCall7cfd76c2011-07-13 01:41:37 +00001537 // Destroy the elements.
1538 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1539 assert(numElements && "no element count for a type with a destructor!");
1540
John McCall7cfd76c2011-07-13 01:41:37 +00001541 llvm::Value *arrayEnd =
1542 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCallfbf780a2011-07-13 08:09:46 +00001543
1544 // Note that it is legal to allocate a zero-length array, and we
1545 // can never fold the check away because the length should always
1546 // come from a cookie.
John McCall7cfd76c2011-07-13 01:41:37 +00001547 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1548 CGF.getDestroyer(dtorKind),
John McCallfbf780a2011-07-13 08:09:46 +00001549 /*checkZeroLength*/ true,
John McCall7cfd76c2011-07-13 01:41:37 +00001550 CGF.needsEHCleanup(dtorKind));
John McCall1e7fe752010-09-02 09:58:18 +00001551 }
1552
John McCall7cfd76c2011-07-13 01:41:37 +00001553 // Pop the cleanup block.
John McCall1e7fe752010-09-02 09:58:18 +00001554 CGF.PopCleanupBlock();
1555}
1556
Anders Carlsson16d81b82009-09-22 22:53:17 +00001557void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregor90916562009-09-29 18:16:17 +00001558 const Expr *Arg = E->getArgument();
Douglas Gregor90916562009-09-29 18:16:17 +00001559 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001560
1561 // Null check the pointer.
1562 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1563 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1564
Anders Carlssonb9241242011-04-11 00:30:07 +00001565 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001566
1567 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1568 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001569
John McCall1e7fe752010-09-02 09:58:18 +00001570 // We might be deleting a pointer to array. If so, GEP down to the
1571 // first non-array element.
1572 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1573 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1574 if (DeleteTy->isConstantArrayType()) {
1575 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001576 SmallVector<llvm::Value*,8> GEP;
John McCall1e7fe752010-09-02 09:58:18 +00001577
1578 GEP.push_back(Zero); // point at the outermost array
1579
1580 // For each layer of array type we're pointing at:
1581 while (const ConstantArrayType *Arr
1582 = getContext().getAsConstantArrayType(DeleteTy)) {
1583 // 1. Unpeel the array type.
1584 DeleteTy = Arr->getElementType();
1585
1586 // 2. GEP to the first element of the array.
1587 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001588 }
John McCall1e7fe752010-09-02 09:58:18 +00001589
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001590 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001591 }
1592
Douglas Gregoreede61a2010-09-02 17:38:50 +00001593 assert(ConvertTypeForMem(DeleteTy) ==
1594 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001595
1596 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001597 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001598 } else {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001599 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1600 E->isGlobalDelete());
John McCall1e7fe752010-09-02 09:58:18 +00001601 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001602
Anders Carlsson16d81b82009-09-22 22:53:17 +00001603 EmitBlock(DeleteEnd);
1604}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001605
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001606static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1607 // void __cxa_bad_typeid();
Chris Lattner8b418682012-02-07 00:39:47 +00001608 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001609
1610 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1611}
1612
1613static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001614 llvm::Value *Fn = getBadTypeidFn(CGF);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001615 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001616 CGF.Builder.CreateUnreachable();
1617}
1618
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001619static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1620 const Expr *E,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001621 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001622 // Get the vtable pointer.
1623 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1624
1625 // C++ [expr.typeid]p2:
1626 // If the glvalue expression is obtained by applying the unary * operator to
1627 // a pointer and the pointer is a null pointer value, the typeid expression
1628 // throws the std::bad_typeid exception.
1629 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1630 if (UO->getOpcode() == UO_Deref) {
1631 llvm::BasicBlock *BadTypeidBlock =
1632 CGF.createBasicBlock("typeid.bad_typeid");
1633 llvm::BasicBlock *EndBlock =
1634 CGF.createBasicBlock("typeid.end");
1635
1636 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1637 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1638
1639 CGF.EmitBlock(BadTypeidBlock);
1640 EmitBadTypeidCall(CGF);
1641 CGF.EmitBlock(EndBlock);
1642 }
1643 }
1644
1645 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1646 StdTypeInfoPtrTy->getPointerTo());
1647
1648 // Load the type info.
1649 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1650 return CGF.Builder.CreateLoad(Value);
1651}
1652
John McCall3ad32c82011-01-28 08:37:24 +00001653llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001654 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001655 ConvertType(E->getType())->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001656
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001657 if (E->isTypeOperand()) {
1658 llvm::Constant *TypeInfo =
1659 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001660 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001661 }
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001662
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001663 // C++ [expr.typeid]p2:
1664 // When typeid is applied to a glvalue expression whose type is a
1665 // polymorphic class type, the result refers to a std::type_info object
1666 // representing the type of the most derived object (that is, the dynamic
1667 // type) to which the glvalue refers.
Richard Smith0d729102012-08-13 20:08:14 +00001668 if (E->isPotentiallyEvaluated())
1669 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1670 StdTypeInfoPtrTy);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001671
1672 QualType OperandTy = E->getExprOperand()->getType();
1673 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1674 StdTypeInfoPtrTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001675}
Mike Stumpc849c052009-11-16 06:50:58 +00001676
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001677static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1678 // void *__dynamic_cast(const void *sub,
1679 // const abi::__class_type_info *src,
1680 // const abi::__class_type_info *dst,
1681 // std::ptrdiff_t src2dst_offset);
1682
Chris Lattner8b418682012-02-07 00:39:47 +00001683 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001684 llvm::Type *PtrDiffTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001685 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1686
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001687 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001688
Chris Lattner2acc6e32011-07-18 04:24:23 +00001689 llvm::FunctionType *FTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001690 llvm::FunctionType::get(Int8PtrTy, Args, false);
1691
1692 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1693}
1694
1695static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1696 // void __cxa_bad_cast();
Chris Lattner8b418682012-02-07 00:39:47 +00001697 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001698 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1699}
1700
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001701static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001702 llvm::Value *Fn = getBadCastFn(CGF);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001703 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001704 CGF.Builder.CreateUnreachable();
1705}
1706
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001707static llvm::Value *
1708EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1709 QualType SrcTy, QualType DestTy,
1710 llvm::BasicBlock *CastEnd) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001711 llvm::Type *PtrDiffLTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001712 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001713 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001714
1715 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1716 if (PTy->getPointeeType()->isVoidType()) {
1717 // C++ [expr.dynamic.cast]p7:
1718 // If T is "pointer to cv void," then the result is a pointer to the
1719 // most derived object pointed to by v.
1720
1721 // Get the vtable pointer.
1722 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1723
1724 // Get the offset-to-top from the vtable.
1725 llvm::Value *OffsetToTop =
1726 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1727 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1728
1729 // Finally, add the offset to the pointer.
1730 Value = CGF.EmitCastToVoidPtr(Value);
1731 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1732
1733 return CGF.Builder.CreateBitCast(Value, DestLTy);
1734 }
1735 }
1736
1737 QualType SrcRecordTy;
1738 QualType DestRecordTy;
1739
1740 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1741 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1742 DestRecordTy = DestPTy->getPointeeType();
1743 } else {
1744 SrcRecordTy = SrcTy;
1745 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1746 }
1747
1748 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1749 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1750
1751 llvm::Value *SrcRTTI =
1752 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1753 llvm::Value *DestRTTI =
1754 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1755
1756 // FIXME: Actually compute a hint here.
1757 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1758
1759 // Emit the call to __dynamic_cast.
1760 Value = CGF.EmitCastToVoidPtr(Value);
1761 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1762 SrcRTTI, DestRTTI, OffsetHint);
1763 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1764
1765 /// C++ [expr.dynamic.cast]p9:
1766 /// A failed cast to reference type throws std::bad_cast
1767 if (DestTy->isReferenceType()) {
1768 llvm::BasicBlock *BadCastBlock =
1769 CGF.createBasicBlock("dynamic_cast.bad_cast");
1770
1771 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1772 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1773
1774 CGF.EmitBlock(BadCastBlock);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001775 EmitBadCastCall(CGF);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001776 }
1777
1778 return Value;
1779}
1780
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001781static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1782 QualType DestTy) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001783 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001784 if (DestTy->isPointerType())
1785 return llvm::Constant::getNullValue(DestLTy);
1786
1787 /// C++ [expr.dynamic.cast]p9:
1788 /// A failed cast to reference type throws std::bad_cast
1789 EmitBadCastCall(CGF);
1790
1791 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1792 return llvm::UndefValue::get(DestLTy);
1793}
1794
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001795llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001796 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001797 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001798
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001799 if (DCE->isAlwaysNull())
1800 return EmitDynamicCastToNull(*this, DestTy);
1801
1802 QualType SrcTy = DCE->getSubExpr()->getType();
1803
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001804 // C++ [expr.dynamic.cast]p4:
1805 // If the value of v is a null pointer value in the pointer case, the result
1806 // is the null pointer value of type T.
1807 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001808
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001809 llvm::BasicBlock *CastNull = 0;
1810 llvm::BasicBlock *CastNotNull = 0;
1811 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001812
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001813 if (ShouldNullCheckSrcValue) {
1814 CastNull = createBasicBlock("dynamic_cast.null");
1815 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1816
1817 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1818 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1819 EmitBlock(CastNotNull);
Mike Stumpc849c052009-11-16 06:50:58 +00001820 }
1821
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001822 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1823
1824 if (ShouldNullCheckSrcValue) {
1825 EmitBranch(CastEnd);
1826
1827 EmitBlock(CastNull);
1828 EmitBranch(CastEnd);
1829 }
1830
1831 EmitBlock(CastEnd);
1832
1833 if (ShouldNullCheckSrcValue) {
1834 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1835 PHI->addIncoming(Value, CastNotNull);
1836 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1837
1838 Value = PHI;
1839 }
1840
1841 return Value;
Mike Stumpc849c052009-11-16 06:50:58 +00001842}
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001843
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001844void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedmanf8823e72012-02-09 03:47:20 +00001845 RunCleanupsScope Scope(*this);
Eli Friedman377ecc72012-04-16 03:54:45 +00001846 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1847 Slot.getAlignment());
Eli Friedmanf8823e72012-02-09 03:47:20 +00001848
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001849 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1850 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1851 e = E->capture_init_end();
Eric Christopherc07b18e2012-02-29 03:25:18 +00001852 i != e; ++i, ++CurField) {
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001853 // Emit initialization
Eli Friedman377ecc72012-04-16 03:54:45 +00001854
David Blaikie581deb32012-06-06 20:45:41 +00001855 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Eli Friedmanb74ed082012-02-14 02:31:03 +00001856 ArrayRef<VarDecl *> ArrayIndexes;
1857 if (CurField->getType()->isArrayType())
1858 ArrayIndexes = E->getCaptureInitIndexVars(i);
David Blaikie581deb32012-06-06 20:45:41 +00001859 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001860 }
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001861}