blob: f6043e5f3f6fb8366302b679b08b3243a0f58847 [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"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Fariborz Jahanian60d215b2010-05-20 21:38:57 +000017#include "CGObjCRuntime.h"
Devang Patel91bbb552010-09-30 19:05:55 +000018#include "CGDebugInfo.h"
Chris Lattner26008e02010-07-20 20:19:24 +000019#include "llvm/Intrinsics.h"
Anders Carlssoncc52f652009-09-22 22:53:17 +000020using namespace clang;
21using namespace CodeGen;
22
Anders Carlsson27da15b2010-01-01 20:29:01 +000023RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
24 llvm::Value *Callee,
25 ReturnValueSlot ReturnValue,
26 llvm::Value *This,
Anders Carlssone36a6b32010-01-02 01:01:18 +000027 llvm::Value *VTT,
Anders Carlsson27da15b2010-01-01 20:29:01 +000028 CallExpr::const_arg_iterator ArgBeg,
29 CallExpr::const_arg_iterator ArgEnd) {
30 assert(MD->isInstance() &&
31 "Trying to emit a member call expr on a static method!");
32
33 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
34
35 CallArgList Args;
36
37 // Push the this ptr.
38 Args.push_back(std::make_pair(RValue::get(This),
39 MD->getThisType(getContext())));
40
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);
44 Args.push_back(std::make_pair(RValue::get(VTT), T));
45 }
46
Anders Carlsson27da15b2010-01-01 20:29:01 +000047 // And the rest of the call args
48 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
49
John McCallab26cfa2010-02-05 21:31:56 +000050 QualType ResultType = FPT->getResultType();
Tilmann Scheller99cc30c2011-03-02 21:36:49 +000051 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
52 FPT->getExtInfo()),
Rafael Espindolac50c27c2010-03-30 20:24:48 +000053 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000054}
55
Anders Carlsson1ae64c52011-01-29 03:52:01 +000056static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
Anders Carlsson6b3afd72011-01-29 05:04:11 +000057 const Expr *E = Base;
58
59 while (true) {
60 E = E->IgnoreParens();
61 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
62 if (CE->getCastKind() == CK_DerivedToBase ||
63 CE->getCastKind() == CK_UncheckedDerivedToBase ||
64 CE->getCastKind() == CK_NoOp) {
65 E = CE->getSubExpr();
66 continue;
67 }
68 }
69
70 break;
71 }
72
73 QualType DerivedType = E->getType();
Anders Carlsson1ae64c52011-01-29 03:52:01 +000074 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
75 DerivedType = PTy->getPointeeType();
76
77 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
78}
79
Anders Carlssonc53d9e82011-04-10 18:20:53 +000080// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
81// quite what we want.
82static const Expr *skipNoOpCastsAndParens(const Expr *E) {
83 while (true) {
84 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
85 E = PE->getSubExpr();
86 continue;
87 }
88
89 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
90 if (CE->getCastKind() == CK_NoOp) {
91 E = CE->getSubExpr();
92 continue;
93 }
94 }
95 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
96 if (UO->getOpcode() == UO_Extension) {
97 E = UO->getSubExpr();
98 continue;
99 }
100 }
101 return E;
102 }
103}
104
Anders Carlsson27da15b2010-01-01 20:29:01 +0000105/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
106/// expr can be devirtualized.
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000107static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
108 const Expr *Base,
Anders Carlssona7911fa2010-10-27 13:28:46 +0000109 const CXXMethodDecl *MD) {
110
Anders Carlsson1ae64c52011-01-29 03:52:01 +0000111 // When building with -fapple-kext, all calls must go through the vtable since
112 // the kernel linker can do runtime patching of vtables.
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000113 if (Context.getLangOptions().AppleKext)
114 return false;
115
Anders Carlsson1ae64c52011-01-29 03:52:01 +0000116 // If the most derived class is marked final, we know that no subclass can
117 // override this member function and so we can devirtualize it. For example:
118 //
119 // struct A { virtual void f(); }
120 // struct B final : A { };
121 //
122 // void f(B *b) {
123 // b->f();
124 // }
125 //
126 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
127 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
128 return true;
129
Anders Carlsson19588aa2011-01-23 21:07:30 +0000130 // If the member function is marked 'final', we know that it can't be
Anders Carlssonb00c2142010-10-27 13:34:43 +0000131 // overridden and can therefore devirtualize it.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000132 if (MD->hasAttr<FinalAttr>())
Anders Carlssona7911fa2010-10-27 13:28:46 +0000133 return true;
Anders Carlssonb00c2142010-10-27 13:34:43 +0000134
Anders Carlsson19588aa2011-01-23 21:07:30 +0000135 // Similarly, if the class itself is marked 'final' it can't be overridden
136 // and we can therefore devirtualize the member function call.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000137 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssonb00c2142010-10-27 13:34:43 +0000138 return true;
139
Anders Carlssonc53d9e82011-04-10 18:20:53 +0000140 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000141 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
142 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
143 // This is a record decl. We know the type and can devirtualize it.
144 return VD->getType()->isRecordType();
145 }
146
147 return false;
148 }
149
150 // We can always devirtualize calls on temporary object expressions.
Eli Friedmana6824272010-01-31 20:58:15 +0000151 if (isa<CXXConstructExpr>(Base))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000152 return true;
153
154 // And calls on bound temporaries.
155 if (isa<CXXBindTemporaryExpr>(Base))
156 return true;
157
158 // Check if this is a call expr that returns a record type.
159 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
160 return CE->getCallReturnType()->isRecordType();
Anders Carlssona7911fa2010-10-27 13:28:46 +0000161
Anders Carlsson27da15b2010-01-01 20:29:01 +0000162 // We can't devirtualize the call.
163 return false;
164}
165
Francois Pichet64225792011-01-18 05:04:39 +0000166// Note: This function also emit constructor calls to support a MSVC
167// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000168RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
169 ReturnValueSlot ReturnValue) {
170 if (isa<BinaryOperator>(CE->getCallee()->IgnoreParens()))
171 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
172
173 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()->IgnoreParens());
174 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
175
Devang Patel91bbb552010-09-30 19:05:55 +0000176 CGDebugInfo *DI = getDebugInfo();
Devang Patel401c9162010-10-22 18:56:27 +0000177 if (DI && CGM.getCodeGenOpts().LimitDebugInfo
178 && !isa<CallExpr>(ME->getBase())) {
Devang Patel91bbb552010-09-30 19:05:55 +0000179 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
180 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
181 DI->getOrCreateRecordType(PTy->getPointeeType(),
182 MD->getParent()->getLocation());
183 }
184 }
185
Anders Carlsson27da15b2010-01-01 20:29:01 +0000186 if (MD->isStatic()) {
187 // The method is static, emit it as we would a regular call.
188 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
189 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
190 ReturnValue, CE->arg_begin(), CE->arg_end());
191 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000192
John McCall0d635f52010-09-03 01:26:39 +0000193 // Compute the object pointer.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000194 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000195 if (ME->isArrow())
196 This = EmitScalarExpr(ME->getBase());
John McCalle26a8722010-12-04 08:14:53 +0000197 else
198 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000199
John McCall0d635f52010-09-03 01:26:39 +0000200 if (MD->isTrivial()) {
201 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichet64225792011-01-18 05:04:39 +0000202 if (isa<CXXConstructorDecl>(MD) &&
203 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
204 return RValue::get(0);
John McCall0d635f52010-09-03 01:26:39 +0000205
Francois Pichet64225792011-01-18 05:04:39 +0000206 if (MD->isCopyAssignmentOperator()) {
207 // We don't like to generate the trivial copy assignment operator when
208 // it isn't necessary; just produce the proper effect here.
209 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
210 EmitAggregateCopy(This, RHS, CE->getType());
211 return RValue::get(This);
212 }
213
214 if (isa<CXXConstructorDecl>(MD) &&
215 cast<CXXConstructorDecl>(MD)->isCopyConstructor()) {
216 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
217 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
218 CE->arg_begin(), CE->arg_end());
219 return RValue::get(This);
220 }
221 llvm_unreachable("unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000222 }
223
John McCall0d635f52010-09-03 01:26:39 +0000224 // Compute the function type we're calling.
Francois Pichet64225792011-01-18 05:04:39 +0000225 const CGFunctionInfo *FInfo = 0;
226 if (isa<CXXDestructorDecl>(MD))
227 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
228 Dtor_Complete);
229 else if (isa<CXXConstructorDecl>(MD))
230 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXConstructorDecl>(MD),
231 Ctor_Complete);
232 else
233 FInfo = &CGM.getTypes().getFunctionInfo(MD);
John McCall0d635f52010-09-03 01:26:39 +0000234
235 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
236 const llvm::Type *Ty
Francois Pichet64225792011-01-18 05:04:39 +0000237 = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
John McCall0d635f52010-09-03 01:26:39 +0000238
Anders Carlsson27da15b2010-01-01 20:29:01 +0000239 // C++ [class.virtual]p12:
240 // Explicit qualification with the scope operator (5.1) suppresses the
241 // virtual call mechanism.
242 //
243 // We also don't emit a virtual call if the base expression has a record type
244 // because then we know what the type is.
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000245 bool UseVirtualCall;
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000246 UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
247 && !canDevirtualizeMemberFunctionCalls(getContext(),
248 ME->getBase(), MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000249 llvm::Value *Callee;
John McCall0d635f52010-09-03 01:26:39 +0000250 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
251 if (UseVirtualCall) {
252 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000253 } else {
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000254 if (getContext().getLangOptions().AppleKext &&
255 MD->isVirtual() &&
256 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000257 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000258 else
259 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000260 }
Francois Pichet64225792011-01-18 05:04:39 +0000261 } else if (const CXXConstructorDecl *Ctor =
262 dyn_cast<CXXConstructorDecl>(MD)) {
263 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000264 } else if (UseVirtualCall) {
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000265 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000266 } else {
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000267 if (getContext().getLangOptions().AppleKext &&
Fariborz Jahanian9f9438b2011-01-28 23:42:29 +0000268 MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000269 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000270 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000271 else
272 Callee = CGM.GetAddrOfFunction(MD, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000273 }
274
Anders Carlssone36a6b32010-01-02 01:01:18 +0000275 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000276 CE->arg_begin(), CE->arg_end());
277}
278
279RValue
280CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
281 ReturnValueSlot ReturnValue) {
282 const BinaryOperator *BO =
283 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
284 const Expr *BaseExpr = BO->getLHS();
285 const Expr *MemFnExpr = BO->getRHS();
286
287 const MemberPointerType *MPT =
288 MemFnExpr->getType()->getAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000289
Anders Carlsson27da15b2010-01-01 20:29:01 +0000290 const FunctionProtoType *FPT =
291 MPT->getPointeeType()->getAs<FunctionProtoType>();
292 const CXXRecordDecl *RD =
293 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
294
Anders Carlsson27da15b2010-01-01 20:29:01 +0000295 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000296 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000297
298 // Emit the 'this' pointer.
299 llvm::Value *This;
300
John McCalle3027922010-08-25 11:45:40 +0000301 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000302 This = EmitScalarExpr(BaseExpr);
303 else
304 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000305
John McCall475999d2010-08-22 00:05:51 +0000306 // Ask the ABI to load the callee. Note that This is modified.
307 llvm::Value *Callee =
John McCallad7c5c12011-02-08 08:22:06 +0000308 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000309
Anders Carlsson27da15b2010-01-01 20:29:01 +0000310 CallArgList Args;
311
312 QualType ThisType =
313 getContext().getPointerType(getContext().getTagDeclType(RD));
314
315 // Push the this ptr.
316 Args.push_back(std::make_pair(RValue::get(This), ThisType));
317
318 // And the rest of the call args
319 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCallab26cfa2010-02-05 21:31:56 +0000320 const FunctionType *BO_FPT = BO->getType()->getAs<FunctionProtoType>();
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000321 return EmitCall(CGM.getTypes().getFunctionInfo(Args, BO_FPT), Callee,
322 ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000323}
324
325RValue
326CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
327 const CXXMethodDecl *MD,
328 ReturnValueSlot ReturnValue) {
329 assert(MD->isInstance() &&
330 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000331 LValue LV = EmitLValue(E->getArg(0));
332 llvm::Value *This = LV.getAddress();
333
Douglas Gregorec3bec02010-09-27 22:37:28 +0000334 if (MD->isCopyAssignmentOperator()) {
Anders Carlsson27da15b2010-01-01 20:29:01 +0000335 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
336 if (ClassDecl->hasTrivialCopyAssignment()) {
337 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
338 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000339 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
340 QualType Ty = E->getType();
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000341 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000342 return RValue::get(This);
343 }
344 }
345
346 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
347 const llvm::Type *Ty =
348 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
349 FPT->isVariadic());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000350 llvm::Value *Callee;
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000351 if (MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000352 !canDevirtualizeMemberFunctionCalls(getContext(),
353 E->getArg(0), MD))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000354 Callee = BuildVirtualCall(MD, This, Ty);
355 else
356 Callee = CGM.GetAddrOfFunction(MD, Ty);
357
Anders Carlssone36a6b32010-01-02 01:01:18 +0000358 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000359 E->arg_begin() + 1, E->arg_end());
360}
361
362void
John McCall7a626f62010-09-15 10:14:12 +0000363CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
364 AggValueSlot Dest) {
365 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000366 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000367
368 // If we require zero initialization before (or instead of) calling the
369 // constructor, as can be the case with a non-user-provided default
370 // constructor, emit the zero initialization now.
371 if (E->requiresZeroInitialization())
John McCall7a626f62010-09-15 10:14:12 +0000372 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor630c76e2010-08-22 16:15:35 +0000373
374 // If this is a call to a trivial default constructor, do nothing.
375 if (CD->isTrivial() && CD->isDefaultConstructor())
376 return;
377
John McCall8ea46b62010-09-18 00:58:34 +0000378 // Elide the constructor if we're constructing from a temporary.
379 // The temporary check is required because Sema sets this on NRVO
380 // returns.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000381 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000382 assert(getContext().hasSameUnqualifiedType(E->getType(),
383 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000384 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
385 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000386 return;
387 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000388 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000389
390 const ConstantArrayType *Array
391 = getContext().getAsConstantArrayType(E->getType());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000392 if (Array) {
393 QualType BaseElementTy = getContext().getBaseElementType(Array);
394 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
395 BasePtr = llvm::PointerType::getUnqual(BasePtr);
396 llvm::Value *BaseAddrPtr =
John McCall7a626f62010-09-15 10:14:12 +0000397 Builder.CreateBitCast(Dest.getAddr(), BasePtr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000398
399 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
400 E->arg_begin(), E->arg_end());
401 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000402 else {
403 CXXCtorType Type =
404 (E->getConstructionKind() == CXXConstructExpr::CK_Complete)
405 ? Ctor_Complete : Ctor_Base;
406 bool ForVirtualBase =
407 E->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
408
Anders Carlsson27da15b2010-01-01 20:29:01 +0000409 // Call the constructor.
John McCall7a626f62010-09-15 10:14:12 +0000410 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000411 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000412 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000413}
414
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000415void
416CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
417 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000418 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000419 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000420 Exp = E->getSubExpr();
421 assert(isa<CXXConstructExpr>(Exp) &&
422 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
423 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
424 const CXXConstructorDecl *CD = E->getConstructor();
425 RunCleanupsScope Scope(*this);
426
427 // If we require zero initialization before (or instead of) calling the
428 // constructor, as can be the case with a non-user-provided default
429 // constructor, emit the zero initialization now.
430 // FIXME. Do I still need this for a copy ctor synthesis?
431 if (E->requiresZeroInitialization())
432 EmitNullInitialization(Dest, E->getType());
433
Chandler Carruth99da11c2010-11-15 13:54:43 +0000434 assert(!getContext().getAsConstantArrayType(E->getType())
435 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000436 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
437 E->arg_begin(), E->arg_end());
438}
439
John McCallaa4149a2010-08-23 01:17:59 +0000440/// Check whether the given operator new[] is the global placement
441/// operator new[].
442static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
443 const FunctionDecl *Fn) {
444 // Must be in global scope. Note that allocation functions can't be
445 // declared in namespaces.
Sebastian Redl50c68252010-08-31 00:36:30 +0000446 if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
John McCallaa4149a2010-08-23 01:17:59 +0000447 return false;
448
449 // Signature must be void *operator new[](size_t, void*).
450 // The size_t is common to all operator new[]s.
451 if (Fn->getNumParams() != 2)
452 return false;
453
454 CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
455 return (ParamType == Ctx.VoidPtrTy);
456}
457
John McCall8ed55a52010-09-02 09:58:18 +0000458static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
459 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000460 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000461 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000462
Anders Carlsson399f4992009-12-13 20:34:34 +0000463 // No cookie is required if the new operator being used is
464 // ::operator new[](size_t, void*).
465 const FunctionDecl *OperatorNew = E->getOperatorNew();
John McCall8ed55a52010-09-02 09:58:18 +0000466 if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
John McCallaa4149a2010-08-23 01:17:59 +0000467 return CharUnits::Zero();
468
John McCall284c48f2011-01-27 09:37:56 +0000469 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000470}
471
Fariborz Jahanian47b46292010-03-24 16:57:01 +0000472static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
Chris Lattnercb46bdc2010-07-20 18:45:57 +0000473 CodeGenFunction &CGF,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000474 const CXXNewExpr *E,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000475 llvm::Value *&NumElements,
476 llvm::Value *&SizeWithoutCookie) {
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000477 QualType ElemType = E->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000478
479 const llvm::IntegerType *SizeTy =
480 cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000481
John McCall8ed55a52010-09-02 09:58:18 +0000482 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
483
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000484 if (!E->isArray()) {
485 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
486 return SizeWithoutCookie;
487 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000488
John McCall8ed55a52010-09-02 09:58:18 +0000489 // Figure out the cookie size.
490 CharUnits CookieSize = CalculateCookiePadding(CGF, E);
491
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000492 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000493 // We multiply the size of all dimensions for NumElements.
494 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000495 NumElements = CGF.EmitScalarExpr(E->getArraySize());
John McCall8ed55a52010-09-02 09:58:18 +0000496 assert(NumElements->getType() == SizeTy && "element count not a size_t");
497
498 uint64_t ArraySizeMultiplier = 1;
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000499 while (const ConstantArrayType *CAT
500 = CGF.getContext().getAsConstantArrayType(ElemType)) {
501 ElemType = CAT->getElementType();
John McCall8ed55a52010-09-02 09:58:18 +0000502 ArraySizeMultiplier *= CAT->getSize().getZExtValue();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000503 }
504
John McCall8ed55a52010-09-02 09:58:18 +0000505 llvm::Value *Size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000506
Chris Lattner32ac5832010-07-20 21:55:52 +0000507 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
508 // Don't bloat the -O0 code.
509 if (llvm::ConstantInt *NumElementsC =
510 dyn_cast<llvm::ConstantInt>(NumElements)) {
Chris Lattner32ac5832010-07-20 21:55:52 +0000511 llvm::APInt NEC = NumElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000512 unsigned SizeWidth = NEC.getBitWidth();
513
514 // Determine if there is an overflow here by doing an extended multiply.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000515 NEC = NEC.zext(SizeWidth*2);
John McCall8ed55a52010-09-02 09:58:18 +0000516 llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
Chris Lattner32ac5832010-07-20 21:55:52 +0000517 SC *= NEC;
John McCall8ed55a52010-09-02 09:58:18 +0000518
519 if (!CookieSize.isZero()) {
520 // Save the current size without a cookie. We don't care if an
521 // overflow's already happened because SizeWithoutCookie isn't
522 // used if the allocator returns null or throws, as it should
523 // always do on an overflow.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000524 llvm::APInt SWC = SC.trunc(SizeWidth);
John McCall8ed55a52010-09-02 09:58:18 +0000525 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
526
527 // Add the cookie size.
528 SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
Chris Lattner32ac5832010-07-20 21:55:52 +0000529 }
530
John McCall8ed55a52010-09-02 09:58:18 +0000531 if (SC.countLeadingZeros() >= SizeWidth) {
Jay Foad6d4db0c2010-12-07 08:25:34 +0000532 SC = SC.trunc(SizeWidth);
John McCall8ed55a52010-09-02 09:58:18 +0000533 Size = llvm::ConstantInt::get(SizeTy, SC);
534 } else {
535 // On overflow, produce a -1 so operator new throws.
536 Size = llvm::Constant::getAllOnesValue(SizeTy);
537 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000538
John McCall8ed55a52010-09-02 09:58:18 +0000539 // Scale NumElements while we're at it.
540 uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
541 NumElements = llvm::ConstantInt::get(SizeTy, N);
542
543 // Otherwise, we don't need to do an overflow-checked multiplication if
544 // we're multiplying by one.
545 } else if (TypeSize.isOne()) {
546 assert(ArraySizeMultiplier == 1);
547
548 Size = NumElements;
549
550 // If we need a cookie, add its size in with an overflow check.
551 // This is maybe a little paranoid.
552 if (!CookieSize.isZero()) {
553 SizeWithoutCookie = Size;
554
555 llvm::Value *CookieSizeV
556 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
557
558 const llvm::Type *Types[] = { SizeTy };
559 llvm::Value *UAddF
560 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
561 llvm::Value *AddRes
562 = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
563
564 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
565 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
566 Size = CGF.Builder.CreateSelect(DidOverflow,
567 llvm::ConstantInt::get(SizeTy, -1),
568 Size);
569 }
570
571 // Otherwise use the int.umul.with.overflow intrinsic.
572 } else {
573 llvm::Value *OutermostElementSize
574 = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
575
576 llvm::Value *NumOutermostElements = NumElements;
577
578 // Scale NumElements by the array size multiplier. This might
579 // overflow, but only if the multiplication below also overflows,
580 // in which case this multiplication isn't used.
581 if (ArraySizeMultiplier != 1)
582 NumElements = CGF.Builder.CreateMul(NumElements,
583 llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
584
585 // The requested size of the outermost array is non-constant.
586 // Multiply that by the static size of the elements of that array;
587 // on unsigned overflow, set the size to -1 to trigger an
588 // exception from the allocation routine. This is sufficient to
589 // prevent buffer overruns from the allocator returning a
590 // seemingly valid pointer to insufficient space. This idea comes
591 // originally from MSVC, and GCC has an open bug requesting
592 // similar behavior:
593 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
594 //
595 // This will not be sufficient for C++0x, which requires a
596 // specific exception class (std::bad_array_new_length).
597 // That will require ABI support that has not yet been specified.
598 const llvm::Type *Types[] = { SizeTy };
599 llvm::Value *UMulF
600 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
601 llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
602 OutermostElementSize);
603
604 // The overflow bit.
605 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
606
607 // The result of the multiplication.
608 Size = CGF.Builder.CreateExtractValue(MulRes, 0);
609
610 // If we have a cookie, we need to add that size in, too.
611 if (!CookieSize.isZero()) {
612 SizeWithoutCookie = Size;
613
614 llvm::Value *CookieSizeV
615 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
616 llvm::Value *UAddF
617 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
618 llvm::Value *AddRes
619 = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
620
621 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
622
623 llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
Eli Friedmandb42a3e2011-04-09 19:54:33 +0000624 DidOverflow = CGF.Builder.CreateOr(DidOverflow, AddDidOverflow);
John McCall8ed55a52010-09-02 09:58:18 +0000625 }
626
627 Size = CGF.Builder.CreateSelect(DidOverflow,
628 llvm::ConstantInt::get(SizeTy, -1),
629 Size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000630 }
John McCall8ed55a52010-09-02 09:58:18 +0000631
632 if (CookieSize.isZero())
633 SizeWithoutCookie = Size;
634 else
635 assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
636
Chris Lattner32ac5832010-07-20 21:55:52 +0000637 return Size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000638}
639
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000640static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
641 llvm::Value *NewPtr) {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000642
643 assert(E->getNumConstructorArgs() == 1 &&
644 "Can only have one argument to initializer of POD type.");
645
646 const Expr *Init = E->getConstructorArg(0);
647 QualType AllocType = E->getAllocatedType();
Daniel Dunbar03816342010-08-21 02:24:36 +0000648
649 unsigned Alignment =
650 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000651 if (!CGF.hasAggregateLLVMType(AllocType))
652 CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
Daniel Dunbar03816342010-08-21 02:24:36 +0000653 AllocType.isVolatileQualified(), Alignment,
654 AllocType);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000655 else if (AllocType->isAnyComplexType())
656 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
657 AllocType.isVolatileQualified());
John McCall7a626f62010-09-15 10:14:12 +0000658 else {
659 AggValueSlot Slot
660 = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
661 CGF.EmitAggExpr(Init, Slot);
662 }
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000663}
664
665void
666CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
667 llvm::Value *NewPtr,
668 llvm::Value *NumElements) {
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000669 // We have a POD type.
670 if (E->getNumConstructorArgs() == 0)
671 return;
672
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000673 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
674
675 // Create a temporary for the loop index and initialize it with 0.
676 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
677 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
678 Builder.CreateStore(Zero, IndexPtr);
679
680 // Start the loop with a block that tests the condition.
681 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
682 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
683
684 EmitBlock(CondBlock);
685
686 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
687
688 // Generate: if (loop-index < number-of-elements fall to the loop body,
689 // otherwise, go to the block after the for-loop.
690 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
691 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
692 // If the condition is true, execute the body.
693 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
694
695 EmitBlock(ForBody);
696
697 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
698 // Inside the loop body, emit the constructor call on the array element.
699 Counter = Builder.CreateLoad(IndexPtr);
700 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
701 "arrayidx");
702 StoreAnyExprIntoOneUnit(*this, E, Address);
703
704 EmitBlock(ContinueBlock);
705
706 // Emit the increment of the loop counter.
707 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
708 Counter = Builder.CreateLoad(IndexPtr);
709 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
710 Builder.CreateStore(NextVal, IndexPtr);
711
712 // Finally, branch back up to the condition for the next iteration.
713 EmitBranch(CondBlock);
714
715 // Emit the fall-through block.
716 EmitBlock(AfterFor, true);
717}
718
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000719static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
720 llvm::Value *NewPtr, llvm::Value *Size) {
John McCallad7c5c12011-02-08 08:22:06 +0000721 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyck705ba072011-01-19 01:58:38 +0000722 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000723 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyck705ba072011-01-19 01:58:38 +0000724 Alignment.getQuantity(), false);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000725}
726
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000727static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
728 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000729 llvm::Value *NumElements,
730 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson3a202f62009-11-24 18:43:52 +0000731 if (E->isArray()) {
Anders Carlssond040e6b2010-05-03 15:09:17 +0000732 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000733 bool RequiresZeroInitialization = false;
734 if (Ctor->getParent()->hasTrivialConstructor()) {
735 // If new expression did not specify value-initialization, then there
736 // is no initialization.
737 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
738 return;
739
John McCall614dbdc2010-08-22 21:01:12 +0000740 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000741 // Optimization: since zero initialization will just set the memory
742 // to all zeroes, generate a single memset to do it in one shot.
743 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
744 AllocSizeWithoutCookie);
745 return;
746 }
747
748 RequiresZeroInitialization = true;
749 }
750
751 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
752 E->constructor_arg_begin(),
753 E->constructor_arg_end(),
754 RequiresZeroInitialization);
Anders Carlssond040e6b2010-05-03 15:09:17 +0000755 return;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000756 } else if (E->getNumConstructorArgs() == 1 &&
757 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
758 // Optimization: since zero initialization will just set the memory
759 // to all zeroes, generate a single memset to do it in one shot.
760 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
761 AllocSizeWithoutCookie);
762 return;
763 } else {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000764 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
765 return;
766 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000767 }
Anders Carlsson3a202f62009-11-24 18:43:52 +0000768
769 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor747eb782010-07-08 06:14:04 +0000770 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
771 // direct initialization. C++ [dcl.init]p5 requires that we
772 // zero-initialize storage if there are no user-declared constructors.
773 if (E->hasInitializer() &&
774 !Ctor->getParent()->hasUserDeclaredConstructor() &&
775 !Ctor->getParent()->isEmpty())
776 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
777
Douglas Gregore1823702010-07-07 23:37:33 +0000778 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
779 NewPtr, E->constructor_arg_begin(),
780 E->constructor_arg_end());
Anders Carlsson3a202f62009-11-24 18:43:52 +0000781
782 return;
783 }
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000784 // We have a POD type.
785 if (E->getNumConstructorArgs() == 0)
786 return;
787
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000788 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000789}
790
John McCall824c2f52010-09-14 07:57:04 +0000791namespace {
792 /// A cleanup to call the given 'operator delete' function upon
793 /// abnormal exit from a new expression.
794 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
795 size_t NumPlacementArgs;
796 const FunctionDecl *OperatorDelete;
797 llvm::Value *Ptr;
798 llvm::Value *AllocSize;
799
800 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
801
802 public:
803 static size_t getExtraSize(size_t NumPlacementArgs) {
804 return NumPlacementArgs * sizeof(RValue);
805 }
806
807 CallDeleteDuringNew(size_t NumPlacementArgs,
808 const FunctionDecl *OperatorDelete,
809 llvm::Value *Ptr,
810 llvm::Value *AllocSize)
811 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
812 Ptr(Ptr), AllocSize(AllocSize) {}
813
814 void setPlacementArg(unsigned I, RValue Arg) {
815 assert(I < NumPlacementArgs && "index out of range");
816 getPlacementArgs()[I] = Arg;
817 }
818
819 void Emit(CodeGenFunction &CGF, bool IsForEH) {
820 const FunctionProtoType *FPT
821 = OperatorDelete->getType()->getAs<FunctionProtoType>();
822 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCalld441b1e2010-09-14 21:45:42 +0000823 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +0000824
825 CallArgList DeleteArgs;
826
827 // The first argument is always a void*.
828 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
829 DeleteArgs.push_back(std::make_pair(RValue::get(Ptr), *AI++));
830
831 // A member 'operator delete' can take an extra 'size_t' argument.
832 if (FPT->getNumArgs() == NumPlacementArgs + 2)
833 DeleteArgs.push_back(std::make_pair(RValue::get(AllocSize), *AI++));
834
835 // Pass the rest of the arguments, which must match exactly.
836 for (unsigned I = 0; I != NumPlacementArgs; ++I)
837 DeleteArgs.push_back(std::make_pair(getPlacementArgs()[I], *AI++));
838
839 // Call 'operator delete'.
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000840 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall824c2f52010-09-14 07:57:04 +0000841 CGF.CGM.GetAddrOfFunction(OperatorDelete),
842 ReturnValueSlot(), DeleteArgs, OperatorDelete);
843 }
844 };
John McCall7f9c92a2010-09-17 00:50:28 +0000845
846 /// A cleanup to call the given 'operator delete' function upon
847 /// abnormal exit from a new expression when the new expression is
848 /// conditional.
849 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
850 size_t NumPlacementArgs;
851 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +0000852 DominatingValue<RValue>::saved_type Ptr;
853 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +0000854
John McCallcb5f77f2011-01-28 10:53:53 +0000855 DominatingValue<RValue>::saved_type *getPlacementArgs() {
856 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +0000857 }
858
859 public:
860 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +0000861 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +0000862 }
863
864 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
865 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +0000866 DominatingValue<RValue>::saved_type Ptr,
867 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +0000868 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
869 Ptr(Ptr), AllocSize(AllocSize) {}
870
John McCallcb5f77f2011-01-28 10:53:53 +0000871 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +0000872 assert(I < NumPlacementArgs && "index out of range");
873 getPlacementArgs()[I] = Arg;
874 }
875
876 void Emit(CodeGenFunction &CGF, bool IsForEH) {
877 const FunctionProtoType *FPT
878 = OperatorDelete->getType()->getAs<FunctionProtoType>();
879 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
880 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
881
882 CallArgList DeleteArgs;
883
884 // The first argument is always a void*.
885 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
John McCallcb5f77f2011-01-28 10:53:53 +0000886 DeleteArgs.push_back(std::make_pair(Ptr.restore(CGF), *AI++));
John McCall7f9c92a2010-09-17 00:50:28 +0000887
888 // A member 'operator delete' can take an extra 'size_t' argument.
889 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +0000890 RValue RV = AllocSize.restore(CGF);
John McCall7f9c92a2010-09-17 00:50:28 +0000891 DeleteArgs.push_back(std::make_pair(RV, *AI++));
892 }
893
894 // Pass the rest of the arguments, which must match exactly.
895 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +0000896 RValue RV = getPlacementArgs()[I].restore(CGF);
John McCall7f9c92a2010-09-17 00:50:28 +0000897 DeleteArgs.push_back(std::make_pair(RV, *AI++));
898 }
899
900 // Call 'operator delete'.
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000901 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall7f9c92a2010-09-17 00:50:28 +0000902 CGF.CGM.GetAddrOfFunction(OperatorDelete),
903 ReturnValueSlot(), DeleteArgs, OperatorDelete);
904 }
905 };
906}
907
908/// Enter a cleanup to call 'operator delete' if the initializer in a
909/// new-expression throws.
910static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
911 const CXXNewExpr *E,
912 llvm::Value *NewPtr,
913 llvm::Value *AllocSize,
914 const CallArgList &NewArgs) {
915 // If we're not inside a conditional branch, then the cleanup will
916 // dominate and we can do the easier (and more efficient) thing.
917 if (!CGF.isInConditionalBranch()) {
918 CallDeleteDuringNew *Cleanup = CGF.EHStack
919 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
920 E->getNumPlacementArgs(),
921 E->getOperatorDelete(),
922 NewPtr, AllocSize);
923 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
924 Cleanup->setPlacementArg(I, NewArgs[I+1].first);
925
926 return;
927 }
928
929 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +0000930 DominatingValue<RValue>::saved_type SavedNewPtr =
931 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
932 DominatingValue<RValue>::saved_type SavedAllocSize =
933 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +0000934
935 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
936 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
937 E->getNumPlacementArgs(),
938 E->getOperatorDelete(),
939 SavedNewPtr,
940 SavedAllocSize);
941 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +0000942 Cleanup->setPlacementArg(I,
943 DominatingValue<RValue>::save(CGF, NewArgs[I+1].first));
John McCall7f9c92a2010-09-17 00:50:28 +0000944
945 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall824c2f52010-09-14 07:57:04 +0000946}
947
Anders Carlssoncc52f652009-09-22 22:53:17 +0000948llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +0000949 // The element type being allocated.
950 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +0000951
John McCall75f94982011-03-07 03:12:35 +0000952 // 1. Build a call to the allocation function.
953 FunctionDecl *allocator = E->getOperatorNew();
954 const FunctionProtoType *allocatorType =
955 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +0000956
John McCall75f94982011-03-07 03:12:35 +0000957 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +0000958
959 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +0000960 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +0000961
John McCall75f94982011-03-07 03:12:35 +0000962 llvm::Value *numElements = 0;
963 llvm::Value *allocSizeWithoutCookie = 0;
964 llvm::Value *allocSize =
965 EmitCXXNewAllocSize(getContext(), *this, E, numElements,
966 allocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000967
John McCall75f94982011-03-07 03:12:35 +0000968 allocatorArgs.push_back(std::make_pair(RValue::get(allocSize), sizeType));
Anders Carlssoncc52f652009-09-22 22:53:17 +0000969
970 // Emit the rest of the arguments.
971 // FIXME: Ideally, this should just use EmitCallArgs.
John McCall75f94982011-03-07 03:12:35 +0000972 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlssoncc52f652009-09-22 22:53:17 +0000973
974 // First, use the types from the function type.
975 // We start at 1 here because the first argument (the allocation size)
976 // has already been emitted.
John McCall75f94982011-03-07 03:12:35 +0000977 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
978 ++i, ++placementArg) {
979 QualType argType = allocatorType->getArgType(i);
Anders Carlssoncc52f652009-09-22 22:53:17 +0000980
John McCall75f94982011-03-07 03:12:35 +0000981 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
982 placementArg->getType()) &&
Anders Carlssoncc52f652009-09-22 22:53:17 +0000983 "type mismatch in call argument!");
984
John McCall32ea9692011-03-11 20:59:21 +0000985 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlssoncc52f652009-09-22 22:53:17 +0000986 }
987
988 // Either we've emitted all the call args, or we have a call to a
989 // variadic function.
John McCall75f94982011-03-07 03:12:35 +0000990 assert((placementArg == E->placement_arg_end() ||
991 allocatorType->isVariadic()) &&
992 "Extra arguments to non-variadic function!");
Anders Carlssoncc52f652009-09-22 22:53:17 +0000993
994 // If we still have any arguments, emit them using the type of the argument.
John McCall75f94982011-03-07 03:12:35 +0000995 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
996 placementArg != placementArgsEnd; ++placementArg) {
John McCall32ea9692011-03-11 20:59:21 +0000997 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlssoncc52f652009-09-22 22:53:17 +0000998 }
999
John McCall75f94982011-03-07 03:12:35 +00001000 // Emit the allocation call.
Anders Carlssoncc52f652009-09-22 22:53:17 +00001001 RValue RV =
John McCall75f94982011-03-07 03:12:35 +00001002 EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocatorType),
1003 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1004 allocatorArgs, allocator);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001005
John McCall75f94982011-03-07 03:12:35 +00001006 // Emit a null check on the allocation result if the allocation
1007 // function is allowed to return null (because it has a non-throwing
1008 // exception spec; for this part, we inline
1009 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1010 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001011 bool nullCheck = allocatorType->isNothrow(getContext()) &&
John McCall75f94982011-03-07 03:12:35 +00001012 !(allocType->isPODType() && !E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001013
John McCall75f94982011-03-07 03:12:35 +00001014 llvm::BasicBlock *nullCheckBB = 0;
1015 llvm::BasicBlock *contBB = 0;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001016
John McCall75f94982011-03-07 03:12:35 +00001017 llvm::Value *allocation = RV.getScalarVal();
1018 unsigned AS =
1019 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001020
John McCallf7dcf322011-03-07 01:52:56 +00001021 // The null-check means that the initializer is conditionally
1022 // evaluated.
1023 ConditionalEvaluation conditional(*this);
1024
John McCall75f94982011-03-07 03:12:35 +00001025 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001026 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001027
1028 nullCheckBB = Builder.GetInsertBlock();
1029 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1030 contBB = createBasicBlock("new.cont");
1031
1032 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1033 Builder.CreateCondBr(isNull, contBB, notNullBB);
1034 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001035 }
Ken Dyck3eb55cf2010-01-26 19:44:24 +00001036
John McCall75f94982011-03-07 03:12:35 +00001037 assert((allocSize == allocSizeWithoutCookie) ==
John McCall8ed55a52010-09-02 09:58:18 +00001038 CalculateCookiePadding(*this, E).isZero());
John McCall75f94982011-03-07 03:12:35 +00001039 if (allocSize != allocSizeWithoutCookie) {
John McCall8ed55a52010-09-02 09:58:18 +00001040 assert(E->isArray());
John McCall75f94982011-03-07 03:12:35 +00001041 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1042 numElements,
1043 E, allocType);
John McCall8ed55a52010-09-02 09:58:18 +00001044 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001045
John McCall824c2f52010-09-14 07:57:04 +00001046 // If there's an operator delete, enter a cleanup to call it if an
1047 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001048 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCall824c2f52010-09-14 07:57:04 +00001049 if (E->getOperatorDelete()) {
John McCall75f94982011-03-07 03:12:35 +00001050 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1051 operatorDeleteCleanup = EHStack.stable_begin();
John McCall824c2f52010-09-14 07:57:04 +00001052 }
1053
John McCall75f94982011-03-07 03:12:35 +00001054 const llvm::Type *elementPtrTy
1055 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1056 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001057
John McCall8ed55a52010-09-02 09:58:18 +00001058 if (E->isArray()) {
John McCall75f94982011-03-07 03:12:35 +00001059 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001060
1061 // NewPtr is a pointer to the base element type. If we're
1062 // allocating an array of arrays, we'll need to cast back to the
1063 // array pointer type.
John McCall75f94982011-03-07 03:12:35 +00001064 const llvm::Type *resultType = ConvertTypeForMem(E->getType());
1065 if (result->getType() != resultType)
1066 result = Builder.CreateBitCast(result, resultType);
John McCall8ed55a52010-09-02 09:58:18 +00001067 } else {
John McCall75f94982011-03-07 03:12:35 +00001068 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001069 }
John McCall824c2f52010-09-14 07:57:04 +00001070
1071 // Deactivate the 'operator delete' cleanup if we finished
1072 // initialization.
John McCall75f94982011-03-07 03:12:35 +00001073 if (operatorDeleteCleanup.isValid())
1074 DeactivateCleanupBlock(operatorDeleteCleanup);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001075
John McCall75f94982011-03-07 03:12:35 +00001076 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001077 conditional.end(*this);
1078
John McCall75f94982011-03-07 03:12:35 +00001079 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1080 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001081
Jay Foad20c0f022011-03-30 11:28:58 +00001082 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001083 PHI->addIncoming(result, notNullBB);
1084 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1085 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001086
John McCall75f94982011-03-07 03:12:35 +00001087 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001088 }
John McCall8ed55a52010-09-02 09:58:18 +00001089
John McCall75f94982011-03-07 03:12:35 +00001090 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001091}
1092
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001093void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1094 llvm::Value *Ptr,
1095 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001096 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1097
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001098 const FunctionProtoType *DeleteFTy =
1099 DeleteFD->getType()->getAs<FunctionProtoType>();
1100
1101 CallArgList DeleteArgs;
1102
Anders Carlsson21122cf2009-12-13 20:04:38 +00001103 // Check if we need to pass the size to the delete operator.
1104 llvm::Value *Size = 0;
1105 QualType SizeTy;
1106 if (DeleteFTy->getNumArgs() == 2) {
1107 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001108 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1109 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1110 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001111 }
1112
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001113 QualType ArgTy = DeleteFTy->getArgType(0);
1114 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1115 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
1116
Anders Carlsson21122cf2009-12-13 20:04:38 +00001117 if (Size)
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001118 DeleteArgs.push_back(std::make_pair(RValue::get(Size), SizeTy));
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001119
1120 // Emit the call to delete.
Tilmann Scheller99cc30c2011-03-02 21:36:49 +00001121 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001122 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001123 DeleteArgs, DeleteFD);
1124}
1125
John McCall8ed55a52010-09-02 09:58:18 +00001126namespace {
1127 /// Calls the given 'operator delete' on a single object.
1128 struct CallObjectDelete : EHScopeStack::Cleanup {
1129 llvm::Value *Ptr;
1130 const FunctionDecl *OperatorDelete;
1131 QualType ElementType;
1132
1133 CallObjectDelete(llvm::Value *Ptr,
1134 const FunctionDecl *OperatorDelete,
1135 QualType ElementType)
1136 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1137
1138 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1139 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1140 }
1141 };
1142}
1143
1144/// Emit the code for deleting a single object.
1145static void EmitObjectDelete(CodeGenFunction &CGF,
1146 const FunctionDecl *OperatorDelete,
1147 llvm::Value *Ptr,
1148 QualType ElementType) {
1149 // Find the destructor for the type, if applicable. If the
1150 // destructor is virtual, we'll just emit the vcall and return.
1151 const CXXDestructorDecl *Dtor = 0;
1152 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1153 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1154 if (!RD->hasTrivialDestructor()) {
1155 Dtor = RD->getDestructor();
1156
1157 if (Dtor->isVirtual()) {
1158 const llvm::Type *Ty =
John McCall0d635f52010-09-03 01:26:39 +00001159 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1160 Dtor_Complete),
John McCall8ed55a52010-09-02 09:58:18 +00001161 /*isVariadic=*/false);
1162
1163 llvm::Value *Callee
1164 = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
1165 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1166 0, 0);
1167
1168 // The dtor took care of deleting the object.
1169 return;
1170 }
1171 }
1172 }
1173
1174 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001175 // This doesn't have to a conditional cleanup because we're going
1176 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001177 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1178 Ptr, OperatorDelete, ElementType);
1179
1180 if (Dtor)
1181 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1182 /*ForVirtualBase=*/false, Ptr);
1183
1184 CGF.PopCleanupBlock();
1185}
1186
1187namespace {
1188 /// Calls the given 'operator delete' on an array of objects.
1189 struct CallArrayDelete : EHScopeStack::Cleanup {
1190 llvm::Value *Ptr;
1191 const FunctionDecl *OperatorDelete;
1192 llvm::Value *NumElements;
1193 QualType ElementType;
1194 CharUnits CookieSize;
1195
1196 CallArrayDelete(llvm::Value *Ptr,
1197 const FunctionDecl *OperatorDelete,
1198 llvm::Value *NumElements,
1199 QualType ElementType,
1200 CharUnits CookieSize)
1201 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1202 ElementType(ElementType), CookieSize(CookieSize) {}
1203
1204 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1205 const FunctionProtoType *DeleteFTy =
1206 OperatorDelete->getType()->getAs<FunctionProtoType>();
1207 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1208
1209 CallArgList Args;
1210
1211 // Pass the pointer as the first argument.
1212 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1213 llvm::Value *DeletePtr
1214 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
1215 Args.push_back(std::make_pair(RValue::get(DeletePtr), VoidPtrTy));
1216
1217 // Pass the original requested size as the second argument.
1218 if (DeleteFTy->getNumArgs() == 2) {
1219 QualType size_t = DeleteFTy->getArgType(1);
1220 const llvm::IntegerType *SizeTy
1221 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1222
1223 CharUnits ElementTypeSize =
1224 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1225
1226 // The size of an element, multiplied by the number of elements.
1227 llvm::Value *Size
1228 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1229 Size = CGF.Builder.CreateMul(Size, NumElements);
1230
1231 // Plus the size of the cookie if applicable.
1232 if (!CookieSize.isZero()) {
1233 llvm::Value *CookieSizeV
1234 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1235 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1236 }
1237
1238 Args.push_back(std::make_pair(RValue::get(Size), size_t));
1239 }
1240
1241 // Emit the call to delete.
Tilmann Scheller99cc30c2011-03-02 21:36:49 +00001242 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
John McCall8ed55a52010-09-02 09:58:18 +00001243 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1244 ReturnValueSlot(), Args, OperatorDelete);
1245 }
1246 };
1247}
1248
1249/// Emit the code for deleting an array of objects.
1250static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001251 const CXXDeleteExpr *E,
John McCall8ed55a52010-09-02 09:58:18 +00001252 llvm::Value *Ptr,
1253 QualType ElementType) {
1254 llvm::Value *NumElements = 0;
1255 llvm::Value *AllocatedPtr = 0;
1256 CharUnits CookieSize;
John McCall284c48f2011-01-27 09:37:56 +00001257 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, E, ElementType,
John McCall8ed55a52010-09-02 09:58:18 +00001258 NumElements, AllocatedPtr, CookieSize);
1259
1260 assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
1261
1262 // Make sure that we call delete even if one of the dtors throws.
John McCall284c48f2011-01-27 09:37:56 +00001263 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001264 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1265 AllocatedPtr, OperatorDelete,
1266 NumElements, ElementType,
1267 CookieSize);
1268
1269 if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
1270 if (!RD->hasTrivialDestructor()) {
1271 assert(NumElements && "ReadArrayCookie didn't find element count"
1272 " for a class with destructor");
1273 CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
1274 }
1275 }
1276
1277 CGF.PopCleanupBlock();
1278}
1279
Anders Carlssoncc52f652009-09-22 22:53:17 +00001280void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +00001281
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001282 // Get at the argument before we performed the implicit conversion
1283 // to void*.
1284 const Expr *Arg = E->getArgument();
1285 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00001286 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001287 ICE->getType()->isVoidPointerType())
1288 Arg = ICE->getSubExpr();
Douglas Gregore364e7b2009-10-01 05:49:51 +00001289 else
1290 break;
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001291 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001292
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001293 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001294
1295 // Null check the pointer.
1296 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1297 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1298
Anders Carlsson98981b12011-04-11 00:30:07 +00001299 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001300
1301 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1302 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001303
John McCall8ed55a52010-09-02 09:58:18 +00001304 // We might be deleting a pointer to array. If so, GEP down to the
1305 // first non-array element.
1306 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1307 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1308 if (DeleteTy->isConstantArrayType()) {
1309 llvm::Value *Zero = Builder.getInt32(0);
1310 llvm::SmallVector<llvm::Value*,8> GEP;
1311
1312 GEP.push_back(Zero); // point at the outermost array
1313
1314 // For each layer of array type we're pointing at:
1315 while (const ConstantArrayType *Arr
1316 = getContext().getAsConstantArrayType(DeleteTy)) {
1317 // 1. Unpeel the array type.
1318 DeleteTy = Arr->getElementType();
1319
1320 // 2. GEP to the first element of the array.
1321 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001322 }
John McCall8ed55a52010-09-02 09:58:18 +00001323
1324 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001325 }
1326
Douglas Gregor04f36212010-09-02 17:38:50 +00001327 assert(ConvertTypeForMem(DeleteTy) ==
1328 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001329
1330 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001331 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001332 } else {
1333 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1334 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001335
Anders Carlssoncc52f652009-09-22 22:53:17 +00001336 EmitBlock(DeleteEnd);
1337}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001338
John McCalle4df6c82011-01-28 08:37:24 +00001339llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Mike Stumpc9b231c2009-11-15 08:09:41 +00001340 QualType Ty = E->getType();
1341 const llvm::Type *LTy = ConvertType(Ty)->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001342
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001343 if (E->isTypeOperand()) {
1344 llvm::Constant *TypeInfo =
1345 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
1346 return Builder.CreateBitCast(TypeInfo, LTy);
1347 }
1348
Mike Stumpc9b231c2009-11-15 08:09:41 +00001349 Expr *subE = E->getExprOperand();
Mike Stump6fdfea62009-11-17 22:33:00 +00001350 Ty = subE->getType();
1351 CanQualType CanTy = CGM.getContext().getCanonicalType(Ty);
1352 Ty = CanTy.getUnqualifiedType().getNonReferenceType();
Mike Stumpc9b231c2009-11-15 08:09:41 +00001353 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1354 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1355 if (RD->isPolymorphic()) {
1356 // FIXME: if subE is an lvalue do
1357 LValue Obj = EmitLValue(subE);
1358 llvm::Value *This = Obj.getAddress();
Mike Stump1bf924b2009-11-15 16:52:53 +00001359 // We need to do a zero check for *p, unless it has NonNullAttr.
1360 // FIXME: PointerType->hasAttr<NonNullAttr>()
1361 bool CanBeZero = false;
Mike Stumpc2c03342009-11-17 00:45:21 +00001362 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(subE->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +00001363 if (UO->getOpcode() == UO_Deref)
Mike Stump1bf924b2009-11-15 16:52:53 +00001364 CanBeZero = true;
1365 if (CanBeZero) {
1366 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
1367 llvm::BasicBlock *ZeroBlock = createBasicBlock();
1368
Dan Gohman8fc50c22010-10-26 18:44:08 +00001369 llvm::Value *Zero = llvm::Constant::getNullValue(This->getType());
1370 Builder.CreateCondBr(Builder.CreateICmpNE(This, Zero),
Mike Stump1bf924b2009-11-15 16:52:53 +00001371 NonZeroBlock, ZeroBlock);
1372 EmitBlock(ZeroBlock);
1373 /// Call __cxa_bad_typeid
John McCallad7c5c12011-02-08 08:22:06 +00001374 const llvm::Type *ResultType = llvm::Type::getVoidTy(getLLVMContext());
Mike Stump1bf924b2009-11-15 16:52:53 +00001375 const llvm::FunctionType *FTy;
1376 FTy = llvm::FunctionType::get(ResultType, false);
1377 llvm::Value *F = CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
Mike Stump65511702009-11-16 06:50:58 +00001378 Builder.CreateCall(F)->setDoesNotReturn();
Mike Stump1bf924b2009-11-15 16:52:53 +00001379 Builder.CreateUnreachable();
1380 EmitBlock(NonZeroBlock);
1381 }
Dan Gohman8fc50c22010-10-26 18:44:08 +00001382 llvm::Value *V = GetVTablePtr(This, LTy->getPointerTo());
Mike Stumpc9b231c2009-11-15 08:09:41 +00001383 V = Builder.CreateConstInBoundsGEP1_64(V, -1ULL);
1384 V = Builder.CreateLoad(V);
1385 return V;
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001386 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001387 }
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001388 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(Ty), LTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001389}
Mike Stump65511702009-11-16 06:50:58 +00001390
1391llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *V,
1392 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001393 QualType SrcTy = DCE->getSubExpr()->getType();
1394 QualType DestTy = DCE->getTypeAsWritten();
1395 QualType InnerType = DestTy->getPointeeType();
1396
Mike Stump65511702009-11-16 06:50:58 +00001397 const llvm::Type *LTy = ConvertType(DCE->getType());
Mike Stump6ca0e212009-11-16 22:52:20 +00001398
Mike Stump65511702009-11-16 06:50:58 +00001399 bool CanBeZero = false;
Mike Stump65511702009-11-16 06:50:58 +00001400 bool ToVoid = false;
Mike Stump6ca0e212009-11-16 22:52:20 +00001401 bool ThrowOnBad = false;
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001402 if (DestTy->isPointerType()) {
Mike Stump65511702009-11-16 06:50:58 +00001403 // FIXME: if PointerType->hasAttr<NonNullAttr>(), we don't set this
1404 CanBeZero = true;
1405 if (InnerType->isVoidType())
1406 ToVoid = true;
1407 } else {
1408 LTy = LTy->getPointerTo();
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001409
1410 // FIXME: What if exceptions are disabled?
Mike Stump65511702009-11-16 06:50:58 +00001411 ThrowOnBad = true;
1412 }
1413
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001414 if (SrcTy->isPointerType() || SrcTy->isReferenceType())
1415 SrcTy = SrcTy->getPointeeType();
1416 SrcTy = SrcTy.getUnqualifiedType();
1417
Anders Carlsson0087bc82009-12-18 14:55:04 +00001418 if (DestTy->isPointerType() || DestTy->isReferenceType())
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001419 DestTy = DestTy->getPointeeType();
1420 DestTy = DestTy.getUnqualifiedType();
Mike Stump65511702009-11-16 06:50:58 +00001421
Mike Stump65511702009-11-16 06:50:58 +00001422 llvm::BasicBlock *ContBlock = createBasicBlock();
1423 llvm::BasicBlock *NullBlock = 0;
1424 llvm::BasicBlock *NonZeroBlock = 0;
1425 if (CanBeZero) {
1426 NonZeroBlock = createBasicBlock();
1427 NullBlock = createBasicBlock();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001428 Builder.CreateCondBr(Builder.CreateIsNotNull(V), NonZeroBlock, NullBlock);
Mike Stump65511702009-11-16 06:50:58 +00001429 EmitBlock(NonZeroBlock);
1430 }
1431
Mike Stump65511702009-11-16 06:50:58 +00001432 llvm::BasicBlock *BadCastBlock = 0;
Mike Stump65511702009-11-16 06:50:58 +00001433
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001434 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
Mike Stump6ca0e212009-11-16 22:52:20 +00001435
1436 // See if this is a dynamic_cast(void*)
1437 if (ToVoid) {
1438 llvm::Value *This = V;
Dan Gohman8fc50c22010-10-26 18:44:08 +00001439 V = GetVTablePtr(This, PtrDiffTy->getPointerTo());
Mike Stump6ca0e212009-11-16 22:52:20 +00001440 V = Builder.CreateConstInBoundsGEP1_64(V, -2ULL);
1441 V = Builder.CreateLoad(V, "offset to top");
John McCallad7c5c12011-02-08 08:22:06 +00001442 This = EmitCastToVoidPtr(This);
Mike Stump6ca0e212009-11-16 22:52:20 +00001443 V = Builder.CreateInBoundsGEP(This, V);
1444 V = Builder.CreateBitCast(V, LTy);
1445 } else {
1446 /// Call __dynamic_cast
John McCallad7c5c12011-02-08 08:22:06 +00001447 const llvm::Type *ResultType = Int8PtrTy;
Mike Stump6ca0e212009-11-16 22:52:20 +00001448 const llvm::FunctionType *FTy;
1449 std::vector<const llvm::Type*> ArgTys;
John McCallad7c5c12011-02-08 08:22:06 +00001450 ArgTys.push_back(Int8PtrTy);
1451 ArgTys.push_back(Int8PtrTy);
1452 ArgTys.push_back(Int8PtrTy);
Mike Stump6ca0e212009-11-16 22:52:20 +00001453 ArgTys.push_back(PtrDiffTy);
1454 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump6ca0e212009-11-16 22:52:20 +00001455
1456 // FIXME: Calculate better hint.
1457 llvm::Value *hint = llvm::ConstantInt::get(PtrDiffTy, -1ULL);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001458
1459 assert(SrcTy->isRecordType() && "Src type must be record type!");
1460 assert(DestTy->isRecordType() && "Dest type must be record type!");
1461
Douglas Gregor247894b2009-12-23 22:04:40 +00001462 llvm::Value *SrcArg
1463 = CGM.GetAddrOfRTTIDescriptor(SrcTy.getUnqualifiedType());
1464 llvm::Value *DestArg
1465 = CGM.GetAddrOfRTTIDescriptor(DestTy.getUnqualifiedType());
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001466
John McCallad7c5c12011-02-08 08:22:06 +00001467 V = Builder.CreateBitCast(V, Int8PtrTy);
Mike Stump6ca0e212009-11-16 22:52:20 +00001468 V = Builder.CreateCall4(CGM.CreateRuntimeFunction(FTy, "__dynamic_cast"),
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001469 V, SrcArg, DestArg, hint);
Mike Stump6ca0e212009-11-16 22:52:20 +00001470 V = Builder.CreateBitCast(V, LTy);
1471
1472 if (ThrowOnBad) {
1473 BadCastBlock = createBasicBlock();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001474 Builder.CreateCondBr(Builder.CreateIsNotNull(V), ContBlock, BadCastBlock);
Mike Stump6ca0e212009-11-16 22:52:20 +00001475 EmitBlock(BadCastBlock);
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001476 /// Invoke __cxa_bad_cast
John McCallad7c5c12011-02-08 08:22:06 +00001477 ResultType = llvm::Type::getVoidTy(getLLVMContext());
Mike Stump6ca0e212009-11-16 22:52:20 +00001478 const llvm::FunctionType *FBadTy;
Mike Stump3afea1d2009-11-17 03:01:03 +00001479 FBadTy = llvm::FunctionType::get(ResultType, false);
Mike Stump6ca0e212009-11-16 22:52:20 +00001480 llvm::Value *F = CGM.CreateRuntimeFunction(FBadTy, "__cxa_bad_cast");
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001481 if (llvm::BasicBlock *InvokeDest = getInvokeDest()) {
1482 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
1483 Builder.CreateInvoke(F, Cont, InvokeDest)->setDoesNotReturn();
1484 EmitBlock(Cont);
1485 } else {
1486 // FIXME: Does this ever make sense?
1487 Builder.CreateCall(F)->setDoesNotReturn();
1488 }
Mike Stumpe8cdcc92009-11-17 00:08:50 +00001489 Builder.CreateUnreachable();
Mike Stump6ca0e212009-11-16 22:52:20 +00001490 }
Mike Stump65511702009-11-16 06:50:58 +00001491 }
1492
1493 if (CanBeZero) {
1494 Builder.CreateBr(ContBlock);
1495 EmitBlock(NullBlock);
1496 Builder.CreateBr(ContBlock);
1497 }
1498 EmitBlock(ContBlock);
1499 if (CanBeZero) {
Jay Foad20c0f022011-03-30 11:28:58 +00001500 llvm::PHINode *PHI = Builder.CreatePHI(LTy, 2);
Mike Stump65511702009-11-16 06:50:58 +00001501 PHI->addIncoming(V, NonZeroBlock);
1502 PHI->addIncoming(llvm::Constant::getNullValue(LTy), NullBlock);
Mike Stump65511702009-11-16 06:50:58 +00001503 V = PHI;
1504 }
1505
1506 return V;
1507}