blob: 100ef02af13be8f614b246916c472a74ec61288b [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlssoncc52f652009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
Devang Patel91bbb552010-09-30 19:05:55 +000014#include "clang/Frontend/CodeGenOptions.h"
Anders Carlssoncc52f652009-09-22 22:53:17 +000015#include "CodeGenFunction.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000016#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000017#include "CGCXXABI.h"
Fariborz Jahanian60d215b2010-05-20 21:38:57 +000018#include "CGObjCRuntime.h"
Devang Patel91bbb552010-09-30 19:05:55 +000019#include "CGDebugInfo.h"
Chris Lattner26008e02010-07-20 20:19:24 +000020#include "llvm/Intrinsics.h"
Anders Carlssonbbe277c2011-04-13 02:35:36 +000021#include "llvm/Support/CallSite.h"
22
Anders Carlssoncc52f652009-09-22 22:53:17 +000023using namespace clang;
24using namespace CodeGen;
25
Anders Carlsson27da15b2010-01-01 20:29:01 +000026RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
27 llvm::Value *Callee,
28 ReturnValueSlot ReturnValue,
29 llvm::Value *This,
Anders Carlssone36a6b32010-01-02 01:01:18 +000030 llvm::Value *VTT,
Anders Carlsson27da15b2010-01-01 20:29:01 +000031 CallExpr::const_arg_iterator ArgBeg,
32 CallExpr::const_arg_iterator ArgEnd) {
33 assert(MD->isInstance() &&
34 "Trying to emit a member call expr on a static method!");
35
Anders Carlsson27da15b2010-01-01 20:29:01 +000036 CallArgList Args;
37
38 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +000039 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson27da15b2010-01-01 20:29:01 +000040
Anders Carlssone36a6b32010-01-02 01:01:18 +000041 // If there is a VTT parameter, emit it.
42 if (VTT) {
43 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +000044 Args.add(RValue::get(VTT), T);
Anders Carlssone36a6b32010-01-02 01:01:18 +000045 }
John McCalla729c622012-02-17 03:33:10 +000046
47 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
48 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Anders Carlssone36a6b32010-01-02 01:01:18 +000049
John McCalla729c622012-02-17 03:33:10 +000050 // And the rest of the call args.
Anders Carlsson27da15b2010-01-01 20:29:01 +000051 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
52
John McCalla729c622012-02-17 03:33:10 +000053 return EmitCall(CGM.getTypes().arrangeFunctionCall(FPT->getResultType(), Args,
54 FPT->getExtInfo(),
55 required),
Rafael Espindolac50c27c2010-03-30 20:24:48 +000056 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000057}
58
Anders Carlssonc53d9e82011-04-10 18:20:53 +000059// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
60// quite what we want.
61static const Expr *skipNoOpCastsAndParens(const Expr *E) {
62 while (true) {
63 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
64 E = PE->getSubExpr();
65 continue;
66 }
67
68 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
69 if (CE->getCastKind() == CK_NoOp) {
70 E = CE->getSubExpr();
71 continue;
72 }
73 }
74 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
75 if (UO->getOpcode() == UO_Extension) {
76 E = UO->getSubExpr();
77 continue;
78 }
79 }
80 return E;
81 }
82}
83
Anders Carlsson27da15b2010-01-01 20:29:01 +000084/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
85/// expr can be devirtualized.
Fariborz Jahanian252a47f2011-01-21 01:04:41 +000086static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
87 const Expr *Base,
Anders Carlssona7911fa2010-10-27 13:28:46 +000088 const CXXMethodDecl *MD) {
89
Anders Carlsson1ae64c52011-01-29 03:52:01 +000090 // When building with -fapple-kext, all calls must go through the vtable since
91 // the kernel linker can do runtime patching of vtables.
David Blaikiebbafb8a2012-03-11 07:00:24 +000092 if (Context.getLangOpts().AppleKext)
Fariborz Jahanian252a47f2011-01-21 01:04:41 +000093 return false;
94
Anders Carlsson1ae64c52011-01-29 03:52:01 +000095 // If the most derived class is marked final, we know that no subclass can
96 // override this member function and so we can devirtualize it. For example:
97 //
98 // struct A { virtual void f(); }
99 // struct B final : A { };
100 //
101 // void f(B *b) {
102 // b->f();
103 // }
104 //
Rafael Espindolab7f5a9c2012-06-27 18:18:05 +0000105 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlsson1ae64c52011-01-29 03:52:01 +0000106 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
107 return true;
108
Anders Carlsson19588aa2011-01-23 21:07:30 +0000109 // If the member function is marked 'final', we know that it can't be
Anders Carlssonb00c2142010-10-27 13:34:43 +0000110 // overridden and can therefore devirtualize it.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000111 if (MD->hasAttr<FinalAttr>())
Anders Carlssona7911fa2010-10-27 13:28:46 +0000112 return true;
Anders Carlssonb00c2142010-10-27 13:34:43 +0000113
Anders Carlsson19588aa2011-01-23 21:07:30 +0000114 // Similarly, if the class itself is marked 'final' it can't be overridden
115 // and we can therefore devirtualize the member function call.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000116 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssonb00c2142010-10-27 13:34:43 +0000117 return true;
118
Anders Carlssonc53d9e82011-04-10 18:20:53 +0000119 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000120 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
121 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
122 // This is a record decl. We know the type and can devirtualize it.
123 return VD->getType()->isRecordType();
124 }
125
126 return false;
127 }
128
129 // We can always devirtualize calls on temporary object expressions.
Eli Friedmana6824272010-01-31 20:58:15 +0000130 if (isa<CXXConstructExpr>(Base))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000131 return true;
132
133 // And calls on bound temporaries.
134 if (isa<CXXBindTemporaryExpr>(Base))
135 return true;
136
137 // Check if this is a call expr that returns a record type.
138 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
139 return CE->getCallReturnType()->isRecordType();
Anders Carlssona7911fa2010-10-27 13:28:46 +0000140
Anders Carlsson27da15b2010-01-01 20:29:01 +0000141 // We can't devirtualize the call.
142 return false;
143}
144
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000145static CXXRecordDecl *getCXXRecord(const Expr *E) {
146 QualType T = E->getType();
147 if (const PointerType *PTy = T->getAs<PointerType>())
148 T = PTy->getPointeeType();
149 const RecordType *Ty = T->castAs<RecordType>();
150 return cast<CXXRecordDecl>(Ty->getDecl());
151}
152
Francois Pichet64225792011-01-18 05:04:39 +0000153// Note: This function also emit constructor calls to support a MSVC
154// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000155RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
156 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +0000157 const Expr *callee = CE->getCallee()->IgnoreParens();
158
159 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000160 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +0000161
162 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000163 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
164
Devang Patel91bbb552010-09-30 19:05:55 +0000165 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000166 if (DI && CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo
Devang Patel401c9162010-10-22 18:56:27 +0000167 && !isa<CallExpr>(ME->getBase())) {
Devang Patel91bbb552010-09-30 19:05:55 +0000168 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
169 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
170 DI->getOrCreateRecordType(PTy->getPointeeType(),
171 MD->getParent()->getLocation());
172 }
173 }
174
Anders Carlsson27da15b2010-01-01 20:29:01 +0000175 if (MD->isStatic()) {
176 // The method is static, emit it as we would a regular call.
177 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
178 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
179 ReturnValue, CE->arg_begin(), CE->arg_end());
180 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000181
John McCall0d635f52010-09-03 01:26:39 +0000182 // Compute the object pointer.
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000183 const Expr *Base = ME->getBase();
184 bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000185
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000186 const CXXMethodDecl *DevirtualizedMethod = NULL;
187 if (CanUseVirtualCall &&
188 canDevirtualizeMemberFunctionCalls(getContext(), Base, MD)) {
189 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
190 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
191 assert(DevirtualizedMethod);
192 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
193 const Expr *Inner = Base->ignoreParenBaseCasts();
194 if (getCXXRecord(Inner) == DevirtualizedClass)
195 // If the class of the Inner expression is where the dynamic method
196 // is defined, build the this pointer from it.
197 Base = Inner;
198 else if (getCXXRecord(Base) != DevirtualizedClass) {
199 // If the method is defined in a class that is not the best dynamic
200 // one or the one of the full expression, we would have to build
201 // a derived-to-base cast to compute the correct this pointer, but
202 // we don't have support for that yet, so do a virtual call.
203 DevirtualizedMethod = NULL;
204 }
205 }
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000206
Anders Carlsson27da15b2010-01-01 20:29:01 +0000207 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000208 if (ME->isArrow())
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000209 This = EmitScalarExpr(Base);
John McCalle26a8722010-12-04 08:14:53 +0000210 else
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000211 This = EmitLValue(Base).getAddress();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000212
Anders Carlsson27da15b2010-01-01 20:29:01 +0000213
John McCall0d635f52010-09-03 01:26:39 +0000214 if (MD->isTrivial()) {
215 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichet64225792011-01-18 05:04:39 +0000216 if (isa<CXXConstructorDecl>(MD) &&
217 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
218 return RValue::get(0);
John McCall0d635f52010-09-03 01:26:39 +0000219
Sebastian Redl22653ba2011-08-30 19:58:05 +0000220 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
221 // We don't like to generate the trivial copy/move assignment operator
222 // when it isn't necessary; just produce the proper effect here.
Francois Pichet64225792011-01-18 05:04:39 +0000223 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
224 EmitAggregateCopy(This, RHS, CE->getType());
225 return RValue::get(This);
226 }
227
228 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000229 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
230 // Trivial move and copy ctor are the same.
Francois Pichet64225792011-01-18 05:04:39 +0000231 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
232 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
233 CE->arg_begin(), CE->arg_end());
234 return RValue::get(This);
235 }
236 llvm_unreachable("unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000237 }
238
John McCall0d635f52010-09-03 01:26:39 +0000239 // Compute the function type we're calling.
Francois Pichet64225792011-01-18 05:04:39 +0000240 const CGFunctionInfo *FInfo = 0;
241 if (isa<CXXDestructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000242 FInfo = &CGM.getTypes().arrangeCXXDestructor(cast<CXXDestructorDecl>(MD),
243 Dtor_Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000244 else if (isa<CXXConstructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000245 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(
246 cast<CXXConstructorDecl>(MD),
247 Ctor_Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000248 else
John McCalla729c622012-02-17 03:33:10 +0000249 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(MD);
John McCall0d635f52010-09-03 01:26:39 +0000250
John McCalla729c622012-02-17 03:33:10 +0000251 llvm::Type *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000252
Anders Carlsson27da15b2010-01-01 20:29:01 +0000253 // C++ [class.virtual]p12:
254 // Explicit qualification with the scope operator (5.1) suppresses the
255 // virtual call mechanism.
256 //
257 // We also don't emit a virtual call if the base expression has a record type
258 // because then we know what the type is.
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000259 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Rafael Espindola49e860b2012-06-26 17:45:31 +0000260
Anders Carlsson27da15b2010-01-01 20:29:01 +0000261 llvm::Value *Callee;
John McCall0d635f52010-09-03 01:26:39 +0000262 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
263 if (UseVirtualCall) {
264 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000265 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000266 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000267 MD->isVirtual() &&
268 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000269 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000270 else if (!DevirtualizedMethod)
Rafael Espindola727a7712012-06-26 19:18:25 +0000271 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000272 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000273 const CXXDestructorDecl *DDtor =
274 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000275 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
276 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000277 }
Francois Pichet64225792011-01-18 05:04:39 +0000278 } else if (const CXXConstructorDecl *Ctor =
279 dyn_cast<CXXConstructorDecl>(MD)) {
280 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000281 } else if (UseVirtualCall) {
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000282 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000283 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000284 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahanian9f9438b2011-01-28 23:42:29 +0000285 MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000286 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000287 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000288 else if (!DevirtualizedMethod)
Rafael Espindola727a7712012-06-26 19:18:25 +0000289 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000290 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000291 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000292 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000293 }
294
Anders Carlssone36a6b32010-01-02 01:01:18 +0000295 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000296 CE->arg_begin(), CE->arg_end());
297}
298
299RValue
300CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
301 ReturnValueSlot ReturnValue) {
302 const BinaryOperator *BO =
303 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
304 const Expr *BaseExpr = BO->getLHS();
305 const Expr *MemFnExpr = BO->getRHS();
306
307 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000308 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000309
Anders Carlsson27da15b2010-01-01 20:29:01 +0000310 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000311 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000312 const CXXRecordDecl *RD =
313 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
314
Anders Carlsson27da15b2010-01-01 20:29:01 +0000315 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000316 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000317
318 // Emit the 'this' pointer.
319 llvm::Value *This;
320
John McCalle3027922010-08-25 11:45:40 +0000321 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000322 This = EmitScalarExpr(BaseExpr);
323 else
324 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000325
John McCall475999d2010-08-22 00:05:51 +0000326 // Ask the ABI to load the callee. Note that This is modified.
327 llvm::Value *Callee =
John McCallad7c5c12011-02-08 08:22:06 +0000328 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000329
Anders Carlsson27da15b2010-01-01 20:29:01 +0000330 CallArgList Args;
331
332 QualType ThisType =
333 getContext().getPointerType(getContext().getTagDeclType(RD));
334
335 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000336 Args.add(RValue::get(This), ThisType);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000337
338 // And the rest of the call args
339 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCalla729c622012-02-17 03:33:10 +0000340 return EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), Callee,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000341 ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000342}
343
344RValue
345CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
346 const CXXMethodDecl *MD,
347 ReturnValueSlot ReturnValue) {
348 assert(MD->isInstance() &&
349 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000350 LValue LV = EmitLValue(E->getArg(0));
351 llvm::Value *This = LV.getAddress();
352
Douglas Gregor146b8e92011-09-06 16:26:56 +0000353 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
354 MD->isTrivial()) {
355 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
356 QualType Ty = E->getType();
357 EmitAggregateCopy(This, Src, Ty);
358 return RValue::get(This);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000359 }
360
Anders Carlssonc36783e2011-05-08 20:32:23 +0000361 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000362 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000363 E->arg_begin() + 1, E->arg_end());
364}
365
Peter Collingbournefe883422011-10-06 18:29:37 +0000366RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
367 ReturnValueSlot ReturnValue) {
368 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
369}
370
Eli Friedmanfde961d2011-10-14 02:27:24 +0000371static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
372 llvm::Value *DestPtr,
373 const CXXRecordDecl *Base) {
374 if (Base->isEmpty())
375 return;
376
377 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
378
379 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
380 CharUnits Size = Layout.getNonVirtualSize();
381 CharUnits Align = Layout.getNonVirtualAlign();
382
383 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
384
385 // If the type contains a pointer to data member we can't memset it to zero.
386 // Instead, create a null constant and copy it to the destination.
387 // TODO: there are other patterns besides zero that we can usefully memset,
388 // like -1, which happens to be the pattern used by member-pointers.
389 // TODO: isZeroInitializable can be over-conservative in the case where a
390 // virtual base contains a member pointer.
391 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
392 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
393
394 llvm::GlobalVariable *NullVariable =
395 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
396 /*isConstant=*/true,
397 llvm::GlobalVariable::PrivateLinkage,
398 NullConstant, Twine());
399 NullVariable->setAlignment(Align.getQuantity());
400 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
401
402 // Get and call the appropriate llvm.memcpy overload.
403 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
404 return;
405 }
406
407 // Otherwise, just memset the whole thing to zero. This is legal
408 // because in LLVM, all default initializers (other than the ones we just
409 // handled above) are guaranteed to have a bit pattern of all zeros.
410 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
411 Align.getQuantity());
412}
413
Anders Carlsson27da15b2010-01-01 20:29:01 +0000414void
John McCall7a626f62010-09-15 10:14:12 +0000415CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
416 AggValueSlot Dest) {
417 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000418 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000419
420 // If we require zero initialization before (or instead of) calling the
421 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000422 // constructor, emit the zero initialization now, unless destination is
423 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000424 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
425 switch (E->getConstructionKind()) {
426 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000427 case CXXConstructExpr::CK_Complete:
428 EmitNullInitialization(Dest.getAddr(), E->getType());
429 break;
430 case CXXConstructExpr::CK_VirtualBase:
431 case CXXConstructExpr::CK_NonVirtualBase:
432 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
433 break;
434 }
435 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000436
437 // If this is a call to a trivial default constructor, do nothing.
438 if (CD->isTrivial() && CD->isDefaultConstructor())
439 return;
440
John McCall8ea46b62010-09-18 00:58:34 +0000441 // Elide the constructor if we're constructing from a temporary.
442 // The temporary check is required because Sema sets this on NRVO
443 // returns.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000444 if (getContext().getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000445 assert(getContext().hasSameUnqualifiedType(E->getType(),
446 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000447 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
448 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000449 return;
450 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000451 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000452
John McCallf677a8e2011-07-13 06:10:41 +0000453 if (const ConstantArrayType *arrayType
454 = getContext().getAsConstantArrayType(E->getType())) {
455 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000456 E->arg_begin(), E->arg_end());
John McCallf677a8e2011-07-13 06:10:41 +0000457 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000458 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000459 bool ForVirtualBase = false;
460
461 switch (E->getConstructionKind()) {
462 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000463 // We should be emitting a constructor; GlobalDecl will assert this
464 Type = CurGD.getCtorType();
Alexis Hunt271c3682011-05-03 20:19:28 +0000465 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000466
Alexis Hunt271c3682011-05-03 20:19:28 +0000467 case CXXConstructExpr::CK_Complete:
468 Type = Ctor_Complete;
469 break;
470
471 case CXXConstructExpr::CK_VirtualBase:
472 ForVirtualBase = true;
473 // fall-through
474
475 case CXXConstructExpr::CK_NonVirtualBase:
476 Type = Ctor_Base;
477 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000478
Anders Carlsson27da15b2010-01-01 20:29:01 +0000479 // Call the constructor.
John McCall7a626f62010-09-15 10:14:12 +0000480 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000481 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000482 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000483}
484
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000485void
486CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
487 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000488 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000489 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000490 Exp = E->getSubExpr();
491 assert(isa<CXXConstructExpr>(Exp) &&
492 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
493 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
494 const CXXConstructorDecl *CD = E->getConstructor();
495 RunCleanupsScope Scope(*this);
496
497 // If we require zero initialization before (or instead of) calling the
498 // constructor, as can be the case with a non-user-provided default
499 // constructor, emit the zero initialization now.
500 // FIXME. Do I still need this for a copy ctor synthesis?
501 if (E->requiresZeroInitialization())
502 EmitNullInitialization(Dest, E->getType());
503
Chandler Carruth99da11c2010-11-15 13:54:43 +0000504 assert(!getContext().getAsConstantArrayType(E->getType())
505 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000506 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
507 E->arg_begin(), E->arg_end());
508}
509
John McCall8ed55a52010-09-02 09:58:18 +0000510static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
511 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000512 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000513 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000514
John McCall7ec4b432011-05-16 01:05:12 +0000515 // No cookie is required if the operator new[] being used is the
516 // reserved placement operator new[].
517 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000518 return CharUnits::Zero();
519
John McCall284c48f2011-01-27 09:37:56 +0000520 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000521}
522
John McCall036f2f62011-05-15 07:14:44 +0000523static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
524 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000525 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000526 llvm::Value *&numElements,
527 llvm::Value *&sizeWithoutCookie) {
528 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000529
John McCall036f2f62011-05-15 07:14:44 +0000530 if (!e->isArray()) {
531 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
532 sizeWithoutCookie
533 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
534 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000535 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000536
John McCall036f2f62011-05-15 07:14:44 +0000537 // The width of size_t.
538 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
539
John McCall8ed55a52010-09-02 09:58:18 +0000540 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000541 llvm::APInt cookieSize(sizeWidth,
542 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000543
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000544 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000545 // We multiply the size of all dimensions for NumElements.
546 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000547 numElements = CGF.EmitScalarExpr(e->getArraySize());
548 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000549
John McCall036f2f62011-05-15 07:14:44 +0000550 // The number of elements can be have an arbitrary integer type;
551 // essentially, we need to multiply it by a constant factor, add a
552 // cookie size, and verify that the result is representable as a
553 // size_t. That's just a gloss, though, and it's wrong in one
554 // important way: if the count is negative, it's an error even if
555 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000556 bool isSigned
557 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000558 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000559 = cast<llvm::IntegerType>(numElements->getType());
560 unsigned numElementsWidth = numElementsType->getBitWidth();
561
562 // Compute the constant factor.
563 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000564 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000565 = CGF.getContext().getAsConstantArrayType(type)) {
566 type = CAT->getElementType();
567 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000568 }
569
John McCall036f2f62011-05-15 07:14:44 +0000570 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
571 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
572 typeSizeMultiplier *= arraySizeMultiplier;
573
574 // This will be a size_t.
575 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000576
Chris Lattner32ac5832010-07-20 21:55:52 +0000577 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
578 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000579 if (llvm::ConstantInt *numElementsC =
580 dyn_cast<llvm::ConstantInt>(numElements)) {
581 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000582
John McCall036f2f62011-05-15 07:14:44 +0000583 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000584
John McCall036f2f62011-05-15 07:14:44 +0000585 // If 'count' was a negative number, it's an overflow.
586 if (isSigned && count.isNegative())
587 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000588
John McCall036f2f62011-05-15 07:14:44 +0000589 // We want to do all this arithmetic in size_t. If numElements is
590 // wider than that, check whether it's already too big, and if so,
591 // overflow.
592 else if (numElementsWidth > sizeWidth &&
593 numElementsWidth - sizeWidth > count.countLeadingZeros())
594 hasAnyOverflow = true;
595
596 // Okay, compute a count at the right width.
597 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
598
Sebastian Redlf862eb62012-02-22 17:37:52 +0000599 // If there is a brace-initializer, we cannot allocate fewer elements than
600 // there are initializers. If we do, that's treated like an overflow.
601 if (adjustedCount.ult(minElements))
602 hasAnyOverflow = true;
603
John McCall036f2f62011-05-15 07:14:44 +0000604 // Scale numElements by that. This might overflow, but we don't
605 // care because it only overflows if allocationSize does, too, and
606 // if that overflows then we shouldn't use this.
607 numElements = llvm::ConstantInt::get(CGF.SizeTy,
608 adjustedCount * arraySizeMultiplier);
609
610 // Compute the size before cookie, and track whether it overflowed.
611 bool overflow;
612 llvm::APInt allocationSize
613 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
614 hasAnyOverflow |= overflow;
615
616 // Add in the cookie, and check whether it's overflowed.
617 if (cookieSize != 0) {
618 // Save the current size without a cookie. This shouldn't be
619 // used if there was overflow.
620 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
621
622 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
623 hasAnyOverflow |= overflow;
624 }
625
626 // On overflow, produce a -1 so operator new will fail.
627 if (hasAnyOverflow) {
628 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
629 } else {
630 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
631 }
632
633 // Otherwise, we might need to use the overflow intrinsics.
634 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000635 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000636 // 1) if isSigned, we need to check whether numElements is negative;
637 // 2) if numElementsWidth > sizeWidth, we need to check whether
638 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000639 // 3) if minElements > 0, we need to check whether numElements is smaller
640 // than that.
641 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000642 // sizeWithoutCookie := numElements * typeSizeMultiplier
643 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000644 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000645 // size := sizeWithoutCookie + cookieSize
646 // and check whether it overflows.
647
648 llvm::Value *hasOverflow = 0;
649
650 // If numElementsWidth > sizeWidth, then one way or another, we're
651 // going to have to do a comparison for (2), and this happens to
652 // take care of (1), too.
653 if (numElementsWidth > sizeWidth) {
654 llvm::APInt threshold(numElementsWidth, 1);
655 threshold <<= sizeWidth;
656
657 llvm::Value *thresholdV
658 = llvm::ConstantInt::get(numElementsType, threshold);
659
660 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
661 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
662
663 // Otherwise, if we're signed, we want to sext up to size_t.
664 } else if (isSigned) {
665 if (numElementsWidth < sizeWidth)
666 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
667
668 // If there's a non-1 type size multiplier, then we can do the
669 // signedness check at the same time as we do the multiply
670 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000671 // unsigned overflow. Otherwise, we have to do it here. But at least
672 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000673 if (typeSizeMultiplier == 1)
674 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000675 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000676
677 // Otherwise, zext up to size_t if necessary.
678 } else if (numElementsWidth < sizeWidth) {
679 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
680 }
681
682 assert(numElements->getType() == CGF.SizeTy);
683
Sebastian Redlf862eb62012-02-22 17:37:52 +0000684 if (minElements) {
685 // Don't allow allocation of fewer elements than we have initializers.
686 if (!hasOverflow) {
687 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
688 llvm::ConstantInt::get(CGF.SizeTy, minElements));
689 } else if (numElementsWidth > sizeWidth) {
690 // The other existing overflow subsumes this check.
691 // We do an unsigned comparison, since any signed value < -1 is
692 // taken care of either above or below.
693 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
694 CGF.Builder.CreateICmpULT(numElements,
695 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
696 }
697 }
698
John McCall036f2f62011-05-15 07:14:44 +0000699 size = numElements;
700
701 // Multiply by the type size if necessary. This multiplier
702 // includes all the factors for nested arrays.
703 //
704 // This step also causes numElements to be scaled up by the
705 // nested-array factor if necessary. Overflow on this computation
706 // can be ignored because the result shouldn't be used if
707 // allocation fails.
708 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000709 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000710 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000711
712 llvm::Value *tsmV =
713 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
714 llvm::Value *result =
715 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
716
717 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
718 if (hasOverflow)
719 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
720 else
721 hasOverflow = overflowed;
722
723 size = CGF.Builder.CreateExtractValue(result, 0);
724
725 // Also scale up numElements by the array size multiplier.
726 if (arraySizeMultiplier != 1) {
727 // If the base element type size is 1, then we can re-use the
728 // multiply we just did.
729 if (typeSize.isOne()) {
730 assert(arraySizeMultiplier == typeSizeMultiplier);
731 numElements = size;
732
733 // Otherwise we need a separate multiply.
734 } else {
735 llvm::Value *asmV =
736 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
737 numElements = CGF.Builder.CreateMul(numElements, asmV);
738 }
739 }
740 } else {
741 // numElements doesn't need to be scaled.
742 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000743 }
744
John McCall036f2f62011-05-15 07:14:44 +0000745 // Add in the cookie size if necessary.
746 if (cookieSize != 0) {
747 sizeWithoutCookie = size;
748
John McCall036f2f62011-05-15 07:14:44 +0000749 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000750 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000751
752 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
753 llvm::Value *result =
754 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
755
756 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
757 if (hasOverflow)
758 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
759 else
760 hasOverflow = overflowed;
761
762 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000763 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000764
John McCall036f2f62011-05-15 07:14:44 +0000765 // If we had any possibility of dynamic overflow, make a select to
766 // overwrite 'size' with an all-ones value, which should cause
767 // operator new to throw.
768 if (hasOverflow)
769 size = CGF.Builder.CreateSelect(hasOverflow,
770 llvm::Constant::getAllOnesValue(CGF.SizeTy),
771 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000772 }
John McCall8ed55a52010-09-02 09:58:18 +0000773
John McCall036f2f62011-05-15 07:14:44 +0000774 if (cookieSize == 0)
775 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000776 else
John McCall036f2f62011-05-15 07:14:44 +0000777 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000778
John McCall036f2f62011-05-15 07:14:44 +0000779 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000780}
781
Sebastian Redlf862eb62012-02-22 17:37:52 +0000782static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
783 QualType AllocType, llvm::Value *NewPtr) {
Daniel Dunbar03816342010-08-21 02:24:36 +0000784
Eli Friedman38cd36d2011-12-03 02:13:40 +0000785 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall1553b192011-06-16 04:16:24 +0000786 if (!CGF.hasAggregateLLVMType(AllocType))
Eli Friedman38cd36d2011-12-03 02:13:40 +0000787 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType,
Eli Friedmana0544d62011-12-03 04:14:32 +0000788 Alignment),
John McCall1553b192011-06-16 04:16:24 +0000789 false);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000790 else if (AllocType->isAnyComplexType())
791 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
792 AllocType.isVolatileQualified());
John McCall7a626f62010-09-15 10:14:12 +0000793 else {
794 AggValueSlot Slot
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000795 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000796 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000797 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000798 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000799 CGF.EmitAggExpr(Init, Slot);
Sebastian Redld026dc42012-02-19 16:03:09 +0000800
801 CGF.MaybeEmitStdInitializerListCleanup(NewPtr, Init);
John McCall7a626f62010-09-15 10:14:12 +0000802 }
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000803}
804
805void
806CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000807 QualType elementType,
808 llvm::Value *beginPtr,
809 llvm::Value *numElements) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000810 if (!E->hasInitializer())
811 return; // We have a POD type.
John McCall99210dc2011-09-15 06:49:18 +0000812
Sebastian Redlf862eb62012-02-22 17:37:52 +0000813 llvm::Value *explicitPtr = beginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000814 // Find the end of the array, hoisted out of the loop.
815 llvm::Value *endPtr =
816 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
817
Sebastian Redlf862eb62012-02-22 17:37:52 +0000818 unsigned initializerElements = 0;
819
820 const Expr *Init = E->getInitializer();
Chad Rosierf62290a2012-02-24 00:13:55 +0000821 llvm::AllocaInst *endOfInit = 0;
822 QualType::DestructionKind dtorKind = elementType.isDestructedType();
823 EHScopeStack::stable_iterator cleanup;
824 llvm::Instruction *cleanupDominator = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000825 // If the initializer is an initializer list, first do the explicit elements.
826 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
827 initializerElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +0000828
829 // Enter a partial-destruction cleanup if necessary.
830 if (needsEHCleanup(dtorKind)) {
831 // In principle we could tell the cleanup where we are more
832 // directly, but the control flow can get so varied here that it
833 // would actually be quite complex. Therefore we go through an
834 // alloca.
835 endOfInit = CreateTempAlloca(beginPtr->getType(), "array.endOfInit");
836 cleanupDominator = Builder.CreateStore(beginPtr, endOfInit);
837 pushIrregularPartialArrayCleanup(beginPtr, endOfInit, elementType,
838 getDestroyer(dtorKind));
839 cleanup = EHStack.stable_begin();
840 }
841
Sebastian Redlf862eb62012-02-22 17:37:52 +0000842 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +0000843 // Tell the cleanup that it needs to destroy up to this
844 // element. TODO: some of these stores can be trivially
845 // observed to be unnecessary.
846 if (endOfInit) Builder.CreateStore(explicitPtr, endOfInit);
Sebastian Redlf862eb62012-02-22 17:37:52 +0000847 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), elementType, explicitPtr);
848 explicitPtr =Builder.CreateConstGEP1_32(explicitPtr, 1, "array.exp.next");
849 }
850
851 // The remaining elements are filled with the array filler expression.
852 Init = ILE->getArrayFiller();
853 }
854
John McCall99210dc2011-09-15 06:49:18 +0000855 // Create the continuation block.
856 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end");
857
Sebastian Redlf862eb62012-02-22 17:37:52 +0000858 // If the number of elements isn't constant, we have to now check if there is
859 // anything left to initialize.
860 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) {
861 // If all elements have already been initialized, skip the whole loop.
Chad Rosierf62290a2012-02-24 00:13:55 +0000862 if (constNum->getZExtValue() <= initializerElements) {
863 // If there was a cleanup, deactivate it.
864 if (cleanupDominator)
865 DeactivateCleanupBlock(cleanup, cleanupDominator);;
866 return;
867 }
Sebastian Redlf862eb62012-02-22 17:37:52 +0000868 } else {
John McCall99210dc2011-09-15 06:49:18 +0000869 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty");
Sebastian Redlf862eb62012-02-22 17:37:52 +0000870 llvm::Value *isEmpty = Builder.CreateICmpEQ(explicitPtr, endPtr,
John McCall99210dc2011-09-15 06:49:18 +0000871 "array.isempty");
872 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
873 EmitBlock(nonEmptyBB);
874 }
875
876 // Enter the loop.
877 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
878 llvm::BasicBlock *loopBB = createBasicBlock("new.loop");
879
880 EmitBlock(loopBB);
881
882 // Set up the current-element phi.
883 llvm::PHINode *curPtr =
Sebastian Redlf862eb62012-02-22 17:37:52 +0000884 Builder.CreatePHI(explicitPtr->getType(), 2, "array.cur");
885 curPtr->addIncoming(explicitPtr, entryBB);
John McCall99210dc2011-09-15 06:49:18 +0000886
Chad Rosierf62290a2012-02-24 00:13:55 +0000887 // Store the new cleanup position for irregular cleanups.
888 if (endOfInit) Builder.CreateStore(curPtr, endOfInit);
889
John McCall99210dc2011-09-15 06:49:18 +0000890 // Enter a partial-destruction cleanup if necessary.
Chad Rosierf62290a2012-02-24 00:13:55 +0000891 if (!cleanupDominator && needsEHCleanup(dtorKind)) {
John McCall99210dc2011-09-15 06:49:18 +0000892 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
893 getDestroyer(dtorKind));
894 cleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +0000895 cleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +0000896 }
897
898 // Emit the initializer into this element.
Sebastian Redlf862eb62012-02-22 17:37:52 +0000899 StoreAnyExprIntoOneUnit(*this, Init, E->getAllocatedType(), curPtr);
John McCall99210dc2011-09-15 06:49:18 +0000900
901 // Leave the cleanup if we entered one.
Eli Friedmande6a86b2011-12-09 23:05:37 +0000902 if (cleanupDominator) {
John McCallf4beacd2011-11-10 10:43:54 +0000903 DeactivateCleanupBlock(cleanup, cleanupDominator);
904 cleanupDominator->eraseFromParent();
905 }
John McCall99210dc2011-09-15 06:49:18 +0000906
907 // Advance to the next element.
908 llvm::Value *nextPtr = Builder.CreateConstGEP1_32(curPtr, 1, "array.next");
909
910 // Check whether we've gotten to the end of the array and, if so,
911 // exit the loop.
912 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend");
913 Builder.CreateCondBr(isEnd, contBB, loopBB);
914 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock());
915
916 EmitBlock(contBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000917}
918
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000919static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
920 llvm::Value *NewPtr, llvm::Value *Size) {
John McCallad7c5c12011-02-08 08:22:06 +0000921 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyck705ba072011-01-19 01:58:38 +0000922 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000923 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyck705ba072011-01-19 01:58:38 +0000924 Alignment.getQuantity(), false);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000925}
926
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000927static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000928 QualType ElementType,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000929 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000930 llvm::Value *NumElements,
931 llvm::Value *AllocSizeWithoutCookie) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000932 const Expr *Init = E->getInitializer();
Anders Carlsson3a202f62009-11-24 18:43:52 +0000933 if (E->isArray()) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000934 if (const CXXConstructExpr *CCE = dyn_cast_or_null<CXXConstructExpr>(Init)){
935 CXXConstructorDecl *Ctor = CCE->getConstructor();
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000936 bool RequiresZeroInitialization = false;
Douglas Gregord1531032012-02-23 17:07:43 +0000937 if (Ctor->isTrivial()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000938 // If new expression did not specify value-initialization, then there
939 // is no initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +0000940 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000941 return;
942
John McCall99210dc2011-09-15 06:49:18 +0000943 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000944 // Optimization: since zero initialization will just set the memory
945 // to all zeroes, generate a single memset to do it in one shot.
John McCall99210dc2011-09-15 06:49:18 +0000946 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000947 return;
948 }
949
950 RequiresZeroInitialization = true;
951 }
John McCallf677a8e2011-07-13 06:10:41 +0000952
Sebastian Redl6047f072012-02-16 12:22:20 +0000953 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
954 CCE->arg_begin(), CCE->arg_end(),
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000955 RequiresZeroInitialization);
Anders Carlssond040e6b2010-05-03 15:09:17 +0000956 return;
Sebastian Redl6047f072012-02-16 12:22:20 +0000957 } else if (Init && isa<ImplicitValueInitExpr>(Init) &&
Eli Friedmande6a86b2011-12-09 23:05:37 +0000958 CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000959 // Optimization: since zero initialization will just set the memory
960 // to all zeroes, generate a single memset to do it in one shot.
John McCall99210dc2011-09-15 06:49:18 +0000961 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
962 return;
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000963 }
Sebastian Redl6047f072012-02-16 12:22:20 +0000964 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
965 return;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000966 }
Anders Carlsson3a202f62009-11-24 18:43:52 +0000967
Sebastian Redl6047f072012-02-16 12:22:20 +0000968 if (!Init)
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000969 return;
Sebastian Redl6047f072012-02-16 12:22:20 +0000970
Sebastian Redlf862eb62012-02-22 17:37:52 +0000971 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000972}
973
John McCall824c2f52010-09-14 07:57:04 +0000974namespace {
975 /// A cleanup to call the given 'operator delete' function upon
976 /// abnormal exit from a new expression.
977 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
978 size_t NumPlacementArgs;
979 const FunctionDecl *OperatorDelete;
980 llvm::Value *Ptr;
981 llvm::Value *AllocSize;
982
983 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
984
985 public:
986 static size_t getExtraSize(size_t NumPlacementArgs) {
987 return NumPlacementArgs * sizeof(RValue);
988 }
989
990 CallDeleteDuringNew(size_t NumPlacementArgs,
991 const FunctionDecl *OperatorDelete,
992 llvm::Value *Ptr,
993 llvm::Value *AllocSize)
994 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
995 Ptr(Ptr), AllocSize(AllocSize) {}
996
997 void setPlacementArg(unsigned I, RValue Arg) {
998 assert(I < NumPlacementArgs && "index out of range");
999 getPlacementArgs()[I] = Arg;
1000 }
1001
John McCall30317fd2011-07-12 20:27:29 +00001002 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall824c2f52010-09-14 07:57:04 +00001003 const FunctionProtoType *FPT
1004 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1005 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCalld441b1e2010-09-14 21:45:42 +00001006 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +00001007
1008 CallArgList DeleteArgs;
1009
1010 // The first argument is always a void*.
1011 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001012 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001013
1014 // A member 'operator delete' can take an extra 'size_t' argument.
1015 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001016 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001017
1018 // Pass the rest of the arguments, which must match exactly.
1019 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001020 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001021
1022 // Call 'operator delete'.
John McCalla729c622012-02-17 03:33:10 +00001023 CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT),
John McCall824c2f52010-09-14 07:57:04 +00001024 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1025 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1026 }
1027 };
John McCall7f9c92a2010-09-17 00:50:28 +00001028
1029 /// A cleanup to call the given 'operator delete' function upon
1030 /// abnormal exit from a new expression when the new expression is
1031 /// conditional.
1032 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1033 size_t NumPlacementArgs;
1034 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +00001035 DominatingValue<RValue>::saved_type Ptr;
1036 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +00001037
John McCallcb5f77f2011-01-28 10:53:53 +00001038 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1039 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +00001040 }
1041
1042 public:
1043 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +00001044 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +00001045 }
1046
1047 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1048 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +00001049 DominatingValue<RValue>::saved_type Ptr,
1050 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +00001051 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1052 Ptr(Ptr), AllocSize(AllocSize) {}
1053
John McCallcb5f77f2011-01-28 10:53:53 +00001054 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +00001055 assert(I < NumPlacementArgs && "index out of range");
1056 getPlacementArgs()[I] = Arg;
1057 }
1058
John McCall30317fd2011-07-12 20:27:29 +00001059 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7f9c92a2010-09-17 00:50:28 +00001060 const FunctionProtoType *FPT
1061 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1062 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
1063 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
1064
1065 CallArgList DeleteArgs;
1066
1067 // The first argument is always a void*.
1068 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001069 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001070
1071 // A member 'operator delete' can take an extra 'size_t' argument.
1072 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +00001073 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001074 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001075 }
1076
1077 // Pass the rest of the arguments, which must match exactly.
1078 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +00001079 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001080 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001081 }
1082
1083 // Call 'operator delete'.
John McCalla729c622012-02-17 03:33:10 +00001084 CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT),
John McCall7f9c92a2010-09-17 00:50:28 +00001085 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1086 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1087 }
1088 };
1089}
1090
1091/// Enter a cleanup to call 'operator delete' if the initializer in a
1092/// new-expression throws.
1093static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1094 const CXXNewExpr *E,
1095 llvm::Value *NewPtr,
1096 llvm::Value *AllocSize,
1097 const CallArgList &NewArgs) {
1098 // If we're not inside a conditional branch, then the cleanup will
1099 // dominate and we can do the easier (and more efficient) thing.
1100 if (!CGF.isInConditionalBranch()) {
1101 CallDeleteDuringNew *Cleanup = CGF.EHStack
1102 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1103 E->getNumPlacementArgs(),
1104 E->getOperatorDelete(),
1105 NewPtr, AllocSize);
1106 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001107 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001108
1109 return;
1110 }
1111
1112 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001113 DominatingValue<RValue>::saved_type SavedNewPtr =
1114 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1115 DominatingValue<RValue>::saved_type SavedAllocSize =
1116 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001117
1118 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCallf4beacd2011-11-10 10:43:54 +00001119 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall7f9c92a2010-09-17 00:50:28 +00001120 E->getNumPlacementArgs(),
1121 E->getOperatorDelete(),
1122 SavedNewPtr,
1123 SavedAllocSize);
1124 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001125 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001126 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001127
John McCallf4beacd2011-11-10 10:43:54 +00001128 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001129}
1130
Anders Carlssoncc52f652009-09-22 22:53:17 +00001131llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001132 // The element type being allocated.
1133 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001134
John McCall75f94982011-03-07 03:12:35 +00001135 // 1. Build a call to the allocation function.
1136 FunctionDecl *allocator = E->getOperatorNew();
1137 const FunctionProtoType *allocatorType =
1138 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001139
John McCall75f94982011-03-07 03:12:35 +00001140 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001141
1142 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001143 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001144
Sebastian Redlf862eb62012-02-22 17:37:52 +00001145 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1146 unsigned minElements = 0;
1147 if (E->isArray() && E->hasInitializer()) {
1148 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1149 minElements = ILE->getNumInits();
1150 }
1151
John McCall75f94982011-03-07 03:12:35 +00001152 llvm::Value *numElements = 0;
1153 llvm::Value *allocSizeWithoutCookie = 0;
1154 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001155 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1156 allocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001157
Eli Friedman43dca6a2011-05-02 17:57:46 +00001158 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001159
1160 // Emit the rest of the arguments.
1161 // FIXME: Ideally, this should just use EmitCallArgs.
John McCall75f94982011-03-07 03:12:35 +00001162 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001163
1164 // First, use the types from the function type.
1165 // We start at 1 here because the first argument (the allocation size)
1166 // has already been emitted.
John McCall75f94982011-03-07 03:12:35 +00001167 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1168 ++i, ++placementArg) {
1169 QualType argType = allocatorType->getArgType(i);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001170
John McCall75f94982011-03-07 03:12:35 +00001171 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1172 placementArg->getType()) &&
Anders Carlssoncc52f652009-09-22 22:53:17 +00001173 "type mismatch in call argument!");
1174
John McCall32ea9692011-03-11 20:59:21 +00001175 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001176 }
1177
1178 // Either we've emitted all the call args, or we have a call to a
1179 // variadic function.
John McCall75f94982011-03-07 03:12:35 +00001180 assert((placementArg == E->placement_arg_end() ||
1181 allocatorType->isVariadic()) &&
1182 "Extra arguments to non-variadic function!");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001183
1184 // If we still have any arguments, emit them using the type of the argument.
John McCall75f94982011-03-07 03:12:35 +00001185 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1186 placementArg != placementArgsEnd; ++placementArg) {
John McCall32ea9692011-03-11 20:59:21 +00001187 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001188 }
1189
John McCall7ec4b432011-05-16 01:05:12 +00001190 // Emit the allocation call. If the allocator is a global placement
1191 // operator, just "inline" it directly.
1192 RValue RV;
1193 if (allocator->isReservedGlobalPlacementOperator()) {
1194 assert(allocatorArgs.size() == 2);
1195 RV = allocatorArgs[1].RV;
1196 // TODO: kill any unnecessary computations done for the size
1197 // argument.
1198 } else {
John McCalla729c622012-02-17 03:33:10 +00001199 RV = EmitCall(CGM.getTypes().arrangeFunctionCall(allocatorArgs,
1200 allocatorType),
John McCall7ec4b432011-05-16 01:05:12 +00001201 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1202 allocatorArgs, allocator);
1203 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001204
John McCall75f94982011-03-07 03:12:35 +00001205 // Emit a null check on the allocation result if the allocation
1206 // function is allowed to return null (because it has a non-throwing
1207 // exception spec; for this part, we inline
1208 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1209 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001210 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001211 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001212
John McCall75f94982011-03-07 03:12:35 +00001213 llvm::BasicBlock *nullCheckBB = 0;
1214 llvm::BasicBlock *contBB = 0;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001215
John McCall75f94982011-03-07 03:12:35 +00001216 llvm::Value *allocation = RV.getScalarVal();
1217 unsigned AS =
1218 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001219
John McCallf7dcf322011-03-07 01:52:56 +00001220 // The null-check means that the initializer is conditionally
1221 // evaluated.
1222 ConditionalEvaluation conditional(*this);
1223
John McCall75f94982011-03-07 03:12:35 +00001224 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001225 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001226
1227 nullCheckBB = Builder.GetInsertBlock();
1228 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1229 contBB = createBasicBlock("new.cont");
1230
1231 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1232 Builder.CreateCondBr(isNull, contBB, notNullBB);
1233 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001234 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001235
John McCall824c2f52010-09-14 07:57:04 +00001236 // If there's an operator delete, enter a cleanup to call it if an
1237 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001238 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCallf4beacd2011-11-10 10:43:54 +00001239 llvm::Instruction *cleanupDominator = 0;
John McCall7ec4b432011-05-16 01:05:12 +00001240 if (E->getOperatorDelete() &&
1241 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCall75f94982011-03-07 03:12:35 +00001242 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1243 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001244 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001245 }
1246
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001247 assert((allocSize == allocSizeWithoutCookie) ==
1248 CalculateCookiePadding(*this, E).isZero());
1249 if (allocSize != allocSizeWithoutCookie) {
1250 assert(E->isArray());
1251 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1252 numElements,
1253 E, allocType);
1254 }
1255
Chris Lattner2192fe52011-07-18 04:24:23 +00001256 llvm::Type *elementPtrTy
John McCall75f94982011-03-07 03:12:35 +00001257 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1258 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001259
John McCall99210dc2011-09-15 06:49:18 +00001260 EmitNewInitializer(*this, E, allocType, result, numElements,
1261 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001262 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001263 // NewPtr is a pointer to the base element type. If we're
1264 // allocating an array of arrays, we'll need to cast back to the
1265 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001266 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall75f94982011-03-07 03:12:35 +00001267 if (result->getType() != resultType)
1268 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001269 }
John McCall824c2f52010-09-14 07:57:04 +00001270
1271 // Deactivate the 'operator delete' cleanup if we finished
1272 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001273 if (operatorDeleteCleanup.isValid()) {
1274 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1275 cleanupDominator->eraseFromParent();
1276 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001277
John McCall75f94982011-03-07 03:12:35 +00001278 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001279 conditional.end(*this);
1280
John McCall75f94982011-03-07 03:12:35 +00001281 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1282 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001283
Jay Foad20c0f022011-03-30 11:28:58 +00001284 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001285 PHI->addIncoming(result, notNullBB);
1286 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1287 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001288
John McCall75f94982011-03-07 03:12:35 +00001289 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001290 }
John McCall8ed55a52010-09-02 09:58:18 +00001291
John McCall75f94982011-03-07 03:12:35 +00001292 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001293}
1294
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001295void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1296 llvm::Value *Ptr,
1297 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001298 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1299
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001300 const FunctionProtoType *DeleteFTy =
1301 DeleteFD->getType()->getAs<FunctionProtoType>();
1302
1303 CallArgList DeleteArgs;
1304
Anders Carlsson21122cf2009-12-13 20:04:38 +00001305 // Check if we need to pass the size to the delete operator.
1306 llvm::Value *Size = 0;
1307 QualType SizeTy;
1308 if (DeleteFTy->getNumArgs() == 2) {
1309 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001310 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1311 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1312 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001313 }
1314
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001315 QualType ArgTy = DeleteFTy->getArgType(0);
1316 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001317 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001318
Anders Carlsson21122cf2009-12-13 20:04:38 +00001319 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001320 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001321
1322 // Emit the call to delete.
John McCalla729c622012-02-17 03:33:10 +00001323 EmitCall(CGM.getTypes().arrangeFunctionCall(DeleteArgs, DeleteFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001324 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001325 DeleteArgs, DeleteFD);
1326}
1327
John McCall8ed55a52010-09-02 09:58:18 +00001328namespace {
1329 /// Calls the given 'operator delete' on a single object.
1330 struct CallObjectDelete : EHScopeStack::Cleanup {
1331 llvm::Value *Ptr;
1332 const FunctionDecl *OperatorDelete;
1333 QualType ElementType;
1334
1335 CallObjectDelete(llvm::Value *Ptr,
1336 const FunctionDecl *OperatorDelete,
1337 QualType ElementType)
1338 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1339
John McCall30317fd2011-07-12 20:27:29 +00001340 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001341 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1342 }
1343 };
1344}
1345
1346/// Emit the code for deleting a single object.
1347static void EmitObjectDelete(CodeGenFunction &CGF,
1348 const FunctionDecl *OperatorDelete,
1349 llvm::Value *Ptr,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001350 QualType ElementType,
1351 bool UseGlobalDelete) {
John McCall8ed55a52010-09-02 09:58:18 +00001352 // Find the destructor for the type, if applicable. If the
1353 // destructor is virtual, we'll just emit the vcall and return.
1354 const CXXDestructorDecl *Dtor = 0;
1355 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1356 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001357 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001358 Dtor = RD->getDestructor();
1359
1360 if (Dtor->isVirtual()) {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001361 if (UseGlobalDelete) {
1362 // If we're supposed to call the global delete, make sure we do so
1363 // even if the destructor throws.
1364 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1365 Ptr, OperatorDelete,
1366 ElementType);
1367 }
1368
Chris Lattner2192fe52011-07-18 04:24:23 +00001369 llvm::Type *Ty =
John McCalla729c622012-02-17 03:33:10 +00001370 CGF.getTypes().GetFunctionType(
1371 CGF.getTypes().arrangeCXXDestructor(Dtor, Dtor_Complete));
John McCall8ed55a52010-09-02 09:58:18 +00001372
1373 llvm::Value *Callee
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001374 = CGF.BuildVirtualCall(Dtor,
1375 UseGlobalDelete? Dtor_Complete : Dtor_Deleting,
1376 Ptr, Ty);
John McCall8ed55a52010-09-02 09:58:18 +00001377 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1378 0, 0);
1379
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001380 if (UseGlobalDelete) {
1381 CGF.PopCleanupBlock();
1382 }
1383
John McCall8ed55a52010-09-02 09:58:18 +00001384 return;
1385 }
1386 }
1387 }
1388
1389 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001390 // This doesn't have to a conditional cleanup because we're going
1391 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001392 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1393 Ptr, OperatorDelete, ElementType);
1394
1395 if (Dtor)
1396 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1397 /*ForVirtualBase=*/false, Ptr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001398 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001399 ElementType->isObjCLifetimeType()) {
1400 switch (ElementType.getObjCLifetime()) {
1401 case Qualifiers::OCL_None:
1402 case Qualifiers::OCL_ExplicitNone:
1403 case Qualifiers::OCL_Autoreleasing:
1404 break;
John McCall8ed55a52010-09-02 09:58:18 +00001405
John McCall31168b02011-06-15 23:02:42 +00001406 case Qualifiers::OCL_Strong: {
1407 // Load the pointer value.
1408 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1409 ElementType.isVolatileQualified());
1410
1411 CGF.EmitARCRelease(PtrValue, /*precise*/ true);
1412 break;
1413 }
1414
1415 case Qualifiers::OCL_Weak:
1416 CGF.EmitARCDestroyWeak(Ptr);
1417 break;
1418 }
1419 }
1420
John McCall8ed55a52010-09-02 09:58:18 +00001421 CGF.PopCleanupBlock();
1422}
1423
1424namespace {
1425 /// Calls the given 'operator delete' on an array of objects.
1426 struct CallArrayDelete : EHScopeStack::Cleanup {
1427 llvm::Value *Ptr;
1428 const FunctionDecl *OperatorDelete;
1429 llvm::Value *NumElements;
1430 QualType ElementType;
1431 CharUnits CookieSize;
1432
1433 CallArrayDelete(llvm::Value *Ptr,
1434 const FunctionDecl *OperatorDelete,
1435 llvm::Value *NumElements,
1436 QualType ElementType,
1437 CharUnits CookieSize)
1438 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1439 ElementType(ElementType), CookieSize(CookieSize) {}
1440
John McCall30317fd2011-07-12 20:27:29 +00001441 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001442 const FunctionProtoType *DeleteFTy =
1443 OperatorDelete->getType()->getAs<FunctionProtoType>();
1444 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1445
1446 CallArgList Args;
1447
1448 // Pass the pointer as the first argument.
1449 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1450 llvm::Value *DeletePtr
1451 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001452 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001453
1454 // Pass the original requested size as the second argument.
1455 if (DeleteFTy->getNumArgs() == 2) {
1456 QualType size_t = DeleteFTy->getArgType(1);
Chris Lattner2192fe52011-07-18 04:24:23 +00001457 llvm::IntegerType *SizeTy
John McCall8ed55a52010-09-02 09:58:18 +00001458 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1459
1460 CharUnits ElementTypeSize =
1461 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1462
1463 // The size of an element, multiplied by the number of elements.
1464 llvm::Value *Size
1465 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1466 Size = CGF.Builder.CreateMul(Size, NumElements);
1467
1468 // Plus the size of the cookie if applicable.
1469 if (!CookieSize.isZero()) {
1470 llvm::Value *CookieSizeV
1471 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1472 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1473 }
1474
Eli Friedman43dca6a2011-05-02 17:57:46 +00001475 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001476 }
1477
1478 // Emit the call to delete.
John McCalla729c622012-02-17 03:33:10 +00001479 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(Args, DeleteFTy),
John McCall8ed55a52010-09-02 09:58:18 +00001480 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1481 ReturnValueSlot(), Args, OperatorDelete);
1482 }
1483 };
1484}
1485
1486/// Emit the code for deleting an array of objects.
1487static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001488 const CXXDeleteExpr *E,
John McCallca2c56f2011-07-13 01:41:37 +00001489 llvm::Value *deletedPtr,
1490 QualType elementType) {
1491 llvm::Value *numElements = 0;
1492 llvm::Value *allocatedPtr = 0;
1493 CharUnits cookieSize;
1494 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1495 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001496
John McCallca2c56f2011-07-13 01:41:37 +00001497 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001498
1499 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001500 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001501 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001502 allocatedPtr, operatorDelete,
1503 numElements, elementType,
1504 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001505
John McCallca2c56f2011-07-13 01:41:37 +00001506 // Destroy the elements.
1507 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1508 assert(numElements && "no element count for a type with a destructor!");
1509
John McCallca2c56f2011-07-13 01:41:37 +00001510 llvm::Value *arrayEnd =
1511 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001512
1513 // Note that it is legal to allocate a zero-length array, and we
1514 // can never fold the check away because the length should always
1515 // come from a cookie.
John McCallca2c56f2011-07-13 01:41:37 +00001516 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1517 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001518 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001519 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001520 }
1521
John McCallca2c56f2011-07-13 01:41:37 +00001522 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001523 CGF.PopCleanupBlock();
1524}
1525
Anders Carlssoncc52f652009-09-22 22:53:17 +00001526void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +00001527
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001528 // Get at the argument before we performed the implicit conversion
1529 // to void*.
1530 const Expr *Arg = E->getArgument();
1531 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00001532 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001533 ICE->getType()->isVoidPointerType())
1534 Arg = ICE->getSubExpr();
Douglas Gregore364e7b2009-10-01 05:49:51 +00001535 else
1536 break;
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001537 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001538
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001539 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001540
1541 // Null check the pointer.
1542 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1543 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1544
Anders Carlsson98981b12011-04-11 00:30:07 +00001545 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001546
1547 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1548 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001549
John McCall8ed55a52010-09-02 09:58:18 +00001550 // We might be deleting a pointer to array. If so, GEP down to the
1551 // first non-array element.
1552 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1553 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1554 if (DeleteTy->isConstantArrayType()) {
1555 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001556 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001557
1558 GEP.push_back(Zero); // point at the outermost array
1559
1560 // For each layer of array type we're pointing at:
1561 while (const ConstantArrayType *Arr
1562 = getContext().getAsConstantArrayType(DeleteTy)) {
1563 // 1. Unpeel the array type.
1564 DeleteTy = Arr->getElementType();
1565
1566 // 2. GEP to the first element of the array.
1567 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001568 }
John McCall8ed55a52010-09-02 09:58:18 +00001569
Jay Foad040dd822011-07-22 08:16:57 +00001570 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001571 }
1572
Douglas Gregor04f36212010-09-02 17:38:50 +00001573 assert(ConvertTypeForMem(DeleteTy) ==
1574 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001575
1576 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001577 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001578 } else {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001579 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1580 E->isGlobalDelete());
John McCall8ed55a52010-09-02 09:58:18 +00001581 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001582
Anders Carlssoncc52f652009-09-22 22:53:17 +00001583 EmitBlock(DeleteEnd);
1584}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001585
Anders Carlsson0c633502011-04-11 14:13:40 +00001586static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1587 // void __cxa_bad_typeid();
Chris Lattnerece04092012-02-07 00:39:47 +00001588 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson0c633502011-04-11 14:13:40 +00001589
1590 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1591}
1592
1593static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001594 llvm::Value *Fn = getBadTypeidFn(CGF);
Jay Foad5bd375a2011-07-15 08:37:34 +00001595 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson0c633502011-04-11 14:13:40 +00001596 CGF.Builder.CreateUnreachable();
1597}
1598
Anders Carlsson940f02d2011-04-18 00:57:03 +00001599static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1600 const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001601 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001602 // Get the vtable pointer.
1603 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1604
1605 // C++ [expr.typeid]p2:
1606 // If the glvalue expression is obtained by applying the unary * operator to
1607 // a pointer and the pointer is a null pointer value, the typeid expression
1608 // throws the std::bad_typeid exception.
1609 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1610 if (UO->getOpcode() == UO_Deref) {
1611 llvm::BasicBlock *BadTypeidBlock =
1612 CGF.createBasicBlock("typeid.bad_typeid");
1613 llvm::BasicBlock *EndBlock =
1614 CGF.createBasicBlock("typeid.end");
1615
1616 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1617 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1618
1619 CGF.EmitBlock(BadTypeidBlock);
1620 EmitBadTypeidCall(CGF);
1621 CGF.EmitBlock(EndBlock);
1622 }
1623 }
1624
1625 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1626 StdTypeInfoPtrTy->getPointerTo());
1627
1628 // Load the type info.
1629 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1630 return CGF.Builder.CreateLoad(Value);
1631}
1632
John McCalle4df6c82011-01-28 08:37:24 +00001633llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001634 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001635 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001636
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001637 if (E->isTypeOperand()) {
1638 llvm::Constant *TypeInfo =
1639 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson940f02d2011-04-18 00:57:03 +00001640 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001641 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001642
Anders Carlsson940f02d2011-04-18 00:57:03 +00001643 // C++ [expr.typeid]p2:
1644 // When typeid is applied to a glvalue expression whose type is a
1645 // polymorphic class type, the result refers to a std::type_info object
1646 // representing the type of the most derived object (that is, the dynamic
1647 // type) to which the glvalue refers.
1648 if (E->getExprOperand()->isGLValue()) {
1649 if (const RecordType *RT =
1650 E->getExprOperand()->getType()->getAs<RecordType>()) {
1651 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1652 if (RD->isPolymorphic())
1653 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1654 StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001655 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001656 }
Anders Carlsson940f02d2011-04-18 00:57:03 +00001657
1658 QualType OperandTy = E->getExprOperand()->getType();
1659 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1660 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001661}
Mike Stump65511702009-11-16 06:50:58 +00001662
Anders Carlsson882d7902011-04-11 00:46:40 +00001663static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1664 // void *__dynamic_cast(const void *sub,
1665 // const abi::__class_type_info *src,
1666 // const abi::__class_type_info *dst,
1667 // std::ptrdiff_t src2dst_offset);
1668
Chris Lattnerece04092012-02-07 00:39:47 +00001669 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001670 llvm::Type *PtrDiffTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001671 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1672
Chris Lattnera5f58b02011-07-09 17:41:47 +00001673 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Anders Carlsson882d7902011-04-11 00:46:40 +00001674
Chris Lattner2192fe52011-07-18 04:24:23 +00001675 llvm::FunctionType *FTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001676 llvm::FunctionType::get(Int8PtrTy, Args, false);
1677
1678 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1679}
1680
1681static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1682 // void __cxa_bad_cast();
Chris Lattnerece04092012-02-07 00:39:47 +00001683 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson882d7902011-04-11 00:46:40 +00001684 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1685}
1686
Anders Carlssonc1c99712011-04-11 01:45:29 +00001687static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001688 llvm::Value *Fn = getBadCastFn(CGF);
Jay Foad5bd375a2011-07-15 08:37:34 +00001689 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlssonc1c99712011-04-11 01:45:29 +00001690 CGF.Builder.CreateUnreachable();
1691}
1692
Anders Carlsson882d7902011-04-11 00:46:40 +00001693static llvm::Value *
1694EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1695 QualType SrcTy, QualType DestTy,
1696 llvm::BasicBlock *CastEnd) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001697 llvm::Type *PtrDiffLTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001698 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2192fe52011-07-18 04:24:23 +00001699 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson882d7902011-04-11 00:46:40 +00001700
1701 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1702 if (PTy->getPointeeType()->isVoidType()) {
1703 // C++ [expr.dynamic.cast]p7:
1704 // If T is "pointer to cv void," then the result is a pointer to the
1705 // most derived object pointed to by v.
1706
1707 // Get the vtable pointer.
1708 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1709
1710 // Get the offset-to-top from the vtable.
1711 llvm::Value *OffsetToTop =
1712 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1713 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1714
1715 // Finally, add the offset to the pointer.
1716 Value = CGF.EmitCastToVoidPtr(Value);
1717 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1718
1719 return CGF.Builder.CreateBitCast(Value, DestLTy);
1720 }
1721 }
1722
1723 QualType SrcRecordTy;
1724 QualType DestRecordTy;
1725
1726 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1727 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1728 DestRecordTy = DestPTy->getPointeeType();
1729 } else {
1730 SrcRecordTy = SrcTy;
1731 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1732 }
1733
1734 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1735 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1736
1737 llvm::Value *SrcRTTI =
1738 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1739 llvm::Value *DestRTTI =
1740 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1741
1742 // FIXME: Actually compute a hint here.
1743 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1744
1745 // Emit the call to __dynamic_cast.
1746 Value = CGF.EmitCastToVoidPtr(Value);
1747 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1748 SrcRTTI, DestRTTI, OffsetHint);
1749 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1750
1751 /// C++ [expr.dynamic.cast]p9:
1752 /// A failed cast to reference type throws std::bad_cast
1753 if (DestTy->isReferenceType()) {
1754 llvm::BasicBlock *BadCastBlock =
1755 CGF.createBasicBlock("dynamic_cast.bad_cast");
1756
1757 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1758 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1759
1760 CGF.EmitBlock(BadCastBlock);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001761 EmitBadCastCall(CGF);
Anders Carlsson882d7902011-04-11 00:46:40 +00001762 }
1763
1764 return Value;
1765}
1766
Anders Carlssonc1c99712011-04-11 01:45:29 +00001767static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1768 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001769 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001770 if (DestTy->isPointerType())
1771 return llvm::Constant::getNullValue(DestLTy);
1772
1773 /// C++ [expr.dynamic.cast]p9:
1774 /// A failed cast to reference type throws std::bad_cast
1775 EmitBadCastCall(CGF);
1776
1777 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1778 return llvm::UndefValue::get(DestLTy);
1779}
1780
Anders Carlsson882d7902011-04-11 00:46:40 +00001781llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001782 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001783 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001784
Anders Carlssonc1c99712011-04-11 01:45:29 +00001785 if (DCE->isAlwaysNull())
1786 return EmitDynamicCastToNull(*this, DestTy);
1787
1788 QualType SrcTy = DCE->getSubExpr()->getType();
1789
Anders Carlsson882d7902011-04-11 00:46:40 +00001790 // C++ [expr.dynamic.cast]p4:
1791 // If the value of v is a null pointer value in the pointer case, the result
1792 // is the null pointer value of type T.
1793 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001794
Anders Carlsson882d7902011-04-11 00:46:40 +00001795 llvm::BasicBlock *CastNull = 0;
1796 llvm::BasicBlock *CastNotNull = 0;
1797 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001798
Anders Carlsson882d7902011-04-11 00:46:40 +00001799 if (ShouldNullCheckSrcValue) {
1800 CastNull = createBasicBlock("dynamic_cast.null");
1801 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1802
1803 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1804 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1805 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001806 }
1807
Anders Carlsson882d7902011-04-11 00:46:40 +00001808 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1809
1810 if (ShouldNullCheckSrcValue) {
1811 EmitBranch(CastEnd);
1812
1813 EmitBlock(CastNull);
1814 EmitBranch(CastEnd);
1815 }
1816
1817 EmitBlock(CastEnd);
1818
1819 if (ShouldNullCheckSrcValue) {
1820 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1821 PHI->addIncoming(Value, CastNotNull);
1822 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1823
1824 Value = PHI;
1825 }
1826
1827 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001828}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001829
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001830void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00001831 RunCleanupsScope Scope(*this);
Eli Friedman7f1ff602012-04-16 03:54:45 +00001832 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1833 Slot.getAlignment());
Eli Friedman8631f3e82012-02-09 03:47:20 +00001834
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001835 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1836 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1837 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00001838 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001839 // Emit initialization
Eli Friedman7f1ff602012-04-16 03:54:45 +00001840
David Blaikie40ed2972012-06-06 20:45:41 +00001841 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Eli Friedman5f1a04f2012-02-14 02:31:03 +00001842 ArrayRef<VarDecl *> ArrayIndexes;
1843 if (CurField->getType()->isArrayType())
1844 ArrayIndexes = E->getCaptureInitIndexVars(i);
David Blaikie40ed2972012-06-06 20:45:41 +00001845 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001846 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001847}