blob: 137c54ab1ed95c4c14b877cc32a868aa0fef2b34 [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();
51 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
Rafael Espindolac50c27c2010-03-30 20:24:48 +000052 FPT->getExtInfo()),
53 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000054}
55
56/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
57/// expr can be devirtualized.
Anders Carlssona7911fa2010-10-27 13:28:46 +000058static bool canDevirtualizeMemberFunctionCalls(const Expr *Base,
59 const CXXMethodDecl *MD) {
60
61 // If the member function has the "final" attribute, we know that it can't be
Anders Carlssonb00c2142010-10-27 13:34:43 +000062 // overridden and can therefore devirtualize it.
Anders Carlssona7911fa2010-10-27 13:28:46 +000063 if (MD->hasAttr<FinalAttr>())
64 return true;
Anders Carlssonb00c2142010-10-27 13:34:43 +000065
66 // Similarly, if the class itself has the "final" attribute it can't be
67 // overridden and we can therefore devirtualize the member function call.
68 if (MD->getParent()->hasAttr<FinalAttr>())
69 return true;
70
Anders Carlsson27da15b2010-01-01 20:29:01 +000071 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
72 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
73 // This is a record decl. We know the type and can devirtualize it.
74 return VD->getType()->isRecordType();
75 }
76
77 return false;
78 }
79
80 // We can always devirtualize calls on temporary object expressions.
Eli Friedmana6824272010-01-31 20:58:15 +000081 if (isa<CXXConstructExpr>(Base))
Anders Carlsson27da15b2010-01-01 20:29:01 +000082 return true;
83
84 // And calls on bound temporaries.
85 if (isa<CXXBindTemporaryExpr>(Base))
86 return true;
87
88 // Check if this is a call expr that returns a record type.
89 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
90 return CE->getCallReturnType()->isRecordType();
Anders Carlssona7911fa2010-10-27 13:28:46 +000091
Anders Carlsson27da15b2010-01-01 20:29:01 +000092 // We can't devirtualize the call.
93 return false;
94}
95
96RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
97 ReturnValueSlot ReturnValue) {
98 if (isa<BinaryOperator>(CE->getCallee()->IgnoreParens()))
99 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
100
101 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()->IgnoreParens());
102 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
103
Devang Patel91bbb552010-09-30 19:05:55 +0000104 CGDebugInfo *DI = getDebugInfo();
Devang Patel401c9162010-10-22 18:56:27 +0000105 if (DI && CGM.getCodeGenOpts().LimitDebugInfo
106 && !isa<CallExpr>(ME->getBase())) {
Devang Patel91bbb552010-09-30 19:05:55 +0000107 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
108 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
109 DI->getOrCreateRecordType(PTy->getPointeeType(),
110 MD->getParent()->getLocation());
111 }
112 }
113
Anders Carlsson27da15b2010-01-01 20:29:01 +0000114 if (MD->isStatic()) {
115 // The method is static, emit it as we would a regular call.
116 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
117 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
118 ReturnValue, CE->arg_begin(), CE->arg_end());
119 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000120
John McCall0d635f52010-09-03 01:26:39 +0000121 // Compute the object pointer.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000122 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000123 if (ME->isArrow())
124 This = EmitScalarExpr(ME->getBase());
125 else {
126 LValue BaseLV = EmitLValue(ME->getBase());
Fariborz Jahanianf93ac892010-09-10 18:56:35 +0000127 if (BaseLV.isPropertyRef() || BaseLV.isKVCRef()) {
128 QualType QT = ME->getBase()->getType();
129 RValue RV =
130 BaseLV.isPropertyRef() ? EmitLoadOfPropertyRefLValue(BaseLV, QT)
131 : EmitLoadOfKVCRefLValue(BaseLV, QT);
132 This = RV.isScalar() ? RV.getScalarVal() : RV.getAggregateAddr();
133 }
134 else
135 This = BaseLV.getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000136 }
137
John McCall0d635f52010-09-03 01:26:39 +0000138 if (MD->isTrivial()) {
139 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
140
Douglas Gregorec3bec02010-09-27 22:37:28 +0000141 assert(MD->isCopyAssignmentOperator() && "unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000142 // We don't like to generate the trivial copy assignment operator when
143 // it isn't necessary; just produce the proper effect here.
144 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
145 EmitAggregateCopy(This, RHS, CE->getType());
146 return RValue::get(This);
147 }
148
John McCall0d635f52010-09-03 01:26:39 +0000149 // Compute the function type we're calling.
150 const CGFunctionInfo &FInfo =
151 (isa<CXXDestructorDecl>(MD)
152 ? CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
153 Dtor_Complete)
154 : CGM.getTypes().getFunctionInfo(MD));
155
156 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
157 const llvm::Type *Ty
158 = CGM.getTypes().GetFunctionType(FInfo, FPT->isVariadic());
159
Anders Carlsson27da15b2010-01-01 20:29:01 +0000160 // C++ [class.virtual]p12:
161 // Explicit qualification with the scope operator (5.1) suppresses the
162 // virtual call mechanism.
163 //
164 // We also don't emit a virtual call if the base expression has a record type
165 // because then we know what the type is.
John McCall0d635f52010-09-03 01:26:39 +0000166 bool UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
Anders Carlssona7911fa2010-10-27 13:28:46 +0000167 && !canDevirtualizeMemberFunctionCalls(ME->getBase(), MD);
John McCall0d635f52010-09-03 01:26:39 +0000168
Anders Carlsson27da15b2010-01-01 20:29:01 +0000169 llvm::Value *Callee;
John McCall0d635f52010-09-03 01:26:39 +0000170 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
171 if (UseVirtualCall) {
172 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000173 } else {
John McCall0d635f52010-09-03 01:26:39 +0000174 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000175 }
John McCall0d635f52010-09-03 01:26:39 +0000176 } else if (UseVirtualCall) {
Anders Carlsson27da15b2010-01-01 20:29:01 +0000177 Callee = BuildVirtualCall(MD, This, Ty);
178 } else {
179 Callee = CGM.GetAddrOfFunction(MD, Ty);
180 }
181
Anders Carlssone36a6b32010-01-02 01:01:18 +0000182 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000183 CE->arg_begin(), CE->arg_end());
184}
185
186RValue
187CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
188 ReturnValueSlot ReturnValue) {
189 const BinaryOperator *BO =
190 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
191 const Expr *BaseExpr = BO->getLHS();
192 const Expr *MemFnExpr = BO->getRHS();
193
194 const MemberPointerType *MPT =
195 MemFnExpr->getType()->getAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000196
Anders Carlsson27da15b2010-01-01 20:29:01 +0000197 const FunctionProtoType *FPT =
198 MPT->getPointeeType()->getAs<FunctionProtoType>();
199 const CXXRecordDecl *RD =
200 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
201
Anders Carlsson27da15b2010-01-01 20:29:01 +0000202 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000203 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000204
205 // Emit the 'this' pointer.
206 llvm::Value *This;
207
John McCalle3027922010-08-25 11:45:40 +0000208 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000209 This = EmitScalarExpr(BaseExpr);
210 else
211 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000212
John McCall475999d2010-08-22 00:05:51 +0000213 // Ask the ABI to load the callee. Note that This is modified.
214 llvm::Value *Callee =
215 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(CGF, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000216
Anders Carlsson27da15b2010-01-01 20:29:01 +0000217 CallArgList Args;
218
219 QualType ThisType =
220 getContext().getPointerType(getContext().getTagDeclType(RD));
221
222 // Push the this ptr.
223 Args.push_back(std::make_pair(RValue::get(This), ThisType));
224
225 // And the rest of the call args
226 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCallab26cfa2010-02-05 21:31:56 +0000227 const FunctionType *BO_FPT = BO->getType()->getAs<FunctionProtoType>();
228 return EmitCall(CGM.getTypes().getFunctionInfo(Args, BO_FPT), Callee,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000229 ReturnValue, Args);
230}
231
232RValue
233CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
234 const CXXMethodDecl *MD,
235 ReturnValueSlot ReturnValue) {
236 assert(MD->isInstance() &&
237 "Trying to emit a member call expr on a static method!");
Douglas Gregorec3bec02010-09-27 22:37:28 +0000238 if (MD->isCopyAssignmentOperator()) {
Anders Carlsson27da15b2010-01-01 20:29:01 +0000239 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
240 if (ClassDecl->hasTrivialCopyAssignment()) {
241 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
242 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
Fariborz Jahanian43a40f92010-05-10 22:57:35 +0000243 LValue LV = EmitLValue(E->getArg(0));
244 llvm::Value *This;
Fariborz Jahanian61a31242010-09-01 19:36:41 +0000245 if (LV.isPropertyRef() || LV.isKVCRef()) {
John McCall7a626f62010-09-15 10:14:12 +0000246 AggValueSlot Slot = CreateAggTemp(E->getArg(1)->getType());
247 EmitAggExpr(E->getArg(1), Slot);
Fariborz Jahanian61a31242010-09-01 19:36:41 +0000248 if (LV.isPropertyRef())
John McCall7a626f62010-09-15 10:14:12 +0000249 EmitObjCPropertySet(LV.getPropertyRefExpr(), Slot.asRValue());
Fariborz Jahanian61a31242010-09-01 19:36:41 +0000250 else
John McCall7a626f62010-09-15 10:14:12 +0000251 EmitObjCPropertySet(LV.getKVCRefExpr(), Slot.asRValue());
Fariborz Jahaniane1b45a52010-05-15 23:05:52 +0000252 return RValue::getAggregate(0, false);
Fariborz Jahanian43a40f92010-05-10 22:57:35 +0000253 }
254 else
255 This = LV.getAddress();
256
Anders Carlsson27da15b2010-01-01 20:29:01 +0000257 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
258 QualType Ty = E->getType();
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000259 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000260 return RValue::get(This);
261 }
262 }
263
264 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
265 const llvm::Type *Ty =
266 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
267 FPT->isVariadic());
Fariborz Jahanianfdf474b2010-05-07 18:56:13 +0000268 LValue LV = EmitLValue(E->getArg(0));
269 llvm::Value *This;
Fariborz Jahanian61a31242010-09-01 19:36:41 +0000270 if (LV.isPropertyRef() || LV.isKVCRef()) {
271 QualType QT = E->getArg(0)->getType();
272 RValue RV =
273 LV.isPropertyRef() ? EmitLoadOfPropertyRefLValue(LV, QT)
274 : EmitLoadOfKVCRefLValue(LV, QT);
Fariborz Jahanian6855ba22010-05-20 16:46:55 +0000275 assert (!RV.isScalar() && "EmitCXXOperatorMemberCallExpr");
276 This = RV.getAggregateAddr();
Fariborz Jahanianfdf474b2010-05-07 18:56:13 +0000277 }
278 else
279 This = LV.getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000280
281 llvm::Value *Callee;
Anders Carlssona7911fa2010-10-27 13:28:46 +0000282 if (MD->isVirtual() && !canDevirtualizeMemberFunctionCalls(E->getArg(0), MD))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000283 Callee = BuildVirtualCall(MD, This, Ty);
284 else
285 Callee = CGM.GetAddrOfFunction(MD, Ty);
286
Anders Carlssone36a6b32010-01-02 01:01:18 +0000287 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000288 E->arg_begin() + 1, E->arg_end());
289}
290
291void
John McCall7a626f62010-09-15 10:14:12 +0000292CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
293 AggValueSlot Dest) {
294 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000295 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000296
297 // If we require zero initialization before (or instead of) calling the
298 // constructor, as can be the case with a non-user-provided default
299 // constructor, emit the zero initialization now.
300 if (E->requiresZeroInitialization())
John McCall7a626f62010-09-15 10:14:12 +0000301 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor630c76e2010-08-22 16:15:35 +0000302
303 // If this is a call to a trivial default constructor, do nothing.
304 if (CD->isTrivial() && CD->isDefaultConstructor())
305 return;
306
John McCall8ea46b62010-09-18 00:58:34 +0000307 // Elide the constructor if we're constructing from a temporary.
308 // The temporary check is required because Sema sets this on NRVO
309 // returns.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000310 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000311 assert(getContext().hasSameUnqualifiedType(E->getType(),
312 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000313 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
314 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000315 return;
316 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000317 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000318
319 const ConstantArrayType *Array
320 = getContext().getAsConstantArrayType(E->getType());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000321 if (Array) {
322 QualType BaseElementTy = getContext().getBaseElementType(Array);
323 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
324 BasePtr = llvm::PointerType::getUnqual(BasePtr);
325 llvm::Value *BaseAddrPtr =
John McCall7a626f62010-09-15 10:14:12 +0000326 Builder.CreateBitCast(Dest.getAddr(), BasePtr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000327
328 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
329 E->arg_begin(), E->arg_end());
330 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000331 else {
332 CXXCtorType Type =
333 (E->getConstructionKind() == CXXConstructExpr::CK_Complete)
334 ? Ctor_Complete : Ctor_Base;
335 bool ForVirtualBase =
336 E->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
337
Anders Carlsson27da15b2010-01-01 20:29:01 +0000338 // Call the constructor.
John McCall7a626f62010-09-15 10:14:12 +0000339 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000340 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000341 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000342}
343
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000344void
345CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
346 llvm::Value *Src,
347 const BlockDeclRefExpr *BDRE) {
348 const Expr *Exp = BDRE->getCopyConstructorExpr();
349 if (const CXXExprWithTemporaries *E = dyn_cast<CXXExprWithTemporaries>(Exp))
350 Exp = E->getSubExpr();
351 assert(isa<CXXConstructExpr>(Exp) &&
352 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
353 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
354 const CXXConstructorDecl *CD = E->getConstructor();
355 RunCleanupsScope Scope(*this);
356
357 // If we require zero initialization before (or instead of) calling the
358 // constructor, as can be the case with a non-user-provided default
359 // constructor, emit the zero initialization now.
360 // FIXME. Do I still need this for a copy ctor synthesis?
361 if (E->requiresZeroInitialization())
362 EmitNullInitialization(Dest, E->getType());
363
364 const ConstantArrayType *Array
365 = getContext().getAsConstantArrayType(E->getType());
366 assert (!Array && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
367 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
368 E->arg_begin(), E->arg_end());
369}
370
John McCallaa4149a2010-08-23 01:17:59 +0000371/// Check whether the given operator new[] is the global placement
372/// operator new[].
373static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
374 const FunctionDecl *Fn) {
375 // Must be in global scope. Note that allocation functions can't be
376 // declared in namespaces.
Sebastian Redl50c68252010-08-31 00:36:30 +0000377 if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
John McCallaa4149a2010-08-23 01:17:59 +0000378 return false;
379
380 // Signature must be void *operator new[](size_t, void*).
381 // The size_t is common to all operator new[]s.
382 if (Fn->getNumParams() != 2)
383 return false;
384
385 CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
386 return (ParamType == Ctx.VoidPtrTy);
387}
388
John McCall8ed55a52010-09-02 09:58:18 +0000389static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
390 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000391 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000392 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000393
Anders Carlsson399f4992009-12-13 20:34:34 +0000394 // No cookie is required if the new operator being used is
395 // ::operator new[](size_t, void*).
396 const FunctionDecl *OperatorNew = E->getOperatorNew();
John McCall8ed55a52010-09-02 09:58:18 +0000397 if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
John McCallaa4149a2010-08-23 01:17:59 +0000398 return CharUnits::Zero();
399
John McCall8ed55a52010-09-02 09:58:18 +0000400 return CGF.CGM.getCXXABI().GetArrayCookieSize(E->getAllocatedType());
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000401}
402
Fariborz Jahanian47b46292010-03-24 16:57:01 +0000403static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
Chris Lattnercb46bdc2010-07-20 18:45:57 +0000404 CodeGenFunction &CGF,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000405 const CXXNewExpr *E,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000406 llvm::Value *&NumElements,
407 llvm::Value *&SizeWithoutCookie) {
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000408 QualType ElemType = E->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000409
410 const llvm::IntegerType *SizeTy =
411 cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000412
John McCall8ed55a52010-09-02 09:58:18 +0000413 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
414
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000415 if (!E->isArray()) {
416 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
417 return SizeWithoutCookie;
418 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000419
John McCall8ed55a52010-09-02 09:58:18 +0000420 // Figure out the cookie size.
421 CharUnits CookieSize = CalculateCookiePadding(CGF, E);
422
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000423 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000424 // We multiply the size of all dimensions for NumElements.
425 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000426 NumElements = CGF.EmitScalarExpr(E->getArraySize());
John McCall8ed55a52010-09-02 09:58:18 +0000427 assert(NumElements->getType() == SizeTy && "element count not a size_t");
428
429 uint64_t ArraySizeMultiplier = 1;
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000430 while (const ConstantArrayType *CAT
431 = CGF.getContext().getAsConstantArrayType(ElemType)) {
432 ElemType = CAT->getElementType();
John McCall8ed55a52010-09-02 09:58:18 +0000433 ArraySizeMultiplier *= CAT->getSize().getZExtValue();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000434 }
435
John McCall8ed55a52010-09-02 09:58:18 +0000436 llvm::Value *Size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000437
Chris Lattner32ac5832010-07-20 21:55:52 +0000438 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
439 // Don't bloat the -O0 code.
440 if (llvm::ConstantInt *NumElementsC =
441 dyn_cast<llvm::ConstantInt>(NumElements)) {
Chris Lattner32ac5832010-07-20 21:55:52 +0000442 llvm::APInt NEC = NumElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000443 unsigned SizeWidth = NEC.getBitWidth();
444
445 // Determine if there is an overflow here by doing an extended multiply.
446 NEC.zext(SizeWidth*2);
447 llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
Chris Lattner32ac5832010-07-20 21:55:52 +0000448 SC *= NEC;
John McCall8ed55a52010-09-02 09:58:18 +0000449
450 if (!CookieSize.isZero()) {
451 // Save the current size without a cookie. We don't care if an
452 // overflow's already happened because SizeWithoutCookie isn't
453 // used if the allocator returns null or throws, as it should
454 // always do on an overflow.
455 llvm::APInt SWC = SC;
456 SWC.trunc(SizeWidth);
457 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
458
459 // Add the cookie size.
460 SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
Chris Lattner32ac5832010-07-20 21:55:52 +0000461 }
462
John McCall8ed55a52010-09-02 09:58:18 +0000463 if (SC.countLeadingZeros() >= SizeWidth) {
464 SC.trunc(SizeWidth);
465 Size = llvm::ConstantInt::get(SizeTy, SC);
466 } else {
467 // On overflow, produce a -1 so operator new throws.
468 Size = llvm::Constant::getAllOnesValue(SizeTy);
469 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000470
John McCall8ed55a52010-09-02 09:58:18 +0000471 // Scale NumElements while we're at it.
472 uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
473 NumElements = llvm::ConstantInt::get(SizeTy, N);
474
475 // Otherwise, we don't need to do an overflow-checked multiplication if
476 // we're multiplying by one.
477 } else if (TypeSize.isOne()) {
478 assert(ArraySizeMultiplier == 1);
479
480 Size = NumElements;
481
482 // If we need a cookie, add its size in with an overflow check.
483 // This is maybe a little paranoid.
484 if (!CookieSize.isZero()) {
485 SizeWithoutCookie = Size;
486
487 llvm::Value *CookieSizeV
488 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
489
490 const llvm::Type *Types[] = { SizeTy };
491 llvm::Value *UAddF
492 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
493 llvm::Value *AddRes
494 = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
495
496 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
497 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
498 Size = CGF.Builder.CreateSelect(DidOverflow,
499 llvm::ConstantInt::get(SizeTy, -1),
500 Size);
501 }
502
503 // Otherwise use the int.umul.with.overflow intrinsic.
504 } else {
505 llvm::Value *OutermostElementSize
506 = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
507
508 llvm::Value *NumOutermostElements = NumElements;
509
510 // Scale NumElements by the array size multiplier. This might
511 // overflow, but only if the multiplication below also overflows,
512 // in which case this multiplication isn't used.
513 if (ArraySizeMultiplier != 1)
514 NumElements = CGF.Builder.CreateMul(NumElements,
515 llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
516
517 // The requested size of the outermost array is non-constant.
518 // Multiply that by the static size of the elements of that array;
519 // on unsigned overflow, set the size to -1 to trigger an
520 // exception from the allocation routine. This is sufficient to
521 // prevent buffer overruns from the allocator returning a
522 // seemingly valid pointer to insufficient space. This idea comes
523 // originally from MSVC, and GCC has an open bug requesting
524 // similar behavior:
525 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
526 //
527 // This will not be sufficient for C++0x, which requires a
528 // specific exception class (std::bad_array_new_length).
529 // That will require ABI support that has not yet been specified.
530 const llvm::Type *Types[] = { SizeTy };
531 llvm::Value *UMulF
532 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
533 llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
534 OutermostElementSize);
535
536 // The overflow bit.
537 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
538
539 // The result of the multiplication.
540 Size = CGF.Builder.CreateExtractValue(MulRes, 0);
541
542 // If we have a cookie, we need to add that size in, too.
543 if (!CookieSize.isZero()) {
544 SizeWithoutCookie = Size;
545
546 llvm::Value *CookieSizeV
547 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
548 llvm::Value *UAddF
549 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
550 llvm::Value *AddRes
551 = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
552
553 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
554
555 llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
556 DidOverflow = CGF.Builder.CreateAnd(DidOverflow, AddDidOverflow);
557 }
558
559 Size = CGF.Builder.CreateSelect(DidOverflow,
560 llvm::ConstantInt::get(SizeTy, -1),
561 Size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000562 }
John McCall8ed55a52010-09-02 09:58:18 +0000563
564 if (CookieSize.isZero())
565 SizeWithoutCookie = Size;
566 else
567 assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
568
Chris Lattner32ac5832010-07-20 21:55:52 +0000569 return Size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000570}
571
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000572static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
573 llvm::Value *NewPtr) {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000574
575 assert(E->getNumConstructorArgs() == 1 &&
576 "Can only have one argument to initializer of POD type.");
577
578 const Expr *Init = E->getConstructorArg(0);
579 QualType AllocType = E->getAllocatedType();
Daniel Dunbar03816342010-08-21 02:24:36 +0000580
581 unsigned Alignment =
582 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000583 if (!CGF.hasAggregateLLVMType(AllocType))
584 CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
Daniel Dunbar03816342010-08-21 02:24:36 +0000585 AllocType.isVolatileQualified(), Alignment,
586 AllocType);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000587 else if (AllocType->isAnyComplexType())
588 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
589 AllocType.isVolatileQualified());
John McCall7a626f62010-09-15 10:14:12 +0000590 else {
591 AggValueSlot Slot
592 = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
593 CGF.EmitAggExpr(Init, Slot);
594 }
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000595}
596
597void
598CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
599 llvm::Value *NewPtr,
600 llvm::Value *NumElements) {
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000601 // We have a POD type.
602 if (E->getNumConstructorArgs() == 0)
603 return;
604
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000605 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
606
607 // Create a temporary for the loop index and initialize it with 0.
608 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
609 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
610 Builder.CreateStore(Zero, IndexPtr);
611
612 // Start the loop with a block that tests the condition.
613 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
614 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
615
616 EmitBlock(CondBlock);
617
618 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
619
620 // Generate: if (loop-index < number-of-elements fall to the loop body,
621 // otherwise, go to the block after the for-loop.
622 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
623 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
624 // If the condition is true, execute the body.
625 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
626
627 EmitBlock(ForBody);
628
629 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
630 // Inside the loop body, emit the constructor call on the array element.
631 Counter = Builder.CreateLoad(IndexPtr);
632 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
633 "arrayidx");
634 StoreAnyExprIntoOneUnit(*this, E, Address);
635
636 EmitBlock(ContinueBlock);
637
638 // Emit the increment of the loop counter.
639 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
640 Counter = Builder.CreateLoad(IndexPtr);
641 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
642 Builder.CreateStore(NextVal, IndexPtr);
643
644 // Finally, branch back up to the condition for the next iteration.
645 EmitBranch(CondBlock);
646
647 // Emit the fall-through block.
648 EmitBlock(AfterFor, true);
649}
650
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000651static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
652 llvm::Value *NewPtr, llvm::Value *Size) {
653 llvm::LLVMContext &VMContext = CGF.CGM.getLLVMContext();
654 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
655 if (NewPtr->getType() != BP)
656 NewPtr = CGF.Builder.CreateBitCast(NewPtr, BP, "tmp");
657
658 CGF.Builder.CreateCall5(CGF.CGM.getMemSetFn(BP, CGF.IntPtrTy), NewPtr,
659 llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)),
660 Size,
661 llvm::ConstantInt::get(CGF.Int32Ty,
662 CGF.getContext().getTypeAlign(T)/8),
663 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext),
664 0));
665}
666
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000667static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
668 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000669 llvm::Value *NumElements,
670 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson3a202f62009-11-24 18:43:52 +0000671 if (E->isArray()) {
Anders Carlssond040e6b2010-05-03 15:09:17 +0000672 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000673 bool RequiresZeroInitialization = false;
674 if (Ctor->getParent()->hasTrivialConstructor()) {
675 // If new expression did not specify value-initialization, then there
676 // is no initialization.
677 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
678 return;
679
John McCall614dbdc2010-08-22 21:01:12 +0000680 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000681 // Optimization: since zero initialization will just set the memory
682 // to all zeroes, generate a single memset to do it in one shot.
683 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
684 AllocSizeWithoutCookie);
685 return;
686 }
687
688 RequiresZeroInitialization = true;
689 }
690
691 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
692 E->constructor_arg_begin(),
693 E->constructor_arg_end(),
694 RequiresZeroInitialization);
Anders Carlssond040e6b2010-05-03 15:09:17 +0000695 return;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000696 } else if (E->getNumConstructorArgs() == 1 &&
697 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
698 // Optimization: since zero initialization will just set the memory
699 // to all zeroes, generate a single memset to do it in one shot.
700 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
701 AllocSizeWithoutCookie);
702 return;
703 } else {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000704 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
705 return;
706 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000707 }
Anders Carlsson3a202f62009-11-24 18:43:52 +0000708
709 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor747eb782010-07-08 06:14:04 +0000710 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
711 // direct initialization. C++ [dcl.init]p5 requires that we
712 // zero-initialize storage if there are no user-declared constructors.
713 if (E->hasInitializer() &&
714 !Ctor->getParent()->hasUserDeclaredConstructor() &&
715 !Ctor->getParent()->isEmpty())
716 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
717
Douglas Gregore1823702010-07-07 23:37:33 +0000718 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
719 NewPtr, E->constructor_arg_begin(),
720 E->constructor_arg_end());
Anders Carlsson3a202f62009-11-24 18:43:52 +0000721
722 return;
723 }
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000724 // We have a POD type.
725 if (E->getNumConstructorArgs() == 0)
726 return;
727
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000728 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000729}
730
Benjamin Kramerfb5e5842010-10-22 16:48:22 +0000731namespace {
John McCall7f9c92a2010-09-17 00:50:28 +0000732/// A utility class for saving an rvalue.
733class SavedRValue {
734public:
735 enum Kind { ScalarLiteral, ScalarAddress,
736 AggregateLiteral, AggregateAddress,
737 Complex };
738
739private:
740 llvm::Value *Value;
741 Kind K;
742
743 SavedRValue(llvm::Value *V, Kind K) : Value(V), K(K) {}
744
745public:
746 SavedRValue() {}
747
748 static SavedRValue forScalarLiteral(llvm::Value *V) {
749 return SavedRValue(V, ScalarLiteral);
750 }
751
752 static SavedRValue forScalarAddress(llvm::Value *Addr) {
753 return SavedRValue(Addr, ScalarAddress);
754 }
755
756 static SavedRValue forAggregateLiteral(llvm::Value *V) {
757 return SavedRValue(V, AggregateLiteral);
758 }
759
760 static SavedRValue forAggregateAddress(llvm::Value *Addr) {
761 return SavedRValue(Addr, AggregateAddress);
762 }
763
764 static SavedRValue forComplexAddress(llvm::Value *Addr) {
765 return SavedRValue(Addr, Complex);
766 }
767
768 Kind getKind() const { return K; }
769 llvm::Value *getValue() const { return Value; }
770};
Benjamin Kramerfb5e5842010-10-22 16:48:22 +0000771} // end anonymous namespace
John McCall7f9c92a2010-09-17 00:50:28 +0000772
773/// Given an r-value, perform the code necessary to make sure that a
774/// future RestoreRValue will be able to load the value without
775/// domination concerns.
776static SavedRValue SaveRValue(CodeGenFunction &CGF, RValue RV) {
777 if (RV.isScalar()) {
778 llvm::Value *V = RV.getScalarVal();
779
780 // These automatically dominate and don't need to be saved.
781 if (isa<llvm::Constant>(V) || isa<llvm::AllocaInst>(V))
782 return SavedRValue::forScalarLiteral(V);
783
784 // Everything else needs an alloca.
785 llvm::Value *Addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
786 CGF.Builder.CreateStore(V, Addr);
787 return SavedRValue::forScalarAddress(Addr);
788 }
789
790 if (RV.isComplex()) {
791 CodeGenFunction::ComplexPairTy V = RV.getComplexVal();
792 const llvm::Type *ComplexTy =
793 llvm::StructType::get(CGF.getLLVMContext(),
794 V.first->getType(), V.second->getType(),
795 (void*) 0);
796 llvm::Value *Addr = CGF.CreateTempAlloca(ComplexTy, "saved-complex");
797 CGF.StoreComplexToAddr(V, Addr, /*volatile*/ false);
798 return SavedRValue::forComplexAddress(Addr);
799 }
800
801 assert(RV.isAggregate());
802 llvm::Value *V = RV.getAggregateAddr(); // TODO: volatile?
803 if (isa<llvm::Constant>(V) || isa<llvm::AllocaInst>(V))
804 return SavedRValue::forAggregateLiteral(V);
805
806 llvm::Value *Addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
807 CGF.Builder.CreateStore(V, Addr);
808 return SavedRValue::forAggregateAddress(Addr);
809}
810
811/// Given a saved r-value produced by SaveRValue, perform the code
812/// necessary to restore it to usability at the current insertion
813/// point.
814static RValue RestoreRValue(CodeGenFunction &CGF, SavedRValue RV) {
815 switch (RV.getKind()) {
816 case SavedRValue::ScalarLiteral:
817 return RValue::get(RV.getValue());
818 case SavedRValue::ScalarAddress:
819 return RValue::get(CGF.Builder.CreateLoad(RV.getValue()));
820 case SavedRValue::AggregateLiteral:
821 return RValue::getAggregate(RV.getValue());
822 case SavedRValue::AggregateAddress:
823 return RValue::getAggregate(CGF.Builder.CreateLoad(RV.getValue()));
824 case SavedRValue::Complex:
825 return RValue::getComplex(CGF.LoadComplexFromAddr(RV.getValue(), false));
826 }
827
828 llvm_unreachable("bad saved r-value kind");
829 return RValue();
830}
831
John McCall824c2f52010-09-14 07:57:04 +0000832namespace {
833 /// A cleanup to call the given 'operator delete' function upon
834 /// abnormal exit from a new expression.
835 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
836 size_t NumPlacementArgs;
837 const FunctionDecl *OperatorDelete;
838 llvm::Value *Ptr;
839 llvm::Value *AllocSize;
840
841 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
842
843 public:
844 static size_t getExtraSize(size_t NumPlacementArgs) {
845 return NumPlacementArgs * sizeof(RValue);
846 }
847
848 CallDeleteDuringNew(size_t NumPlacementArgs,
849 const FunctionDecl *OperatorDelete,
850 llvm::Value *Ptr,
851 llvm::Value *AllocSize)
852 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
853 Ptr(Ptr), AllocSize(AllocSize) {}
854
855 void setPlacementArg(unsigned I, RValue Arg) {
856 assert(I < NumPlacementArgs && "index out of range");
857 getPlacementArgs()[I] = Arg;
858 }
859
860 void Emit(CodeGenFunction &CGF, bool IsForEH) {
861 const FunctionProtoType *FPT
862 = OperatorDelete->getType()->getAs<FunctionProtoType>();
863 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCalld441b1e2010-09-14 21:45:42 +0000864 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +0000865
866 CallArgList DeleteArgs;
867
868 // The first argument is always a void*.
869 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
870 DeleteArgs.push_back(std::make_pair(RValue::get(Ptr), *AI++));
871
872 // A member 'operator delete' can take an extra 'size_t' argument.
873 if (FPT->getNumArgs() == NumPlacementArgs + 2)
874 DeleteArgs.push_back(std::make_pair(RValue::get(AllocSize), *AI++));
875
876 // Pass the rest of the arguments, which must match exactly.
877 for (unsigned I = 0; I != NumPlacementArgs; ++I)
878 DeleteArgs.push_back(std::make_pair(getPlacementArgs()[I], *AI++));
879
880 // Call 'operator delete'.
881 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
882 CGF.CGM.GetAddrOfFunction(OperatorDelete),
883 ReturnValueSlot(), DeleteArgs, OperatorDelete);
884 }
885 };
John McCall7f9c92a2010-09-17 00:50:28 +0000886
887 /// A cleanup to call the given 'operator delete' function upon
888 /// abnormal exit from a new expression when the new expression is
889 /// conditional.
890 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
891 size_t NumPlacementArgs;
892 const FunctionDecl *OperatorDelete;
893 SavedRValue Ptr;
894 SavedRValue AllocSize;
895
896 SavedRValue *getPlacementArgs() {
897 return reinterpret_cast<SavedRValue*>(this+1);
898 }
899
900 public:
901 static size_t getExtraSize(size_t NumPlacementArgs) {
902 return NumPlacementArgs * sizeof(SavedRValue);
903 }
904
905 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
906 const FunctionDecl *OperatorDelete,
907 SavedRValue Ptr,
908 SavedRValue AllocSize)
909 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
910 Ptr(Ptr), AllocSize(AllocSize) {}
911
912 void setPlacementArg(unsigned I, SavedRValue Arg) {
913 assert(I < NumPlacementArgs && "index out of range");
914 getPlacementArgs()[I] = Arg;
915 }
916
917 void Emit(CodeGenFunction &CGF, bool IsForEH) {
918 const FunctionProtoType *FPT
919 = OperatorDelete->getType()->getAs<FunctionProtoType>();
920 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
921 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
922
923 CallArgList DeleteArgs;
924
925 // The first argument is always a void*.
926 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
927 DeleteArgs.push_back(std::make_pair(RestoreRValue(CGF, Ptr), *AI++));
928
929 // A member 'operator delete' can take an extra 'size_t' argument.
930 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
931 RValue RV = RestoreRValue(CGF, AllocSize);
932 DeleteArgs.push_back(std::make_pair(RV, *AI++));
933 }
934
935 // Pass the rest of the arguments, which must match exactly.
936 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
937 RValue RV = RestoreRValue(CGF, getPlacementArgs()[I]);
938 DeleteArgs.push_back(std::make_pair(RV, *AI++));
939 }
940
941 // Call 'operator delete'.
942 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
943 CGF.CGM.GetAddrOfFunction(OperatorDelete),
944 ReturnValueSlot(), DeleteArgs, OperatorDelete);
945 }
946 };
947}
948
949/// Enter a cleanup to call 'operator delete' if the initializer in a
950/// new-expression throws.
951static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
952 const CXXNewExpr *E,
953 llvm::Value *NewPtr,
954 llvm::Value *AllocSize,
955 const CallArgList &NewArgs) {
956 // If we're not inside a conditional branch, then the cleanup will
957 // dominate and we can do the easier (and more efficient) thing.
958 if (!CGF.isInConditionalBranch()) {
959 CallDeleteDuringNew *Cleanup = CGF.EHStack
960 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
961 E->getNumPlacementArgs(),
962 E->getOperatorDelete(),
963 NewPtr, AllocSize);
964 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
965 Cleanup->setPlacementArg(I, NewArgs[I+1].first);
966
967 return;
968 }
969
970 // Otherwise, we need to save all this stuff.
971 SavedRValue SavedNewPtr = SaveRValue(CGF, RValue::get(NewPtr));
972 SavedRValue SavedAllocSize = SaveRValue(CGF, RValue::get(AllocSize));
973
974 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
975 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
976 E->getNumPlacementArgs(),
977 E->getOperatorDelete(),
978 SavedNewPtr,
979 SavedAllocSize);
980 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
981 Cleanup->setPlacementArg(I, SaveRValue(CGF, NewArgs[I+1].first));
982
983 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall824c2f52010-09-14 07:57:04 +0000984}
985
Anders Carlssoncc52f652009-09-22 22:53:17 +0000986llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssoncc52f652009-09-22 22:53:17 +0000987 QualType AllocType = E->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000988 if (AllocType->isArrayType())
989 while (const ArrayType *AType = getContext().getAsArrayType(AllocType))
990 AllocType = AType->getElementType();
991
Anders Carlssoncc52f652009-09-22 22:53:17 +0000992 FunctionDecl *NewFD = E->getOperatorNew();
993 const FunctionProtoType *NewFTy = NewFD->getType()->getAs<FunctionProtoType>();
994
995 CallArgList NewArgs;
996
997 // The allocation size is the first argument.
998 QualType SizeTy = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +0000999
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001000 llvm::Value *NumElements = 0;
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001001 llvm::Value *AllocSizeWithoutCookie = 0;
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001002 llvm::Value *AllocSize = EmitCXXNewAllocSize(getContext(),
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001003 *this, E, NumElements,
1004 AllocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001005
Anders Carlssoncc52f652009-09-22 22:53:17 +00001006 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
1007
1008 // Emit the rest of the arguments.
1009 // FIXME: Ideally, this should just use EmitCallArgs.
1010 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
1011
1012 // First, use the types from the function type.
1013 // We start at 1 here because the first argument (the allocation size)
1014 // has already been emitted.
1015 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
1016 QualType ArgType = NewFTy->getArgType(i);
1017
1018 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
1019 getTypePtr() ==
1020 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
1021 "type mismatch in call argument!");
1022
1023 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
1024 ArgType));
1025
1026 }
1027
1028 // Either we've emitted all the call args, or we have a call to a
1029 // variadic function.
1030 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
1031 "Extra arguments in non-variadic function!");
1032
1033 // If we still have any arguments, emit them using the type of the argument.
1034 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
1035 NewArg != NewArgEnd; ++NewArg) {
1036 QualType ArgType = NewArg->getType();
1037 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
1038 ArgType));
1039 }
1040
1041 // Emit the call to new.
1042 RValue RV =
John McCallab26cfa2010-02-05 21:31:56 +00001043 EmitCall(CGM.getTypes().getFunctionInfo(NewArgs, NewFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001044 CGM.GetAddrOfFunction(NewFD), ReturnValueSlot(), NewArgs, NewFD);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001045
1046 // If an allocation function is declared with an empty exception specification
1047 // it returns null to indicate failure to allocate storage. [expr.new]p13.
1048 // (We don't need to check for null when there's no new initializer and
1049 // we're allocating a POD type).
1050 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
1051 !(AllocType->isPODType() && !E->hasInitializer());
1052
John McCall8ed55a52010-09-02 09:58:18 +00001053 llvm::BasicBlock *NullCheckSource = 0;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001054 llvm::BasicBlock *NewNotNull = 0;
1055 llvm::BasicBlock *NewEnd = 0;
1056
1057 llvm::Value *NewPtr = RV.getScalarVal();
John McCall8ed55a52010-09-02 09:58:18 +00001058 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001059
1060 if (NullCheckResult) {
John McCall8ed55a52010-09-02 09:58:18 +00001061 NullCheckSource = Builder.GetInsertBlock();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001062 NewNotNull = createBasicBlock("new.notnull");
1063 NewEnd = createBasicBlock("new.end");
1064
John McCall8ed55a52010-09-02 09:58:18 +00001065 llvm::Value *IsNull = Builder.CreateIsNull(NewPtr, "new.isnull");
1066 Builder.CreateCondBr(IsNull, NewEnd, NewNotNull);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001067 EmitBlock(NewNotNull);
1068 }
Ken Dyck3eb55cf2010-01-26 19:44:24 +00001069
John McCall8ed55a52010-09-02 09:58:18 +00001070 assert((AllocSize == AllocSizeWithoutCookie) ==
1071 CalculateCookiePadding(*this, E).isZero());
1072 if (AllocSize != AllocSizeWithoutCookie) {
1073 assert(E->isArray());
1074 NewPtr = CGM.getCXXABI().InitializeArrayCookie(CGF, NewPtr, NumElements,
1075 AllocType);
1076 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001077
John McCall824c2f52010-09-14 07:57:04 +00001078 // If there's an operator delete, enter a cleanup to call it if an
1079 // exception is thrown.
1080 EHScopeStack::stable_iterator CallOperatorDelete;
1081 if (E->getOperatorDelete()) {
John McCall7f9c92a2010-09-17 00:50:28 +00001082 EnterNewDeleteCleanup(*this, E, NewPtr, AllocSize, NewArgs);
John McCall824c2f52010-09-14 07:57:04 +00001083 CallOperatorDelete = EHStack.stable_begin();
1084 }
1085
Douglas Gregor040ad502010-09-02 23:24:14 +00001086 const llvm::Type *ElementPtrTy
1087 = ConvertTypeForMem(AllocType)->getPointerTo(AS);
John McCall8ed55a52010-09-02 09:58:18 +00001088 NewPtr = Builder.CreateBitCast(NewPtr, ElementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001089
John McCall8ed55a52010-09-02 09:58:18 +00001090 if (E->isArray()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001091 EmitNewInitializer(*this, E, NewPtr, NumElements, AllocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001092
1093 // NewPtr is a pointer to the base element type. If we're
1094 // allocating an array of arrays, we'll need to cast back to the
1095 // array pointer type.
Douglas Gregor040ad502010-09-02 23:24:14 +00001096 const llvm::Type *ResultTy = ConvertTypeForMem(E->getType());
John McCall8ed55a52010-09-02 09:58:18 +00001097 if (NewPtr->getType() != ResultTy)
1098 NewPtr = Builder.CreateBitCast(NewPtr, ResultTy);
1099 } else {
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001100 EmitNewInitializer(*this, E, NewPtr, NumElements, AllocSizeWithoutCookie);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001101 }
John McCall824c2f52010-09-14 07:57:04 +00001102
1103 // Deactivate the 'operator delete' cleanup if we finished
1104 // initialization.
1105 if (CallOperatorDelete.isValid())
1106 DeactivateCleanupBlock(CallOperatorDelete);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001107
Anders Carlssoncc52f652009-09-22 22:53:17 +00001108 if (NullCheckResult) {
1109 Builder.CreateBr(NewEnd);
John McCall8ed55a52010-09-02 09:58:18 +00001110 llvm::BasicBlock *NotNullSource = Builder.GetInsertBlock();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001111 EmitBlock(NewEnd);
1112
1113 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
1114 PHI->reserveOperandSpace(2);
John McCall8ed55a52010-09-02 09:58:18 +00001115 PHI->addIncoming(NewPtr, NotNullSource);
1116 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()),
1117 NullCheckSource);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001118
1119 NewPtr = PHI;
1120 }
John McCall8ed55a52010-09-02 09:58:18 +00001121
Anders Carlssoncc52f652009-09-22 22:53:17 +00001122 return NewPtr;
1123}
1124
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001125void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1126 llvm::Value *Ptr,
1127 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001128 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1129
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001130 const FunctionProtoType *DeleteFTy =
1131 DeleteFD->getType()->getAs<FunctionProtoType>();
1132
1133 CallArgList DeleteArgs;
1134
Anders Carlsson21122cf2009-12-13 20:04:38 +00001135 // Check if we need to pass the size to the delete operator.
1136 llvm::Value *Size = 0;
1137 QualType SizeTy;
1138 if (DeleteFTy->getNumArgs() == 2) {
1139 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001140 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1141 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1142 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001143 }
1144
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001145 QualType ArgTy = DeleteFTy->getArgType(0);
1146 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1147 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
1148
Anders Carlsson21122cf2009-12-13 20:04:38 +00001149 if (Size)
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001150 DeleteArgs.push_back(std::make_pair(RValue::get(Size), SizeTy));
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001151
1152 // Emit the call to delete.
John McCallab26cfa2010-02-05 21:31:56 +00001153 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001154 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001155 DeleteArgs, DeleteFD);
1156}
1157
John McCall8ed55a52010-09-02 09:58:18 +00001158namespace {
1159 /// Calls the given 'operator delete' on a single object.
1160 struct CallObjectDelete : EHScopeStack::Cleanup {
1161 llvm::Value *Ptr;
1162 const FunctionDecl *OperatorDelete;
1163 QualType ElementType;
1164
1165 CallObjectDelete(llvm::Value *Ptr,
1166 const FunctionDecl *OperatorDelete,
1167 QualType ElementType)
1168 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1169
1170 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1171 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1172 }
1173 };
1174}
1175
1176/// Emit the code for deleting a single object.
1177static void EmitObjectDelete(CodeGenFunction &CGF,
1178 const FunctionDecl *OperatorDelete,
1179 llvm::Value *Ptr,
1180 QualType ElementType) {
1181 // Find the destructor for the type, if applicable. If the
1182 // destructor is virtual, we'll just emit the vcall and return.
1183 const CXXDestructorDecl *Dtor = 0;
1184 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1185 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1186 if (!RD->hasTrivialDestructor()) {
1187 Dtor = RD->getDestructor();
1188
1189 if (Dtor->isVirtual()) {
1190 const llvm::Type *Ty =
John McCall0d635f52010-09-03 01:26:39 +00001191 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1192 Dtor_Complete),
John McCall8ed55a52010-09-02 09:58:18 +00001193 /*isVariadic=*/false);
1194
1195 llvm::Value *Callee
1196 = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
1197 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1198 0, 0);
1199
1200 // The dtor took care of deleting the object.
1201 return;
1202 }
1203 }
1204 }
1205
1206 // Make sure that we call delete even if the dtor throws.
1207 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1208 Ptr, OperatorDelete, ElementType);
1209
1210 if (Dtor)
1211 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1212 /*ForVirtualBase=*/false, Ptr);
1213
1214 CGF.PopCleanupBlock();
1215}
1216
1217namespace {
1218 /// Calls the given 'operator delete' on an array of objects.
1219 struct CallArrayDelete : EHScopeStack::Cleanup {
1220 llvm::Value *Ptr;
1221 const FunctionDecl *OperatorDelete;
1222 llvm::Value *NumElements;
1223 QualType ElementType;
1224 CharUnits CookieSize;
1225
1226 CallArrayDelete(llvm::Value *Ptr,
1227 const FunctionDecl *OperatorDelete,
1228 llvm::Value *NumElements,
1229 QualType ElementType,
1230 CharUnits CookieSize)
1231 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1232 ElementType(ElementType), CookieSize(CookieSize) {}
1233
1234 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1235 const FunctionProtoType *DeleteFTy =
1236 OperatorDelete->getType()->getAs<FunctionProtoType>();
1237 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1238
1239 CallArgList Args;
1240
1241 // Pass the pointer as the first argument.
1242 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1243 llvm::Value *DeletePtr
1244 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
1245 Args.push_back(std::make_pair(RValue::get(DeletePtr), VoidPtrTy));
1246
1247 // Pass the original requested size as the second argument.
1248 if (DeleteFTy->getNumArgs() == 2) {
1249 QualType size_t = DeleteFTy->getArgType(1);
1250 const llvm::IntegerType *SizeTy
1251 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1252
1253 CharUnits ElementTypeSize =
1254 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1255
1256 // The size of an element, multiplied by the number of elements.
1257 llvm::Value *Size
1258 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1259 Size = CGF.Builder.CreateMul(Size, NumElements);
1260
1261 // Plus the size of the cookie if applicable.
1262 if (!CookieSize.isZero()) {
1263 llvm::Value *CookieSizeV
1264 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1265 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1266 }
1267
1268 Args.push_back(std::make_pair(RValue::get(Size), size_t));
1269 }
1270
1271 // Emit the call to delete.
1272 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
1273 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1274 ReturnValueSlot(), Args, OperatorDelete);
1275 }
1276 };
1277}
1278
1279/// Emit the code for deleting an array of objects.
1280static void EmitArrayDelete(CodeGenFunction &CGF,
1281 const FunctionDecl *OperatorDelete,
1282 llvm::Value *Ptr,
1283 QualType ElementType) {
1284 llvm::Value *NumElements = 0;
1285 llvm::Value *AllocatedPtr = 0;
1286 CharUnits CookieSize;
1287 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, ElementType,
1288 NumElements, AllocatedPtr, CookieSize);
1289
1290 assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
1291
1292 // Make sure that we call delete even if one of the dtors throws.
1293 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1294 AllocatedPtr, OperatorDelete,
1295 NumElements, ElementType,
1296 CookieSize);
1297
1298 if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
1299 if (!RD->hasTrivialDestructor()) {
1300 assert(NumElements && "ReadArrayCookie didn't find element count"
1301 " for a class with destructor");
1302 CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
1303 }
1304 }
1305
1306 CGF.PopCleanupBlock();
1307}
1308
Anders Carlssoncc52f652009-09-22 22:53:17 +00001309void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +00001310
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001311 // Get at the argument before we performed the implicit conversion
1312 // to void*.
1313 const Expr *Arg = E->getArgument();
1314 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00001315 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001316 ICE->getType()->isVoidPointerType())
1317 Arg = ICE->getSubExpr();
Douglas Gregore364e7b2009-10-01 05:49:51 +00001318 else
1319 break;
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001320 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001321
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001322 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001323
1324 // Null check the pointer.
1325 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1326 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1327
1328 llvm::Value *IsNull =
1329 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
1330 "isnull");
1331
1332 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1333 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001334
John McCall8ed55a52010-09-02 09:58:18 +00001335 // We might be deleting a pointer to array. If so, GEP down to the
1336 // first non-array element.
1337 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1338 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1339 if (DeleteTy->isConstantArrayType()) {
1340 llvm::Value *Zero = Builder.getInt32(0);
1341 llvm::SmallVector<llvm::Value*,8> GEP;
1342
1343 GEP.push_back(Zero); // point at the outermost array
1344
1345 // For each layer of array type we're pointing at:
1346 while (const ConstantArrayType *Arr
1347 = getContext().getAsConstantArrayType(DeleteTy)) {
1348 // 1. Unpeel the array type.
1349 DeleteTy = Arr->getElementType();
1350
1351 // 2. GEP to the first element of the array.
1352 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001353 }
John McCall8ed55a52010-09-02 09:58:18 +00001354
1355 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001356 }
1357
Douglas Gregor04f36212010-09-02 17:38:50 +00001358 assert(ConvertTypeForMem(DeleteTy) ==
1359 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001360
1361 if (E->isArrayForm()) {
1362 EmitArrayDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1363 } else {
1364 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1365 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001366
Anders Carlssoncc52f652009-09-22 22:53:17 +00001367 EmitBlock(DeleteEnd);
1368}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001369
1370llvm::Value * CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
1371 QualType Ty = E->getType();
1372 const llvm::Type *LTy = ConvertType(Ty)->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001373
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001374 if (E->isTypeOperand()) {
1375 llvm::Constant *TypeInfo =
1376 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
1377 return Builder.CreateBitCast(TypeInfo, LTy);
1378 }
1379
Mike Stumpc9b231c2009-11-15 08:09:41 +00001380 Expr *subE = E->getExprOperand();
Mike Stump6fdfea62009-11-17 22:33:00 +00001381 Ty = subE->getType();
1382 CanQualType CanTy = CGM.getContext().getCanonicalType(Ty);
1383 Ty = CanTy.getUnqualifiedType().getNonReferenceType();
Mike Stumpc9b231c2009-11-15 08:09:41 +00001384 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1385 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1386 if (RD->isPolymorphic()) {
1387 // FIXME: if subE is an lvalue do
1388 LValue Obj = EmitLValue(subE);
1389 llvm::Value *This = Obj.getAddress();
Mike Stump1bf924b2009-11-15 16:52:53 +00001390 // We need to do a zero check for *p, unless it has NonNullAttr.
1391 // FIXME: PointerType->hasAttr<NonNullAttr>()
1392 bool CanBeZero = false;
Mike Stumpc2c03342009-11-17 00:45:21 +00001393 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(subE->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +00001394 if (UO->getOpcode() == UO_Deref)
Mike Stump1bf924b2009-11-15 16:52:53 +00001395 CanBeZero = true;
1396 if (CanBeZero) {
1397 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
1398 llvm::BasicBlock *ZeroBlock = createBasicBlock();
1399
Dan Gohman8fc50c22010-10-26 18:44:08 +00001400 llvm::Value *Zero = llvm::Constant::getNullValue(This->getType());
1401 Builder.CreateCondBr(Builder.CreateICmpNE(This, Zero),
Mike Stump1bf924b2009-11-15 16:52:53 +00001402 NonZeroBlock, ZeroBlock);
1403 EmitBlock(ZeroBlock);
1404 /// Call __cxa_bad_typeid
1405 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1406 const llvm::FunctionType *FTy;
1407 FTy = llvm::FunctionType::get(ResultType, false);
1408 llvm::Value *F = CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
Mike Stump65511702009-11-16 06:50:58 +00001409 Builder.CreateCall(F)->setDoesNotReturn();
Mike Stump1bf924b2009-11-15 16:52:53 +00001410 Builder.CreateUnreachable();
1411 EmitBlock(NonZeroBlock);
1412 }
Dan Gohman8fc50c22010-10-26 18:44:08 +00001413 llvm::Value *V = GetVTablePtr(This, LTy->getPointerTo());
Mike Stumpc9b231c2009-11-15 08:09:41 +00001414 V = Builder.CreateConstInBoundsGEP1_64(V, -1ULL);
1415 V = Builder.CreateLoad(V);
1416 return V;
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001417 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001418 }
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001419 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(Ty), LTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001420}
Mike Stump65511702009-11-16 06:50:58 +00001421
1422llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *V,
1423 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001424 QualType SrcTy = DCE->getSubExpr()->getType();
1425 QualType DestTy = DCE->getTypeAsWritten();
1426 QualType InnerType = DestTy->getPointeeType();
1427
Mike Stump65511702009-11-16 06:50:58 +00001428 const llvm::Type *LTy = ConvertType(DCE->getType());
Mike Stump6ca0e212009-11-16 22:52:20 +00001429
Mike Stump65511702009-11-16 06:50:58 +00001430 bool CanBeZero = false;
Mike Stump65511702009-11-16 06:50:58 +00001431 bool ToVoid = false;
Mike Stump6ca0e212009-11-16 22:52:20 +00001432 bool ThrowOnBad = false;
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001433 if (DestTy->isPointerType()) {
Mike Stump65511702009-11-16 06:50:58 +00001434 // FIXME: if PointerType->hasAttr<NonNullAttr>(), we don't set this
1435 CanBeZero = true;
1436 if (InnerType->isVoidType())
1437 ToVoid = true;
1438 } else {
1439 LTy = LTy->getPointerTo();
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001440
1441 // FIXME: What if exceptions are disabled?
Mike Stump65511702009-11-16 06:50:58 +00001442 ThrowOnBad = true;
1443 }
1444
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001445 if (SrcTy->isPointerType() || SrcTy->isReferenceType())
1446 SrcTy = SrcTy->getPointeeType();
1447 SrcTy = SrcTy.getUnqualifiedType();
1448
Anders Carlsson0087bc82009-12-18 14:55:04 +00001449 if (DestTy->isPointerType() || DestTy->isReferenceType())
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001450 DestTy = DestTy->getPointeeType();
1451 DestTy = DestTy.getUnqualifiedType();
Mike Stump65511702009-11-16 06:50:58 +00001452
Mike Stump65511702009-11-16 06:50:58 +00001453 llvm::BasicBlock *ContBlock = createBasicBlock();
1454 llvm::BasicBlock *NullBlock = 0;
1455 llvm::BasicBlock *NonZeroBlock = 0;
1456 if (CanBeZero) {
1457 NonZeroBlock = createBasicBlock();
1458 NullBlock = createBasicBlock();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001459 Builder.CreateCondBr(Builder.CreateIsNotNull(V), NonZeroBlock, NullBlock);
Mike Stump65511702009-11-16 06:50:58 +00001460 EmitBlock(NonZeroBlock);
1461 }
1462
Mike Stump65511702009-11-16 06:50:58 +00001463 llvm::BasicBlock *BadCastBlock = 0;
Mike Stump65511702009-11-16 06:50:58 +00001464
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001465 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
Mike Stump6ca0e212009-11-16 22:52:20 +00001466
1467 // See if this is a dynamic_cast(void*)
1468 if (ToVoid) {
1469 llvm::Value *This = V;
Dan Gohman8fc50c22010-10-26 18:44:08 +00001470 V = GetVTablePtr(This, PtrDiffTy->getPointerTo());
Mike Stump6ca0e212009-11-16 22:52:20 +00001471 V = Builder.CreateConstInBoundsGEP1_64(V, -2ULL);
1472 V = Builder.CreateLoad(V, "offset to top");
1473 This = Builder.CreateBitCast(This, llvm::Type::getInt8PtrTy(VMContext));
1474 V = Builder.CreateInBoundsGEP(This, V);
1475 V = Builder.CreateBitCast(V, LTy);
1476 } else {
1477 /// Call __dynamic_cast
1478 const llvm::Type *ResultType = llvm::Type::getInt8PtrTy(VMContext);
1479 const llvm::FunctionType *FTy;
1480 std::vector<const llvm::Type*> ArgTys;
1481 const llvm::Type *PtrToInt8Ty
1482 = llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1483 ArgTys.push_back(PtrToInt8Ty);
1484 ArgTys.push_back(PtrToInt8Ty);
1485 ArgTys.push_back(PtrToInt8Ty);
1486 ArgTys.push_back(PtrDiffTy);
1487 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump6ca0e212009-11-16 22:52:20 +00001488
1489 // FIXME: Calculate better hint.
1490 llvm::Value *hint = llvm::ConstantInt::get(PtrDiffTy, -1ULL);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001491
1492 assert(SrcTy->isRecordType() && "Src type must be record type!");
1493 assert(DestTy->isRecordType() && "Dest type must be record type!");
1494
Douglas Gregor247894b2009-12-23 22:04:40 +00001495 llvm::Value *SrcArg
1496 = CGM.GetAddrOfRTTIDescriptor(SrcTy.getUnqualifiedType());
1497 llvm::Value *DestArg
1498 = CGM.GetAddrOfRTTIDescriptor(DestTy.getUnqualifiedType());
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001499
Mike Stump6ca0e212009-11-16 22:52:20 +00001500 V = Builder.CreateBitCast(V, PtrToInt8Ty);
1501 V = Builder.CreateCall4(CGM.CreateRuntimeFunction(FTy, "__dynamic_cast"),
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001502 V, SrcArg, DestArg, hint);
Mike Stump6ca0e212009-11-16 22:52:20 +00001503 V = Builder.CreateBitCast(V, LTy);
1504
1505 if (ThrowOnBad) {
1506 BadCastBlock = createBasicBlock();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001507 Builder.CreateCondBr(Builder.CreateIsNotNull(V), ContBlock, BadCastBlock);
Mike Stump6ca0e212009-11-16 22:52:20 +00001508 EmitBlock(BadCastBlock);
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001509 /// Invoke __cxa_bad_cast
Mike Stump6ca0e212009-11-16 22:52:20 +00001510 ResultType = llvm::Type::getVoidTy(VMContext);
1511 const llvm::FunctionType *FBadTy;
Mike Stump3afea1d2009-11-17 03:01:03 +00001512 FBadTy = llvm::FunctionType::get(ResultType, false);
Mike Stump6ca0e212009-11-16 22:52:20 +00001513 llvm::Value *F = CGM.CreateRuntimeFunction(FBadTy, "__cxa_bad_cast");
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001514 if (llvm::BasicBlock *InvokeDest = getInvokeDest()) {
1515 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
1516 Builder.CreateInvoke(F, Cont, InvokeDest)->setDoesNotReturn();
1517 EmitBlock(Cont);
1518 } else {
1519 // FIXME: Does this ever make sense?
1520 Builder.CreateCall(F)->setDoesNotReturn();
1521 }
Mike Stumpe8cdcc92009-11-17 00:08:50 +00001522 Builder.CreateUnreachable();
Mike Stump6ca0e212009-11-16 22:52:20 +00001523 }
Mike Stump65511702009-11-16 06:50:58 +00001524 }
1525
1526 if (CanBeZero) {
1527 Builder.CreateBr(ContBlock);
1528 EmitBlock(NullBlock);
1529 Builder.CreateBr(ContBlock);
1530 }
1531 EmitBlock(ContBlock);
1532 if (CanBeZero) {
1533 llvm::PHINode *PHI = Builder.CreatePHI(LTy);
Mike Stump4d0e9092009-11-17 00:10:05 +00001534 PHI->reserveOperandSpace(2);
Mike Stump65511702009-11-16 06:50:58 +00001535 PHI->addIncoming(V, NonZeroBlock);
1536 PHI->addIncoming(llvm::Constant::getNullValue(LTy), NullBlock);
Mike Stump65511702009-11-16 06:50:58 +00001537 V = PHI;
1538 }
1539
1540 return V;
1541}