blob: f35287d5406f8b977c34bc4fab92c2553c2af4a5 [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlssoncc52f652009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
Devang Patel91bbb552010-09-30 19:05:55 +000014#include "clang/Frontend/CodeGenOptions.h"
Anders Carlssoncc52f652009-09-22 22:53:17 +000015#include "CodeGenFunction.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000016#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000017#include "CGCXXABI.h"
Fariborz Jahanian60d215b2010-05-20 21:38:57 +000018#include "CGObjCRuntime.h"
Devang Patel91bbb552010-09-30 19:05:55 +000019#include "CGDebugInfo.h"
Chris Lattner26008e02010-07-20 20:19:24 +000020#include "llvm/Intrinsics.h"
Anders Carlssonbbe277c2011-04-13 02:35:36 +000021#include "llvm/Support/CallSite.h"
22
Anders Carlssoncc52f652009-09-22 22:53:17 +000023using namespace clang;
24using namespace CodeGen;
25
Anders Carlsson27da15b2010-01-01 20:29:01 +000026RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
27 llvm::Value *Callee,
28 ReturnValueSlot ReturnValue,
29 llvm::Value *This,
Anders Carlssone36a6b32010-01-02 01:01:18 +000030 llvm::Value *VTT,
Anders Carlsson27da15b2010-01-01 20:29:01 +000031 CallExpr::const_arg_iterator ArgBeg,
32 CallExpr::const_arg_iterator ArgEnd) {
33 assert(MD->isInstance() &&
34 "Trying to emit a member call expr on a static method!");
35
Anders Carlsson27da15b2010-01-01 20:29:01 +000036 CallArgList Args;
37
38 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +000039 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson27da15b2010-01-01 20:29:01 +000040
Anders Carlssone36a6b32010-01-02 01:01:18 +000041 // If there is a VTT parameter, emit it.
42 if (VTT) {
43 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +000044 Args.add(RValue::get(VTT), T);
Anders Carlssone36a6b32010-01-02 01:01:18 +000045 }
John McCalla729c622012-02-17 03:33:10 +000046
47 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
48 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Anders Carlssone36a6b32010-01-02 01:01:18 +000049
John McCalla729c622012-02-17 03:33:10 +000050 // And the rest of the call args.
Anders Carlsson27da15b2010-01-01 20:29:01 +000051 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
52
John McCalla729c622012-02-17 03:33:10 +000053 return EmitCall(CGM.getTypes().arrangeFunctionCall(FPT->getResultType(), Args,
54 FPT->getExtInfo(),
55 required),
Rafael Espindolac50c27c2010-03-30 20:24:48 +000056 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000057}
58
Anders Carlssonc53d9e82011-04-10 18:20:53 +000059// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
60// quite what we want.
61static const Expr *skipNoOpCastsAndParens(const Expr *E) {
62 while (true) {
63 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
64 E = PE->getSubExpr();
65 continue;
66 }
67
68 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
69 if (CE->getCastKind() == CK_NoOp) {
70 E = CE->getSubExpr();
71 continue;
72 }
73 }
74 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
75 if (UO->getOpcode() == UO_Extension) {
76 E = UO->getSubExpr();
77 continue;
78 }
79 }
80 return E;
81 }
82}
83
Anders Carlsson27da15b2010-01-01 20:29:01 +000084/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
85/// expr can be devirtualized.
Fariborz Jahanian252a47f2011-01-21 01:04:41 +000086static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
87 const Expr *Base,
Anders Carlssona7911fa2010-10-27 13:28:46 +000088 const CXXMethodDecl *MD) {
89
Anders Carlsson1ae64c52011-01-29 03:52:01 +000090 // When building with -fapple-kext, all calls must go through the vtable since
91 // the kernel linker can do runtime patching of vtables.
David Blaikiebbafb8a2012-03-11 07:00:24 +000092 if (Context.getLangOpts().AppleKext)
Fariborz Jahanian252a47f2011-01-21 01:04:41 +000093 return false;
94
Anders Carlsson1ae64c52011-01-29 03:52:01 +000095 // If the most derived class is marked final, we know that no subclass can
96 // override this member function and so we can devirtualize it. For example:
97 //
98 // struct A { virtual void f(); }
99 // struct B final : A { };
100 //
101 // void f(B *b) {
102 // b->f();
103 // }
104 //
Rafael Espindola49e860b2012-06-26 17:45:31 +0000105 const CXXRecordDecl *MostDerivedClassDecl =
106 Base->getMostDerivedClassDeclForType();
Anders Carlsson1ae64c52011-01-29 03:52:01 +0000107 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
108 return true;
109
Anders Carlsson19588aa2011-01-23 21:07:30 +0000110 // If the member function is marked 'final', we know that it can't be
Anders Carlssonb00c2142010-10-27 13:34:43 +0000111 // overridden and can therefore devirtualize it.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000112 if (MD->hasAttr<FinalAttr>())
Anders Carlssona7911fa2010-10-27 13:28:46 +0000113 return true;
Anders Carlssonb00c2142010-10-27 13:34:43 +0000114
Anders Carlsson19588aa2011-01-23 21:07:30 +0000115 // Similarly, if the class itself is marked 'final' it can't be overridden
116 // and we can therefore devirtualize the member function call.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000117 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssonb00c2142010-10-27 13:34:43 +0000118 return true;
119
Anders Carlssonc53d9e82011-04-10 18:20:53 +0000120 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000121 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
122 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
123 // This is a record decl. We know the type and can devirtualize it.
124 return VD->getType()->isRecordType();
125 }
126
127 return false;
128 }
129
130 // We can always devirtualize calls on temporary object expressions.
Eli Friedmana6824272010-01-31 20:58:15 +0000131 if (isa<CXXConstructExpr>(Base))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000132 return true;
133
134 // And calls on bound temporaries.
135 if (isa<CXXBindTemporaryExpr>(Base))
136 return true;
137
138 // Check if this is a call expr that returns a record type.
139 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
140 return CE->getCallReturnType()->isRecordType();
Anders Carlssona7911fa2010-10-27 13:28:46 +0000141
Anders Carlsson27da15b2010-01-01 20:29:01 +0000142 // We can't devirtualize the call.
143 return false;
144}
145
Francois Pichet64225792011-01-18 05:04:39 +0000146// Note: This function also emit constructor calls to support a MSVC
147// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000148RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
149 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +0000150 const Expr *callee = CE->getCallee()->IgnoreParens();
151
152 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000153 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +0000154
155 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000156 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
157
Devang Patel91bbb552010-09-30 19:05:55 +0000158 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000159 if (DI && CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo
Devang Patel401c9162010-10-22 18:56:27 +0000160 && !isa<CallExpr>(ME->getBase())) {
Devang Patel91bbb552010-09-30 19:05:55 +0000161 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
162 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
163 DI->getOrCreateRecordType(PTy->getPointeeType(),
164 MD->getParent()->getLocation());
165 }
166 }
167
Anders Carlsson27da15b2010-01-01 20:29:01 +0000168 if (MD->isStatic()) {
169 // The method is static, emit it as we would a regular call.
170 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
171 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
172 ReturnValue, CE->arg_begin(), CE->arg_end());
173 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000174
John McCall0d635f52010-09-03 01:26:39 +0000175 // Compute the object pointer.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000176 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000177 if (ME->isArrow())
178 This = EmitScalarExpr(ME->getBase());
John McCalle26a8722010-12-04 08:14:53 +0000179 else
180 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000181
John McCall0d635f52010-09-03 01:26:39 +0000182 if (MD->isTrivial()) {
183 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichet64225792011-01-18 05:04:39 +0000184 if (isa<CXXConstructorDecl>(MD) &&
185 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
186 return RValue::get(0);
John McCall0d635f52010-09-03 01:26:39 +0000187
Sebastian Redl22653ba2011-08-30 19:58:05 +0000188 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
189 // We don't like to generate the trivial copy/move assignment operator
190 // when it isn't necessary; just produce the proper effect here.
Francois Pichet64225792011-01-18 05:04:39 +0000191 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
192 EmitAggregateCopy(This, RHS, CE->getType());
193 return RValue::get(This);
194 }
195
196 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000197 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
198 // Trivial move and copy ctor are the same.
Francois Pichet64225792011-01-18 05:04:39 +0000199 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
200 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
201 CE->arg_begin(), CE->arg_end());
202 return RValue::get(This);
203 }
204 llvm_unreachable("unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000205 }
206
John McCall0d635f52010-09-03 01:26:39 +0000207 // Compute the function type we're calling.
Francois Pichet64225792011-01-18 05:04:39 +0000208 const CGFunctionInfo *FInfo = 0;
209 if (isa<CXXDestructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000210 FInfo = &CGM.getTypes().arrangeCXXDestructor(cast<CXXDestructorDecl>(MD),
211 Dtor_Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000212 else if (isa<CXXConstructorDecl>(MD))
John McCalla729c622012-02-17 03:33:10 +0000213 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(
214 cast<CXXConstructorDecl>(MD),
215 Ctor_Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000216 else
John McCalla729c622012-02-17 03:33:10 +0000217 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(MD);
John McCall0d635f52010-09-03 01:26:39 +0000218
John McCalla729c622012-02-17 03:33:10 +0000219 llvm::Type *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000220
Anders Carlsson27da15b2010-01-01 20:29:01 +0000221 // C++ [class.virtual]p12:
222 // Explicit qualification with the scope operator (5.1) suppresses the
223 // virtual call mechanism.
224 //
225 // We also don't emit a virtual call if the base expression has a record type
226 // because then we know what the type is.
Rafael Espindola49e860b2012-06-26 17:45:31 +0000227 const Expr *Base = ME->getBase();
228 bool UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
229 && !canDevirtualizeMemberFunctionCalls(getContext(),
230 Base, MD);
231 const CXXRecordDecl *MostDerivedClassDecl =
232 Base->getMostDerivedClassDeclForType();
233
Anders Carlsson27da15b2010-01-01 20:29:01 +0000234 llvm::Value *Callee;
John McCall0d635f52010-09-03 01:26:39 +0000235 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
236 if (UseVirtualCall) {
237 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000238 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000239 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000240 MD->isVirtual() &&
241 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000242 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000243 else {
244 const CXXMethodDecl *DM =
245 Dtor->getCorrespondingMethodInClass(MostDerivedClassDecl);
246 assert(DM);
247 const CXXDestructorDecl *DDtor = cast<CXXDestructorDecl>(DM);
248 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
249 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000250 }
Francois Pichet64225792011-01-18 05:04:39 +0000251 } else if (const CXXConstructorDecl *Ctor =
252 dyn_cast<CXXConstructorDecl>(MD)) {
253 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000254 } else if (UseVirtualCall) {
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000255 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000256 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000257 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahanian9f9438b2011-01-28 23:42:29 +0000258 MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000259 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000260 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000261 else {
262 const CXXMethodDecl *DerivedMethod =
263 MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
264 assert(DerivedMethod);
265 Callee = CGM.GetAddrOfFunction(DerivedMethod, Ty);
266 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000267 }
268
Anders Carlssone36a6b32010-01-02 01:01:18 +0000269 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000270 CE->arg_begin(), CE->arg_end());
271}
272
273RValue
274CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
275 ReturnValueSlot ReturnValue) {
276 const BinaryOperator *BO =
277 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
278 const Expr *BaseExpr = BO->getLHS();
279 const Expr *MemFnExpr = BO->getRHS();
280
281 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000282 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000283
Anders Carlsson27da15b2010-01-01 20:29:01 +0000284 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000285 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000286 const CXXRecordDecl *RD =
287 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
288
Anders Carlsson27da15b2010-01-01 20:29:01 +0000289 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000290 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000291
292 // Emit the 'this' pointer.
293 llvm::Value *This;
294
John McCalle3027922010-08-25 11:45:40 +0000295 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000296 This = EmitScalarExpr(BaseExpr);
297 else
298 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000299
John McCall475999d2010-08-22 00:05:51 +0000300 // Ask the ABI to load the callee. Note that This is modified.
301 llvm::Value *Callee =
John McCallad7c5c12011-02-08 08:22:06 +0000302 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000303
Anders Carlsson27da15b2010-01-01 20:29:01 +0000304 CallArgList Args;
305
306 QualType ThisType =
307 getContext().getPointerType(getContext().getTagDeclType(RD));
308
309 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000310 Args.add(RValue::get(This), ThisType);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000311
312 // And the rest of the call args
313 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCalla729c622012-02-17 03:33:10 +0000314 return EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), Callee,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000315 ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000316}
317
318RValue
319CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
320 const CXXMethodDecl *MD,
321 ReturnValueSlot ReturnValue) {
322 assert(MD->isInstance() &&
323 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000324 LValue LV = EmitLValue(E->getArg(0));
325 llvm::Value *This = LV.getAddress();
326
Douglas Gregor146b8e92011-09-06 16:26:56 +0000327 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
328 MD->isTrivial()) {
329 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
330 QualType Ty = E->getType();
331 EmitAggregateCopy(This, Src, Ty);
332 return RValue::get(This);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000333 }
334
Anders Carlssonc36783e2011-05-08 20:32:23 +0000335 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000336 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000337 E->arg_begin() + 1, E->arg_end());
338}
339
Peter Collingbournefe883422011-10-06 18:29:37 +0000340RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
341 ReturnValueSlot ReturnValue) {
342 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
343}
344
Eli Friedmanfde961d2011-10-14 02:27:24 +0000345static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
346 llvm::Value *DestPtr,
347 const CXXRecordDecl *Base) {
348 if (Base->isEmpty())
349 return;
350
351 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
352
353 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
354 CharUnits Size = Layout.getNonVirtualSize();
355 CharUnits Align = Layout.getNonVirtualAlign();
356
357 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
358
359 // If the type contains a pointer to data member we can't memset it to zero.
360 // Instead, create a null constant and copy it to the destination.
361 // TODO: there are other patterns besides zero that we can usefully memset,
362 // like -1, which happens to be the pattern used by member-pointers.
363 // TODO: isZeroInitializable can be over-conservative in the case where a
364 // virtual base contains a member pointer.
365 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
366 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
367
368 llvm::GlobalVariable *NullVariable =
369 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
370 /*isConstant=*/true,
371 llvm::GlobalVariable::PrivateLinkage,
372 NullConstant, Twine());
373 NullVariable->setAlignment(Align.getQuantity());
374 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
375
376 // Get and call the appropriate llvm.memcpy overload.
377 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
378 return;
379 }
380
381 // Otherwise, just memset the whole thing to zero. This is legal
382 // because in LLVM, all default initializers (other than the ones we just
383 // handled above) are guaranteed to have a bit pattern of all zeros.
384 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
385 Align.getQuantity());
386}
387
Anders Carlsson27da15b2010-01-01 20:29:01 +0000388void
John McCall7a626f62010-09-15 10:14:12 +0000389CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
390 AggValueSlot Dest) {
391 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000392 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000393
394 // If we require zero initialization before (or instead of) calling the
395 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000396 // constructor, emit the zero initialization now, unless destination is
397 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000398 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
399 switch (E->getConstructionKind()) {
400 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000401 case CXXConstructExpr::CK_Complete:
402 EmitNullInitialization(Dest.getAddr(), E->getType());
403 break;
404 case CXXConstructExpr::CK_VirtualBase:
405 case CXXConstructExpr::CK_NonVirtualBase:
406 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
407 break;
408 }
409 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000410
411 // If this is a call to a trivial default constructor, do nothing.
412 if (CD->isTrivial() && CD->isDefaultConstructor())
413 return;
414
John McCall8ea46b62010-09-18 00:58:34 +0000415 // Elide the constructor if we're constructing from a temporary.
416 // The temporary check is required because Sema sets this on NRVO
417 // returns.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000418 if (getContext().getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000419 assert(getContext().hasSameUnqualifiedType(E->getType(),
420 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000421 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
422 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000423 return;
424 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000425 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000426
John McCallf677a8e2011-07-13 06:10:41 +0000427 if (const ConstantArrayType *arrayType
428 = getContext().getAsConstantArrayType(E->getType())) {
429 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000430 E->arg_begin(), E->arg_end());
John McCallf677a8e2011-07-13 06:10:41 +0000431 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000432 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000433 bool ForVirtualBase = false;
434
435 switch (E->getConstructionKind()) {
436 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000437 // We should be emitting a constructor; GlobalDecl will assert this
438 Type = CurGD.getCtorType();
Alexis Hunt271c3682011-05-03 20:19:28 +0000439 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000440
Alexis Hunt271c3682011-05-03 20:19:28 +0000441 case CXXConstructExpr::CK_Complete:
442 Type = Ctor_Complete;
443 break;
444
445 case CXXConstructExpr::CK_VirtualBase:
446 ForVirtualBase = true;
447 // fall-through
448
449 case CXXConstructExpr::CK_NonVirtualBase:
450 Type = Ctor_Base;
451 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000452
Anders Carlsson27da15b2010-01-01 20:29:01 +0000453 // Call the constructor.
John McCall7a626f62010-09-15 10:14:12 +0000454 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000455 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000456 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000457}
458
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000459void
460CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
461 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000462 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000463 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000464 Exp = E->getSubExpr();
465 assert(isa<CXXConstructExpr>(Exp) &&
466 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
467 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
468 const CXXConstructorDecl *CD = E->getConstructor();
469 RunCleanupsScope Scope(*this);
470
471 // If we require zero initialization before (or instead of) calling the
472 // constructor, as can be the case with a non-user-provided default
473 // constructor, emit the zero initialization now.
474 // FIXME. Do I still need this for a copy ctor synthesis?
475 if (E->requiresZeroInitialization())
476 EmitNullInitialization(Dest, E->getType());
477
Chandler Carruth99da11c2010-11-15 13:54:43 +0000478 assert(!getContext().getAsConstantArrayType(E->getType())
479 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000480 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
481 E->arg_begin(), E->arg_end());
482}
483
John McCall8ed55a52010-09-02 09:58:18 +0000484static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
485 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000486 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000487 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000488
John McCall7ec4b432011-05-16 01:05:12 +0000489 // No cookie is required if the operator new[] being used is the
490 // reserved placement operator new[].
491 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000492 return CharUnits::Zero();
493
John McCall284c48f2011-01-27 09:37:56 +0000494 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000495}
496
John McCall036f2f62011-05-15 07:14:44 +0000497static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
498 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000499 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000500 llvm::Value *&numElements,
501 llvm::Value *&sizeWithoutCookie) {
502 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000503
John McCall036f2f62011-05-15 07:14:44 +0000504 if (!e->isArray()) {
505 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
506 sizeWithoutCookie
507 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
508 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000509 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000510
John McCall036f2f62011-05-15 07:14:44 +0000511 // The width of size_t.
512 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
513
John McCall8ed55a52010-09-02 09:58:18 +0000514 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000515 llvm::APInt cookieSize(sizeWidth,
516 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000517
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000518 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000519 // We multiply the size of all dimensions for NumElements.
520 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000521 numElements = CGF.EmitScalarExpr(e->getArraySize());
522 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000523
John McCall036f2f62011-05-15 07:14:44 +0000524 // The number of elements can be have an arbitrary integer type;
525 // essentially, we need to multiply it by a constant factor, add a
526 // cookie size, and verify that the result is representable as a
527 // size_t. That's just a gloss, though, and it's wrong in one
528 // important way: if the count is negative, it's an error even if
529 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000530 bool isSigned
531 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000532 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000533 = cast<llvm::IntegerType>(numElements->getType());
534 unsigned numElementsWidth = numElementsType->getBitWidth();
535
536 // Compute the constant factor.
537 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000538 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000539 = CGF.getContext().getAsConstantArrayType(type)) {
540 type = CAT->getElementType();
541 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000542 }
543
John McCall036f2f62011-05-15 07:14:44 +0000544 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
545 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
546 typeSizeMultiplier *= arraySizeMultiplier;
547
548 // This will be a size_t.
549 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000550
Chris Lattner32ac5832010-07-20 21:55:52 +0000551 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
552 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000553 if (llvm::ConstantInt *numElementsC =
554 dyn_cast<llvm::ConstantInt>(numElements)) {
555 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000556
John McCall036f2f62011-05-15 07:14:44 +0000557 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000558
John McCall036f2f62011-05-15 07:14:44 +0000559 // If 'count' was a negative number, it's an overflow.
560 if (isSigned && count.isNegative())
561 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000562
John McCall036f2f62011-05-15 07:14:44 +0000563 // We want to do all this arithmetic in size_t. If numElements is
564 // wider than that, check whether it's already too big, and if so,
565 // overflow.
566 else if (numElementsWidth > sizeWidth &&
567 numElementsWidth - sizeWidth > count.countLeadingZeros())
568 hasAnyOverflow = true;
569
570 // Okay, compute a count at the right width.
571 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
572
Sebastian Redlf862eb62012-02-22 17:37:52 +0000573 // If there is a brace-initializer, we cannot allocate fewer elements than
574 // there are initializers. If we do, that's treated like an overflow.
575 if (adjustedCount.ult(minElements))
576 hasAnyOverflow = true;
577
John McCall036f2f62011-05-15 07:14:44 +0000578 // Scale numElements by that. This might overflow, but we don't
579 // care because it only overflows if allocationSize does, too, and
580 // if that overflows then we shouldn't use this.
581 numElements = llvm::ConstantInt::get(CGF.SizeTy,
582 adjustedCount * arraySizeMultiplier);
583
584 // Compute the size before cookie, and track whether it overflowed.
585 bool overflow;
586 llvm::APInt allocationSize
587 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
588 hasAnyOverflow |= overflow;
589
590 // Add in the cookie, and check whether it's overflowed.
591 if (cookieSize != 0) {
592 // Save the current size without a cookie. This shouldn't be
593 // used if there was overflow.
594 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
595
596 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
597 hasAnyOverflow |= overflow;
598 }
599
600 // On overflow, produce a -1 so operator new will fail.
601 if (hasAnyOverflow) {
602 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
603 } else {
604 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
605 }
606
607 // Otherwise, we might need to use the overflow intrinsics.
608 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000609 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000610 // 1) if isSigned, we need to check whether numElements is negative;
611 // 2) if numElementsWidth > sizeWidth, we need to check whether
612 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000613 // 3) if minElements > 0, we need to check whether numElements is smaller
614 // than that.
615 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000616 // sizeWithoutCookie := numElements * typeSizeMultiplier
617 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000618 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000619 // size := sizeWithoutCookie + cookieSize
620 // and check whether it overflows.
621
622 llvm::Value *hasOverflow = 0;
623
624 // If numElementsWidth > sizeWidth, then one way or another, we're
625 // going to have to do a comparison for (2), and this happens to
626 // take care of (1), too.
627 if (numElementsWidth > sizeWidth) {
628 llvm::APInt threshold(numElementsWidth, 1);
629 threshold <<= sizeWidth;
630
631 llvm::Value *thresholdV
632 = llvm::ConstantInt::get(numElementsType, threshold);
633
634 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
635 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
636
637 // Otherwise, if we're signed, we want to sext up to size_t.
638 } else if (isSigned) {
639 if (numElementsWidth < sizeWidth)
640 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
641
642 // If there's a non-1 type size multiplier, then we can do the
643 // signedness check at the same time as we do the multiply
644 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000645 // unsigned overflow. Otherwise, we have to do it here. But at least
646 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000647 if (typeSizeMultiplier == 1)
648 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000649 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000650
651 // Otherwise, zext up to size_t if necessary.
652 } else if (numElementsWidth < sizeWidth) {
653 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
654 }
655
656 assert(numElements->getType() == CGF.SizeTy);
657
Sebastian Redlf862eb62012-02-22 17:37:52 +0000658 if (minElements) {
659 // Don't allow allocation of fewer elements than we have initializers.
660 if (!hasOverflow) {
661 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
662 llvm::ConstantInt::get(CGF.SizeTy, minElements));
663 } else if (numElementsWidth > sizeWidth) {
664 // The other existing overflow subsumes this check.
665 // We do an unsigned comparison, since any signed value < -1 is
666 // taken care of either above or below.
667 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
668 CGF.Builder.CreateICmpULT(numElements,
669 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
670 }
671 }
672
John McCall036f2f62011-05-15 07:14:44 +0000673 size = numElements;
674
675 // Multiply by the type size if necessary. This multiplier
676 // includes all the factors for nested arrays.
677 //
678 // This step also causes numElements to be scaled up by the
679 // nested-array factor if necessary. Overflow on this computation
680 // can be ignored because the result shouldn't be used if
681 // allocation fails.
682 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000683 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000684 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000685
686 llvm::Value *tsmV =
687 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
688 llvm::Value *result =
689 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
690
691 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
692 if (hasOverflow)
693 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
694 else
695 hasOverflow = overflowed;
696
697 size = CGF.Builder.CreateExtractValue(result, 0);
698
699 // Also scale up numElements by the array size multiplier.
700 if (arraySizeMultiplier != 1) {
701 // If the base element type size is 1, then we can re-use the
702 // multiply we just did.
703 if (typeSize.isOne()) {
704 assert(arraySizeMultiplier == typeSizeMultiplier);
705 numElements = size;
706
707 // Otherwise we need a separate multiply.
708 } else {
709 llvm::Value *asmV =
710 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
711 numElements = CGF.Builder.CreateMul(numElements, asmV);
712 }
713 }
714 } else {
715 // numElements doesn't need to be scaled.
716 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000717 }
718
John McCall036f2f62011-05-15 07:14:44 +0000719 // Add in the cookie size if necessary.
720 if (cookieSize != 0) {
721 sizeWithoutCookie = size;
722
John McCall036f2f62011-05-15 07:14:44 +0000723 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000724 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000725
726 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
727 llvm::Value *result =
728 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
729
730 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
731 if (hasOverflow)
732 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
733 else
734 hasOverflow = overflowed;
735
736 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000737 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000738
John McCall036f2f62011-05-15 07:14:44 +0000739 // If we had any possibility of dynamic overflow, make a select to
740 // overwrite 'size' with an all-ones value, which should cause
741 // operator new to throw.
742 if (hasOverflow)
743 size = CGF.Builder.CreateSelect(hasOverflow,
744 llvm::Constant::getAllOnesValue(CGF.SizeTy),
745 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000746 }
John McCall8ed55a52010-09-02 09:58:18 +0000747
John McCall036f2f62011-05-15 07:14:44 +0000748 if (cookieSize == 0)
749 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000750 else
John McCall036f2f62011-05-15 07:14:44 +0000751 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000752
John McCall036f2f62011-05-15 07:14:44 +0000753 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000754}
755
Sebastian Redlf862eb62012-02-22 17:37:52 +0000756static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
757 QualType AllocType, llvm::Value *NewPtr) {
Daniel Dunbar03816342010-08-21 02:24:36 +0000758
Eli Friedman38cd36d2011-12-03 02:13:40 +0000759 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall1553b192011-06-16 04:16:24 +0000760 if (!CGF.hasAggregateLLVMType(AllocType))
Eli Friedman38cd36d2011-12-03 02:13:40 +0000761 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType,
Eli Friedmana0544d62011-12-03 04:14:32 +0000762 Alignment),
John McCall1553b192011-06-16 04:16:24 +0000763 false);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000764 else if (AllocType->isAnyComplexType())
765 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
766 AllocType.isVolatileQualified());
John McCall7a626f62010-09-15 10:14:12 +0000767 else {
768 AggValueSlot Slot
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000769 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000770 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000771 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000772 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000773 CGF.EmitAggExpr(Init, Slot);
Sebastian Redld026dc42012-02-19 16:03:09 +0000774
775 CGF.MaybeEmitStdInitializerListCleanup(NewPtr, Init);
John McCall7a626f62010-09-15 10:14:12 +0000776 }
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000777}
778
779void
780CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000781 QualType elementType,
782 llvm::Value *beginPtr,
783 llvm::Value *numElements) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000784 if (!E->hasInitializer())
785 return; // We have a POD type.
John McCall99210dc2011-09-15 06:49:18 +0000786
Sebastian Redlf862eb62012-02-22 17:37:52 +0000787 llvm::Value *explicitPtr = beginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000788 // Find the end of the array, hoisted out of the loop.
789 llvm::Value *endPtr =
790 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
791
Sebastian Redlf862eb62012-02-22 17:37:52 +0000792 unsigned initializerElements = 0;
793
794 const Expr *Init = E->getInitializer();
Chad Rosierf62290a2012-02-24 00:13:55 +0000795 llvm::AllocaInst *endOfInit = 0;
796 QualType::DestructionKind dtorKind = elementType.isDestructedType();
797 EHScopeStack::stable_iterator cleanup;
798 llvm::Instruction *cleanupDominator = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000799 // If the initializer is an initializer list, first do the explicit elements.
800 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
801 initializerElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +0000802
803 // Enter a partial-destruction cleanup if necessary.
804 if (needsEHCleanup(dtorKind)) {
805 // In principle we could tell the cleanup where we are more
806 // directly, but the control flow can get so varied here that it
807 // would actually be quite complex. Therefore we go through an
808 // alloca.
809 endOfInit = CreateTempAlloca(beginPtr->getType(), "array.endOfInit");
810 cleanupDominator = Builder.CreateStore(beginPtr, endOfInit);
811 pushIrregularPartialArrayCleanup(beginPtr, endOfInit, elementType,
812 getDestroyer(dtorKind));
813 cleanup = EHStack.stable_begin();
814 }
815
Sebastian Redlf862eb62012-02-22 17:37:52 +0000816 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +0000817 // Tell the cleanup that it needs to destroy up to this
818 // element. TODO: some of these stores can be trivially
819 // observed to be unnecessary.
820 if (endOfInit) Builder.CreateStore(explicitPtr, endOfInit);
Sebastian Redlf862eb62012-02-22 17:37:52 +0000821 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), elementType, explicitPtr);
822 explicitPtr =Builder.CreateConstGEP1_32(explicitPtr, 1, "array.exp.next");
823 }
824
825 // The remaining elements are filled with the array filler expression.
826 Init = ILE->getArrayFiller();
827 }
828
John McCall99210dc2011-09-15 06:49:18 +0000829 // Create the continuation block.
830 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end");
831
Sebastian Redlf862eb62012-02-22 17:37:52 +0000832 // If the number of elements isn't constant, we have to now check if there is
833 // anything left to initialize.
834 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) {
835 // If all elements have already been initialized, skip the whole loop.
Chad Rosierf62290a2012-02-24 00:13:55 +0000836 if (constNum->getZExtValue() <= initializerElements) {
837 // If there was a cleanup, deactivate it.
838 if (cleanupDominator)
839 DeactivateCleanupBlock(cleanup, cleanupDominator);;
840 return;
841 }
Sebastian Redlf862eb62012-02-22 17:37:52 +0000842 } else {
John McCall99210dc2011-09-15 06:49:18 +0000843 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty");
Sebastian Redlf862eb62012-02-22 17:37:52 +0000844 llvm::Value *isEmpty = Builder.CreateICmpEQ(explicitPtr, endPtr,
John McCall99210dc2011-09-15 06:49:18 +0000845 "array.isempty");
846 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
847 EmitBlock(nonEmptyBB);
848 }
849
850 // Enter the loop.
851 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
852 llvm::BasicBlock *loopBB = createBasicBlock("new.loop");
853
854 EmitBlock(loopBB);
855
856 // Set up the current-element phi.
857 llvm::PHINode *curPtr =
Sebastian Redlf862eb62012-02-22 17:37:52 +0000858 Builder.CreatePHI(explicitPtr->getType(), 2, "array.cur");
859 curPtr->addIncoming(explicitPtr, entryBB);
John McCall99210dc2011-09-15 06:49:18 +0000860
Chad Rosierf62290a2012-02-24 00:13:55 +0000861 // Store the new cleanup position for irregular cleanups.
862 if (endOfInit) Builder.CreateStore(curPtr, endOfInit);
863
John McCall99210dc2011-09-15 06:49:18 +0000864 // Enter a partial-destruction cleanup if necessary.
Chad Rosierf62290a2012-02-24 00:13:55 +0000865 if (!cleanupDominator && needsEHCleanup(dtorKind)) {
John McCall99210dc2011-09-15 06:49:18 +0000866 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
867 getDestroyer(dtorKind));
868 cleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +0000869 cleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +0000870 }
871
872 // Emit the initializer into this element.
Sebastian Redlf862eb62012-02-22 17:37:52 +0000873 StoreAnyExprIntoOneUnit(*this, Init, E->getAllocatedType(), curPtr);
John McCall99210dc2011-09-15 06:49:18 +0000874
875 // Leave the cleanup if we entered one.
Eli Friedmande6a86b2011-12-09 23:05:37 +0000876 if (cleanupDominator) {
John McCallf4beacd2011-11-10 10:43:54 +0000877 DeactivateCleanupBlock(cleanup, cleanupDominator);
878 cleanupDominator->eraseFromParent();
879 }
John McCall99210dc2011-09-15 06:49:18 +0000880
881 // Advance to the next element.
882 llvm::Value *nextPtr = Builder.CreateConstGEP1_32(curPtr, 1, "array.next");
883
884 // Check whether we've gotten to the end of the array and, if so,
885 // exit the loop.
886 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend");
887 Builder.CreateCondBr(isEnd, contBB, loopBB);
888 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock());
889
890 EmitBlock(contBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000891}
892
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000893static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
894 llvm::Value *NewPtr, llvm::Value *Size) {
John McCallad7c5c12011-02-08 08:22:06 +0000895 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyck705ba072011-01-19 01:58:38 +0000896 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000897 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyck705ba072011-01-19 01:58:38 +0000898 Alignment.getQuantity(), false);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000899}
900
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000901static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000902 QualType ElementType,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000903 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000904 llvm::Value *NumElements,
905 llvm::Value *AllocSizeWithoutCookie) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000906 const Expr *Init = E->getInitializer();
Anders Carlsson3a202f62009-11-24 18:43:52 +0000907 if (E->isArray()) {
Sebastian Redl6047f072012-02-16 12:22:20 +0000908 if (const CXXConstructExpr *CCE = dyn_cast_or_null<CXXConstructExpr>(Init)){
909 CXXConstructorDecl *Ctor = CCE->getConstructor();
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000910 bool RequiresZeroInitialization = false;
Douglas Gregord1531032012-02-23 17:07:43 +0000911 if (Ctor->isTrivial()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000912 // If new expression did not specify value-initialization, then there
913 // is no initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +0000914 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000915 return;
916
John McCall99210dc2011-09-15 06:49:18 +0000917 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000918 // Optimization: since zero initialization will just set the memory
919 // to all zeroes, generate a single memset to do it in one shot.
John McCall99210dc2011-09-15 06:49:18 +0000920 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000921 return;
922 }
923
924 RequiresZeroInitialization = true;
925 }
John McCallf677a8e2011-07-13 06:10:41 +0000926
Sebastian Redl6047f072012-02-16 12:22:20 +0000927 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
928 CCE->arg_begin(), CCE->arg_end(),
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000929 RequiresZeroInitialization);
Anders Carlssond040e6b2010-05-03 15:09:17 +0000930 return;
Sebastian Redl6047f072012-02-16 12:22:20 +0000931 } else if (Init && isa<ImplicitValueInitExpr>(Init) &&
Eli Friedmande6a86b2011-12-09 23:05:37 +0000932 CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000933 // Optimization: since zero initialization will just set the memory
934 // to all zeroes, generate a single memset to do it in one shot.
John McCall99210dc2011-09-15 06:49:18 +0000935 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
936 return;
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000937 }
Sebastian Redl6047f072012-02-16 12:22:20 +0000938 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
939 return;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000940 }
Anders Carlsson3a202f62009-11-24 18:43:52 +0000941
Sebastian Redl6047f072012-02-16 12:22:20 +0000942 if (!Init)
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000943 return;
Sebastian Redl6047f072012-02-16 12:22:20 +0000944
Sebastian Redlf862eb62012-02-22 17:37:52 +0000945 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000946}
947
John McCall824c2f52010-09-14 07:57:04 +0000948namespace {
949 /// A cleanup to call the given 'operator delete' function upon
950 /// abnormal exit from a new expression.
951 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
952 size_t NumPlacementArgs;
953 const FunctionDecl *OperatorDelete;
954 llvm::Value *Ptr;
955 llvm::Value *AllocSize;
956
957 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
958
959 public:
960 static size_t getExtraSize(size_t NumPlacementArgs) {
961 return NumPlacementArgs * sizeof(RValue);
962 }
963
964 CallDeleteDuringNew(size_t NumPlacementArgs,
965 const FunctionDecl *OperatorDelete,
966 llvm::Value *Ptr,
967 llvm::Value *AllocSize)
968 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
969 Ptr(Ptr), AllocSize(AllocSize) {}
970
971 void setPlacementArg(unsigned I, RValue Arg) {
972 assert(I < NumPlacementArgs && "index out of range");
973 getPlacementArgs()[I] = Arg;
974 }
975
John McCall30317fd2011-07-12 20:27:29 +0000976 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall824c2f52010-09-14 07:57:04 +0000977 const FunctionProtoType *FPT
978 = OperatorDelete->getType()->getAs<FunctionProtoType>();
979 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCalld441b1e2010-09-14 21:45:42 +0000980 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +0000981
982 CallArgList DeleteArgs;
983
984 // The first argument is always a void*.
985 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +0000986 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000987
988 // A member 'operator delete' can take an extra 'size_t' argument.
989 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +0000990 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000991
992 // Pass the rest of the arguments, which must match exactly.
993 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +0000994 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000995
996 // Call 'operator delete'.
John McCalla729c622012-02-17 03:33:10 +0000997 CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT),
John McCall824c2f52010-09-14 07:57:04 +0000998 CGF.CGM.GetAddrOfFunction(OperatorDelete),
999 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1000 }
1001 };
John McCall7f9c92a2010-09-17 00:50:28 +00001002
1003 /// A cleanup to call the given 'operator delete' function upon
1004 /// abnormal exit from a new expression when the new expression is
1005 /// conditional.
1006 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1007 size_t NumPlacementArgs;
1008 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +00001009 DominatingValue<RValue>::saved_type Ptr;
1010 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +00001011
John McCallcb5f77f2011-01-28 10:53:53 +00001012 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1013 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +00001014 }
1015
1016 public:
1017 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +00001018 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +00001019 }
1020
1021 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1022 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +00001023 DominatingValue<RValue>::saved_type Ptr,
1024 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +00001025 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1026 Ptr(Ptr), AllocSize(AllocSize) {}
1027
John McCallcb5f77f2011-01-28 10:53:53 +00001028 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +00001029 assert(I < NumPlacementArgs && "index out of range");
1030 getPlacementArgs()[I] = Arg;
1031 }
1032
John McCall30317fd2011-07-12 20:27:29 +00001033 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7f9c92a2010-09-17 00:50:28 +00001034 const FunctionProtoType *FPT
1035 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1036 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
1037 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
1038
1039 CallArgList DeleteArgs;
1040
1041 // The first argument is always a void*.
1042 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001043 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001044
1045 // A member 'operator delete' can take an extra 'size_t' argument.
1046 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +00001047 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001048 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001049 }
1050
1051 // Pass the rest of the arguments, which must match exactly.
1052 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +00001053 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001054 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001055 }
1056
1057 // Call 'operator delete'.
John McCalla729c622012-02-17 03:33:10 +00001058 CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT),
John McCall7f9c92a2010-09-17 00:50:28 +00001059 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1060 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1061 }
1062 };
1063}
1064
1065/// Enter a cleanup to call 'operator delete' if the initializer in a
1066/// new-expression throws.
1067static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1068 const CXXNewExpr *E,
1069 llvm::Value *NewPtr,
1070 llvm::Value *AllocSize,
1071 const CallArgList &NewArgs) {
1072 // If we're not inside a conditional branch, then the cleanup will
1073 // dominate and we can do the easier (and more efficient) thing.
1074 if (!CGF.isInConditionalBranch()) {
1075 CallDeleteDuringNew *Cleanup = CGF.EHStack
1076 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1077 E->getNumPlacementArgs(),
1078 E->getOperatorDelete(),
1079 NewPtr, AllocSize);
1080 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001081 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001082
1083 return;
1084 }
1085
1086 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001087 DominatingValue<RValue>::saved_type SavedNewPtr =
1088 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1089 DominatingValue<RValue>::saved_type SavedAllocSize =
1090 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001091
1092 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCallf4beacd2011-11-10 10:43:54 +00001093 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall7f9c92a2010-09-17 00:50:28 +00001094 E->getNumPlacementArgs(),
1095 E->getOperatorDelete(),
1096 SavedNewPtr,
1097 SavedAllocSize);
1098 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001099 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001100 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001101
John McCallf4beacd2011-11-10 10:43:54 +00001102 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001103}
1104
Anders Carlssoncc52f652009-09-22 22:53:17 +00001105llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001106 // The element type being allocated.
1107 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001108
John McCall75f94982011-03-07 03:12:35 +00001109 // 1. Build a call to the allocation function.
1110 FunctionDecl *allocator = E->getOperatorNew();
1111 const FunctionProtoType *allocatorType =
1112 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001113
John McCall75f94982011-03-07 03:12:35 +00001114 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001115
1116 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001117 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001118
Sebastian Redlf862eb62012-02-22 17:37:52 +00001119 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1120 unsigned minElements = 0;
1121 if (E->isArray() && E->hasInitializer()) {
1122 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1123 minElements = ILE->getNumInits();
1124 }
1125
John McCall75f94982011-03-07 03:12:35 +00001126 llvm::Value *numElements = 0;
1127 llvm::Value *allocSizeWithoutCookie = 0;
1128 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001129 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1130 allocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001131
Eli Friedman43dca6a2011-05-02 17:57:46 +00001132 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001133
1134 // Emit the rest of the arguments.
1135 // FIXME: Ideally, this should just use EmitCallArgs.
John McCall75f94982011-03-07 03:12:35 +00001136 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001137
1138 // First, use the types from the function type.
1139 // We start at 1 here because the first argument (the allocation size)
1140 // has already been emitted.
John McCall75f94982011-03-07 03:12:35 +00001141 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1142 ++i, ++placementArg) {
1143 QualType argType = allocatorType->getArgType(i);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001144
John McCall75f94982011-03-07 03:12:35 +00001145 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1146 placementArg->getType()) &&
Anders Carlssoncc52f652009-09-22 22:53:17 +00001147 "type mismatch in call argument!");
1148
John McCall32ea9692011-03-11 20:59:21 +00001149 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001150 }
1151
1152 // Either we've emitted all the call args, or we have a call to a
1153 // variadic function.
John McCall75f94982011-03-07 03:12:35 +00001154 assert((placementArg == E->placement_arg_end() ||
1155 allocatorType->isVariadic()) &&
1156 "Extra arguments to non-variadic function!");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001157
1158 // If we still have any arguments, emit them using the type of the argument.
John McCall75f94982011-03-07 03:12:35 +00001159 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1160 placementArg != placementArgsEnd; ++placementArg) {
John McCall32ea9692011-03-11 20:59:21 +00001161 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001162 }
1163
John McCall7ec4b432011-05-16 01:05:12 +00001164 // Emit the allocation call. If the allocator is a global placement
1165 // operator, just "inline" it directly.
1166 RValue RV;
1167 if (allocator->isReservedGlobalPlacementOperator()) {
1168 assert(allocatorArgs.size() == 2);
1169 RV = allocatorArgs[1].RV;
1170 // TODO: kill any unnecessary computations done for the size
1171 // argument.
1172 } else {
John McCalla729c622012-02-17 03:33:10 +00001173 RV = EmitCall(CGM.getTypes().arrangeFunctionCall(allocatorArgs,
1174 allocatorType),
John McCall7ec4b432011-05-16 01:05:12 +00001175 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1176 allocatorArgs, allocator);
1177 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001178
John McCall75f94982011-03-07 03:12:35 +00001179 // Emit a null check on the allocation result if the allocation
1180 // function is allowed to return null (because it has a non-throwing
1181 // exception spec; for this part, we inline
1182 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1183 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001184 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001185 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001186
John McCall75f94982011-03-07 03:12:35 +00001187 llvm::BasicBlock *nullCheckBB = 0;
1188 llvm::BasicBlock *contBB = 0;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001189
John McCall75f94982011-03-07 03:12:35 +00001190 llvm::Value *allocation = RV.getScalarVal();
1191 unsigned AS =
1192 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001193
John McCallf7dcf322011-03-07 01:52:56 +00001194 // The null-check means that the initializer is conditionally
1195 // evaluated.
1196 ConditionalEvaluation conditional(*this);
1197
John McCall75f94982011-03-07 03:12:35 +00001198 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001199 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001200
1201 nullCheckBB = Builder.GetInsertBlock();
1202 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1203 contBB = createBasicBlock("new.cont");
1204
1205 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1206 Builder.CreateCondBr(isNull, contBB, notNullBB);
1207 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001208 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001209
John McCall824c2f52010-09-14 07:57:04 +00001210 // If there's an operator delete, enter a cleanup to call it if an
1211 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001212 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCallf4beacd2011-11-10 10:43:54 +00001213 llvm::Instruction *cleanupDominator = 0;
John McCall7ec4b432011-05-16 01:05:12 +00001214 if (E->getOperatorDelete() &&
1215 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCall75f94982011-03-07 03:12:35 +00001216 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1217 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001218 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001219 }
1220
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001221 assert((allocSize == allocSizeWithoutCookie) ==
1222 CalculateCookiePadding(*this, E).isZero());
1223 if (allocSize != allocSizeWithoutCookie) {
1224 assert(E->isArray());
1225 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1226 numElements,
1227 E, allocType);
1228 }
1229
Chris Lattner2192fe52011-07-18 04:24:23 +00001230 llvm::Type *elementPtrTy
John McCall75f94982011-03-07 03:12:35 +00001231 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1232 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001233
John McCall99210dc2011-09-15 06:49:18 +00001234 EmitNewInitializer(*this, E, allocType, result, numElements,
1235 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001236 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001237 // NewPtr is a pointer to the base element type. If we're
1238 // allocating an array of arrays, we'll need to cast back to the
1239 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001240 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall75f94982011-03-07 03:12:35 +00001241 if (result->getType() != resultType)
1242 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001243 }
John McCall824c2f52010-09-14 07:57:04 +00001244
1245 // Deactivate the 'operator delete' cleanup if we finished
1246 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001247 if (operatorDeleteCleanup.isValid()) {
1248 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1249 cleanupDominator->eraseFromParent();
1250 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001251
John McCall75f94982011-03-07 03:12:35 +00001252 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001253 conditional.end(*this);
1254
John McCall75f94982011-03-07 03:12:35 +00001255 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1256 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001257
Jay Foad20c0f022011-03-30 11:28:58 +00001258 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001259 PHI->addIncoming(result, notNullBB);
1260 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1261 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001262
John McCall75f94982011-03-07 03:12:35 +00001263 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001264 }
John McCall8ed55a52010-09-02 09:58:18 +00001265
John McCall75f94982011-03-07 03:12:35 +00001266 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001267}
1268
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001269void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1270 llvm::Value *Ptr,
1271 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001272 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1273
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001274 const FunctionProtoType *DeleteFTy =
1275 DeleteFD->getType()->getAs<FunctionProtoType>();
1276
1277 CallArgList DeleteArgs;
1278
Anders Carlsson21122cf2009-12-13 20:04:38 +00001279 // Check if we need to pass the size to the delete operator.
1280 llvm::Value *Size = 0;
1281 QualType SizeTy;
1282 if (DeleteFTy->getNumArgs() == 2) {
1283 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001284 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1285 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1286 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001287 }
1288
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001289 QualType ArgTy = DeleteFTy->getArgType(0);
1290 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001291 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001292
Anders Carlsson21122cf2009-12-13 20:04:38 +00001293 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001294 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001295
1296 // Emit the call to delete.
John McCalla729c622012-02-17 03:33:10 +00001297 EmitCall(CGM.getTypes().arrangeFunctionCall(DeleteArgs, DeleteFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001298 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001299 DeleteArgs, DeleteFD);
1300}
1301
John McCall8ed55a52010-09-02 09:58:18 +00001302namespace {
1303 /// Calls the given 'operator delete' on a single object.
1304 struct CallObjectDelete : EHScopeStack::Cleanup {
1305 llvm::Value *Ptr;
1306 const FunctionDecl *OperatorDelete;
1307 QualType ElementType;
1308
1309 CallObjectDelete(llvm::Value *Ptr,
1310 const FunctionDecl *OperatorDelete,
1311 QualType ElementType)
1312 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1313
John McCall30317fd2011-07-12 20:27:29 +00001314 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001315 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1316 }
1317 };
1318}
1319
1320/// Emit the code for deleting a single object.
1321static void EmitObjectDelete(CodeGenFunction &CGF,
1322 const FunctionDecl *OperatorDelete,
1323 llvm::Value *Ptr,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001324 QualType ElementType,
1325 bool UseGlobalDelete) {
John McCall8ed55a52010-09-02 09:58:18 +00001326 // Find the destructor for the type, if applicable. If the
1327 // destructor is virtual, we'll just emit the vcall and return.
1328 const CXXDestructorDecl *Dtor = 0;
1329 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1330 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001331 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001332 Dtor = RD->getDestructor();
1333
1334 if (Dtor->isVirtual()) {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001335 if (UseGlobalDelete) {
1336 // If we're supposed to call the global delete, make sure we do so
1337 // even if the destructor throws.
1338 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1339 Ptr, OperatorDelete,
1340 ElementType);
1341 }
1342
Chris Lattner2192fe52011-07-18 04:24:23 +00001343 llvm::Type *Ty =
John McCalla729c622012-02-17 03:33:10 +00001344 CGF.getTypes().GetFunctionType(
1345 CGF.getTypes().arrangeCXXDestructor(Dtor, Dtor_Complete));
John McCall8ed55a52010-09-02 09:58:18 +00001346
1347 llvm::Value *Callee
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001348 = CGF.BuildVirtualCall(Dtor,
1349 UseGlobalDelete? Dtor_Complete : Dtor_Deleting,
1350 Ptr, Ty);
John McCall8ed55a52010-09-02 09:58:18 +00001351 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1352 0, 0);
1353
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001354 if (UseGlobalDelete) {
1355 CGF.PopCleanupBlock();
1356 }
1357
John McCall8ed55a52010-09-02 09:58:18 +00001358 return;
1359 }
1360 }
1361 }
1362
1363 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001364 // This doesn't have to a conditional cleanup because we're going
1365 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001366 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1367 Ptr, OperatorDelete, ElementType);
1368
1369 if (Dtor)
1370 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1371 /*ForVirtualBase=*/false, Ptr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001372 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001373 ElementType->isObjCLifetimeType()) {
1374 switch (ElementType.getObjCLifetime()) {
1375 case Qualifiers::OCL_None:
1376 case Qualifiers::OCL_ExplicitNone:
1377 case Qualifiers::OCL_Autoreleasing:
1378 break;
John McCall8ed55a52010-09-02 09:58:18 +00001379
John McCall31168b02011-06-15 23:02:42 +00001380 case Qualifiers::OCL_Strong: {
1381 // Load the pointer value.
1382 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1383 ElementType.isVolatileQualified());
1384
1385 CGF.EmitARCRelease(PtrValue, /*precise*/ true);
1386 break;
1387 }
1388
1389 case Qualifiers::OCL_Weak:
1390 CGF.EmitARCDestroyWeak(Ptr);
1391 break;
1392 }
1393 }
1394
John McCall8ed55a52010-09-02 09:58:18 +00001395 CGF.PopCleanupBlock();
1396}
1397
1398namespace {
1399 /// Calls the given 'operator delete' on an array of objects.
1400 struct CallArrayDelete : EHScopeStack::Cleanup {
1401 llvm::Value *Ptr;
1402 const FunctionDecl *OperatorDelete;
1403 llvm::Value *NumElements;
1404 QualType ElementType;
1405 CharUnits CookieSize;
1406
1407 CallArrayDelete(llvm::Value *Ptr,
1408 const FunctionDecl *OperatorDelete,
1409 llvm::Value *NumElements,
1410 QualType ElementType,
1411 CharUnits CookieSize)
1412 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1413 ElementType(ElementType), CookieSize(CookieSize) {}
1414
John McCall30317fd2011-07-12 20:27:29 +00001415 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall8ed55a52010-09-02 09:58:18 +00001416 const FunctionProtoType *DeleteFTy =
1417 OperatorDelete->getType()->getAs<FunctionProtoType>();
1418 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1419
1420 CallArgList Args;
1421
1422 // Pass the pointer as the first argument.
1423 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1424 llvm::Value *DeletePtr
1425 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001426 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001427
1428 // Pass the original requested size as the second argument.
1429 if (DeleteFTy->getNumArgs() == 2) {
1430 QualType size_t = DeleteFTy->getArgType(1);
Chris Lattner2192fe52011-07-18 04:24:23 +00001431 llvm::IntegerType *SizeTy
John McCall8ed55a52010-09-02 09:58:18 +00001432 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1433
1434 CharUnits ElementTypeSize =
1435 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1436
1437 // The size of an element, multiplied by the number of elements.
1438 llvm::Value *Size
1439 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1440 Size = CGF.Builder.CreateMul(Size, NumElements);
1441
1442 // Plus the size of the cookie if applicable.
1443 if (!CookieSize.isZero()) {
1444 llvm::Value *CookieSizeV
1445 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1446 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1447 }
1448
Eli Friedman43dca6a2011-05-02 17:57:46 +00001449 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001450 }
1451
1452 // Emit the call to delete.
John McCalla729c622012-02-17 03:33:10 +00001453 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(Args, DeleteFTy),
John McCall8ed55a52010-09-02 09:58:18 +00001454 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1455 ReturnValueSlot(), Args, OperatorDelete);
1456 }
1457 };
1458}
1459
1460/// Emit the code for deleting an array of objects.
1461static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001462 const CXXDeleteExpr *E,
John McCallca2c56f2011-07-13 01:41:37 +00001463 llvm::Value *deletedPtr,
1464 QualType elementType) {
1465 llvm::Value *numElements = 0;
1466 llvm::Value *allocatedPtr = 0;
1467 CharUnits cookieSize;
1468 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1469 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001470
John McCallca2c56f2011-07-13 01:41:37 +00001471 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001472
1473 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001474 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001475 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001476 allocatedPtr, operatorDelete,
1477 numElements, elementType,
1478 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001479
John McCallca2c56f2011-07-13 01:41:37 +00001480 // Destroy the elements.
1481 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1482 assert(numElements && "no element count for a type with a destructor!");
1483
John McCallca2c56f2011-07-13 01:41:37 +00001484 llvm::Value *arrayEnd =
1485 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001486
1487 // Note that it is legal to allocate a zero-length array, and we
1488 // can never fold the check away because the length should always
1489 // come from a cookie.
John McCallca2c56f2011-07-13 01:41:37 +00001490 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1491 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001492 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001493 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001494 }
1495
John McCallca2c56f2011-07-13 01:41:37 +00001496 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001497 CGF.PopCleanupBlock();
1498}
1499
Anders Carlssoncc52f652009-09-22 22:53:17 +00001500void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +00001501
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001502 // Get at the argument before we performed the implicit conversion
1503 // to void*.
1504 const Expr *Arg = E->getArgument();
1505 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00001506 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001507 ICE->getType()->isVoidPointerType())
1508 Arg = ICE->getSubExpr();
Douglas Gregore364e7b2009-10-01 05:49:51 +00001509 else
1510 break;
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001511 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001512
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001513 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001514
1515 // Null check the pointer.
1516 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1517 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1518
Anders Carlsson98981b12011-04-11 00:30:07 +00001519 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001520
1521 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1522 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001523
John McCall8ed55a52010-09-02 09:58:18 +00001524 // We might be deleting a pointer to array. If so, GEP down to the
1525 // first non-array element.
1526 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1527 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1528 if (DeleteTy->isConstantArrayType()) {
1529 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001530 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001531
1532 GEP.push_back(Zero); // point at the outermost array
1533
1534 // For each layer of array type we're pointing at:
1535 while (const ConstantArrayType *Arr
1536 = getContext().getAsConstantArrayType(DeleteTy)) {
1537 // 1. Unpeel the array type.
1538 DeleteTy = Arr->getElementType();
1539
1540 // 2. GEP to the first element of the array.
1541 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001542 }
John McCall8ed55a52010-09-02 09:58:18 +00001543
Jay Foad040dd822011-07-22 08:16:57 +00001544 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001545 }
1546
Douglas Gregor04f36212010-09-02 17:38:50 +00001547 assert(ConvertTypeForMem(DeleteTy) ==
1548 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001549
1550 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001551 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001552 } else {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001553 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1554 E->isGlobalDelete());
John McCall8ed55a52010-09-02 09:58:18 +00001555 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001556
Anders Carlssoncc52f652009-09-22 22:53:17 +00001557 EmitBlock(DeleteEnd);
1558}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001559
Anders Carlsson0c633502011-04-11 14:13:40 +00001560static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1561 // void __cxa_bad_typeid();
Chris Lattnerece04092012-02-07 00:39:47 +00001562 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson0c633502011-04-11 14:13:40 +00001563
1564 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1565}
1566
1567static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001568 llvm::Value *Fn = getBadTypeidFn(CGF);
Jay Foad5bd375a2011-07-15 08:37:34 +00001569 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson0c633502011-04-11 14:13:40 +00001570 CGF.Builder.CreateUnreachable();
1571}
1572
Anders Carlsson940f02d2011-04-18 00:57:03 +00001573static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1574 const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001575 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001576 // Get the vtable pointer.
1577 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1578
1579 // C++ [expr.typeid]p2:
1580 // If the glvalue expression is obtained by applying the unary * operator to
1581 // a pointer and the pointer is a null pointer value, the typeid expression
1582 // throws the std::bad_typeid exception.
1583 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1584 if (UO->getOpcode() == UO_Deref) {
1585 llvm::BasicBlock *BadTypeidBlock =
1586 CGF.createBasicBlock("typeid.bad_typeid");
1587 llvm::BasicBlock *EndBlock =
1588 CGF.createBasicBlock("typeid.end");
1589
1590 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1591 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1592
1593 CGF.EmitBlock(BadTypeidBlock);
1594 EmitBadTypeidCall(CGF);
1595 CGF.EmitBlock(EndBlock);
1596 }
1597 }
1598
1599 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1600 StdTypeInfoPtrTy->getPointerTo());
1601
1602 // Load the type info.
1603 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1604 return CGF.Builder.CreateLoad(Value);
1605}
1606
John McCalle4df6c82011-01-28 08:37:24 +00001607llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001608 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001609 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001610
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001611 if (E->isTypeOperand()) {
1612 llvm::Constant *TypeInfo =
1613 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson940f02d2011-04-18 00:57:03 +00001614 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001615 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001616
Anders Carlsson940f02d2011-04-18 00:57:03 +00001617 // C++ [expr.typeid]p2:
1618 // When typeid is applied to a glvalue expression whose type is a
1619 // polymorphic class type, the result refers to a std::type_info object
1620 // representing the type of the most derived object (that is, the dynamic
1621 // type) to which the glvalue refers.
1622 if (E->getExprOperand()->isGLValue()) {
1623 if (const RecordType *RT =
1624 E->getExprOperand()->getType()->getAs<RecordType>()) {
1625 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1626 if (RD->isPolymorphic())
1627 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1628 StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001629 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001630 }
Anders Carlsson940f02d2011-04-18 00:57:03 +00001631
1632 QualType OperandTy = E->getExprOperand()->getType();
1633 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1634 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001635}
Mike Stump65511702009-11-16 06:50:58 +00001636
Anders Carlsson882d7902011-04-11 00:46:40 +00001637static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1638 // void *__dynamic_cast(const void *sub,
1639 // const abi::__class_type_info *src,
1640 // const abi::__class_type_info *dst,
1641 // std::ptrdiff_t src2dst_offset);
1642
Chris Lattnerece04092012-02-07 00:39:47 +00001643 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001644 llvm::Type *PtrDiffTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001645 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1646
Chris Lattnera5f58b02011-07-09 17:41:47 +00001647 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Anders Carlsson882d7902011-04-11 00:46:40 +00001648
Chris Lattner2192fe52011-07-18 04:24:23 +00001649 llvm::FunctionType *FTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001650 llvm::FunctionType::get(Int8PtrTy, Args, false);
1651
1652 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1653}
1654
1655static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1656 // void __cxa_bad_cast();
Chris Lattnerece04092012-02-07 00:39:47 +00001657 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson882d7902011-04-11 00:46:40 +00001658 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1659}
1660
Anders Carlssonc1c99712011-04-11 01:45:29 +00001661static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001662 llvm::Value *Fn = getBadCastFn(CGF);
Jay Foad5bd375a2011-07-15 08:37:34 +00001663 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlssonc1c99712011-04-11 01:45:29 +00001664 CGF.Builder.CreateUnreachable();
1665}
1666
Anders Carlsson882d7902011-04-11 00:46:40 +00001667static llvm::Value *
1668EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1669 QualType SrcTy, QualType DestTy,
1670 llvm::BasicBlock *CastEnd) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001671 llvm::Type *PtrDiffLTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001672 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2192fe52011-07-18 04:24:23 +00001673 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson882d7902011-04-11 00:46:40 +00001674
1675 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1676 if (PTy->getPointeeType()->isVoidType()) {
1677 // C++ [expr.dynamic.cast]p7:
1678 // If T is "pointer to cv void," then the result is a pointer to the
1679 // most derived object pointed to by v.
1680
1681 // Get the vtable pointer.
1682 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1683
1684 // Get the offset-to-top from the vtable.
1685 llvm::Value *OffsetToTop =
1686 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1687 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1688
1689 // Finally, add the offset to the pointer.
1690 Value = CGF.EmitCastToVoidPtr(Value);
1691 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1692
1693 return CGF.Builder.CreateBitCast(Value, DestLTy);
1694 }
1695 }
1696
1697 QualType SrcRecordTy;
1698 QualType DestRecordTy;
1699
1700 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1701 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1702 DestRecordTy = DestPTy->getPointeeType();
1703 } else {
1704 SrcRecordTy = SrcTy;
1705 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1706 }
1707
1708 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1709 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1710
1711 llvm::Value *SrcRTTI =
1712 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1713 llvm::Value *DestRTTI =
1714 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1715
1716 // FIXME: Actually compute a hint here.
1717 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1718
1719 // Emit the call to __dynamic_cast.
1720 Value = CGF.EmitCastToVoidPtr(Value);
1721 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1722 SrcRTTI, DestRTTI, OffsetHint);
1723 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1724
1725 /// C++ [expr.dynamic.cast]p9:
1726 /// A failed cast to reference type throws std::bad_cast
1727 if (DestTy->isReferenceType()) {
1728 llvm::BasicBlock *BadCastBlock =
1729 CGF.createBasicBlock("dynamic_cast.bad_cast");
1730
1731 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1732 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1733
1734 CGF.EmitBlock(BadCastBlock);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001735 EmitBadCastCall(CGF);
Anders Carlsson882d7902011-04-11 00:46:40 +00001736 }
1737
1738 return Value;
1739}
1740
Anders Carlssonc1c99712011-04-11 01:45:29 +00001741static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1742 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001743 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001744 if (DestTy->isPointerType())
1745 return llvm::Constant::getNullValue(DestLTy);
1746
1747 /// C++ [expr.dynamic.cast]p9:
1748 /// A failed cast to reference type throws std::bad_cast
1749 EmitBadCastCall(CGF);
1750
1751 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1752 return llvm::UndefValue::get(DestLTy);
1753}
1754
Anders Carlsson882d7902011-04-11 00:46:40 +00001755llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001756 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001757 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001758
Anders Carlssonc1c99712011-04-11 01:45:29 +00001759 if (DCE->isAlwaysNull())
1760 return EmitDynamicCastToNull(*this, DestTy);
1761
1762 QualType SrcTy = DCE->getSubExpr()->getType();
1763
Anders Carlsson882d7902011-04-11 00:46:40 +00001764 // C++ [expr.dynamic.cast]p4:
1765 // If the value of v is a null pointer value in the pointer case, the result
1766 // is the null pointer value of type T.
1767 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001768
Anders Carlsson882d7902011-04-11 00:46:40 +00001769 llvm::BasicBlock *CastNull = 0;
1770 llvm::BasicBlock *CastNotNull = 0;
1771 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001772
Anders Carlsson882d7902011-04-11 00:46:40 +00001773 if (ShouldNullCheckSrcValue) {
1774 CastNull = createBasicBlock("dynamic_cast.null");
1775 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1776
1777 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1778 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1779 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001780 }
1781
Anders Carlsson882d7902011-04-11 00:46:40 +00001782 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1783
1784 if (ShouldNullCheckSrcValue) {
1785 EmitBranch(CastEnd);
1786
1787 EmitBlock(CastNull);
1788 EmitBranch(CastEnd);
1789 }
1790
1791 EmitBlock(CastEnd);
1792
1793 if (ShouldNullCheckSrcValue) {
1794 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1795 PHI->addIncoming(Value, CastNotNull);
1796 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1797
1798 Value = PHI;
1799 }
1800
1801 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001802}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001803
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001804void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00001805 RunCleanupsScope Scope(*this);
Eli Friedman7f1ff602012-04-16 03:54:45 +00001806 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1807 Slot.getAlignment());
Eli Friedman8631f3e82012-02-09 03:47:20 +00001808
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001809 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1810 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1811 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00001812 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001813 // Emit initialization
Eli Friedman7f1ff602012-04-16 03:54:45 +00001814
David Blaikie40ed2972012-06-06 20:45:41 +00001815 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Eli Friedman5f1a04f2012-02-14 02:31:03 +00001816 ArrayRef<VarDecl *> ArrayIndexes;
1817 if (CurField->getType()->isArrayType())
1818 ArrayIndexes = E->getCaptureInitIndexVars(i);
David Blaikie40ed2972012-06-06 20:45:41 +00001819 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001820 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001821}