blob: 99c54f0456b8830e31d6d40c697a08405e7fd70f [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlsson16d81b82009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
Devang Patelc69e1cf2010-09-30 19:05:55 +000014#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson16d81b82009-09-22 22:53:17 +000015#include "CodeGenFunction.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Fariborz Jahanian842ddd02010-05-20 21:38:57 +000017#include "CGObjCRuntime.h"
Devang Patelc69e1cf2010-09-30 19:05:55 +000018#include "CGDebugInfo.h"
Chris Lattner6c552c12010-07-20 20:19:24 +000019#include "llvm/Intrinsics.h"
Anders Carlsson16d81b82009-09-22 22:53:17 +000020using namespace clang;
21using namespace CodeGen;
22
Anders Carlsson3b5ad222010-01-01 20:29:01 +000023RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
24 llvm::Value *Callee,
25 ReturnValueSlot ReturnValue,
26 llvm::Value *This,
Anders Carlssonc997d422010-01-02 01:01:18 +000027 llvm::Value *VTT,
Anders Carlsson3b5ad222010-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 Carlssonc997d422010-01-02 01:01:18 +000041 // If there is a VTT parameter, emit it.
42 if (VTT) {
43 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
44 Args.push_back(std::make_pair(RValue::get(VTT), T));
45 }
46
Anders Carlsson3b5ad222010-01-01 20:29:01 +000047 // And the rest of the call args
48 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
49
John McCall04a67a62010-02-05 21:31:56 +000050 QualType ResultType = FPT->getResultType();
51 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +000052 FPT->getExtInfo()),
53 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000054}
55
Anders Carlsson1679f5a2011-01-29 03:52:01 +000056static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
Anders Carlsson268ab8c2011-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 Carlsson1679f5a2011-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 Carlsson3b5ad222010-01-01 20:29:01 +000080/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
81/// expr can be devirtualized.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +000082static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
83 const Expr *Base,
Anders Carlssonbd2bfae2010-10-27 13:28:46 +000084 const CXXMethodDecl *MD) {
85
Anders Carlsson1679f5a2011-01-29 03:52:01 +000086 // When building with -fapple-kext, all calls must go through the vtable since
87 // the kernel linker can do runtime patching of vtables.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +000088 if (Context.getLangOptions().AppleKext)
89 return false;
90
Anders Carlsson1679f5a2011-01-29 03:52:01 +000091 // If the most derived class is marked final, we know that no subclass can
92 // override this member function and so we can devirtualize it. For example:
93 //
94 // struct A { virtual void f(); }
95 // struct B final : A { };
96 //
97 // void f(B *b) {
98 // b->f();
99 // }
100 //
101 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
102 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
103 return true;
104
Anders Carlssonf89e0422011-01-23 21:07:30 +0000105 // If the member function is marked 'final', we know that it can't be
Anders Carlssond66f4282010-10-27 13:34:43 +0000106 // overridden and can therefore devirtualize it.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000107 if (MD->hasAttr<FinalAttr>())
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000108 return true;
Anders Carlssond66f4282010-10-27 13:34:43 +0000109
Anders Carlssonf89e0422011-01-23 21:07:30 +0000110 // Similarly, if the class itself is marked 'final' it can't be overridden
111 // and we can therefore devirtualize the member function call.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000112 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssond66f4282010-10-27 13:34:43 +0000113 return true;
114
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000115 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
116 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
117 // This is a record decl. We know the type and can devirtualize it.
118 return VD->getType()->isRecordType();
119 }
120
121 return false;
122 }
123
124 // We can always devirtualize calls on temporary object expressions.
Eli Friedman6997aae2010-01-31 20:58:15 +0000125 if (isa<CXXConstructExpr>(Base))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000126 return true;
127
128 // And calls on bound temporaries.
129 if (isa<CXXBindTemporaryExpr>(Base))
130 return true;
131
132 // Check if this is a call expr that returns a record type.
133 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
134 return CE->getCallReturnType()->isRecordType();
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000135
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000136 // We can't devirtualize the call.
137 return false;
138}
139
Francois Pichetdbee3412011-01-18 05:04:39 +0000140// Note: This function also emit constructor calls to support a MSVC
141// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000142RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
143 ReturnValueSlot ReturnValue) {
144 if (isa<BinaryOperator>(CE->getCallee()->IgnoreParens()))
145 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
146
147 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()->IgnoreParens());
148 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
149
Devang Patelc69e1cf2010-09-30 19:05:55 +0000150 CGDebugInfo *DI = getDebugInfo();
Devang Patel68020272010-10-22 18:56:27 +0000151 if (DI && CGM.getCodeGenOpts().LimitDebugInfo
152 && !isa<CallExpr>(ME->getBase())) {
Devang Patelc69e1cf2010-09-30 19:05:55 +0000153 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
154 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
155 DI->getOrCreateRecordType(PTy->getPointeeType(),
156 MD->getParent()->getLocation());
157 }
158 }
159
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000160 if (MD->isStatic()) {
161 // The method is static, emit it as we would a regular call.
162 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
163 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
164 ReturnValue, CE->arg_begin(), CE->arg_end());
165 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000166
John McCallfc400282010-09-03 01:26:39 +0000167 // Compute the object pointer.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000168 llvm::Value *This;
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000169 if (ME->isArrow())
170 This = EmitScalarExpr(ME->getBase());
John McCall0e800c92010-12-04 08:14:53 +0000171 else
172 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000173
John McCallfc400282010-09-03 01:26:39 +0000174 if (MD->isTrivial()) {
175 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichetdbee3412011-01-18 05:04:39 +0000176 if (isa<CXXConstructorDecl>(MD) &&
177 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
178 return RValue::get(0);
John McCallfc400282010-09-03 01:26:39 +0000179
Francois Pichetdbee3412011-01-18 05:04:39 +0000180 if (MD->isCopyAssignmentOperator()) {
181 // We don't like to generate the trivial copy assignment operator when
182 // it isn't necessary; just produce the proper effect here.
183 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
184 EmitAggregateCopy(This, RHS, CE->getType());
185 return RValue::get(This);
186 }
187
188 if (isa<CXXConstructorDecl>(MD) &&
189 cast<CXXConstructorDecl>(MD)->isCopyConstructor()) {
190 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
191 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
192 CE->arg_begin(), CE->arg_end());
193 return RValue::get(This);
194 }
195 llvm_unreachable("unknown trivial member function");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000196 }
197
John McCallfc400282010-09-03 01:26:39 +0000198 // Compute the function type we're calling.
Francois Pichetdbee3412011-01-18 05:04:39 +0000199 const CGFunctionInfo *FInfo = 0;
200 if (isa<CXXDestructorDecl>(MD))
201 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
202 Dtor_Complete);
203 else if (isa<CXXConstructorDecl>(MD))
204 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXConstructorDecl>(MD),
205 Ctor_Complete);
206 else
207 FInfo = &CGM.getTypes().getFunctionInfo(MD);
John McCallfc400282010-09-03 01:26:39 +0000208
209 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
210 const llvm::Type *Ty
Francois Pichetdbee3412011-01-18 05:04:39 +0000211 = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
John McCallfc400282010-09-03 01:26:39 +0000212
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000213 // C++ [class.virtual]p12:
214 // Explicit qualification with the scope operator (5.1) suppresses the
215 // virtual call mechanism.
216 //
217 // We also don't emit a virtual call if the base expression has a record type
218 // because then we know what the type is.
Fariborz Jahanian27262672011-01-20 17:19:02 +0000219 bool UseVirtualCall;
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000220 UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
221 && !canDevirtualizeMemberFunctionCalls(getContext(),
222 ME->getBase(), MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000223 llvm::Value *Callee;
John McCallfc400282010-09-03 01:26:39 +0000224 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
225 if (UseVirtualCall) {
226 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000227 } else {
John McCallfc400282010-09-03 01:26:39 +0000228 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000229 }
Francois Pichetdbee3412011-01-18 05:04:39 +0000230 } else if (const CXXConstructorDecl *Ctor =
231 dyn_cast<CXXConstructorDecl>(MD)) {
232 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000233 } else if (UseVirtualCall) {
Fariborz Jahanian27262672011-01-20 17:19:02 +0000234 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000235 } else {
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000236 if (getContext().getLangOptions().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000237 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000238 ME->hasQualifier())
239 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), This, Ty);
240 else
241 Callee = CGM.GetAddrOfFunction(MD, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000242 }
243
Anders Carlssonc997d422010-01-02 01:01:18 +0000244 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000245 CE->arg_begin(), CE->arg_end());
246}
247
248RValue
249CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
250 ReturnValueSlot ReturnValue) {
251 const BinaryOperator *BO =
252 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
253 const Expr *BaseExpr = BO->getLHS();
254 const Expr *MemFnExpr = BO->getRHS();
255
256 const MemberPointerType *MPT =
257 MemFnExpr->getType()->getAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000258
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000259 const FunctionProtoType *FPT =
260 MPT->getPointeeType()->getAs<FunctionProtoType>();
261 const CXXRecordDecl *RD =
262 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
263
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000264 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000265 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000266
267 // Emit the 'this' pointer.
268 llvm::Value *This;
269
John McCall2de56d12010-08-25 11:45:40 +0000270 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000271 This = EmitScalarExpr(BaseExpr);
272 else
273 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000274
John McCall93d557b2010-08-22 00:05:51 +0000275 // Ask the ABI to load the callee. Note that This is modified.
276 llvm::Value *Callee =
277 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(CGF, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000278
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000279 CallArgList Args;
280
281 QualType ThisType =
282 getContext().getPointerType(getContext().getTagDeclType(RD));
283
284 // Push the this ptr.
285 Args.push_back(std::make_pair(RValue::get(This), ThisType));
286
287 // And the rest of the call args
288 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall04a67a62010-02-05 21:31:56 +0000289 const FunctionType *BO_FPT = BO->getType()->getAs<FunctionProtoType>();
290 return EmitCall(CGM.getTypes().getFunctionInfo(Args, BO_FPT), Callee,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000291 ReturnValue, Args);
292}
293
294RValue
295CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
296 const CXXMethodDecl *MD,
297 ReturnValueSlot ReturnValue) {
298 assert(MD->isInstance() &&
299 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000300 LValue LV = EmitLValue(E->getArg(0));
301 llvm::Value *This = LV.getAddress();
302
Douglas Gregor3e9438b2010-09-27 22:37:28 +0000303 if (MD->isCopyAssignmentOperator()) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000304 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
305 if (ClassDecl->hasTrivialCopyAssignment()) {
306 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
307 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000308 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
309 QualType Ty = E->getType();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000310 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000311 return RValue::get(This);
312 }
313 }
314
315 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
316 const llvm::Type *Ty =
317 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
318 FPT->isVariadic());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000319 llvm::Value *Callee;
Fariborz Jahanian27262672011-01-20 17:19:02 +0000320 if (MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000321 !canDevirtualizeMemberFunctionCalls(getContext(),
322 E->getArg(0), MD))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000323 Callee = BuildVirtualCall(MD, This, Ty);
324 else
325 Callee = CGM.GetAddrOfFunction(MD, Ty);
326
Anders Carlssonc997d422010-01-02 01:01:18 +0000327 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000328 E->arg_begin() + 1, E->arg_end());
329}
330
331void
John McCall558d2ab2010-09-15 10:14:12 +0000332CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
333 AggValueSlot Dest) {
334 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000335 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000336
337 // If we require zero initialization before (or instead of) calling the
338 // constructor, as can be the case with a non-user-provided default
339 // constructor, emit the zero initialization now.
340 if (E->requiresZeroInitialization())
John McCall558d2ab2010-09-15 10:14:12 +0000341 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor759e41b2010-08-22 16:15:35 +0000342
343 // If this is a call to a trivial default constructor, do nothing.
344 if (CD->isTrivial() && CD->isDefaultConstructor())
345 return;
346
John McCallfc1e6c72010-09-18 00:58:34 +0000347 // Elide the constructor if we're constructing from a temporary.
348 // The temporary check is required because Sema sets this on NRVO
349 // returns.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000350 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000351 assert(getContext().hasSameUnqualifiedType(E->getType(),
352 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000353 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
354 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000355 return;
356 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000357 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000358
359 const ConstantArrayType *Array
360 = getContext().getAsConstantArrayType(E->getType());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000361 if (Array) {
362 QualType BaseElementTy = getContext().getBaseElementType(Array);
363 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
364 BasePtr = llvm::PointerType::getUnqual(BasePtr);
365 llvm::Value *BaseAddrPtr =
John McCall558d2ab2010-09-15 10:14:12 +0000366 Builder.CreateBitCast(Dest.getAddr(), BasePtr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000367
368 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
369 E->arg_begin(), E->arg_end());
370 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000371 else {
372 CXXCtorType Type =
373 (E->getConstructionKind() == CXXConstructExpr::CK_Complete)
374 ? Ctor_Complete : Ctor_Base;
375 bool ForVirtualBase =
376 E->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
377
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000378 // Call the constructor.
John McCall558d2ab2010-09-15 10:14:12 +0000379 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000380 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000381 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000382}
383
Fariborz Jahanian34999872010-11-13 21:53:34 +0000384void
385CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
386 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000387 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000388 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000389 Exp = E->getSubExpr();
390 assert(isa<CXXConstructExpr>(Exp) &&
391 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
392 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
393 const CXXConstructorDecl *CD = E->getConstructor();
394 RunCleanupsScope Scope(*this);
395
396 // If we require zero initialization before (or instead of) calling the
397 // constructor, as can be the case with a non-user-provided default
398 // constructor, emit the zero initialization now.
399 // FIXME. Do I still need this for a copy ctor synthesis?
400 if (E->requiresZeroInitialization())
401 EmitNullInitialization(Dest, E->getType());
402
Chandler Carruth858a5462010-11-15 13:54:43 +0000403 assert(!getContext().getAsConstantArrayType(E->getType())
404 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000405 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
406 E->arg_begin(), E->arg_end());
407}
408
John McCall5172ed92010-08-23 01:17:59 +0000409/// Check whether the given operator new[] is the global placement
410/// operator new[].
411static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
412 const FunctionDecl *Fn) {
413 // Must be in global scope. Note that allocation functions can't be
414 // declared in namespaces.
Sebastian Redl7a126a42010-08-31 00:36:30 +0000415 if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
John McCall5172ed92010-08-23 01:17:59 +0000416 return false;
417
418 // Signature must be void *operator new[](size_t, void*).
419 // The size_t is common to all operator new[]s.
420 if (Fn->getNumParams() != 2)
421 return false;
422
423 CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
424 return (ParamType == Ctx.VoidPtrTy);
425}
426
John McCall1e7fe752010-09-02 09:58:18 +0000427static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
428 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000429 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000430 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000431
Anders Carlssondd937552009-12-13 20:34:34 +0000432 // No cookie is required if the new operator being used is
433 // ::operator new[](size_t, void*).
434 const FunctionDecl *OperatorNew = E->getOperatorNew();
John McCall1e7fe752010-09-02 09:58:18 +0000435 if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
John McCall5172ed92010-08-23 01:17:59 +0000436 return CharUnits::Zero();
437
John McCall6ec278d2011-01-27 09:37:56 +0000438 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000439}
440
Fariborz Jahanianceb43b62010-03-24 16:57:01 +0000441static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
Chris Lattnerdefe8b22010-07-20 18:45:57 +0000442 CodeGenFunction &CGF,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000443 const CXXNewExpr *E,
Douglas Gregor59174c02010-07-21 01:10:17 +0000444 llvm::Value *&NumElements,
445 llvm::Value *&SizeWithoutCookie) {
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000446 QualType ElemType = E->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000447
448 const llvm::IntegerType *SizeTy =
449 cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
Anders Carlssona4d4c012009-09-23 16:07:23 +0000450
John McCall1e7fe752010-09-02 09:58:18 +0000451 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
452
Douglas Gregor59174c02010-07-21 01:10:17 +0000453 if (!E->isArray()) {
454 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
455 return SizeWithoutCookie;
456 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000457
John McCall1e7fe752010-09-02 09:58:18 +0000458 // Figure out the cookie size.
459 CharUnits CookieSize = CalculateCookiePadding(CGF, E);
460
Anders Carlssona4d4c012009-09-23 16:07:23 +0000461 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000462 // We multiply the size of all dimensions for NumElements.
463 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
Anders Carlssona4d4c012009-09-23 16:07:23 +0000464 NumElements = CGF.EmitScalarExpr(E->getArraySize());
John McCall1e7fe752010-09-02 09:58:18 +0000465 assert(NumElements->getType() == SizeTy && "element count not a size_t");
466
467 uint64_t ArraySizeMultiplier = 1;
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000468 while (const ConstantArrayType *CAT
469 = CGF.getContext().getAsConstantArrayType(ElemType)) {
470 ElemType = CAT->getElementType();
John McCall1e7fe752010-09-02 09:58:18 +0000471 ArraySizeMultiplier *= CAT->getSize().getZExtValue();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000472 }
473
John McCall1e7fe752010-09-02 09:58:18 +0000474 llvm::Value *Size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000475
Chris Lattner806941e2010-07-20 21:55:52 +0000476 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
477 // Don't bloat the -O0 code.
478 if (llvm::ConstantInt *NumElementsC =
479 dyn_cast<llvm::ConstantInt>(NumElements)) {
Chris Lattner806941e2010-07-20 21:55:52 +0000480 llvm::APInt NEC = NumElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000481 unsigned SizeWidth = NEC.getBitWidth();
482
483 // Determine if there is an overflow here by doing an extended multiply.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000484 NEC = NEC.zext(SizeWidth*2);
John McCall1e7fe752010-09-02 09:58:18 +0000485 llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
Chris Lattner806941e2010-07-20 21:55:52 +0000486 SC *= NEC;
John McCall1e7fe752010-09-02 09:58:18 +0000487
488 if (!CookieSize.isZero()) {
489 // Save the current size without a cookie. We don't care if an
490 // overflow's already happened because SizeWithoutCookie isn't
491 // used if the allocator returns null or throws, as it should
492 // always do on an overflow.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000493 llvm::APInt SWC = SC.trunc(SizeWidth);
John McCall1e7fe752010-09-02 09:58:18 +0000494 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
495
496 // Add the cookie size.
497 SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
Chris Lattner806941e2010-07-20 21:55:52 +0000498 }
499
John McCall1e7fe752010-09-02 09:58:18 +0000500 if (SC.countLeadingZeros() >= SizeWidth) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000501 SC = SC.trunc(SizeWidth);
John McCall1e7fe752010-09-02 09:58:18 +0000502 Size = llvm::ConstantInt::get(SizeTy, SC);
503 } else {
504 // On overflow, produce a -1 so operator new throws.
505 Size = llvm::Constant::getAllOnesValue(SizeTy);
506 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000507
John McCall1e7fe752010-09-02 09:58:18 +0000508 // Scale NumElements while we're at it.
509 uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
510 NumElements = llvm::ConstantInt::get(SizeTy, N);
511
512 // Otherwise, we don't need to do an overflow-checked multiplication if
513 // we're multiplying by one.
514 } else if (TypeSize.isOne()) {
515 assert(ArraySizeMultiplier == 1);
516
517 Size = NumElements;
518
519 // If we need a cookie, add its size in with an overflow check.
520 // This is maybe a little paranoid.
521 if (!CookieSize.isZero()) {
522 SizeWithoutCookie = Size;
523
524 llvm::Value *CookieSizeV
525 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
526
527 const llvm::Type *Types[] = { SizeTy };
528 llvm::Value *UAddF
529 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
530 llvm::Value *AddRes
531 = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
532
533 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
534 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
535 Size = CGF.Builder.CreateSelect(DidOverflow,
536 llvm::ConstantInt::get(SizeTy, -1),
537 Size);
538 }
539
540 // Otherwise use the int.umul.with.overflow intrinsic.
541 } else {
542 llvm::Value *OutermostElementSize
543 = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
544
545 llvm::Value *NumOutermostElements = NumElements;
546
547 // Scale NumElements by the array size multiplier. This might
548 // overflow, but only if the multiplication below also overflows,
549 // in which case this multiplication isn't used.
550 if (ArraySizeMultiplier != 1)
551 NumElements = CGF.Builder.CreateMul(NumElements,
552 llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
553
554 // The requested size of the outermost array is non-constant.
555 // Multiply that by the static size of the elements of that array;
556 // on unsigned overflow, set the size to -1 to trigger an
557 // exception from the allocation routine. This is sufficient to
558 // prevent buffer overruns from the allocator returning a
559 // seemingly valid pointer to insufficient space. This idea comes
560 // originally from MSVC, and GCC has an open bug requesting
561 // similar behavior:
562 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
563 //
564 // This will not be sufficient for C++0x, which requires a
565 // specific exception class (std::bad_array_new_length).
566 // That will require ABI support that has not yet been specified.
567 const llvm::Type *Types[] = { SizeTy };
568 llvm::Value *UMulF
569 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
570 llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
571 OutermostElementSize);
572
573 // The overflow bit.
574 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
575
576 // The result of the multiplication.
577 Size = CGF.Builder.CreateExtractValue(MulRes, 0);
578
579 // If we have a cookie, we need to add that size in, too.
580 if (!CookieSize.isZero()) {
581 SizeWithoutCookie = Size;
582
583 llvm::Value *CookieSizeV
584 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
585 llvm::Value *UAddF
586 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
587 llvm::Value *AddRes
588 = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
589
590 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
591
592 llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
593 DidOverflow = CGF.Builder.CreateAnd(DidOverflow, AddDidOverflow);
594 }
595
596 Size = CGF.Builder.CreateSelect(DidOverflow,
597 llvm::ConstantInt::get(SizeTy, -1),
598 Size);
Chris Lattner806941e2010-07-20 21:55:52 +0000599 }
John McCall1e7fe752010-09-02 09:58:18 +0000600
601 if (CookieSize.isZero())
602 SizeWithoutCookie = Size;
603 else
604 assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
605
Chris Lattner806941e2010-07-20 21:55:52 +0000606 return Size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000607}
608
Fariborz Jahanianef668722010-06-25 18:26:07 +0000609static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
610 llvm::Value *NewPtr) {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000611
612 assert(E->getNumConstructorArgs() == 1 &&
613 "Can only have one argument to initializer of POD type.");
614
615 const Expr *Init = E->getConstructorArg(0);
616 QualType AllocType = E->getAllocatedType();
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000617
618 unsigned Alignment =
619 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
Fariborz Jahanianef668722010-06-25 18:26:07 +0000620 if (!CGF.hasAggregateLLVMType(AllocType))
621 CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000622 AllocType.isVolatileQualified(), Alignment,
623 AllocType);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000624 else if (AllocType->isAnyComplexType())
625 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
626 AllocType.isVolatileQualified());
John McCall558d2ab2010-09-15 10:14:12 +0000627 else {
628 AggValueSlot Slot
629 = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
630 CGF.EmitAggExpr(Init, Slot);
631 }
Fariborz Jahanianef668722010-06-25 18:26:07 +0000632}
633
634void
635CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
636 llvm::Value *NewPtr,
637 llvm::Value *NumElements) {
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000638 // We have a POD type.
639 if (E->getNumConstructorArgs() == 0)
640 return;
641
Fariborz Jahanianef668722010-06-25 18:26:07 +0000642 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
643
644 // Create a temporary for the loop index and initialize it with 0.
645 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
646 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
647 Builder.CreateStore(Zero, IndexPtr);
648
649 // Start the loop with a block that tests the condition.
650 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
651 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
652
653 EmitBlock(CondBlock);
654
655 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
656
657 // Generate: if (loop-index < number-of-elements fall to the loop body,
658 // otherwise, go to the block after the for-loop.
659 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
660 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
661 // If the condition is true, execute the body.
662 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
663
664 EmitBlock(ForBody);
665
666 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
667 // Inside the loop body, emit the constructor call on the array element.
668 Counter = Builder.CreateLoad(IndexPtr);
669 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
670 "arrayidx");
671 StoreAnyExprIntoOneUnit(*this, E, Address);
672
673 EmitBlock(ContinueBlock);
674
675 // Emit the increment of the loop counter.
676 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
677 Counter = Builder.CreateLoad(IndexPtr);
678 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
679 Builder.CreateStore(NextVal, IndexPtr);
680
681 // Finally, branch back up to the condition for the next iteration.
682 EmitBranch(CondBlock);
683
684 // Emit the fall-through block.
685 EmitBlock(AfterFor, true);
686}
687
Douglas Gregor59174c02010-07-21 01:10:17 +0000688static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
689 llvm::Value *NewPtr, llvm::Value *Size) {
690 llvm::LLVMContext &VMContext = CGF.CGM.getLLVMContext();
691 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
692 if (NewPtr->getType() != BP)
693 NewPtr = CGF.Builder.CreateBitCast(NewPtr, BP, "tmp");
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000694
Ken Dyckfe710082011-01-19 01:58:38 +0000695 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000696 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000697 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000698}
699
Anders Carlssona4d4c012009-09-23 16:07:23 +0000700static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
701 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000702 llvm::Value *NumElements,
703 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000704 if (E->isArray()) {
Anders Carlssone99bdb62010-05-03 15:09:17 +0000705 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000706 bool RequiresZeroInitialization = false;
707 if (Ctor->getParent()->hasTrivialConstructor()) {
708 // If new expression did not specify value-initialization, then there
709 // is no initialization.
710 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
711 return;
712
John McCallf16aa102010-08-22 21:01:12 +0000713 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000714 // Optimization: since zero initialization will just set the memory
715 // to all zeroes, generate a single memset to do it in one shot.
716 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
717 AllocSizeWithoutCookie);
718 return;
719 }
720
721 RequiresZeroInitialization = true;
722 }
723
724 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
725 E->constructor_arg_begin(),
726 E->constructor_arg_end(),
727 RequiresZeroInitialization);
Anders Carlssone99bdb62010-05-03 15:09:17 +0000728 return;
Douglas Gregor59174c02010-07-21 01:10:17 +0000729 } else if (E->getNumConstructorArgs() == 1 &&
730 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
731 // Optimization: since zero initialization will just set the memory
732 // to all zeroes, generate a single memset to do it in one shot.
733 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
734 AllocSizeWithoutCookie);
735 return;
736 } else {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000737 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
738 return;
739 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000740 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000741
742 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregored8abf12010-07-08 06:14:04 +0000743 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
744 // direct initialization. C++ [dcl.init]p5 requires that we
745 // zero-initialize storage if there are no user-declared constructors.
746 if (E->hasInitializer() &&
747 !Ctor->getParent()->hasUserDeclaredConstructor() &&
748 !Ctor->getParent()->isEmpty())
749 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
750
Douglas Gregor84745672010-07-07 23:37:33 +0000751 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
752 NewPtr, E->constructor_arg_begin(),
753 E->constructor_arg_end());
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000754
755 return;
756 }
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000757 // We have a POD type.
758 if (E->getNumConstructorArgs() == 0)
759 return;
760
Fariborz Jahanianef668722010-06-25 18:26:07 +0000761 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000762}
763
John McCall7d8647f2010-09-14 07:57:04 +0000764namespace {
765 /// A cleanup to call the given 'operator delete' function upon
766 /// abnormal exit from a new expression.
767 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
768 size_t NumPlacementArgs;
769 const FunctionDecl *OperatorDelete;
770 llvm::Value *Ptr;
771 llvm::Value *AllocSize;
772
773 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
774
775 public:
776 static size_t getExtraSize(size_t NumPlacementArgs) {
777 return NumPlacementArgs * sizeof(RValue);
778 }
779
780 CallDeleteDuringNew(size_t NumPlacementArgs,
781 const FunctionDecl *OperatorDelete,
782 llvm::Value *Ptr,
783 llvm::Value *AllocSize)
784 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
785 Ptr(Ptr), AllocSize(AllocSize) {}
786
787 void setPlacementArg(unsigned I, RValue Arg) {
788 assert(I < NumPlacementArgs && "index out of range");
789 getPlacementArgs()[I] = Arg;
790 }
791
792 void Emit(CodeGenFunction &CGF, bool IsForEH) {
793 const FunctionProtoType *FPT
794 = OperatorDelete->getType()->getAs<FunctionProtoType>();
795 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +0000796 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +0000797
798 CallArgList DeleteArgs;
799
800 // The first argument is always a void*.
801 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
802 DeleteArgs.push_back(std::make_pair(RValue::get(Ptr), *AI++));
803
804 // A member 'operator delete' can take an extra 'size_t' argument.
805 if (FPT->getNumArgs() == NumPlacementArgs + 2)
806 DeleteArgs.push_back(std::make_pair(RValue::get(AllocSize), *AI++));
807
808 // Pass the rest of the arguments, which must match exactly.
809 for (unsigned I = 0; I != NumPlacementArgs; ++I)
810 DeleteArgs.push_back(std::make_pair(getPlacementArgs()[I], *AI++));
811
812 // Call 'operator delete'.
813 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
814 CGF.CGM.GetAddrOfFunction(OperatorDelete),
815 ReturnValueSlot(), DeleteArgs, OperatorDelete);
816 }
817 };
John McCall3019c442010-09-17 00:50:28 +0000818
819 /// A cleanup to call the given 'operator delete' function upon
820 /// abnormal exit from a new expression when the new expression is
821 /// conditional.
822 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
823 size_t NumPlacementArgs;
824 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +0000825 DominatingValue<RValue>::saved_type Ptr;
826 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +0000827
John McCall804b8072011-01-28 10:53:53 +0000828 DominatingValue<RValue>::saved_type *getPlacementArgs() {
829 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +0000830 }
831
832 public:
833 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +0000834 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +0000835 }
836
837 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
838 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +0000839 DominatingValue<RValue>::saved_type Ptr,
840 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +0000841 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
842 Ptr(Ptr), AllocSize(AllocSize) {}
843
John McCall804b8072011-01-28 10:53:53 +0000844 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +0000845 assert(I < NumPlacementArgs && "index out of range");
846 getPlacementArgs()[I] = Arg;
847 }
848
849 void Emit(CodeGenFunction &CGF, bool IsForEH) {
850 const FunctionProtoType *FPT
851 = OperatorDelete->getType()->getAs<FunctionProtoType>();
852 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
853 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
854
855 CallArgList DeleteArgs;
856
857 // The first argument is always a void*.
858 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
John McCall804b8072011-01-28 10:53:53 +0000859 DeleteArgs.push_back(std::make_pair(Ptr.restore(CGF), *AI++));
John McCall3019c442010-09-17 00:50:28 +0000860
861 // A member 'operator delete' can take an extra 'size_t' argument.
862 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +0000863 RValue RV = AllocSize.restore(CGF);
John McCall3019c442010-09-17 00:50:28 +0000864 DeleteArgs.push_back(std::make_pair(RV, *AI++));
865 }
866
867 // Pass the rest of the arguments, which must match exactly.
868 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +0000869 RValue RV = getPlacementArgs()[I].restore(CGF);
John McCall3019c442010-09-17 00:50:28 +0000870 DeleteArgs.push_back(std::make_pair(RV, *AI++));
871 }
872
873 // Call 'operator delete'.
874 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
875 CGF.CGM.GetAddrOfFunction(OperatorDelete),
876 ReturnValueSlot(), DeleteArgs, OperatorDelete);
877 }
878 };
879}
880
881/// Enter a cleanup to call 'operator delete' if the initializer in a
882/// new-expression throws.
883static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
884 const CXXNewExpr *E,
885 llvm::Value *NewPtr,
886 llvm::Value *AllocSize,
887 const CallArgList &NewArgs) {
888 // If we're not inside a conditional branch, then the cleanup will
889 // dominate and we can do the easier (and more efficient) thing.
890 if (!CGF.isInConditionalBranch()) {
891 CallDeleteDuringNew *Cleanup = CGF.EHStack
892 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
893 E->getNumPlacementArgs(),
894 E->getOperatorDelete(),
895 NewPtr, AllocSize);
896 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
897 Cleanup->setPlacementArg(I, NewArgs[I+1].first);
898
899 return;
900 }
901
902 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +0000903 DominatingValue<RValue>::saved_type SavedNewPtr =
904 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
905 DominatingValue<RValue>::saved_type SavedAllocSize =
906 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +0000907
908 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
909 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
910 E->getNumPlacementArgs(),
911 E->getOperatorDelete(),
912 SavedNewPtr,
913 SavedAllocSize);
914 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +0000915 Cleanup->setPlacementArg(I,
916 DominatingValue<RValue>::save(CGF, NewArgs[I+1].first));
John McCall3019c442010-09-17 00:50:28 +0000917
918 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall7d8647f2010-09-14 07:57:04 +0000919}
920
Anders Carlsson16d81b82009-09-22 22:53:17 +0000921llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlsson16d81b82009-09-22 22:53:17 +0000922 QualType AllocType = E->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000923 if (AllocType->isArrayType())
924 while (const ArrayType *AType = getContext().getAsArrayType(AllocType))
925 AllocType = AType->getElementType();
926
Anders Carlsson16d81b82009-09-22 22:53:17 +0000927 FunctionDecl *NewFD = E->getOperatorNew();
928 const FunctionProtoType *NewFTy = NewFD->getType()->getAs<FunctionProtoType>();
929
930 CallArgList NewArgs;
931
932 // The allocation size is the first argument.
933 QualType SizeTy = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000934
Anders Carlssona4d4c012009-09-23 16:07:23 +0000935 llvm::Value *NumElements = 0;
Douglas Gregor59174c02010-07-21 01:10:17 +0000936 llvm::Value *AllocSizeWithoutCookie = 0;
Fariborz Jahanianceb43b62010-03-24 16:57:01 +0000937 llvm::Value *AllocSize = EmitCXXNewAllocSize(getContext(),
Douglas Gregor59174c02010-07-21 01:10:17 +0000938 *this, E, NumElements,
939 AllocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000940
Anders Carlsson16d81b82009-09-22 22:53:17 +0000941 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
942
943 // Emit the rest of the arguments.
944 // FIXME: Ideally, this should just use EmitCallArgs.
945 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
946
947 // First, use the types from the function type.
948 // We start at 1 here because the first argument (the allocation size)
949 // has already been emitted.
950 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
951 QualType ArgType = NewFTy->getArgType(i);
952
953 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
954 getTypePtr() ==
955 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
956 "type mismatch in call argument!");
957
958 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
959 ArgType));
960
961 }
962
963 // Either we've emitted all the call args, or we have a call to a
964 // variadic function.
965 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
966 "Extra arguments in non-variadic function!");
967
968 // If we still have any arguments, emit them using the type of the argument.
969 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
970 NewArg != NewArgEnd; ++NewArg) {
971 QualType ArgType = NewArg->getType();
972 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
973 ArgType));
974 }
975
976 // Emit the call to new.
977 RValue RV =
John McCall04a67a62010-02-05 21:31:56 +0000978 EmitCall(CGM.getTypes().getFunctionInfo(NewArgs, NewFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000979 CGM.GetAddrOfFunction(NewFD), ReturnValueSlot(), NewArgs, NewFD);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000980
981 // If an allocation function is declared with an empty exception specification
982 // it returns null to indicate failure to allocate storage. [expr.new]p13.
983 // (We don't need to check for null when there's no new initializer and
984 // we're allocating a POD type).
985 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
986 !(AllocType->isPODType() && !E->hasInitializer());
987
John McCall1e7fe752010-09-02 09:58:18 +0000988 llvm::BasicBlock *NullCheckSource = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +0000989 llvm::BasicBlock *NewNotNull = 0;
990 llvm::BasicBlock *NewEnd = 0;
991
992 llvm::Value *NewPtr = RV.getScalarVal();
John McCall1e7fe752010-09-02 09:58:18 +0000993 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000994
995 if (NullCheckResult) {
John McCall1e7fe752010-09-02 09:58:18 +0000996 NullCheckSource = Builder.GetInsertBlock();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000997 NewNotNull = createBasicBlock("new.notnull");
998 NewEnd = createBasicBlock("new.end");
999
John McCall1e7fe752010-09-02 09:58:18 +00001000 llvm::Value *IsNull = Builder.CreateIsNull(NewPtr, "new.isnull");
1001 Builder.CreateCondBr(IsNull, NewEnd, NewNotNull);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001002 EmitBlock(NewNotNull);
1003 }
Ken Dyckcaf647c2010-01-26 19:44:24 +00001004
John McCall1e7fe752010-09-02 09:58:18 +00001005 assert((AllocSize == AllocSizeWithoutCookie) ==
1006 CalculateCookiePadding(*this, E).isZero());
1007 if (AllocSize != AllocSizeWithoutCookie) {
1008 assert(E->isArray());
1009 NewPtr = CGM.getCXXABI().InitializeArrayCookie(CGF, NewPtr, NumElements,
John McCall6ec278d2011-01-27 09:37:56 +00001010 E, AllocType);
John McCall1e7fe752010-09-02 09:58:18 +00001011 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001012
John McCall7d8647f2010-09-14 07:57:04 +00001013 // If there's an operator delete, enter a cleanup to call it if an
1014 // exception is thrown.
1015 EHScopeStack::stable_iterator CallOperatorDelete;
1016 if (E->getOperatorDelete()) {
John McCall3019c442010-09-17 00:50:28 +00001017 EnterNewDeleteCleanup(*this, E, NewPtr, AllocSize, NewArgs);
John McCall7d8647f2010-09-14 07:57:04 +00001018 CallOperatorDelete = EHStack.stable_begin();
1019 }
1020
Douglas Gregorcc09c022010-09-02 23:24:14 +00001021 const llvm::Type *ElementPtrTy
1022 = ConvertTypeForMem(AllocType)->getPointerTo(AS);
John McCall1e7fe752010-09-02 09:58:18 +00001023 NewPtr = Builder.CreateBitCast(NewPtr, ElementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001024
John McCall1e7fe752010-09-02 09:58:18 +00001025 if (E->isArray()) {
Douglas Gregor59174c02010-07-21 01:10:17 +00001026 EmitNewInitializer(*this, E, NewPtr, NumElements, AllocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001027
1028 // NewPtr is a pointer to the base element type. If we're
1029 // allocating an array of arrays, we'll need to cast back to the
1030 // array pointer type.
Douglas Gregorcc09c022010-09-02 23:24:14 +00001031 const llvm::Type *ResultTy = ConvertTypeForMem(E->getType());
John McCall1e7fe752010-09-02 09:58:18 +00001032 if (NewPtr->getType() != ResultTy)
1033 NewPtr = Builder.CreateBitCast(NewPtr, ResultTy);
1034 } else {
Douglas Gregor59174c02010-07-21 01:10:17 +00001035 EmitNewInitializer(*this, E, NewPtr, NumElements, AllocSizeWithoutCookie);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001036 }
John McCall7d8647f2010-09-14 07:57:04 +00001037
1038 // Deactivate the 'operator delete' cleanup if we finished
1039 // initialization.
1040 if (CallOperatorDelete.isValid())
1041 DeactivateCleanupBlock(CallOperatorDelete);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001042
Anders Carlsson16d81b82009-09-22 22:53:17 +00001043 if (NullCheckResult) {
1044 Builder.CreateBr(NewEnd);
John McCall1e7fe752010-09-02 09:58:18 +00001045 llvm::BasicBlock *NotNullSource = Builder.GetInsertBlock();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001046 EmitBlock(NewEnd);
1047
1048 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
1049 PHI->reserveOperandSpace(2);
John McCall1e7fe752010-09-02 09:58:18 +00001050 PHI->addIncoming(NewPtr, NotNullSource);
1051 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()),
1052 NullCheckSource);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001053
1054 NewPtr = PHI;
1055 }
John McCall1e7fe752010-09-02 09:58:18 +00001056
Anders Carlsson16d81b82009-09-22 22:53:17 +00001057 return NewPtr;
1058}
1059
Eli Friedman5fe05982009-11-18 00:50:08 +00001060void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1061 llvm::Value *Ptr,
1062 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001063 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1064
Eli Friedman5fe05982009-11-18 00:50:08 +00001065 const FunctionProtoType *DeleteFTy =
1066 DeleteFD->getType()->getAs<FunctionProtoType>();
1067
1068 CallArgList DeleteArgs;
1069
Anders Carlsson871d0782009-12-13 20:04:38 +00001070 // Check if we need to pass the size to the delete operator.
1071 llvm::Value *Size = 0;
1072 QualType SizeTy;
1073 if (DeleteFTy->getNumArgs() == 2) {
1074 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001075 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1076 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1077 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001078 }
1079
Eli Friedman5fe05982009-11-18 00:50:08 +00001080 QualType ArgTy = DeleteFTy->getArgType(0);
1081 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1082 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
1083
Anders Carlsson871d0782009-12-13 20:04:38 +00001084 if (Size)
Eli Friedman5fe05982009-11-18 00:50:08 +00001085 DeleteArgs.push_back(std::make_pair(RValue::get(Size), SizeTy));
Eli Friedman5fe05982009-11-18 00:50:08 +00001086
1087 // Emit the call to delete.
John McCall04a67a62010-02-05 21:31:56 +00001088 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001089 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +00001090 DeleteArgs, DeleteFD);
1091}
1092
John McCall1e7fe752010-09-02 09:58:18 +00001093namespace {
1094 /// Calls the given 'operator delete' on a single object.
1095 struct CallObjectDelete : EHScopeStack::Cleanup {
1096 llvm::Value *Ptr;
1097 const FunctionDecl *OperatorDelete;
1098 QualType ElementType;
1099
1100 CallObjectDelete(llvm::Value *Ptr,
1101 const FunctionDecl *OperatorDelete,
1102 QualType ElementType)
1103 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1104
1105 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1106 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1107 }
1108 };
1109}
1110
1111/// Emit the code for deleting a single object.
1112static void EmitObjectDelete(CodeGenFunction &CGF,
1113 const FunctionDecl *OperatorDelete,
1114 llvm::Value *Ptr,
1115 QualType ElementType) {
1116 // Find the destructor for the type, if applicable. If the
1117 // destructor is virtual, we'll just emit the vcall and return.
1118 const CXXDestructorDecl *Dtor = 0;
1119 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1120 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1121 if (!RD->hasTrivialDestructor()) {
1122 Dtor = RD->getDestructor();
1123
1124 if (Dtor->isVirtual()) {
1125 const llvm::Type *Ty =
John McCallfc400282010-09-03 01:26:39 +00001126 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1127 Dtor_Complete),
John McCall1e7fe752010-09-02 09:58:18 +00001128 /*isVariadic=*/false);
1129
1130 llvm::Value *Callee
1131 = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
1132 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1133 0, 0);
1134
1135 // The dtor took care of deleting the object.
1136 return;
1137 }
1138 }
1139 }
1140
1141 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001142 // This doesn't have to a conditional cleanup because we're going
1143 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001144 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1145 Ptr, OperatorDelete, ElementType);
1146
1147 if (Dtor)
1148 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1149 /*ForVirtualBase=*/false, Ptr);
1150
1151 CGF.PopCleanupBlock();
1152}
1153
1154namespace {
1155 /// Calls the given 'operator delete' on an array of objects.
1156 struct CallArrayDelete : EHScopeStack::Cleanup {
1157 llvm::Value *Ptr;
1158 const FunctionDecl *OperatorDelete;
1159 llvm::Value *NumElements;
1160 QualType ElementType;
1161 CharUnits CookieSize;
1162
1163 CallArrayDelete(llvm::Value *Ptr,
1164 const FunctionDecl *OperatorDelete,
1165 llvm::Value *NumElements,
1166 QualType ElementType,
1167 CharUnits CookieSize)
1168 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1169 ElementType(ElementType), CookieSize(CookieSize) {}
1170
1171 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1172 const FunctionProtoType *DeleteFTy =
1173 OperatorDelete->getType()->getAs<FunctionProtoType>();
1174 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1175
1176 CallArgList Args;
1177
1178 // Pass the pointer as the first argument.
1179 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1180 llvm::Value *DeletePtr
1181 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
1182 Args.push_back(std::make_pair(RValue::get(DeletePtr), VoidPtrTy));
1183
1184 // Pass the original requested size as the second argument.
1185 if (DeleteFTy->getNumArgs() == 2) {
1186 QualType size_t = DeleteFTy->getArgType(1);
1187 const llvm::IntegerType *SizeTy
1188 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1189
1190 CharUnits ElementTypeSize =
1191 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1192
1193 // The size of an element, multiplied by the number of elements.
1194 llvm::Value *Size
1195 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1196 Size = CGF.Builder.CreateMul(Size, NumElements);
1197
1198 // Plus the size of the cookie if applicable.
1199 if (!CookieSize.isZero()) {
1200 llvm::Value *CookieSizeV
1201 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1202 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1203 }
1204
1205 Args.push_back(std::make_pair(RValue::get(Size), size_t));
1206 }
1207
1208 // Emit the call to delete.
1209 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
1210 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1211 ReturnValueSlot(), Args, OperatorDelete);
1212 }
1213 };
1214}
1215
1216/// Emit the code for deleting an array of objects.
1217static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001218 const CXXDeleteExpr *E,
John McCall1e7fe752010-09-02 09:58:18 +00001219 llvm::Value *Ptr,
1220 QualType ElementType) {
1221 llvm::Value *NumElements = 0;
1222 llvm::Value *AllocatedPtr = 0;
1223 CharUnits CookieSize;
John McCall6ec278d2011-01-27 09:37:56 +00001224 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, E, ElementType,
John McCall1e7fe752010-09-02 09:58:18 +00001225 NumElements, AllocatedPtr, CookieSize);
1226
1227 assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
1228
1229 // Make sure that we call delete even if one of the dtors throws.
John McCall6ec278d2011-01-27 09:37:56 +00001230 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001231 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1232 AllocatedPtr, OperatorDelete,
1233 NumElements, ElementType,
1234 CookieSize);
1235
1236 if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
1237 if (!RD->hasTrivialDestructor()) {
1238 assert(NumElements && "ReadArrayCookie didn't find element count"
1239 " for a class with destructor");
1240 CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
1241 }
1242 }
1243
1244 CGF.PopCleanupBlock();
1245}
1246
Anders Carlsson16d81b82009-09-22 22:53:17 +00001247void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian72c21532009-11-13 19:27:47 +00001248
Douglas Gregor90916562009-09-29 18:16:17 +00001249 // Get at the argument before we performed the implicit conversion
1250 // to void*.
1251 const Expr *Arg = E->getArgument();
1252 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00001253 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregor90916562009-09-29 18:16:17 +00001254 ICE->getType()->isVoidPointerType())
1255 Arg = ICE->getSubExpr();
Douglas Gregord69dd782009-10-01 05:49:51 +00001256 else
1257 break;
Douglas Gregor90916562009-09-29 18:16:17 +00001258 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001259
Douglas Gregor90916562009-09-29 18:16:17 +00001260 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001261
1262 // Null check the pointer.
1263 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1264 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1265
1266 llvm::Value *IsNull =
1267 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
1268 "isnull");
1269
1270 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1271 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001272
John McCall1e7fe752010-09-02 09:58:18 +00001273 // We might be deleting a pointer to array. If so, GEP down to the
1274 // first non-array element.
1275 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1276 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1277 if (DeleteTy->isConstantArrayType()) {
1278 llvm::Value *Zero = Builder.getInt32(0);
1279 llvm::SmallVector<llvm::Value*,8> GEP;
1280
1281 GEP.push_back(Zero); // point at the outermost array
1282
1283 // For each layer of array type we're pointing at:
1284 while (const ConstantArrayType *Arr
1285 = getContext().getAsConstantArrayType(DeleteTy)) {
1286 // 1. Unpeel the array type.
1287 DeleteTy = Arr->getElementType();
1288
1289 // 2. GEP to the first element of the array.
1290 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001291 }
John McCall1e7fe752010-09-02 09:58:18 +00001292
1293 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001294 }
1295
Douglas Gregoreede61a2010-09-02 17:38:50 +00001296 assert(ConvertTypeForMem(DeleteTy) ==
1297 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001298
1299 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001300 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001301 } else {
1302 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1303 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001304
Anders Carlsson16d81b82009-09-22 22:53:17 +00001305 EmitBlock(DeleteEnd);
1306}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001307
John McCall3ad32c82011-01-28 08:37:24 +00001308llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001309 QualType Ty = E->getType();
1310 const llvm::Type *LTy = ConvertType(Ty)->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001311
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001312 if (E->isTypeOperand()) {
1313 llvm::Constant *TypeInfo =
1314 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
1315 return Builder.CreateBitCast(TypeInfo, LTy);
1316 }
1317
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001318 Expr *subE = E->getExprOperand();
Mike Stump5fae8562009-11-17 22:33:00 +00001319 Ty = subE->getType();
1320 CanQualType CanTy = CGM.getContext().getCanonicalType(Ty);
1321 Ty = CanTy.getUnqualifiedType().getNonReferenceType();
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001322 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1323 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1324 if (RD->isPolymorphic()) {
1325 // FIXME: if subE is an lvalue do
1326 LValue Obj = EmitLValue(subE);
1327 llvm::Value *This = Obj.getAddress();
Mike Stumpf549e892009-11-15 16:52:53 +00001328 // We need to do a zero check for *p, unless it has NonNullAttr.
1329 // FIXME: PointerType->hasAttr<NonNullAttr>()
1330 bool CanBeZero = false;
Mike Stumpdb519a42009-11-17 00:45:21 +00001331 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(subE->IgnoreParens()))
John McCall2de56d12010-08-25 11:45:40 +00001332 if (UO->getOpcode() == UO_Deref)
Mike Stumpf549e892009-11-15 16:52:53 +00001333 CanBeZero = true;
1334 if (CanBeZero) {
1335 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
1336 llvm::BasicBlock *ZeroBlock = createBasicBlock();
1337
Dan Gohman043fb9a2010-10-26 18:44:08 +00001338 llvm::Value *Zero = llvm::Constant::getNullValue(This->getType());
1339 Builder.CreateCondBr(Builder.CreateICmpNE(This, Zero),
Mike Stumpf549e892009-11-15 16:52:53 +00001340 NonZeroBlock, ZeroBlock);
1341 EmitBlock(ZeroBlock);
1342 /// Call __cxa_bad_typeid
1343 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1344 const llvm::FunctionType *FTy;
1345 FTy = llvm::FunctionType::get(ResultType, false);
1346 llvm::Value *F = CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
Mike Stumpc849c052009-11-16 06:50:58 +00001347 Builder.CreateCall(F)->setDoesNotReturn();
Mike Stumpf549e892009-11-15 16:52:53 +00001348 Builder.CreateUnreachable();
1349 EmitBlock(NonZeroBlock);
1350 }
Dan Gohman043fb9a2010-10-26 18:44:08 +00001351 llvm::Value *V = GetVTablePtr(This, LTy->getPointerTo());
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001352 V = Builder.CreateConstInBoundsGEP1_64(V, -1ULL);
1353 V = Builder.CreateLoad(V);
1354 return V;
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001355 }
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001356 }
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001357 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(Ty), LTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001358}
Mike Stumpc849c052009-11-16 06:50:58 +00001359
1360llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *V,
1361 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001362 QualType SrcTy = DCE->getSubExpr()->getType();
1363 QualType DestTy = DCE->getTypeAsWritten();
1364 QualType InnerType = DestTy->getPointeeType();
1365
Mike Stumpc849c052009-11-16 06:50:58 +00001366 const llvm::Type *LTy = ConvertType(DCE->getType());
Mike Stump2b35baf2009-11-16 22:52:20 +00001367
Mike Stumpc849c052009-11-16 06:50:58 +00001368 bool CanBeZero = false;
Mike Stumpc849c052009-11-16 06:50:58 +00001369 bool ToVoid = false;
Mike Stump2b35baf2009-11-16 22:52:20 +00001370 bool ThrowOnBad = false;
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001371 if (DestTy->isPointerType()) {
Mike Stumpc849c052009-11-16 06:50:58 +00001372 // FIXME: if PointerType->hasAttr<NonNullAttr>(), we don't set this
1373 CanBeZero = true;
1374 if (InnerType->isVoidType())
1375 ToVoid = true;
1376 } else {
1377 LTy = LTy->getPointerTo();
Douglas Gregor485ee322010-05-14 21:14:41 +00001378
1379 // FIXME: What if exceptions are disabled?
Mike Stumpc849c052009-11-16 06:50:58 +00001380 ThrowOnBad = true;
1381 }
1382
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001383 if (SrcTy->isPointerType() || SrcTy->isReferenceType())
1384 SrcTy = SrcTy->getPointeeType();
1385 SrcTy = SrcTy.getUnqualifiedType();
1386
Anders Carlsson6f0e4852009-12-18 14:55:04 +00001387 if (DestTy->isPointerType() || DestTy->isReferenceType())
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001388 DestTy = DestTy->getPointeeType();
1389 DestTy = DestTy.getUnqualifiedType();
Mike Stumpc849c052009-11-16 06:50:58 +00001390
Mike Stumpc849c052009-11-16 06:50:58 +00001391 llvm::BasicBlock *ContBlock = createBasicBlock();
1392 llvm::BasicBlock *NullBlock = 0;
1393 llvm::BasicBlock *NonZeroBlock = 0;
1394 if (CanBeZero) {
1395 NonZeroBlock = createBasicBlock();
1396 NullBlock = createBasicBlock();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001397 Builder.CreateCondBr(Builder.CreateIsNotNull(V), NonZeroBlock, NullBlock);
Mike Stumpc849c052009-11-16 06:50:58 +00001398 EmitBlock(NonZeroBlock);
1399 }
1400
Mike Stumpc849c052009-11-16 06:50:58 +00001401 llvm::BasicBlock *BadCastBlock = 0;
Mike Stumpc849c052009-11-16 06:50:58 +00001402
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001403 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
Mike Stump2b35baf2009-11-16 22:52:20 +00001404
1405 // See if this is a dynamic_cast(void*)
1406 if (ToVoid) {
1407 llvm::Value *This = V;
Dan Gohman043fb9a2010-10-26 18:44:08 +00001408 V = GetVTablePtr(This, PtrDiffTy->getPointerTo());
Mike Stump2b35baf2009-11-16 22:52:20 +00001409 V = Builder.CreateConstInBoundsGEP1_64(V, -2ULL);
1410 V = Builder.CreateLoad(V, "offset to top");
1411 This = Builder.CreateBitCast(This, llvm::Type::getInt8PtrTy(VMContext));
1412 V = Builder.CreateInBoundsGEP(This, V);
1413 V = Builder.CreateBitCast(V, LTy);
1414 } else {
1415 /// Call __dynamic_cast
1416 const llvm::Type *ResultType = llvm::Type::getInt8PtrTy(VMContext);
1417 const llvm::FunctionType *FTy;
1418 std::vector<const llvm::Type*> ArgTys;
1419 const llvm::Type *PtrToInt8Ty
1420 = llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1421 ArgTys.push_back(PtrToInt8Ty);
1422 ArgTys.push_back(PtrToInt8Ty);
1423 ArgTys.push_back(PtrToInt8Ty);
1424 ArgTys.push_back(PtrDiffTy);
1425 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump2b35baf2009-11-16 22:52:20 +00001426
1427 // FIXME: Calculate better hint.
1428 llvm::Value *hint = llvm::ConstantInt::get(PtrDiffTy, -1ULL);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001429
1430 assert(SrcTy->isRecordType() && "Src type must be record type!");
1431 assert(DestTy->isRecordType() && "Dest type must be record type!");
1432
Douglas Gregor154fe982009-12-23 22:04:40 +00001433 llvm::Value *SrcArg
1434 = CGM.GetAddrOfRTTIDescriptor(SrcTy.getUnqualifiedType());
1435 llvm::Value *DestArg
1436 = CGM.GetAddrOfRTTIDescriptor(DestTy.getUnqualifiedType());
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001437
Mike Stump2b35baf2009-11-16 22:52:20 +00001438 V = Builder.CreateBitCast(V, PtrToInt8Ty);
1439 V = Builder.CreateCall4(CGM.CreateRuntimeFunction(FTy, "__dynamic_cast"),
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001440 V, SrcArg, DestArg, hint);
Mike Stump2b35baf2009-11-16 22:52:20 +00001441 V = Builder.CreateBitCast(V, LTy);
1442
1443 if (ThrowOnBad) {
1444 BadCastBlock = createBasicBlock();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001445 Builder.CreateCondBr(Builder.CreateIsNotNull(V), ContBlock, BadCastBlock);
Mike Stump2b35baf2009-11-16 22:52:20 +00001446 EmitBlock(BadCastBlock);
Douglas Gregor485ee322010-05-14 21:14:41 +00001447 /// Invoke __cxa_bad_cast
Mike Stump2b35baf2009-11-16 22:52:20 +00001448 ResultType = llvm::Type::getVoidTy(VMContext);
1449 const llvm::FunctionType *FBadTy;
Mike Stumpfde17be2009-11-17 03:01:03 +00001450 FBadTy = llvm::FunctionType::get(ResultType, false);
Mike Stump2b35baf2009-11-16 22:52:20 +00001451 llvm::Value *F = CGM.CreateRuntimeFunction(FBadTy, "__cxa_bad_cast");
Douglas Gregor485ee322010-05-14 21:14:41 +00001452 if (llvm::BasicBlock *InvokeDest = getInvokeDest()) {
1453 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
1454 Builder.CreateInvoke(F, Cont, InvokeDest)->setDoesNotReturn();
1455 EmitBlock(Cont);
1456 } else {
1457 // FIXME: Does this ever make sense?
1458 Builder.CreateCall(F)->setDoesNotReturn();
1459 }
Mike Stump8b152b82009-11-17 00:08:50 +00001460 Builder.CreateUnreachable();
Mike Stump2b35baf2009-11-16 22:52:20 +00001461 }
Mike Stumpc849c052009-11-16 06:50:58 +00001462 }
1463
1464 if (CanBeZero) {
1465 Builder.CreateBr(ContBlock);
1466 EmitBlock(NullBlock);
1467 Builder.CreateBr(ContBlock);
1468 }
1469 EmitBlock(ContBlock);
1470 if (CanBeZero) {
1471 llvm::PHINode *PHI = Builder.CreatePHI(LTy);
Mike Stump14431c12009-11-17 00:10:05 +00001472 PHI->reserveOperandSpace(2);
Mike Stumpc849c052009-11-16 06:50:58 +00001473 PHI->addIncoming(V, NonZeroBlock);
1474 PHI->addIncoming(llvm::Constant::getNullValue(LTy), NullBlock);
Mike Stumpc849c052009-11-16 06:50:58 +00001475 V = PHI;
1476 }
1477
1478 return V;
1479}