blob: 79ebe515b0e79dfe40e60cbe854743b12214cb4c [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlsson16d81b82009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
Devang Patelc69e1cf2010-09-30 19:05:55 +000014#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson16d81b82009-09-22 22:53:17 +000015#include "CodeGenFunction.h"
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000016#include "CGCUDARuntime.h"
John McCall4c40d982010-08-31 07:33:07 +000017#include "CGCXXABI.h"
Fariborz Jahanian842ddd02010-05-20 21:38:57 +000018#include "CGObjCRuntime.h"
Devang Patelc69e1cf2010-09-30 19:05:55 +000019#include "CGDebugInfo.h"
Chris Lattner6c552c12010-07-20 20:19:24 +000020#include "llvm/Intrinsics.h"
Anders Carlssonad3692bb2011-04-13 02:35:36 +000021#include "llvm/Support/CallSite.h"
22
Anders Carlsson16d81b82009-09-22 22:53:17 +000023using namespace clang;
24using namespace CodeGen;
25
Anders Carlsson3b5ad222010-01-01 20:29:01 +000026RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
27 llvm::Value *Callee,
28 ReturnValueSlot ReturnValue,
29 llvm::Value *This,
Anders Carlssonc997d422010-01-02 01:01:18 +000030 llvm::Value *VTT,
Anders Carlsson3b5ad222010-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 Carlsson3b5ad222010-01-01 20:29:01 +000036 CallArgList Args;
37
38 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +000039 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000040
Anders Carlssonc997d422010-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 Friedman04c9a492011-05-02 17:57:46 +000044 Args.add(RValue::get(VTT), T);
Anders Carlssonc997d422010-01-02 01:01:18 +000045 }
John McCallde5d3c72012-02-17 03:33:10 +000046
47 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
48 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Anders Carlssonc997d422010-01-02 01:01:18 +000049
John McCallde5d3c72012-02-17 03:33:10 +000050 // And the rest of the call args.
Anders Carlsson3b5ad222010-01-01 20:29:01 +000051 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
52
John McCall0f3d0972012-07-07 06:41:13 +000053 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
Rafael Espindola264ba482010-03-30 20:24:48 +000054 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000055}
56
Anders Carlssoncd0b32e2011-04-10 18:20:53 +000057// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
58// quite what we want.
59static const Expr *skipNoOpCastsAndParens(const Expr *E) {
60 while (true) {
61 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
62 E = PE->getSubExpr();
63 continue;
64 }
65
66 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
67 if (CE->getCastKind() == CK_NoOp) {
68 E = CE->getSubExpr();
69 continue;
70 }
71 }
72 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
73 if (UO->getOpcode() == UO_Extension) {
74 E = UO->getSubExpr();
75 continue;
76 }
77 }
78 return E;
79 }
80}
81
Anders Carlsson3b5ad222010-01-01 20:29:01 +000082/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
83/// expr can be devirtualized.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +000084static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
85 const Expr *Base,
Anders Carlssonbd2bfae2010-10-27 13:28:46 +000086 const CXXMethodDecl *MD) {
87
Anders Carlsson1679f5a2011-01-29 03:52:01 +000088 // When building with -fapple-kext, all calls must go through the vtable since
89 // the kernel linker can do runtime patching of vtables.
David Blaikie4e4d0842012-03-11 07:00:24 +000090 if (Context.getLangOpts().AppleKext)
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +000091 return false;
92
Anders Carlsson1679f5a2011-01-29 03:52:01 +000093 // If the most derived class is marked final, we know that no subclass can
94 // override this member function and so we can devirtualize it. For example:
95 //
96 // struct A { virtual void f(); }
97 // struct B final : A { };
98 //
99 // void f(B *b) {
100 // b->f();
101 // }
102 //
Rafael Espindola8d852e32012-06-27 18:18:05 +0000103 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000104 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
105 return true;
106
Anders Carlssonf89e0422011-01-23 21:07:30 +0000107 // If the member function is marked 'final', we know that it can't be
Anders Carlssond66f4282010-10-27 13:34:43 +0000108 // overridden and can therefore devirtualize it.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000109 if (MD->hasAttr<FinalAttr>())
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000110 return true;
Anders Carlssond66f4282010-10-27 13:34:43 +0000111
Anders Carlssonf89e0422011-01-23 21:07:30 +0000112 // Similarly, if the class itself is marked 'final' it can't be overridden
113 // and we can therefore devirtualize the member function call.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000114 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssond66f4282010-10-27 13:34:43 +0000115 return true;
116
Anders Carlssoncd0b32e2011-04-10 18:20:53 +0000117 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000118 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
119 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
120 // This is a record decl. We know the type and can devirtualize it.
121 return VD->getType()->isRecordType();
122 }
123
124 return false;
125 }
126
127 // We can always devirtualize calls on temporary object expressions.
Eli Friedman6997aae2010-01-31 20:58:15 +0000128 if (isa<CXXConstructExpr>(Base))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000129 return true;
130
131 // And calls on bound temporaries.
132 if (isa<CXXBindTemporaryExpr>(Base))
133 return true;
134
135 // Check if this is a call expr that returns a record type.
136 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
137 return CE->getCallReturnType()->isRecordType();
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000138
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000139 // We can't devirtualize the call.
140 return false;
141}
142
Rafael Espindolaea01d762012-06-28 14:28:57 +0000143static CXXRecordDecl *getCXXRecord(const Expr *E) {
144 QualType T = E->getType();
145 if (const PointerType *PTy = T->getAs<PointerType>())
146 T = PTy->getPointeeType();
147 const RecordType *Ty = T->castAs<RecordType>();
148 return cast<CXXRecordDecl>(Ty->getDecl());
149}
150
Francois Pichetdbee3412011-01-18 05:04:39 +0000151// Note: This function also emit constructor calls to support a MSVC
152// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000153RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
154 ReturnValueSlot ReturnValue) {
John McCall379b5152011-04-11 07:02:50 +0000155 const Expr *callee = CE->getCallee()->IgnoreParens();
156
157 if (isa<BinaryOperator>(callee))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000158 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall379b5152011-04-11 07:02:50 +0000159
160 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000161 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
162
Devang Patelc69e1cf2010-09-30 19:05:55 +0000163 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000164 if (DI && CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo
Devang Patel68020272010-10-22 18:56:27 +0000165 && !isa<CallExpr>(ME->getBase())) {
Devang Patelc69e1cf2010-09-30 19:05:55 +0000166 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
167 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
168 DI->getOrCreateRecordType(PTy->getPointeeType(),
169 MD->getParent()->getLocation());
170 }
171 }
172
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000173 if (MD->isStatic()) {
174 // The method is static, emit it as we would a regular call.
175 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
176 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
177 ReturnValue, CE->arg_begin(), CE->arg_end());
178 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000179
John McCallfc400282010-09-03 01:26:39 +0000180 // Compute the object pointer.
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000181 const Expr *Base = ME->getBase();
182 bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000183
Rafael Espindolaea01d762012-06-28 14:28:57 +0000184 const CXXMethodDecl *DevirtualizedMethod = NULL;
185 if (CanUseVirtualCall &&
186 canDevirtualizeMemberFunctionCalls(getContext(), Base, MD)) {
187 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
188 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
189 assert(DevirtualizedMethod);
190 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
191 const Expr *Inner = Base->ignoreParenBaseCasts();
192 if (getCXXRecord(Inner) == DevirtualizedClass)
193 // If the class of the Inner expression is where the dynamic method
194 // is defined, build the this pointer from it.
195 Base = Inner;
196 else if (getCXXRecord(Base) != DevirtualizedClass) {
197 // If the method is defined in a class that is not the best dynamic
198 // one or the one of the full expression, we would have to build
199 // a derived-to-base cast to compute the correct this pointer, but
200 // we don't have support for that yet, so do a virtual call.
201 DevirtualizedMethod = NULL;
202 }
Rafael Espindola80bc96e2012-06-28 17:57:36 +0000203 // If the return types are not the same, this might be a case where more
204 // code needs to run to compensate for it. For example, the derived
205 // method might return a type that inherits form from the return
206 // type of MD and has a prefix.
207 // For now we just avoid devirtualizing these covariant cases.
208 if (DevirtualizedMethod &&
209 DevirtualizedMethod->getResultType().getCanonicalType() !=
210 MD->getResultType().getCanonicalType())
Rafael Espindola4a889e42012-06-28 15:11:39 +0000211 DevirtualizedMethod = NULL;
Rafael Espindolaea01d762012-06-28 14:28:57 +0000212 }
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000213
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000214 llvm::Value *This;
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000215 if (ME->isArrow())
Rafael Espindolaea01d762012-06-28 14:28:57 +0000216 This = EmitScalarExpr(Base);
John McCall0e800c92010-12-04 08:14:53 +0000217 else
Rafael Espindolaea01d762012-06-28 14:28:57 +0000218 This = EmitLValue(Base).getAddress();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000219
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000220
John McCallfc400282010-09-03 01:26:39 +0000221 if (MD->isTrivial()) {
222 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichetdbee3412011-01-18 05:04:39 +0000223 if (isa<CXXConstructorDecl>(MD) &&
224 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
225 return RValue::get(0);
John McCallfc400282010-09-03 01:26:39 +0000226
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000227 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
228 // We don't like to generate the trivial copy/move assignment operator
229 // when it isn't necessary; just produce the proper effect here.
Francois Pichetdbee3412011-01-18 05:04:39 +0000230 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
231 EmitAggregateCopy(This, RHS, CE->getType());
232 return RValue::get(This);
233 }
234
235 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000236 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
237 // Trivial move and copy ctor are the same.
Francois Pichetdbee3412011-01-18 05:04:39 +0000238 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
239 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
240 CE->arg_begin(), CE->arg_end());
241 return RValue::get(This);
242 }
243 llvm_unreachable("unknown trivial member function");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000244 }
245
John McCallfc400282010-09-03 01:26:39 +0000246 // Compute the function type we're calling.
Francois Pichetdbee3412011-01-18 05:04:39 +0000247 const CGFunctionInfo *FInfo = 0;
248 if (isa<CXXDestructorDecl>(MD))
John McCallde5d3c72012-02-17 03:33:10 +0000249 FInfo = &CGM.getTypes().arrangeCXXDestructor(cast<CXXDestructorDecl>(MD),
250 Dtor_Complete);
Francois Pichetdbee3412011-01-18 05:04:39 +0000251 else if (isa<CXXConstructorDecl>(MD))
John McCallde5d3c72012-02-17 03:33:10 +0000252 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(
253 cast<CXXConstructorDecl>(MD),
254 Ctor_Complete);
Francois Pichetdbee3412011-01-18 05:04:39 +0000255 else
John McCallde5d3c72012-02-17 03:33:10 +0000256 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(MD);
John McCallfc400282010-09-03 01:26:39 +0000257
John McCallde5d3c72012-02-17 03:33:10 +0000258 llvm::Type *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCallfc400282010-09-03 01:26:39 +0000259
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000260 // C++ [class.virtual]p12:
261 // Explicit qualification with the scope operator (5.1) suppresses the
262 // virtual call mechanism.
263 //
264 // We also don't emit a virtual call if the base expression has a record type
265 // because then we know what the type is.
Rafael Espindolaea01d762012-06-28 14:28:57 +0000266 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000267
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000268 llvm::Value *Callee;
John McCallfc400282010-09-03 01:26:39 +0000269 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
270 if (UseVirtualCall) {
271 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000272 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +0000273 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000274 MD->isVirtual() &&
275 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000276 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000277 else if (!DevirtualizedMethod)
Rafael Espindola12582bd2012-06-26 19:18:25 +0000278 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000279 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000280 const CXXDestructorDecl *DDtor =
281 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000282 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
283 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000284 }
Francois Pichetdbee3412011-01-18 05:04:39 +0000285 } else if (const CXXConstructorDecl *Ctor =
286 dyn_cast<CXXConstructorDecl>(MD)) {
287 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000288 } else if (UseVirtualCall) {
Fariborz Jahanian27262672011-01-20 17:19:02 +0000289 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000290 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +0000291 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000292 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000293 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000294 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000295 else if (!DevirtualizedMethod)
Rafael Espindola12582bd2012-06-26 19:18:25 +0000296 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000297 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000298 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000299 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000300 }
301
Anders Carlssonc997d422010-01-02 01:01:18 +0000302 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000303 CE->arg_begin(), CE->arg_end());
304}
305
306RValue
307CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
308 ReturnValueSlot ReturnValue) {
309 const BinaryOperator *BO =
310 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
311 const Expr *BaseExpr = BO->getLHS();
312 const Expr *MemFnExpr = BO->getRHS();
313
314 const MemberPointerType *MPT =
John McCall864c0412011-04-26 20:42:42 +0000315 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000316
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000317 const FunctionProtoType *FPT =
John McCall864c0412011-04-26 20:42:42 +0000318 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000319 const CXXRecordDecl *RD =
320 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
321
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000322 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000323 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000324
325 // Emit the 'this' pointer.
326 llvm::Value *This;
327
John McCall2de56d12010-08-25 11:45:40 +0000328 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000329 This = EmitScalarExpr(BaseExpr);
330 else
331 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000332
John McCall93d557b2010-08-22 00:05:51 +0000333 // Ask the ABI to load the callee. Note that This is modified.
334 llvm::Value *Callee =
John McCalld16c2cf2011-02-08 08:22:06 +0000335 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000336
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000337 CallArgList Args;
338
339 QualType ThisType =
340 getContext().getPointerType(getContext().getTagDeclType(RD));
341
342 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +0000343 Args.add(RValue::get(This), ThisType);
John McCall0f3d0972012-07-07 06:41:13 +0000344
345 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000346
347 // And the rest of the call args
348 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall0f3d0972012-07-07 06:41:13 +0000349 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required), Callee,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000350 ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000351}
352
353RValue
354CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
355 const CXXMethodDecl *MD,
356 ReturnValueSlot ReturnValue) {
357 assert(MD->isInstance() &&
358 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000359 LValue LV = EmitLValue(E->getArg(0));
360 llvm::Value *This = LV.getAddress();
361
Douglas Gregorb2b56582011-09-06 16:26:56 +0000362 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
363 MD->isTrivial()) {
364 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
365 QualType Ty = E->getType();
366 EmitAggregateCopy(This, Src, Ty);
367 return RValue::get(This);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000368 }
369
Anders Carlssona2447e02011-05-08 20:32:23 +0000370 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Anders Carlssonc997d422010-01-02 01:01:18 +0000371 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000372 E->arg_begin() + 1, E->arg_end());
373}
374
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000375RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
376 ReturnValueSlot ReturnValue) {
377 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
378}
379
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000380static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
381 llvm::Value *DestPtr,
382 const CXXRecordDecl *Base) {
383 if (Base->isEmpty())
384 return;
385
386 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
387
388 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
389 CharUnits Size = Layout.getNonVirtualSize();
390 CharUnits Align = Layout.getNonVirtualAlign();
391
392 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
393
394 // If the type contains a pointer to data member we can't memset it to zero.
395 // Instead, create a null constant and copy it to the destination.
396 // TODO: there are other patterns besides zero that we can usefully memset,
397 // like -1, which happens to be the pattern used by member-pointers.
398 // TODO: isZeroInitializable can be over-conservative in the case where a
399 // virtual base contains a member pointer.
400 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
401 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
402
403 llvm::GlobalVariable *NullVariable =
404 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
405 /*isConstant=*/true,
406 llvm::GlobalVariable::PrivateLinkage,
407 NullConstant, Twine());
408 NullVariable->setAlignment(Align.getQuantity());
409 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
410
411 // Get and call the appropriate llvm.memcpy overload.
412 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
413 return;
414 }
415
416 // Otherwise, just memset the whole thing to zero. This is legal
417 // because in LLVM, all default initializers (other than the ones we just
418 // handled above) are guaranteed to have a bit pattern of all zeros.
419 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
420 Align.getQuantity());
421}
422
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000423void
John McCall558d2ab2010-09-15 10:14:12 +0000424CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
425 AggValueSlot Dest) {
426 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000427 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000428
429 // If we require zero initialization before (or instead of) calling the
430 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +0000431 // constructor, emit the zero initialization now, unless destination is
432 // already zeroed.
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000433 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
434 switch (E->getConstructionKind()) {
435 case CXXConstructExpr::CK_Delegating:
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000436 case CXXConstructExpr::CK_Complete:
437 EmitNullInitialization(Dest.getAddr(), E->getType());
438 break;
439 case CXXConstructExpr::CK_VirtualBase:
440 case CXXConstructExpr::CK_NonVirtualBase:
441 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
442 break;
443 }
444 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000445
446 // If this is a call to a trivial default constructor, do nothing.
447 if (CD->isTrivial() && CD->isDefaultConstructor())
448 return;
449
John McCallfc1e6c72010-09-18 00:58:34 +0000450 // Elide the constructor if we're constructing from a temporary.
451 // The temporary check is required because Sema sets this on NRVO
452 // returns.
David Blaikie4e4d0842012-03-11 07:00:24 +0000453 if (getContext().getLangOpts().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000454 assert(getContext().hasSameUnqualifiedType(E->getType(),
455 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000456 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
457 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000458 return;
459 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000460 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000461
John McCallc3c07662011-07-13 06:10:41 +0000462 if (const ConstantArrayType *arrayType
463 = getContext().getAsConstantArrayType(E->getType())) {
464 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000465 E->arg_begin(), E->arg_end());
John McCallc3c07662011-07-13 06:10:41 +0000466 } else {
Cameron Esfahani6bd2f6a2011-05-06 21:28:42 +0000467 CXXCtorType Type = Ctor_Complete;
Sean Huntd49bd552011-05-03 20:19:28 +0000468 bool ForVirtualBase = false;
469
470 switch (E->getConstructionKind()) {
471 case CXXConstructExpr::CK_Delegating:
Sean Hunt059ce0d2011-05-01 07:04:31 +0000472 // We should be emitting a constructor; GlobalDecl will assert this
473 Type = CurGD.getCtorType();
Sean Huntd49bd552011-05-03 20:19:28 +0000474 break;
Sean Hunt059ce0d2011-05-01 07:04:31 +0000475
Sean Huntd49bd552011-05-03 20:19:28 +0000476 case CXXConstructExpr::CK_Complete:
477 Type = Ctor_Complete;
478 break;
479
480 case CXXConstructExpr::CK_VirtualBase:
481 ForVirtualBase = true;
482 // fall-through
483
484 case CXXConstructExpr::CK_NonVirtualBase:
485 Type = Ctor_Base;
486 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000487
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000488 // Call the constructor.
John McCall558d2ab2010-09-15 10:14:12 +0000489 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000490 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000491 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000492}
493
Fariborz Jahanian34999872010-11-13 21:53:34 +0000494void
495CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
496 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000497 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000498 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000499 Exp = E->getSubExpr();
500 assert(isa<CXXConstructExpr>(Exp) &&
501 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
502 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
503 const CXXConstructorDecl *CD = E->getConstructor();
504 RunCleanupsScope Scope(*this);
505
506 // If we require zero initialization before (or instead of) calling the
507 // constructor, as can be the case with a non-user-provided default
508 // constructor, emit the zero initialization now.
509 // FIXME. Do I still need this for a copy ctor synthesis?
510 if (E->requiresZeroInitialization())
511 EmitNullInitialization(Dest, E->getType());
512
Chandler Carruth858a5462010-11-15 13:54:43 +0000513 assert(!getContext().getAsConstantArrayType(E->getType())
514 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000515 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
516 E->arg_begin(), E->arg_end());
517}
518
John McCall1e7fe752010-09-02 09:58:18 +0000519static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
520 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000521 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000522 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000523
John McCallb1c98a32011-05-16 01:05:12 +0000524 // No cookie is required if the operator new[] being used is the
525 // reserved placement operator new[].
526 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCall5172ed92010-08-23 01:17:59 +0000527 return CharUnits::Zero();
528
John McCall6ec278d2011-01-27 09:37:56 +0000529 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000530}
531
John McCall7d166272011-05-15 07:14:44 +0000532static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
533 const CXXNewExpr *e,
Sebastian Redl92036472012-02-22 17:37:52 +0000534 unsigned minElements,
John McCall7d166272011-05-15 07:14:44 +0000535 llvm::Value *&numElements,
536 llvm::Value *&sizeWithoutCookie) {
537 QualType type = e->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000538
John McCall7d166272011-05-15 07:14:44 +0000539 if (!e->isArray()) {
540 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
541 sizeWithoutCookie
542 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
543 return sizeWithoutCookie;
Douglas Gregor59174c02010-07-21 01:10:17 +0000544 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000545
John McCall7d166272011-05-15 07:14:44 +0000546 // The width of size_t.
547 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
548
John McCall1e7fe752010-09-02 09:58:18 +0000549 // Figure out the cookie size.
John McCall7d166272011-05-15 07:14:44 +0000550 llvm::APInt cookieSize(sizeWidth,
551 CalculateCookiePadding(CGF, e).getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000552
Anders Carlssona4d4c012009-09-23 16:07:23 +0000553 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000554 // We multiply the size of all dimensions for NumElements.
555 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall7d166272011-05-15 07:14:44 +0000556 numElements = CGF.EmitScalarExpr(e->getArraySize());
557 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall1e7fe752010-09-02 09:58:18 +0000558
John McCall7d166272011-05-15 07:14:44 +0000559 // The number of elements can be have an arbitrary integer type;
560 // essentially, we need to multiply it by a constant factor, add a
561 // cookie size, and verify that the result is representable as a
562 // size_t. That's just a gloss, though, and it's wrong in one
563 // important way: if the count is negative, it's an error even if
564 // the cookie size would bring the total size >= 0.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000565 bool isSigned
566 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000567 llvm::IntegerType *numElementsType
John McCall7d166272011-05-15 07:14:44 +0000568 = cast<llvm::IntegerType>(numElements->getType());
569 unsigned numElementsWidth = numElementsType->getBitWidth();
570
571 // Compute the constant factor.
572 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000573 while (const ConstantArrayType *CAT
John McCall7d166272011-05-15 07:14:44 +0000574 = CGF.getContext().getAsConstantArrayType(type)) {
575 type = CAT->getElementType();
576 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000577 }
578
John McCall7d166272011-05-15 07:14:44 +0000579 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
580 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
581 typeSizeMultiplier *= arraySizeMultiplier;
582
583 // This will be a size_t.
584 llvm::Value *size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000585
Chris Lattner806941e2010-07-20 21:55:52 +0000586 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
587 // Don't bloat the -O0 code.
John McCall7d166272011-05-15 07:14:44 +0000588 if (llvm::ConstantInt *numElementsC =
589 dyn_cast<llvm::ConstantInt>(numElements)) {
590 const llvm::APInt &count = numElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000591
John McCall7d166272011-05-15 07:14:44 +0000592 bool hasAnyOverflow = false;
John McCall1e7fe752010-09-02 09:58:18 +0000593
John McCall7d166272011-05-15 07:14:44 +0000594 // If 'count' was a negative number, it's an overflow.
595 if (isSigned && count.isNegative())
596 hasAnyOverflow = true;
John McCall1e7fe752010-09-02 09:58:18 +0000597
John McCall7d166272011-05-15 07:14:44 +0000598 // We want to do all this arithmetic in size_t. If numElements is
599 // wider than that, check whether it's already too big, and if so,
600 // overflow.
601 else if (numElementsWidth > sizeWidth &&
602 numElementsWidth - sizeWidth > count.countLeadingZeros())
603 hasAnyOverflow = true;
604
605 // Okay, compute a count at the right width.
606 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
607
Sebastian Redl92036472012-02-22 17:37:52 +0000608 // If there is a brace-initializer, we cannot allocate fewer elements than
609 // there are initializers. If we do, that's treated like an overflow.
610 if (adjustedCount.ult(minElements))
611 hasAnyOverflow = true;
612
John McCall7d166272011-05-15 07:14:44 +0000613 // Scale numElements by that. This might overflow, but we don't
614 // care because it only overflows if allocationSize does, too, and
615 // if that overflows then we shouldn't use this.
616 numElements = llvm::ConstantInt::get(CGF.SizeTy,
617 adjustedCount * arraySizeMultiplier);
618
619 // Compute the size before cookie, and track whether it overflowed.
620 bool overflow;
621 llvm::APInt allocationSize
622 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
623 hasAnyOverflow |= overflow;
624
625 // Add in the cookie, and check whether it's overflowed.
626 if (cookieSize != 0) {
627 // Save the current size without a cookie. This shouldn't be
628 // used if there was overflow.
629 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
630
631 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
632 hasAnyOverflow |= overflow;
633 }
634
635 // On overflow, produce a -1 so operator new will fail.
636 if (hasAnyOverflow) {
637 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
638 } else {
639 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
640 }
641
642 // Otherwise, we might need to use the overflow intrinsics.
643 } else {
Sebastian Redl92036472012-02-22 17:37:52 +0000644 // There are up to five conditions we need to test for:
John McCall7d166272011-05-15 07:14:44 +0000645 // 1) if isSigned, we need to check whether numElements is negative;
646 // 2) if numElementsWidth > sizeWidth, we need to check whether
647 // numElements is larger than something representable in size_t;
Sebastian Redl92036472012-02-22 17:37:52 +0000648 // 3) if minElements > 0, we need to check whether numElements is smaller
649 // than that.
650 // 4) we need to compute
John McCall7d166272011-05-15 07:14:44 +0000651 // sizeWithoutCookie := numElements * typeSizeMultiplier
652 // and check whether it overflows; and
Sebastian Redl92036472012-02-22 17:37:52 +0000653 // 5) if we need a cookie, we need to compute
John McCall7d166272011-05-15 07:14:44 +0000654 // size := sizeWithoutCookie + cookieSize
655 // and check whether it overflows.
656
657 llvm::Value *hasOverflow = 0;
658
659 // If numElementsWidth > sizeWidth, then one way or another, we're
660 // going to have to do a comparison for (2), and this happens to
661 // take care of (1), too.
662 if (numElementsWidth > sizeWidth) {
663 llvm::APInt threshold(numElementsWidth, 1);
664 threshold <<= sizeWidth;
665
666 llvm::Value *thresholdV
667 = llvm::ConstantInt::get(numElementsType, threshold);
668
669 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
670 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
671
672 // Otherwise, if we're signed, we want to sext up to size_t.
673 } else if (isSigned) {
674 if (numElementsWidth < sizeWidth)
675 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
676
677 // If there's a non-1 type size multiplier, then we can do the
678 // signedness check at the same time as we do the multiply
679 // because a negative number times anything will cause an
Sebastian Redl92036472012-02-22 17:37:52 +0000680 // unsigned overflow. Otherwise, we have to do it here. But at least
681 // in this case, we can subsume the >= minElements check.
John McCall7d166272011-05-15 07:14:44 +0000682 if (typeSizeMultiplier == 1)
683 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redl92036472012-02-22 17:37:52 +0000684 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall7d166272011-05-15 07:14:44 +0000685
686 // Otherwise, zext up to size_t if necessary.
687 } else if (numElementsWidth < sizeWidth) {
688 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
689 }
690
691 assert(numElements->getType() == CGF.SizeTy);
692
Sebastian Redl92036472012-02-22 17:37:52 +0000693 if (minElements) {
694 // Don't allow allocation of fewer elements than we have initializers.
695 if (!hasOverflow) {
696 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
697 llvm::ConstantInt::get(CGF.SizeTy, minElements));
698 } else if (numElementsWidth > sizeWidth) {
699 // The other existing overflow subsumes this check.
700 // We do an unsigned comparison, since any signed value < -1 is
701 // taken care of either above or below.
702 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
703 CGF.Builder.CreateICmpULT(numElements,
704 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
705 }
706 }
707
John McCall7d166272011-05-15 07:14:44 +0000708 size = numElements;
709
710 // Multiply by the type size if necessary. This multiplier
711 // includes all the factors for nested arrays.
712 //
713 // This step also causes numElements to be scaled up by the
714 // nested-array factor if necessary. Overflow on this computation
715 // can be ignored because the result shouldn't be used if
716 // allocation fails.
717 if (typeSizeMultiplier != 1) {
John McCall7d166272011-05-15 07:14:44 +0000718 llvm::Value *umul_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000719 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000720
721 llvm::Value *tsmV =
722 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
723 llvm::Value *result =
724 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
725
726 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
727 if (hasOverflow)
728 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
729 else
730 hasOverflow = overflowed;
731
732 size = CGF.Builder.CreateExtractValue(result, 0);
733
734 // Also scale up numElements by the array size multiplier.
735 if (arraySizeMultiplier != 1) {
736 // If the base element type size is 1, then we can re-use the
737 // multiply we just did.
738 if (typeSize.isOne()) {
739 assert(arraySizeMultiplier == typeSizeMultiplier);
740 numElements = size;
741
742 // Otherwise we need a separate multiply.
743 } else {
744 llvm::Value *asmV =
745 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
746 numElements = CGF.Builder.CreateMul(numElements, asmV);
747 }
748 }
749 } else {
750 // numElements doesn't need to be scaled.
751 assert(arraySizeMultiplier == 1);
Chris Lattner806941e2010-07-20 21:55:52 +0000752 }
753
John McCall7d166272011-05-15 07:14:44 +0000754 // Add in the cookie size if necessary.
755 if (cookieSize != 0) {
756 sizeWithoutCookie = size;
757
John McCall7d166272011-05-15 07:14:44 +0000758 llvm::Value *uadd_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000759 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000760
761 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
762 llvm::Value *result =
763 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
764
765 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
766 if (hasOverflow)
767 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
768 else
769 hasOverflow = overflowed;
770
771 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall1e7fe752010-09-02 09:58:18 +0000772 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000773
John McCall7d166272011-05-15 07:14:44 +0000774 // If we had any possibility of dynamic overflow, make a select to
775 // overwrite 'size' with an all-ones value, which should cause
776 // operator new to throw.
777 if (hasOverflow)
778 size = CGF.Builder.CreateSelect(hasOverflow,
779 llvm::Constant::getAllOnesValue(CGF.SizeTy),
780 size);
Chris Lattner806941e2010-07-20 21:55:52 +0000781 }
John McCall1e7fe752010-09-02 09:58:18 +0000782
John McCall7d166272011-05-15 07:14:44 +0000783 if (cookieSize == 0)
784 sizeWithoutCookie = size;
John McCall1e7fe752010-09-02 09:58:18 +0000785 else
John McCall7d166272011-05-15 07:14:44 +0000786 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall1e7fe752010-09-02 09:58:18 +0000787
John McCall7d166272011-05-15 07:14:44 +0000788 return size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000789}
790
Sebastian Redl92036472012-02-22 17:37:52 +0000791static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
792 QualType AllocType, llvm::Value *NewPtr) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000793
Eli Friedmand7722d92011-12-03 02:13:40 +0000794 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCalla07398e2011-06-16 04:16:24 +0000795 if (!CGF.hasAggregateLLVMType(AllocType))
Eli Friedmand7722d92011-12-03 02:13:40 +0000796 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType,
Eli Friedman6da2c712011-12-03 04:14:32 +0000797 Alignment),
John McCalla07398e2011-06-16 04:16:24 +0000798 false);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000799 else if (AllocType->isAnyComplexType())
800 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
801 AllocType.isVolatileQualified());
John McCall558d2ab2010-09-15 10:14:12 +0000802 else {
803 AggValueSlot Slot
Eli Friedmanf3940782011-12-03 00:54:26 +0000804 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000805 AggValueSlot::IsDestructed,
John McCall44184392011-08-26 07:31:35 +0000806 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000807 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000808 CGF.EmitAggExpr(Init, Slot);
Sebastian Redl972edf02012-02-19 16:03:09 +0000809
810 CGF.MaybeEmitStdInitializerListCleanup(NewPtr, Init);
John McCall558d2ab2010-09-15 10:14:12 +0000811 }
Fariborz Jahanianef668722010-06-25 18:26:07 +0000812}
813
814void
815CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000816 QualType elementType,
817 llvm::Value *beginPtr,
818 llvm::Value *numElements) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000819 if (!E->hasInitializer())
820 return; // We have a POD type.
John McCall19705672011-09-15 06:49:18 +0000821
Sebastian Redl92036472012-02-22 17:37:52 +0000822 llvm::Value *explicitPtr = beginPtr;
John McCall19705672011-09-15 06:49:18 +0000823 // Find the end of the array, hoisted out of the loop.
824 llvm::Value *endPtr =
825 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
826
Sebastian Redl92036472012-02-22 17:37:52 +0000827 unsigned initializerElements = 0;
828
829 const Expr *Init = E->getInitializer();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000830 llvm::AllocaInst *endOfInit = 0;
831 QualType::DestructionKind dtorKind = elementType.isDestructedType();
832 EHScopeStack::stable_iterator cleanup;
833 llvm::Instruction *cleanupDominator = 0;
Sebastian Redl92036472012-02-22 17:37:52 +0000834 // If the initializer is an initializer list, first do the explicit elements.
835 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
836 initializerElements = ILE->getNumInits();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000837
838 // Enter a partial-destruction cleanup if necessary.
839 if (needsEHCleanup(dtorKind)) {
840 // In principle we could tell the cleanup where we are more
841 // directly, but the control flow can get so varied here that it
842 // would actually be quite complex. Therefore we go through an
843 // alloca.
844 endOfInit = CreateTempAlloca(beginPtr->getType(), "array.endOfInit");
845 cleanupDominator = Builder.CreateStore(beginPtr, endOfInit);
846 pushIrregularPartialArrayCleanup(beginPtr, endOfInit, elementType,
847 getDestroyer(dtorKind));
848 cleanup = EHStack.stable_begin();
849 }
850
Sebastian Redl92036472012-02-22 17:37:52 +0000851 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosier577fb5b2012-02-24 00:13:55 +0000852 // Tell the cleanup that it needs to destroy up to this
853 // element. TODO: some of these stores can be trivially
854 // observed to be unnecessary.
855 if (endOfInit) Builder.CreateStore(explicitPtr, endOfInit);
Sebastian Redl92036472012-02-22 17:37:52 +0000856 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), elementType, explicitPtr);
857 explicitPtr =Builder.CreateConstGEP1_32(explicitPtr, 1, "array.exp.next");
858 }
859
860 // The remaining elements are filled with the array filler expression.
861 Init = ILE->getArrayFiller();
862 }
863
John McCall19705672011-09-15 06:49:18 +0000864 // Create the continuation block.
865 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end");
866
Sebastian Redl92036472012-02-22 17:37:52 +0000867 // If the number of elements isn't constant, we have to now check if there is
868 // anything left to initialize.
869 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) {
870 // If all elements have already been initialized, skip the whole loop.
Chad Rosier577fb5b2012-02-24 00:13:55 +0000871 if (constNum->getZExtValue() <= initializerElements) {
872 // If there was a cleanup, deactivate it.
873 if (cleanupDominator)
874 DeactivateCleanupBlock(cleanup, cleanupDominator);;
875 return;
876 }
Sebastian Redl92036472012-02-22 17:37:52 +0000877 } else {
John McCall19705672011-09-15 06:49:18 +0000878 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty");
Sebastian Redl92036472012-02-22 17:37:52 +0000879 llvm::Value *isEmpty = Builder.CreateICmpEQ(explicitPtr, endPtr,
John McCall19705672011-09-15 06:49:18 +0000880 "array.isempty");
881 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
882 EmitBlock(nonEmptyBB);
883 }
884
885 // Enter the loop.
886 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
887 llvm::BasicBlock *loopBB = createBasicBlock("new.loop");
888
889 EmitBlock(loopBB);
890
891 // Set up the current-element phi.
892 llvm::PHINode *curPtr =
Sebastian Redl92036472012-02-22 17:37:52 +0000893 Builder.CreatePHI(explicitPtr->getType(), 2, "array.cur");
894 curPtr->addIncoming(explicitPtr, entryBB);
John McCall19705672011-09-15 06:49:18 +0000895
Chad Rosier577fb5b2012-02-24 00:13:55 +0000896 // Store the new cleanup position for irregular cleanups.
897 if (endOfInit) Builder.CreateStore(curPtr, endOfInit);
898
John McCall19705672011-09-15 06:49:18 +0000899 // Enter a partial-destruction cleanup if necessary.
Chad Rosier577fb5b2012-02-24 00:13:55 +0000900 if (!cleanupDominator && needsEHCleanup(dtorKind)) {
John McCall19705672011-09-15 06:49:18 +0000901 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
902 getDestroyer(dtorKind));
903 cleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +0000904 cleanupDominator = Builder.CreateUnreachable();
John McCall19705672011-09-15 06:49:18 +0000905 }
906
907 // Emit the initializer into this element.
Sebastian Redl92036472012-02-22 17:37:52 +0000908 StoreAnyExprIntoOneUnit(*this, Init, E->getAllocatedType(), curPtr);
John McCall19705672011-09-15 06:49:18 +0000909
910 // Leave the cleanup if we entered one.
Eli Friedman40563cd2011-12-09 23:05:37 +0000911 if (cleanupDominator) {
John McCall6f103ba2011-11-10 10:43:54 +0000912 DeactivateCleanupBlock(cleanup, cleanupDominator);
913 cleanupDominator->eraseFromParent();
914 }
John McCall19705672011-09-15 06:49:18 +0000915
916 // Advance to the next element.
917 llvm::Value *nextPtr = Builder.CreateConstGEP1_32(curPtr, 1, "array.next");
918
919 // Check whether we've gotten to the end of the array and, if so,
920 // exit the loop.
921 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend");
922 Builder.CreateCondBr(isEnd, contBB, loopBB);
923 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock());
924
925 EmitBlock(contBB);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000926}
927
Douglas Gregor59174c02010-07-21 01:10:17 +0000928static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
929 llvm::Value *NewPtr, llvm::Value *Size) {
John McCalld16c2cf2011-02-08 08:22:06 +0000930 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyckfe710082011-01-19 01:58:38 +0000931 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000932 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000933 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000934}
935
Anders Carlssona4d4c012009-09-23 16:07:23 +0000936static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000937 QualType ElementType,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000938 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000939 llvm::Value *NumElements,
940 llvm::Value *AllocSizeWithoutCookie) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000941 const Expr *Init = E->getInitializer();
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000942 if (E->isArray()) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000943 if (const CXXConstructExpr *CCE = dyn_cast_or_null<CXXConstructExpr>(Init)){
944 CXXConstructorDecl *Ctor = CCE->getConstructor();
Douglas Gregor59174c02010-07-21 01:10:17 +0000945 bool RequiresZeroInitialization = false;
Douglas Gregor887ddf32012-02-23 17:07:43 +0000946 if (Ctor->isTrivial()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000947 // If new expression did not specify value-initialization, then there
948 // is no initialization.
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000949 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
Douglas Gregor59174c02010-07-21 01:10:17 +0000950 return;
951
John McCall19705672011-09-15 06:49:18 +0000952 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000953 // Optimization: since zero initialization will just set the memory
954 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +0000955 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
Douglas Gregor59174c02010-07-21 01:10:17 +0000956 return;
957 }
958
959 RequiresZeroInitialization = true;
960 }
John McCallc3c07662011-07-13 06:10:41 +0000961
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000962 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
963 CCE->arg_begin(), CCE->arg_end(),
Douglas Gregor59174c02010-07-21 01:10:17 +0000964 RequiresZeroInitialization);
Anders Carlssone99bdb62010-05-03 15:09:17 +0000965 return;
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000966 } else if (Init && isa<ImplicitValueInitExpr>(Init) &&
Eli Friedman40563cd2011-12-09 23:05:37 +0000967 CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000968 // Optimization: since zero initialization will just set the memory
969 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +0000970 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
971 return;
Fariborz Jahanianef668722010-06-25 18:26:07 +0000972 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000973 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
974 return;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000975 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000976
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000977 if (!Init)
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000978 return;
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000979
Sebastian Redl92036472012-02-22 17:37:52 +0000980 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000981}
982
John McCall7d8647f2010-09-14 07:57:04 +0000983namespace {
984 /// A cleanup to call the given 'operator delete' function upon
985 /// abnormal exit from a new expression.
986 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
987 size_t NumPlacementArgs;
988 const FunctionDecl *OperatorDelete;
989 llvm::Value *Ptr;
990 llvm::Value *AllocSize;
991
992 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
993
994 public:
995 static size_t getExtraSize(size_t NumPlacementArgs) {
996 return NumPlacementArgs * sizeof(RValue);
997 }
998
999 CallDeleteDuringNew(size_t NumPlacementArgs,
1000 const FunctionDecl *OperatorDelete,
1001 llvm::Value *Ptr,
1002 llvm::Value *AllocSize)
1003 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1004 Ptr(Ptr), AllocSize(AllocSize) {}
1005
1006 void setPlacementArg(unsigned I, RValue Arg) {
1007 assert(I < NumPlacementArgs && "index out of range");
1008 getPlacementArgs()[I] = Arg;
1009 }
1010
John McCallad346f42011-07-12 20:27:29 +00001011 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7d8647f2010-09-14 07:57:04 +00001012 const FunctionProtoType *FPT
1013 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1014 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +00001015 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +00001016
1017 CallArgList DeleteArgs;
1018
1019 // The first argument is always a void*.
1020 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001021 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001022
1023 // A member 'operator delete' can take an extra 'size_t' argument.
1024 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman04c9a492011-05-02 17:57:46 +00001025 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001026
1027 // Pass the rest of the arguments, which must match exactly.
1028 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman04c9a492011-05-02 17:57:46 +00001029 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001030
1031 // Call 'operator delete'.
John McCall0f3d0972012-07-07 06:41:13 +00001032 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, FPT),
John McCall7d8647f2010-09-14 07:57:04 +00001033 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1034 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1035 }
1036 };
John McCall3019c442010-09-17 00:50:28 +00001037
1038 /// A cleanup to call the given 'operator delete' function upon
1039 /// abnormal exit from a new expression when the new expression is
1040 /// conditional.
1041 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1042 size_t NumPlacementArgs;
1043 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +00001044 DominatingValue<RValue>::saved_type Ptr;
1045 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +00001046
John McCall804b8072011-01-28 10:53:53 +00001047 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1048 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +00001049 }
1050
1051 public:
1052 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +00001053 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +00001054 }
1055
1056 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1057 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +00001058 DominatingValue<RValue>::saved_type Ptr,
1059 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +00001060 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1061 Ptr(Ptr), AllocSize(AllocSize) {}
1062
John McCall804b8072011-01-28 10:53:53 +00001063 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +00001064 assert(I < NumPlacementArgs && "index out of range");
1065 getPlacementArgs()[I] = Arg;
1066 }
1067
John McCallad346f42011-07-12 20:27:29 +00001068 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall3019c442010-09-17 00:50:28 +00001069 const FunctionProtoType *FPT
1070 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1071 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
1072 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
1073
1074 CallArgList DeleteArgs;
1075
1076 // The first argument is always a void*.
1077 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001078 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall3019c442010-09-17 00:50:28 +00001079
1080 // A member 'operator delete' can take an extra 'size_t' argument.
1081 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +00001082 RValue RV = AllocSize.restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001083 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001084 }
1085
1086 // Pass the rest of the arguments, which must match exactly.
1087 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +00001088 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001089 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001090 }
1091
1092 // Call 'operator delete'.
John McCall0f3d0972012-07-07 06:41:13 +00001093 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, FPT),
John McCall3019c442010-09-17 00:50:28 +00001094 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1095 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1096 }
1097 };
1098}
1099
1100/// Enter a cleanup to call 'operator delete' if the initializer in a
1101/// new-expression throws.
1102static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1103 const CXXNewExpr *E,
1104 llvm::Value *NewPtr,
1105 llvm::Value *AllocSize,
1106 const CallArgList &NewArgs) {
1107 // If we're not inside a conditional branch, then the cleanup will
1108 // dominate and we can do the easier (and more efficient) thing.
1109 if (!CGF.isInConditionalBranch()) {
1110 CallDeleteDuringNew *Cleanup = CGF.EHStack
1111 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1112 E->getNumPlacementArgs(),
1113 E->getOperatorDelete(),
1114 NewPtr, AllocSize);
1115 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanc6d07822011-05-02 18:05:27 +00001116 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall3019c442010-09-17 00:50:28 +00001117
1118 return;
1119 }
1120
1121 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +00001122 DominatingValue<RValue>::saved_type SavedNewPtr =
1123 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1124 DominatingValue<RValue>::saved_type SavedAllocSize =
1125 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +00001126
1127 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCall6f103ba2011-11-10 10:43:54 +00001128 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall3019c442010-09-17 00:50:28 +00001129 E->getNumPlacementArgs(),
1130 E->getOperatorDelete(),
1131 SavedNewPtr,
1132 SavedAllocSize);
1133 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +00001134 Cleanup->setPlacementArg(I,
Eli Friedmanc6d07822011-05-02 18:05:27 +00001135 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall3019c442010-09-17 00:50:28 +00001136
John McCall6f103ba2011-11-10 10:43:54 +00001137 CGF.initFullExprCleanup();
John McCall7d8647f2010-09-14 07:57:04 +00001138}
1139
Anders Carlsson16d81b82009-09-22 22:53:17 +00001140llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001141 // The element type being allocated.
1142 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +00001143
John McCallc2f3e7f2011-03-07 03:12:35 +00001144 // 1. Build a call to the allocation function.
1145 FunctionDecl *allocator = E->getOperatorNew();
1146 const FunctionProtoType *allocatorType =
1147 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001148
John McCallc2f3e7f2011-03-07 03:12:35 +00001149 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001150
1151 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001152 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001153
Sebastian Redl92036472012-02-22 17:37:52 +00001154 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1155 unsigned minElements = 0;
1156 if (E->isArray() && E->hasInitializer()) {
1157 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1158 minElements = ILE->getNumInits();
1159 }
1160
John McCallc2f3e7f2011-03-07 03:12:35 +00001161 llvm::Value *numElements = 0;
1162 llvm::Value *allocSizeWithoutCookie = 0;
1163 llvm::Value *allocSize =
Sebastian Redl92036472012-02-22 17:37:52 +00001164 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1165 allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +00001166
Eli Friedman04c9a492011-05-02 17:57:46 +00001167 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001168
1169 // Emit the rest of the arguments.
1170 // FIXME: Ideally, this should just use EmitCallArgs.
John McCallc2f3e7f2011-03-07 03:12:35 +00001171 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001172
1173 // First, use the types from the function type.
1174 // We start at 1 here because the first argument (the allocation size)
1175 // has already been emitted.
John McCallc2f3e7f2011-03-07 03:12:35 +00001176 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1177 ++i, ++placementArg) {
1178 QualType argType = allocatorType->getArgType(i);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001179
John McCallc2f3e7f2011-03-07 03:12:35 +00001180 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1181 placementArg->getType()) &&
Anders Carlsson16d81b82009-09-22 22:53:17 +00001182 "type mismatch in call argument!");
1183
John McCall413ebdb2011-03-11 20:59:21 +00001184 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001185 }
1186
1187 // Either we've emitted all the call args, or we have a call to a
1188 // variadic function.
John McCallc2f3e7f2011-03-07 03:12:35 +00001189 assert((placementArg == E->placement_arg_end() ||
1190 allocatorType->isVariadic()) &&
1191 "Extra arguments to non-variadic function!");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001192
1193 // If we still have any arguments, emit them using the type of the argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001194 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1195 placementArg != placementArgsEnd; ++placementArg) {
John McCall413ebdb2011-03-11 20:59:21 +00001196 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001197 }
1198
John McCallb1c98a32011-05-16 01:05:12 +00001199 // Emit the allocation call. If the allocator is a global placement
1200 // operator, just "inline" it directly.
1201 RValue RV;
1202 if (allocator->isReservedGlobalPlacementOperator()) {
1203 assert(allocatorArgs.size() == 2);
1204 RV = allocatorArgs[1].RV;
1205 // TODO: kill any unnecessary computations done for the size
1206 // argument.
1207 } else {
John McCall0f3d0972012-07-07 06:41:13 +00001208 RV = EmitCall(CGM.getTypes().arrangeFreeFunctionCall(allocatorArgs,
1209 allocatorType),
John McCallb1c98a32011-05-16 01:05:12 +00001210 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1211 allocatorArgs, allocator);
1212 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001213
John McCallc2f3e7f2011-03-07 03:12:35 +00001214 // Emit a null check on the allocation result if the allocation
1215 // function is allowed to return null (because it has a non-throwing
1216 // exception spec; for this part, we inline
1217 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1218 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001219 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001220 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001221
John McCallc2f3e7f2011-03-07 03:12:35 +00001222 llvm::BasicBlock *nullCheckBB = 0;
1223 llvm::BasicBlock *contBB = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001224
John McCallc2f3e7f2011-03-07 03:12:35 +00001225 llvm::Value *allocation = RV.getScalarVal();
1226 unsigned AS =
1227 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001228
John McCalla7f633f2011-03-07 01:52:56 +00001229 // The null-check means that the initializer is conditionally
1230 // evaluated.
1231 ConditionalEvaluation conditional(*this);
1232
John McCallc2f3e7f2011-03-07 03:12:35 +00001233 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001234 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001235
1236 nullCheckBB = Builder.GetInsertBlock();
1237 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1238 contBB = createBasicBlock("new.cont");
1239
1240 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1241 Builder.CreateCondBr(isNull, contBB, notNullBB);
1242 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001243 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001244
John McCall7d8647f2010-09-14 07:57:04 +00001245 // If there's an operator delete, enter a cleanup to call it if an
1246 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001247 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCall6f103ba2011-11-10 10:43:54 +00001248 llvm::Instruction *cleanupDominator = 0;
John McCallb1c98a32011-05-16 01:05:12 +00001249 if (E->getOperatorDelete() &&
1250 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001251 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1252 operatorDeleteCleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +00001253 cleanupDominator = Builder.CreateUnreachable();
John McCall7d8647f2010-09-14 07:57:04 +00001254 }
1255
Eli Friedman576cf172011-09-06 18:53:03 +00001256 assert((allocSize == allocSizeWithoutCookie) ==
1257 CalculateCookiePadding(*this, E).isZero());
1258 if (allocSize != allocSizeWithoutCookie) {
1259 assert(E->isArray());
1260 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1261 numElements,
1262 E, allocType);
1263 }
1264
Chris Lattner2acc6e32011-07-18 04:24:23 +00001265 llvm::Type *elementPtrTy
John McCallc2f3e7f2011-03-07 03:12:35 +00001266 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1267 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001268
John McCall19705672011-09-15 06:49:18 +00001269 EmitNewInitializer(*this, E, allocType, result, numElements,
1270 allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001271 if (E->isArray()) {
John McCall1e7fe752010-09-02 09:58:18 +00001272 // NewPtr is a pointer to the base element type. If we're
1273 // allocating an array of arrays, we'll need to cast back to the
1274 // array pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001275 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCallc2f3e7f2011-03-07 03:12:35 +00001276 if (result->getType() != resultType)
1277 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001278 }
John McCall7d8647f2010-09-14 07:57:04 +00001279
1280 // Deactivate the 'operator delete' cleanup if we finished
1281 // initialization.
John McCall6f103ba2011-11-10 10:43:54 +00001282 if (operatorDeleteCleanup.isValid()) {
1283 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1284 cleanupDominator->eraseFromParent();
1285 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001286
John McCallc2f3e7f2011-03-07 03:12:35 +00001287 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001288 conditional.end(*this);
1289
John McCallc2f3e7f2011-03-07 03:12:35 +00001290 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1291 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001292
Jay Foadbbf3bac2011-03-30 11:28:58 +00001293 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001294 PHI->addIncoming(result, notNullBB);
1295 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1296 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001297
John McCallc2f3e7f2011-03-07 03:12:35 +00001298 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001299 }
John McCall1e7fe752010-09-02 09:58:18 +00001300
John McCallc2f3e7f2011-03-07 03:12:35 +00001301 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001302}
1303
Eli Friedman5fe05982009-11-18 00:50:08 +00001304void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1305 llvm::Value *Ptr,
1306 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001307 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1308
Eli Friedman5fe05982009-11-18 00:50:08 +00001309 const FunctionProtoType *DeleteFTy =
1310 DeleteFD->getType()->getAs<FunctionProtoType>();
1311
1312 CallArgList DeleteArgs;
1313
Anders Carlsson871d0782009-12-13 20:04:38 +00001314 // Check if we need to pass the size to the delete operator.
1315 llvm::Value *Size = 0;
1316 QualType SizeTy;
1317 if (DeleteFTy->getNumArgs() == 2) {
1318 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001319 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1320 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1321 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001322 }
1323
Eli Friedman5fe05982009-11-18 00:50:08 +00001324 QualType ArgTy = DeleteFTy->getArgType(0);
1325 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001326 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001327
Anders Carlsson871d0782009-12-13 20:04:38 +00001328 if (Size)
Eli Friedman04c9a492011-05-02 17:57:46 +00001329 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001330
1331 // Emit the call to delete.
John McCall0f3d0972012-07-07 06:41:13 +00001332 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001333 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +00001334 DeleteArgs, DeleteFD);
1335}
1336
John McCall1e7fe752010-09-02 09:58:18 +00001337namespace {
1338 /// Calls the given 'operator delete' on a single object.
1339 struct CallObjectDelete : EHScopeStack::Cleanup {
1340 llvm::Value *Ptr;
1341 const FunctionDecl *OperatorDelete;
1342 QualType ElementType;
1343
1344 CallObjectDelete(llvm::Value *Ptr,
1345 const FunctionDecl *OperatorDelete,
1346 QualType ElementType)
1347 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1348
John McCallad346f42011-07-12 20:27:29 +00001349 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001350 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1351 }
1352 };
1353}
1354
1355/// Emit the code for deleting a single object.
1356static void EmitObjectDelete(CodeGenFunction &CGF,
1357 const FunctionDecl *OperatorDelete,
1358 llvm::Value *Ptr,
Douglas Gregora8b20f72011-07-13 00:54:47 +00001359 QualType ElementType,
1360 bool UseGlobalDelete) {
John McCall1e7fe752010-09-02 09:58:18 +00001361 // Find the destructor for the type, if applicable. If the
1362 // destructor is virtual, we'll just emit the vcall and return.
1363 const CXXDestructorDecl *Dtor = 0;
1364 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1365 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanaebab722011-08-02 18:05:30 +00001366 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall1e7fe752010-09-02 09:58:18 +00001367 Dtor = RD->getDestructor();
1368
1369 if (Dtor->isVirtual()) {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001370 if (UseGlobalDelete) {
1371 // If we're supposed to call the global delete, make sure we do so
1372 // even if the destructor throws.
1373 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1374 Ptr, OperatorDelete,
1375 ElementType);
1376 }
1377
Chris Lattner2acc6e32011-07-18 04:24:23 +00001378 llvm::Type *Ty =
John McCallde5d3c72012-02-17 03:33:10 +00001379 CGF.getTypes().GetFunctionType(
1380 CGF.getTypes().arrangeCXXDestructor(Dtor, Dtor_Complete));
John McCall1e7fe752010-09-02 09:58:18 +00001381
1382 llvm::Value *Callee
Douglas Gregora8b20f72011-07-13 00:54:47 +00001383 = CGF.BuildVirtualCall(Dtor,
1384 UseGlobalDelete? Dtor_Complete : Dtor_Deleting,
1385 Ptr, Ty);
John McCall1e7fe752010-09-02 09:58:18 +00001386 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1387 0, 0);
1388
Douglas Gregora8b20f72011-07-13 00:54:47 +00001389 if (UseGlobalDelete) {
1390 CGF.PopCleanupBlock();
1391 }
1392
John McCall1e7fe752010-09-02 09:58:18 +00001393 return;
1394 }
1395 }
1396 }
1397
1398 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001399 // This doesn't have to a conditional cleanup because we're going
1400 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001401 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1402 Ptr, OperatorDelete, ElementType);
1403
1404 if (Dtor)
1405 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1406 /*ForVirtualBase=*/false, Ptr);
David Blaikie4e4d0842012-03-11 07:00:24 +00001407 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001408 ElementType->isObjCLifetimeType()) {
1409 switch (ElementType.getObjCLifetime()) {
1410 case Qualifiers::OCL_None:
1411 case Qualifiers::OCL_ExplicitNone:
1412 case Qualifiers::OCL_Autoreleasing:
1413 break;
John McCall1e7fe752010-09-02 09:58:18 +00001414
John McCallf85e1932011-06-15 23:02:42 +00001415 case Qualifiers::OCL_Strong: {
1416 // Load the pointer value.
1417 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1418 ElementType.isVolatileQualified());
1419
1420 CGF.EmitARCRelease(PtrValue, /*precise*/ true);
1421 break;
1422 }
1423
1424 case Qualifiers::OCL_Weak:
1425 CGF.EmitARCDestroyWeak(Ptr);
1426 break;
1427 }
1428 }
1429
John McCall1e7fe752010-09-02 09:58:18 +00001430 CGF.PopCleanupBlock();
1431}
1432
1433namespace {
1434 /// Calls the given 'operator delete' on an array of objects.
1435 struct CallArrayDelete : EHScopeStack::Cleanup {
1436 llvm::Value *Ptr;
1437 const FunctionDecl *OperatorDelete;
1438 llvm::Value *NumElements;
1439 QualType ElementType;
1440 CharUnits CookieSize;
1441
1442 CallArrayDelete(llvm::Value *Ptr,
1443 const FunctionDecl *OperatorDelete,
1444 llvm::Value *NumElements,
1445 QualType ElementType,
1446 CharUnits CookieSize)
1447 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1448 ElementType(ElementType), CookieSize(CookieSize) {}
1449
John McCallad346f42011-07-12 20:27:29 +00001450 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001451 const FunctionProtoType *DeleteFTy =
1452 OperatorDelete->getType()->getAs<FunctionProtoType>();
1453 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1454
1455 CallArgList Args;
1456
1457 // Pass the pointer as the first argument.
1458 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1459 llvm::Value *DeletePtr
1460 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001461 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall1e7fe752010-09-02 09:58:18 +00001462
1463 // Pass the original requested size as the second argument.
1464 if (DeleteFTy->getNumArgs() == 2) {
1465 QualType size_t = DeleteFTy->getArgType(1);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001466 llvm::IntegerType *SizeTy
John McCall1e7fe752010-09-02 09:58:18 +00001467 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1468
1469 CharUnits ElementTypeSize =
1470 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1471
1472 // The size of an element, multiplied by the number of elements.
1473 llvm::Value *Size
1474 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1475 Size = CGF.Builder.CreateMul(Size, NumElements);
1476
1477 // Plus the size of the cookie if applicable.
1478 if (!CookieSize.isZero()) {
1479 llvm::Value *CookieSizeV
1480 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1481 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1482 }
1483
Eli Friedman04c9a492011-05-02 17:57:46 +00001484 Args.add(RValue::get(Size), size_t);
John McCall1e7fe752010-09-02 09:58:18 +00001485 }
1486
1487 // Emit the call to delete.
John McCall0f3d0972012-07-07 06:41:13 +00001488 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Args, DeleteFTy),
John McCall1e7fe752010-09-02 09:58:18 +00001489 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1490 ReturnValueSlot(), Args, OperatorDelete);
1491 }
1492 };
1493}
1494
1495/// Emit the code for deleting an array of objects.
1496static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001497 const CXXDeleteExpr *E,
John McCall7cfd76c2011-07-13 01:41:37 +00001498 llvm::Value *deletedPtr,
1499 QualType elementType) {
1500 llvm::Value *numElements = 0;
1501 llvm::Value *allocatedPtr = 0;
1502 CharUnits cookieSize;
1503 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1504 numElements, allocatedPtr, cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001505
John McCall7cfd76c2011-07-13 01:41:37 +00001506 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall1e7fe752010-09-02 09:58:18 +00001507
1508 // Make sure that we call delete even if one of the dtors throws.
John McCall7cfd76c2011-07-13 01:41:37 +00001509 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001510 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCall7cfd76c2011-07-13 01:41:37 +00001511 allocatedPtr, operatorDelete,
1512 numElements, elementType,
1513 cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001514
John McCall7cfd76c2011-07-13 01:41:37 +00001515 // Destroy the elements.
1516 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1517 assert(numElements && "no element count for a type with a destructor!");
1518
John McCall7cfd76c2011-07-13 01:41:37 +00001519 llvm::Value *arrayEnd =
1520 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCallfbf780a2011-07-13 08:09:46 +00001521
1522 // Note that it is legal to allocate a zero-length array, and we
1523 // can never fold the check away because the length should always
1524 // come from a cookie.
John McCall7cfd76c2011-07-13 01:41:37 +00001525 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1526 CGF.getDestroyer(dtorKind),
John McCallfbf780a2011-07-13 08:09:46 +00001527 /*checkZeroLength*/ true,
John McCall7cfd76c2011-07-13 01:41:37 +00001528 CGF.needsEHCleanup(dtorKind));
John McCall1e7fe752010-09-02 09:58:18 +00001529 }
1530
John McCall7cfd76c2011-07-13 01:41:37 +00001531 // Pop the cleanup block.
John McCall1e7fe752010-09-02 09:58:18 +00001532 CGF.PopCleanupBlock();
1533}
1534
Anders Carlsson16d81b82009-09-22 22:53:17 +00001535void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregor90916562009-09-29 18:16:17 +00001536 const Expr *Arg = E->getArgument();
Douglas Gregor90916562009-09-29 18:16:17 +00001537 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001538
1539 // Null check the pointer.
1540 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1541 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1542
Anders Carlssonb9241242011-04-11 00:30:07 +00001543 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001544
1545 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1546 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001547
John McCall1e7fe752010-09-02 09:58:18 +00001548 // We might be deleting a pointer to array. If so, GEP down to the
1549 // first non-array element.
1550 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1551 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1552 if (DeleteTy->isConstantArrayType()) {
1553 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001554 SmallVector<llvm::Value*,8> GEP;
John McCall1e7fe752010-09-02 09:58:18 +00001555
1556 GEP.push_back(Zero); // point at the outermost array
1557
1558 // For each layer of array type we're pointing at:
1559 while (const ConstantArrayType *Arr
1560 = getContext().getAsConstantArrayType(DeleteTy)) {
1561 // 1. Unpeel the array type.
1562 DeleteTy = Arr->getElementType();
1563
1564 // 2. GEP to the first element of the array.
1565 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001566 }
John McCall1e7fe752010-09-02 09:58:18 +00001567
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001568 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001569 }
1570
Douglas Gregoreede61a2010-09-02 17:38:50 +00001571 assert(ConvertTypeForMem(DeleteTy) ==
1572 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001573
1574 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001575 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001576 } else {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001577 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1578 E->isGlobalDelete());
John McCall1e7fe752010-09-02 09:58:18 +00001579 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001580
Anders Carlsson16d81b82009-09-22 22:53:17 +00001581 EmitBlock(DeleteEnd);
1582}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001583
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001584static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1585 // void __cxa_bad_typeid();
Chris Lattner8b418682012-02-07 00:39:47 +00001586 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001587
1588 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1589}
1590
1591static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001592 llvm::Value *Fn = getBadTypeidFn(CGF);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001593 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001594 CGF.Builder.CreateUnreachable();
1595}
1596
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001597static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1598 const Expr *E,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001599 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001600 // Get the vtable pointer.
1601 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1602
1603 // C++ [expr.typeid]p2:
1604 // If the glvalue expression is obtained by applying the unary * operator to
1605 // a pointer and the pointer is a null pointer value, the typeid expression
1606 // throws the std::bad_typeid exception.
1607 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1608 if (UO->getOpcode() == UO_Deref) {
1609 llvm::BasicBlock *BadTypeidBlock =
1610 CGF.createBasicBlock("typeid.bad_typeid");
1611 llvm::BasicBlock *EndBlock =
1612 CGF.createBasicBlock("typeid.end");
1613
1614 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1615 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1616
1617 CGF.EmitBlock(BadTypeidBlock);
1618 EmitBadTypeidCall(CGF);
1619 CGF.EmitBlock(EndBlock);
1620 }
1621 }
1622
1623 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1624 StdTypeInfoPtrTy->getPointerTo());
1625
1626 // Load the type info.
1627 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1628 return CGF.Builder.CreateLoad(Value);
1629}
1630
John McCall3ad32c82011-01-28 08:37:24 +00001631llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001632 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001633 ConvertType(E->getType())->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001634
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001635 if (E->isTypeOperand()) {
1636 llvm::Constant *TypeInfo =
1637 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001638 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001639 }
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001640
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001641 // C++ [expr.typeid]p2:
1642 // When typeid is applied to a glvalue expression whose type is a
1643 // polymorphic class type, the result refers to a std::type_info object
1644 // representing the type of the most derived object (that is, the dynamic
1645 // type) to which the glvalue refers.
1646 if (E->getExprOperand()->isGLValue()) {
1647 if (const RecordType *RT =
1648 E->getExprOperand()->getType()->getAs<RecordType>()) {
1649 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1650 if (RD->isPolymorphic())
1651 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1652 StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001653 }
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001654 }
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001655
1656 QualType OperandTy = E->getExprOperand()->getType();
1657 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1658 StdTypeInfoPtrTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001659}
Mike Stumpc849c052009-11-16 06:50:58 +00001660
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001661static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1662 // void *__dynamic_cast(const void *sub,
1663 // const abi::__class_type_info *src,
1664 // const abi::__class_type_info *dst,
1665 // std::ptrdiff_t src2dst_offset);
1666
Chris Lattner8b418682012-02-07 00:39:47 +00001667 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001668 llvm::Type *PtrDiffTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001669 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1670
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001671 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001672
Chris Lattner2acc6e32011-07-18 04:24:23 +00001673 llvm::FunctionType *FTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001674 llvm::FunctionType::get(Int8PtrTy, Args, false);
1675
1676 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1677}
1678
1679static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1680 // void __cxa_bad_cast();
Chris Lattner8b418682012-02-07 00:39:47 +00001681 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001682 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1683}
1684
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001685static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001686 llvm::Value *Fn = getBadCastFn(CGF);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001687 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001688 CGF.Builder.CreateUnreachable();
1689}
1690
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001691static llvm::Value *
1692EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1693 QualType SrcTy, QualType DestTy,
1694 llvm::BasicBlock *CastEnd) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001695 llvm::Type *PtrDiffLTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001696 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001697 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001698
1699 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1700 if (PTy->getPointeeType()->isVoidType()) {
1701 // C++ [expr.dynamic.cast]p7:
1702 // If T is "pointer to cv void," then the result is a pointer to the
1703 // most derived object pointed to by v.
1704
1705 // Get the vtable pointer.
1706 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1707
1708 // Get the offset-to-top from the vtable.
1709 llvm::Value *OffsetToTop =
1710 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1711 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1712
1713 // Finally, add the offset to the pointer.
1714 Value = CGF.EmitCastToVoidPtr(Value);
1715 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1716
1717 return CGF.Builder.CreateBitCast(Value, DestLTy);
1718 }
1719 }
1720
1721 QualType SrcRecordTy;
1722 QualType DestRecordTy;
1723
1724 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1725 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1726 DestRecordTy = DestPTy->getPointeeType();
1727 } else {
1728 SrcRecordTy = SrcTy;
1729 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1730 }
1731
1732 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1733 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1734
1735 llvm::Value *SrcRTTI =
1736 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1737 llvm::Value *DestRTTI =
1738 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1739
1740 // FIXME: Actually compute a hint here.
1741 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1742
1743 // Emit the call to __dynamic_cast.
1744 Value = CGF.EmitCastToVoidPtr(Value);
1745 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1746 SrcRTTI, DestRTTI, OffsetHint);
1747 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1748
1749 /// C++ [expr.dynamic.cast]p9:
1750 /// A failed cast to reference type throws std::bad_cast
1751 if (DestTy->isReferenceType()) {
1752 llvm::BasicBlock *BadCastBlock =
1753 CGF.createBasicBlock("dynamic_cast.bad_cast");
1754
1755 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1756 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1757
1758 CGF.EmitBlock(BadCastBlock);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001759 EmitBadCastCall(CGF);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001760 }
1761
1762 return Value;
1763}
1764
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001765static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1766 QualType DestTy) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001767 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001768 if (DestTy->isPointerType())
1769 return llvm::Constant::getNullValue(DestLTy);
1770
1771 /// C++ [expr.dynamic.cast]p9:
1772 /// A failed cast to reference type throws std::bad_cast
1773 EmitBadCastCall(CGF);
1774
1775 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1776 return llvm::UndefValue::get(DestLTy);
1777}
1778
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001779llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001780 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001781 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001782
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001783 if (DCE->isAlwaysNull())
1784 return EmitDynamicCastToNull(*this, DestTy);
1785
1786 QualType SrcTy = DCE->getSubExpr()->getType();
1787
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001788 // C++ [expr.dynamic.cast]p4:
1789 // If the value of v is a null pointer value in the pointer case, the result
1790 // is the null pointer value of type T.
1791 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001792
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001793 llvm::BasicBlock *CastNull = 0;
1794 llvm::BasicBlock *CastNotNull = 0;
1795 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001796
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001797 if (ShouldNullCheckSrcValue) {
1798 CastNull = createBasicBlock("dynamic_cast.null");
1799 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1800
1801 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1802 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1803 EmitBlock(CastNotNull);
Mike Stumpc849c052009-11-16 06:50:58 +00001804 }
1805
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001806 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1807
1808 if (ShouldNullCheckSrcValue) {
1809 EmitBranch(CastEnd);
1810
1811 EmitBlock(CastNull);
1812 EmitBranch(CastEnd);
1813 }
1814
1815 EmitBlock(CastEnd);
1816
1817 if (ShouldNullCheckSrcValue) {
1818 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1819 PHI->addIncoming(Value, CastNotNull);
1820 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1821
1822 Value = PHI;
1823 }
1824
1825 return Value;
Mike Stumpc849c052009-11-16 06:50:58 +00001826}
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001827
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001828void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedmanf8823e72012-02-09 03:47:20 +00001829 RunCleanupsScope Scope(*this);
Eli Friedman377ecc72012-04-16 03:54:45 +00001830 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1831 Slot.getAlignment());
Eli Friedmanf8823e72012-02-09 03:47:20 +00001832
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001833 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1834 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1835 e = E->capture_init_end();
Eric Christopherc07b18e2012-02-29 03:25:18 +00001836 i != e; ++i, ++CurField) {
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001837 // Emit initialization
Eli Friedman377ecc72012-04-16 03:54:45 +00001838
David Blaikie581deb32012-06-06 20:45:41 +00001839 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Eli Friedmanb74ed082012-02-14 02:31:03 +00001840 ArrayRef<VarDecl *> ArrayIndexes;
1841 if (CurField->getType()->isArrayType())
1842 ArrayIndexes = E->getCaptureInitIndexVars(i);
David Blaikie581deb32012-06-06 20:45:41 +00001843 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001844 }
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001845}