blob: d0d0f4eb1fafbf57b3af173c3e71561192ad0752 [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();
Tilmann Scheller9c6082f2011-03-02 21:36:49 +000051 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
52 FPT->getExtInfo()),
Rafael Espindola264ba482010-03-30 20:24:48 +000053 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 {
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000228 if (getContext().getLangOptions().AppleKext &&
229 MD->isVirtual() &&
230 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000231 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000232 else
233 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000234 }
Francois Pichetdbee3412011-01-18 05:04:39 +0000235 } else if (const CXXConstructorDecl *Ctor =
236 dyn_cast<CXXConstructorDecl>(MD)) {
237 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000238 } else if (UseVirtualCall) {
Fariborz Jahanian27262672011-01-20 17:19:02 +0000239 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000240 } else {
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000241 if (getContext().getLangOptions().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000242 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000243 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000244 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000245 else
246 Callee = CGM.GetAddrOfFunction(MD, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000247 }
248
Anders Carlssonc997d422010-01-02 01:01:18 +0000249 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000250 CE->arg_begin(), CE->arg_end());
251}
252
253RValue
254CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
255 ReturnValueSlot ReturnValue) {
256 const BinaryOperator *BO =
257 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
258 const Expr *BaseExpr = BO->getLHS();
259 const Expr *MemFnExpr = BO->getRHS();
260
261 const MemberPointerType *MPT =
262 MemFnExpr->getType()->getAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000263
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000264 const FunctionProtoType *FPT =
265 MPT->getPointeeType()->getAs<FunctionProtoType>();
266 const CXXRecordDecl *RD =
267 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
268
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000269 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000270 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000271
272 // Emit the 'this' pointer.
273 llvm::Value *This;
274
John McCall2de56d12010-08-25 11:45:40 +0000275 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000276 This = EmitScalarExpr(BaseExpr);
277 else
278 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000279
John McCall93d557b2010-08-22 00:05:51 +0000280 // Ask the ABI to load the callee. Note that This is modified.
281 llvm::Value *Callee =
John McCalld16c2cf2011-02-08 08:22:06 +0000282 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000283
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000284 CallArgList Args;
285
286 QualType ThisType =
287 getContext().getPointerType(getContext().getTagDeclType(RD));
288
289 // Push the this ptr.
290 Args.push_back(std::make_pair(RValue::get(This), ThisType));
291
292 // And the rest of the call args
293 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall04a67a62010-02-05 21:31:56 +0000294 const FunctionType *BO_FPT = BO->getType()->getAs<FunctionProtoType>();
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000295 return EmitCall(CGM.getTypes().getFunctionInfo(Args, BO_FPT), Callee,
296 ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000297}
298
299RValue
300CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
301 const CXXMethodDecl *MD,
302 ReturnValueSlot ReturnValue) {
303 assert(MD->isInstance() &&
304 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000305 LValue LV = EmitLValue(E->getArg(0));
306 llvm::Value *This = LV.getAddress();
307
Douglas Gregor3e9438b2010-09-27 22:37:28 +0000308 if (MD->isCopyAssignmentOperator()) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000309 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
310 if (ClassDecl->hasTrivialCopyAssignment()) {
311 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
312 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000313 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
314 QualType Ty = E->getType();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000315 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000316 return RValue::get(This);
317 }
318 }
319
320 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
321 const llvm::Type *Ty =
322 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
323 FPT->isVariadic());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000324 llvm::Value *Callee;
Fariborz Jahanian27262672011-01-20 17:19:02 +0000325 if (MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000326 !canDevirtualizeMemberFunctionCalls(getContext(),
327 E->getArg(0), MD))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000328 Callee = BuildVirtualCall(MD, This, Ty);
329 else
330 Callee = CGM.GetAddrOfFunction(MD, Ty);
331
Anders Carlssonc997d422010-01-02 01:01:18 +0000332 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000333 E->arg_begin() + 1, E->arg_end());
334}
335
336void
John McCall558d2ab2010-09-15 10:14:12 +0000337CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
338 AggValueSlot Dest) {
339 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000340 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000341
342 // If we require zero initialization before (or instead of) calling the
343 // constructor, as can be the case with a non-user-provided default
344 // constructor, emit the zero initialization now.
345 if (E->requiresZeroInitialization())
John McCall558d2ab2010-09-15 10:14:12 +0000346 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor759e41b2010-08-22 16:15:35 +0000347
348 // If this is a call to a trivial default constructor, do nothing.
349 if (CD->isTrivial() && CD->isDefaultConstructor())
350 return;
351
John McCallfc1e6c72010-09-18 00:58:34 +0000352 // Elide the constructor if we're constructing from a temporary.
353 // The temporary check is required because Sema sets this on NRVO
354 // returns.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000355 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000356 assert(getContext().hasSameUnqualifiedType(E->getType(),
357 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000358 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
359 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000360 return;
361 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000362 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000363
364 const ConstantArrayType *Array
365 = getContext().getAsConstantArrayType(E->getType());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000366 if (Array) {
367 QualType BaseElementTy = getContext().getBaseElementType(Array);
368 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
369 BasePtr = llvm::PointerType::getUnqual(BasePtr);
370 llvm::Value *BaseAddrPtr =
John McCall558d2ab2010-09-15 10:14:12 +0000371 Builder.CreateBitCast(Dest.getAddr(), BasePtr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000372
373 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
374 E->arg_begin(), E->arg_end());
375 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000376 else {
377 CXXCtorType Type =
378 (E->getConstructionKind() == CXXConstructExpr::CK_Complete)
379 ? Ctor_Complete : Ctor_Base;
380 bool ForVirtualBase =
381 E->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
382
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000383 // Call the constructor.
John McCall558d2ab2010-09-15 10:14:12 +0000384 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000385 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000386 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000387}
388
Fariborz Jahanian34999872010-11-13 21:53:34 +0000389void
390CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
391 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000392 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000393 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000394 Exp = E->getSubExpr();
395 assert(isa<CXXConstructExpr>(Exp) &&
396 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
397 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
398 const CXXConstructorDecl *CD = E->getConstructor();
399 RunCleanupsScope Scope(*this);
400
401 // If we require zero initialization before (or instead of) calling the
402 // constructor, as can be the case with a non-user-provided default
403 // constructor, emit the zero initialization now.
404 // FIXME. Do I still need this for a copy ctor synthesis?
405 if (E->requiresZeroInitialization())
406 EmitNullInitialization(Dest, E->getType());
407
Chandler Carruth858a5462010-11-15 13:54:43 +0000408 assert(!getContext().getAsConstantArrayType(E->getType())
409 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000410 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
411 E->arg_begin(), E->arg_end());
412}
413
John McCall5172ed92010-08-23 01:17:59 +0000414/// Check whether the given operator new[] is the global placement
415/// operator new[].
416static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
417 const FunctionDecl *Fn) {
418 // Must be in global scope. Note that allocation functions can't be
419 // declared in namespaces.
Sebastian Redl7a126a42010-08-31 00:36:30 +0000420 if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
John McCall5172ed92010-08-23 01:17:59 +0000421 return false;
422
423 // Signature must be void *operator new[](size_t, void*).
424 // The size_t is common to all operator new[]s.
425 if (Fn->getNumParams() != 2)
426 return false;
427
428 CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
429 return (ParamType == Ctx.VoidPtrTy);
430}
431
John McCall1e7fe752010-09-02 09:58:18 +0000432static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
433 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000434 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000435 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000436
Anders Carlssondd937552009-12-13 20:34:34 +0000437 // No cookie is required if the new operator being used is
438 // ::operator new[](size_t, void*).
439 const FunctionDecl *OperatorNew = E->getOperatorNew();
John McCall1e7fe752010-09-02 09:58:18 +0000440 if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
John McCall5172ed92010-08-23 01:17:59 +0000441 return CharUnits::Zero();
442
John McCall6ec278d2011-01-27 09:37:56 +0000443 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000444}
445
Fariborz Jahanianceb43b62010-03-24 16:57:01 +0000446static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
Chris Lattnerdefe8b22010-07-20 18:45:57 +0000447 CodeGenFunction &CGF,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000448 const CXXNewExpr *E,
Douglas Gregor59174c02010-07-21 01:10:17 +0000449 llvm::Value *&NumElements,
450 llvm::Value *&SizeWithoutCookie) {
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000451 QualType ElemType = E->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000452
453 const llvm::IntegerType *SizeTy =
454 cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
Anders Carlssona4d4c012009-09-23 16:07:23 +0000455
John McCall1e7fe752010-09-02 09:58:18 +0000456 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
457
Douglas Gregor59174c02010-07-21 01:10:17 +0000458 if (!E->isArray()) {
459 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
460 return SizeWithoutCookie;
461 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000462
John McCall1e7fe752010-09-02 09:58:18 +0000463 // Figure out the cookie size.
464 CharUnits CookieSize = CalculateCookiePadding(CGF, E);
465
Anders Carlssona4d4c012009-09-23 16:07:23 +0000466 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000467 // We multiply the size of all dimensions for NumElements.
468 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
Anders Carlssona4d4c012009-09-23 16:07:23 +0000469 NumElements = CGF.EmitScalarExpr(E->getArraySize());
John McCall1e7fe752010-09-02 09:58:18 +0000470 assert(NumElements->getType() == SizeTy && "element count not a size_t");
471
472 uint64_t ArraySizeMultiplier = 1;
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000473 while (const ConstantArrayType *CAT
474 = CGF.getContext().getAsConstantArrayType(ElemType)) {
475 ElemType = CAT->getElementType();
John McCall1e7fe752010-09-02 09:58:18 +0000476 ArraySizeMultiplier *= CAT->getSize().getZExtValue();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000477 }
478
John McCall1e7fe752010-09-02 09:58:18 +0000479 llvm::Value *Size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000480
Chris Lattner806941e2010-07-20 21:55:52 +0000481 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
482 // Don't bloat the -O0 code.
483 if (llvm::ConstantInt *NumElementsC =
484 dyn_cast<llvm::ConstantInt>(NumElements)) {
Chris Lattner806941e2010-07-20 21:55:52 +0000485 llvm::APInt NEC = NumElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000486 unsigned SizeWidth = NEC.getBitWidth();
487
488 // Determine if there is an overflow here by doing an extended multiply.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000489 NEC = NEC.zext(SizeWidth*2);
John McCall1e7fe752010-09-02 09:58:18 +0000490 llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
Chris Lattner806941e2010-07-20 21:55:52 +0000491 SC *= NEC;
John McCall1e7fe752010-09-02 09:58:18 +0000492
493 if (!CookieSize.isZero()) {
494 // Save the current size without a cookie. We don't care if an
495 // overflow's already happened because SizeWithoutCookie isn't
496 // used if the allocator returns null or throws, as it should
497 // always do on an overflow.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000498 llvm::APInt SWC = SC.trunc(SizeWidth);
John McCall1e7fe752010-09-02 09:58:18 +0000499 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
500
501 // Add the cookie size.
502 SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
Chris Lattner806941e2010-07-20 21:55:52 +0000503 }
504
John McCall1e7fe752010-09-02 09:58:18 +0000505 if (SC.countLeadingZeros() >= SizeWidth) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000506 SC = SC.trunc(SizeWidth);
John McCall1e7fe752010-09-02 09:58:18 +0000507 Size = llvm::ConstantInt::get(SizeTy, SC);
508 } else {
509 // On overflow, produce a -1 so operator new throws.
510 Size = llvm::Constant::getAllOnesValue(SizeTy);
511 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000512
John McCall1e7fe752010-09-02 09:58:18 +0000513 // Scale NumElements while we're at it.
514 uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
515 NumElements = llvm::ConstantInt::get(SizeTy, N);
516
517 // Otherwise, we don't need to do an overflow-checked multiplication if
518 // we're multiplying by one.
519 } else if (TypeSize.isOne()) {
520 assert(ArraySizeMultiplier == 1);
521
522 Size = NumElements;
523
524 // If we need a cookie, add its size in with an overflow check.
525 // This is maybe a little paranoid.
526 if (!CookieSize.isZero()) {
527 SizeWithoutCookie = Size;
528
529 llvm::Value *CookieSizeV
530 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
531
532 const llvm::Type *Types[] = { SizeTy };
533 llvm::Value *UAddF
534 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
535 llvm::Value *AddRes
536 = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
537
538 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
539 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
540 Size = CGF.Builder.CreateSelect(DidOverflow,
541 llvm::ConstantInt::get(SizeTy, -1),
542 Size);
543 }
544
545 // Otherwise use the int.umul.with.overflow intrinsic.
546 } else {
547 llvm::Value *OutermostElementSize
548 = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
549
550 llvm::Value *NumOutermostElements = NumElements;
551
552 // Scale NumElements by the array size multiplier. This might
553 // overflow, but only if the multiplication below also overflows,
554 // in which case this multiplication isn't used.
555 if (ArraySizeMultiplier != 1)
556 NumElements = CGF.Builder.CreateMul(NumElements,
557 llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
558
559 // The requested size of the outermost array is non-constant.
560 // Multiply that by the static size of the elements of that array;
561 // on unsigned overflow, set the size to -1 to trigger an
562 // exception from the allocation routine. This is sufficient to
563 // prevent buffer overruns from the allocator returning a
564 // seemingly valid pointer to insufficient space. This idea comes
565 // originally from MSVC, and GCC has an open bug requesting
566 // similar behavior:
567 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
568 //
569 // This will not be sufficient for C++0x, which requires a
570 // specific exception class (std::bad_array_new_length).
571 // That will require ABI support that has not yet been specified.
572 const llvm::Type *Types[] = { SizeTy };
573 llvm::Value *UMulF
574 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
575 llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
576 OutermostElementSize);
577
578 // The overflow bit.
579 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
580
581 // The result of the multiplication.
582 Size = CGF.Builder.CreateExtractValue(MulRes, 0);
583
584 // If we have a cookie, we need to add that size in, too.
585 if (!CookieSize.isZero()) {
586 SizeWithoutCookie = Size;
587
588 llvm::Value *CookieSizeV
589 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
590 llvm::Value *UAddF
591 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
592 llvm::Value *AddRes
593 = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
594
595 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
596
597 llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
598 DidOverflow = CGF.Builder.CreateAnd(DidOverflow, AddDidOverflow);
599 }
600
601 Size = CGF.Builder.CreateSelect(DidOverflow,
602 llvm::ConstantInt::get(SizeTy, -1),
603 Size);
Chris Lattner806941e2010-07-20 21:55:52 +0000604 }
John McCall1e7fe752010-09-02 09:58:18 +0000605
606 if (CookieSize.isZero())
607 SizeWithoutCookie = Size;
608 else
609 assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
610
Chris Lattner806941e2010-07-20 21:55:52 +0000611 return Size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000612}
613
Fariborz Jahanianef668722010-06-25 18:26:07 +0000614static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
615 llvm::Value *NewPtr) {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000616
617 assert(E->getNumConstructorArgs() == 1 &&
618 "Can only have one argument to initializer of POD type.");
619
620 const Expr *Init = E->getConstructorArg(0);
621 QualType AllocType = E->getAllocatedType();
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000622
623 unsigned Alignment =
624 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
Fariborz Jahanianef668722010-06-25 18:26:07 +0000625 if (!CGF.hasAggregateLLVMType(AllocType))
626 CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000627 AllocType.isVolatileQualified(), Alignment,
628 AllocType);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000629 else if (AllocType->isAnyComplexType())
630 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
631 AllocType.isVolatileQualified());
John McCall558d2ab2010-09-15 10:14:12 +0000632 else {
633 AggValueSlot Slot
634 = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
635 CGF.EmitAggExpr(Init, Slot);
636 }
Fariborz Jahanianef668722010-06-25 18:26:07 +0000637}
638
639void
640CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
641 llvm::Value *NewPtr,
642 llvm::Value *NumElements) {
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000643 // We have a POD type.
644 if (E->getNumConstructorArgs() == 0)
645 return;
646
Fariborz Jahanianef668722010-06-25 18:26:07 +0000647 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
648
649 // Create a temporary for the loop index and initialize it with 0.
650 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
651 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
652 Builder.CreateStore(Zero, IndexPtr);
653
654 // Start the loop with a block that tests the condition.
655 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
656 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
657
658 EmitBlock(CondBlock);
659
660 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
661
662 // Generate: if (loop-index < number-of-elements fall to the loop body,
663 // otherwise, go to the block after the for-loop.
664 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
665 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
666 // If the condition is true, execute the body.
667 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
668
669 EmitBlock(ForBody);
670
671 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
672 // Inside the loop body, emit the constructor call on the array element.
673 Counter = Builder.CreateLoad(IndexPtr);
674 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
675 "arrayidx");
676 StoreAnyExprIntoOneUnit(*this, E, Address);
677
678 EmitBlock(ContinueBlock);
679
680 // Emit the increment of the loop counter.
681 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
682 Counter = Builder.CreateLoad(IndexPtr);
683 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
684 Builder.CreateStore(NextVal, IndexPtr);
685
686 // Finally, branch back up to the condition for the next iteration.
687 EmitBranch(CondBlock);
688
689 // Emit the fall-through block.
690 EmitBlock(AfterFor, true);
691}
692
Douglas Gregor59174c02010-07-21 01:10:17 +0000693static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
694 llvm::Value *NewPtr, llvm::Value *Size) {
John McCalld16c2cf2011-02-08 08:22:06 +0000695 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyckfe710082011-01-19 01:58:38 +0000696 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000697 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000698 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000699}
700
Anders Carlssona4d4c012009-09-23 16:07:23 +0000701static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
702 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000703 llvm::Value *NumElements,
704 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000705 if (E->isArray()) {
Anders Carlssone99bdb62010-05-03 15:09:17 +0000706 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000707 bool RequiresZeroInitialization = false;
708 if (Ctor->getParent()->hasTrivialConstructor()) {
709 // If new expression did not specify value-initialization, then there
710 // is no initialization.
711 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
712 return;
713
John McCallf16aa102010-08-22 21:01:12 +0000714 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000715 // Optimization: since zero initialization will just set the memory
716 // to all zeroes, generate a single memset to do it in one shot.
717 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
718 AllocSizeWithoutCookie);
719 return;
720 }
721
722 RequiresZeroInitialization = true;
723 }
724
725 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
726 E->constructor_arg_begin(),
727 E->constructor_arg_end(),
728 RequiresZeroInitialization);
Anders Carlssone99bdb62010-05-03 15:09:17 +0000729 return;
Douglas Gregor59174c02010-07-21 01:10:17 +0000730 } else if (E->getNumConstructorArgs() == 1 &&
731 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
732 // Optimization: since zero initialization will just set the memory
733 // to all zeroes, generate a single memset to do it in one shot.
734 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
735 AllocSizeWithoutCookie);
736 return;
737 } else {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000738 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
739 return;
740 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000741 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000742
743 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregored8abf12010-07-08 06:14:04 +0000744 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
745 // direct initialization. C++ [dcl.init]p5 requires that we
746 // zero-initialize storage if there are no user-declared constructors.
747 if (E->hasInitializer() &&
748 !Ctor->getParent()->hasUserDeclaredConstructor() &&
749 !Ctor->getParent()->isEmpty())
750 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
751
Douglas Gregor84745672010-07-07 23:37:33 +0000752 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
753 NewPtr, E->constructor_arg_begin(),
754 E->constructor_arg_end());
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000755
756 return;
757 }
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000758 // We have a POD type.
759 if (E->getNumConstructorArgs() == 0)
760 return;
761
Fariborz Jahanianef668722010-06-25 18:26:07 +0000762 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000763}
764
John McCall7d8647f2010-09-14 07:57:04 +0000765namespace {
766 /// A cleanup to call the given 'operator delete' function upon
767 /// abnormal exit from a new expression.
768 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
769 size_t NumPlacementArgs;
770 const FunctionDecl *OperatorDelete;
771 llvm::Value *Ptr;
772 llvm::Value *AllocSize;
773
774 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
775
776 public:
777 static size_t getExtraSize(size_t NumPlacementArgs) {
778 return NumPlacementArgs * sizeof(RValue);
779 }
780
781 CallDeleteDuringNew(size_t NumPlacementArgs,
782 const FunctionDecl *OperatorDelete,
783 llvm::Value *Ptr,
784 llvm::Value *AllocSize)
785 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
786 Ptr(Ptr), AllocSize(AllocSize) {}
787
788 void setPlacementArg(unsigned I, RValue Arg) {
789 assert(I < NumPlacementArgs && "index out of range");
790 getPlacementArgs()[I] = Arg;
791 }
792
793 void Emit(CodeGenFunction &CGF, bool IsForEH) {
794 const FunctionProtoType *FPT
795 = OperatorDelete->getType()->getAs<FunctionProtoType>();
796 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +0000797 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +0000798
799 CallArgList DeleteArgs;
800
801 // The first argument is always a void*.
802 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
803 DeleteArgs.push_back(std::make_pair(RValue::get(Ptr), *AI++));
804
805 // A member 'operator delete' can take an extra 'size_t' argument.
806 if (FPT->getNumArgs() == NumPlacementArgs + 2)
807 DeleteArgs.push_back(std::make_pair(RValue::get(AllocSize), *AI++));
808
809 // Pass the rest of the arguments, which must match exactly.
810 for (unsigned I = 0; I != NumPlacementArgs; ++I)
811 DeleteArgs.push_back(std::make_pair(getPlacementArgs()[I], *AI++));
812
813 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000814 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall7d8647f2010-09-14 07:57:04 +0000815 CGF.CGM.GetAddrOfFunction(OperatorDelete),
816 ReturnValueSlot(), DeleteArgs, OperatorDelete);
817 }
818 };
John McCall3019c442010-09-17 00:50:28 +0000819
820 /// A cleanup to call the given 'operator delete' function upon
821 /// abnormal exit from a new expression when the new expression is
822 /// conditional.
823 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
824 size_t NumPlacementArgs;
825 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +0000826 DominatingValue<RValue>::saved_type Ptr;
827 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +0000828
John McCall804b8072011-01-28 10:53:53 +0000829 DominatingValue<RValue>::saved_type *getPlacementArgs() {
830 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +0000831 }
832
833 public:
834 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +0000835 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +0000836 }
837
838 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
839 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +0000840 DominatingValue<RValue>::saved_type Ptr,
841 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +0000842 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
843 Ptr(Ptr), AllocSize(AllocSize) {}
844
John McCall804b8072011-01-28 10:53:53 +0000845 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +0000846 assert(I < NumPlacementArgs && "index out of range");
847 getPlacementArgs()[I] = Arg;
848 }
849
850 void Emit(CodeGenFunction &CGF, bool IsForEH) {
851 const FunctionProtoType *FPT
852 = OperatorDelete->getType()->getAs<FunctionProtoType>();
853 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
854 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
855
856 CallArgList DeleteArgs;
857
858 // The first argument is always a void*.
859 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
John McCall804b8072011-01-28 10:53:53 +0000860 DeleteArgs.push_back(std::make_pair(Ptr.restore(CGF), *AI++));
John McCall3019c442010-09-17 00:50:28 +0000861
862 // A member 'operator delete' can take an extra 'size_t' argument.
863 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +0000864 RValue RV = AllocSize.restore(CGF);
John McCall3019c442010-09-17 00:50:28 +0000865 DeleteArgs.push_back(std::make_pair(RV, *AI++));
866 }
867
868 // Pass the rest of the arguments, which must match exactly.
869 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +0000870 RValue RV = getPlacementArgs()[I].restore(CGF);
John McCall3019c442010-09-17 00:50:28 +0000871 DeleteArgs.push_back(std::make_pair(RV, *AI++));
872 }
873
874 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000875 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall3019c442010-09-17 00:50:28 +0000876 CGF.CGM.GetAddrOfFunction(OperatorDelete),
877 ReturnValueSlot(), DeleteArgs, OperatorDelete);
878 }
879 };
880}
881
882/// Enter a cleanup to call 'operator delete' if the initializer in a
883/// new-expression throws.
884static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
885 const CXXNewExpr *E,
886 llvm::Value *NewPtr,
887 llvm::Value *AllocSize,
888 const CallArgList &NewArgs) {
889 // If we're not inside a conditional branch, then the cleanup will
890 // dominate and we can do the easier (and more efficient) thing.
891 if (!CGF.isInConditionalBranch()) {
892 CallDeleteDuringNew *Cleanup = CGF.EHStack
893 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
894 E->getNumPlacementArgs(),
895 E->getOperatorDelete(),
896 NewPtr, AllocSize);
897 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
898 Cleanup->setPlacementArg(I, NewArgs[I+1].first);
899
900 return;
901 }
902
903 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +0000904 DominatingValue<RValue>::saved_type SavedNewPtr =
905 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
906 DominatingValue<RValue>::saved_type SavedAllocSize =
907 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +0000908
909 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
910 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
911 E->getNumPlacementArgs(),
912 E->getOperatorDelete(),
913 SavedNewPtr,
914 SavedAllocSize);
915 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +0000916 Cleanup->setPlacementArg(I,
917 DominatingValue<RValue>::save(CGF, NewArgs[I+1].first));
John McCall3019c442010-09-17 00:50:28 +0000918
919 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall7d8647f2010-09-14 07:57:04 +0000920}
921
Anders Carlsson16d81b82009-09-22 22:53:17 +0000922llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +0000923 // The element type being allocated.
924 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +0000925
John McCallc2f3e7f2011-03-07 03:12:35 +0000926 // 1. Build a call to the allocation function.
927 FunctionDecl *allocator = E->getOperatorNew();
928 const FunctionProtoType *allocatorType =
929 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000930
John McCallc2f3e7f2011-03-07 03:12:35 +0000931 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +0000932
933 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +0000934 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000935
John McCallc2f3e7f2011-03-07 03:12:35 +0000936 llvm::Value *numElements = 0;
937 llvm::Value *allocSizeWithoutCookie = 0;
938 llvm::Value *allocSize =
939 EmitCXXNewAllocSize(getContext(), *this, E, numElements,
940 allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000941
John McCallc2f3e7f2011-03-07 03:12:35 +0000942 allocatorArgs.push_back(std::make_pair(RValue::get(allocSize), sizeType));
Anders Carlsson16d81b82009-09-22 22:53:17 +0000943
944 // Emit the rest of the arguments.
945 // FIXME: Ideally, this should just use EmitCallArgs.
John McCallc2f3e7f2011-03-07 03:12:35 +0000946 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000947
948 // First, use the types from the function type.
949 // We start at 1 here because the first argument (the allocation size)
950 // has already been emitted.
John McCallc2f3e7f2011-03-07 03:12:35 +0000951 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
952 ++i, ++placementArg) {
953 QualType argType = allocatorType->getArgType(i);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000954
John McCallc2f3e7f2011-03-07 03:12:35 +0000955 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
956 placementArg->getType()) &&
Anders Carlsson16d81b82009-09-22 22:53:17 +0000957 "type mismatch in call argument!");
958
John McCallc2f3e7f2011-03-07 03:12:35 +0000959 allocatorArgs.push_back(std::make_pair(EmitCallArg(*placementArg, argType),
960 argType));
Anders Carlsson16d81b82009-09-22 22:53:17 +0000961
962 }
963
964 // Either we've emitted all the call args, or we have a call to a
965 // variadic function.
John McCallc2f3e7f2011-03-07 03:12:35 +0000966 assert((placementArg == E->placement_arg_end() ||
967 allocatorType->isVariadic()) &&
968 "Extra arguments to non-variadic function!");
Anders Carlsson16d81b82009-09-22 22:53:17 +0000969
970 // If we still have any arguments, emit them using the type of the argument.
John McCallc2f3e7f2011-03-07 03:12:35 +0000971 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
972 placementArg != placementArgsEnd; ++placementArg) {
973 QualType argType = placementArg->getType();
974 allocatorArgs.push_back(std::make_pair(EmitCallArg(*placementArg, argType),
975 argType));
Anders Carlsson16d81b82009-09-22 22:53:17 +0000976 }
977
John McCallc2f3e7f2011-03-07 03:12:35 +0000978 // Emit the allocation call.
Anders Carlsson16d81b82009-09-22 22:53:17 +0000979 RValue RV =
John McCallc2f3e7f2011-03-07 03:12:35 +0000980 EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocatorType),
981 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
982 allocatorArgs, allocator);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000983
John McCallc2f3e7f2011-03-07 03:12:35 +0000984 // Emit a null check on the allocation result if the allocation
985 // function is allowed to return null (because it has a non-throwing
986 // exception spec; for this part, we inline
987 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
988 // interesting initializer.
989 bool nullCheck = allocatorType->hasNonThrowingExceptionSpec() &&
990 !(allocType->isPODType() && !E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +0000991
John McCallc2f3e7f2011-03-07 03:12:35 +0000992 llvm::BasicBlock *nullCheckBB = 0;
993 llvm::BasicBlock *contBB = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +0000994
John McCallc2f3e7f2011-03-07 03:12:35 +0000995 llvm::Value *allocation = RV.getScalarVal();
996 unsigned AS =
997 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000998
John McCalla7f633f2011-03-07 01:52:56 +0000999 // The null-check means that the initializer is conditionally
1000 // evaluated.
1001 ConditionalEvaluation conditional(*this);
1002
John McCallc2f3e7f2011-03-07 03:12:35 +00001003 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001004 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001005
1006 nullCheckBB = Builder.GetInsertBlock();
1007 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1008 contBB = createBasicBlock("new.cont");
1009
1010 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1011 Builder.CreateCondBr(isNull, contBB, notNullBB);
1012 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001013 }
Ken Dyckcaf647c2010-01-26 19:44:24 +00001014
John McCallc2f3e7f2011-03-07 03:12:35 +00001015 assert((allocSize == allocSizeWithoutCookie) ==
John McCall1e7fe752010-09-02 09:58:18 +00001016 CalculateCookiePadding(*this, E).isZero());
John McCallc2f3e7f2011-03-07 03:12:35 +00001017 if (allocSize != allocSizeWithoutCookie) {
John McCall1e7fe752010-09-02 09:58:18 +00001018 assert(E->isArray());
John McCallc2f3e7f2011-03-07 03:12:35 +00001019 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1020 numElements,
1021 E, allocType);
John McCall1e7fe752010-09-02 09:58:18 +00001022 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001023
John McCall7d8647f2010-09-14 07:57:04 +00001024 // If there's an operator delete, enter a cleanup to call it if an
1025 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001026 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCall7d8647f2010-09-14 07:57:04 +00001027 if (E->getOperatorDelete()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001028 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1029 operatorDeleteCleanup = EHStack.stable_begin();
John McCall7d8647f2010-09-14 07:57:04 +00001030 }
1031
John McCallc2f3e7f2011-03-07 03:12:35 +00001032 const llvm::Type *elementPtrTy
1033 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1034 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001035
John McCall1e7fe752010-09-02 09:58:18 +00001036 if (E->isArray()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001037 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001038
1039 // NewPtr is a pointer to the base element type. If we're
1040 // allocating an array of arrays, we'll need to cast back to the
1041 // array pointer type.
John McCallc2f3e7f2011-03-07 03:12:35 +00001042 const llvm::Type *resultType = ConvertTypeForMem(E->getType());
1043 if (result->getType() != resultType)
1044 result = Builder.CreateBitCast(result, resultType);
John McCall1e7fe752010-09-02 09:58:18 +00001045 } else {
John McCallc2f3e7f2011-03-07 03:12:35 +00001046 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001047 }
John McCall7d8647f2010-09-14 07:57:04 +00001048
1049 // Deactivate the 'operator delete' cleanup if we finished
1050 // initialization.
John McCallc2f3e7f2011-03-07 03:12:35 +00001051 if (operatorDeleteCleanup.isValid())
1052 DeactivateCleanupBlock(operatorDeleteCleanup);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001053
John McCallc2f3e7f2011-03-07 03:12:35 +00001054 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001055 conditional.end(*this);
1056
John McCallc2f3e7f2011-03-07 03:12:35 +00001057 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1058 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001059
John McCallc2f3e7f2011-03-07 03:12:35 +00001060 llvm::PHINode *PHI = Builder.CreatePHI(result->getType());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001061 PHI->reserveOperandSpace(2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001062 PHI->addIncoming(result, notNullBB);
1063 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1064 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001065
John McCallc2f3e7f2011-03-07 03:12:35 +00001066 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001067 }
John McCall1e7fe752010-09-02 09:58:18 +00001068
John McCallc2f3e7f2011-03-07 03:12:35 +00001069 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001070}
1071
Eli Friedman5fe05982009-11-18 00:50:08 +00001072void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1073 llvm::Value *Ptr,
1074 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001075 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1076
Eli Friedman5fe05982009-11-18 00:50:08 +00001077 const FunctionProtoType *DeleteFTy =
1078 DeleteFD->getType()->getAs<FunctionProtoType>();
1079
1080 CallArgList DeleteArgs;
1081
Anders Carlsson871d0782009-12-13 20:04:38 +00001082 // Check if we need to pass the size to the delete operator.
1083 llvm::Value *Size = 0;
1084 QualType SizeTy;
1085 if (DeleteFTy->getNumArgs() == 2) {
1086 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001087 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1088 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1089 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001090 }
1091
Eli Friedman5fe05982009-11-18 00:50:08 +00001092 QualType ArgTy = DeleteFTy->getArgType(0);
1093 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1094 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
1095
Anders Carlsson871d0782009-12-13 20:04:38 +00001096 if (Size)
Eli Friedman5fe05982009-11-18 00:50:08 +00001097 DeleteArgs.push_back(std::make_pair(RValue::get(Size), SizeTy));
Eli Friedman5fe05982009-11-18 00:50:08 +00001098
1099 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001100 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001101 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +00001102 DeleteArgs, DeleteFD);
1103}
1104
John McCall1e7fe752010-09-02 09:58:18 +00001105namespace {
1106 /// Calls the given 'operator delete' on a single object.
1107 struct CallObjectDelete : EHScopeStack::Cleanup {
1108 llvm::Value *Ptr;
1109 const FunctionDecl *OperatorDelete;
1110 QualType ElementType;
1111
1112 CallObjectDelete(llvm::Value *Ptr,
1113 const FunctionDecl *OperatorDelete,
1114 QualType ElementType)
1115 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1116
1117 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1118 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1119 }
1120 };
1121}
1122
1123/// Emit the code for deleting a single object.
1124static void EmitObjectDelete(CodeGenFunction &CGF,
1125 const FunctionDecl *OperatorDelete,
1126 llvm::Value *Ptr,
1127 QualType ElementType) {
1128 // Find the destructor for the type, if applicable. If the
1129 // destructor is virtual, we'll just emit the vcall and return.
1130 const CXXDestructorDecl *Dtor = 0;
1131 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1132 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1133 if (!RD->hasTrivialDestructor()) {
1134 Dtor = RD->getDestructor();
1135
1136 if (Dtor->isVirtual()) {
1137 const llvm::Type *Ty =
John McCallfc400282010-09-03 01:26:39 +00001138 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1139 Dtor_Complete),
John McCall1e7fe752010-09-02 09:58:18 +00001140 /*isVariadic=*/false);
1141
1142 llvm::Value *Callee
1143 = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
1144 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1145 0, 0);
1146
1147 // The dtor took care of deleting the object.
1148 return;
1149 }
1150 }
1151 }
1152
1153 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001154 // This doesn't have to a conditional cleanup because we're going
1155 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001156 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1157 Ptr, OperatorDelete, ElementType);
1158
1159 if (Dtor)
1160 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1161 /*ForVirtualBase=*/false, Ptr);
1162
1163 CGF.PopCleanupBlock();
1164}
1165
1166namespace {
1167 /// Calls the given 'operator delete' on an array of objects.
1168 struct CallArrayDelete : EHScopeStack::Cleanup {
1169 llvm::Value *Ptr;
1170 const FunctionDecl *OperatorDelete;
1171 llvm::Value *NumElements;
1172 QualType ElementType;
1173 CharUnits CookieSize;
1174
1175 CallArrayDelete(llvm::Value *Ptr,
1176 const FunctionDecl *OperatorDelete,
1177 llvm::Value *NumElements,
1178 QualType ElementType,
1179 CharUnits CookieSize)
1180 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1181 ElementType(ElementType), CookieSize(CookieSize) {}
1182
1183 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1184 const FunctionProtoType *DeleteFTy =
1185 OperatorDelete->getType()->getAs<FunctionProtoType>();
1186 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1187
1188 CallArgList Args;
1189
1190 // Pass the pointer as the first argument.
1191 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1192 llvm::Value *DeletePtr
1193 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
1194 Args.push_back(std::make_pair(RValue::get(DeletePtr), VoidPtrTy));
1195
1196 // Pass the original requested size as the second argument.
1197 if (DeleteFTy->getNumArgs() == 2) {
1198 QualType size_t = DeleteFTy->getArgType(1);
1199 const llvm::IntegerType *SizeTy
1200 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1201
1202 CharUnits ElementTypeSize =
1203 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1204
1205 // The size of an element, multiplied by the number of elements.
1206 llvm::Value *Size
1207 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1208 Size = CGF.Builder.CreateMul(Size, NumElements);
1209
1210 // Plus the size of the cookie if applicable.
1211 if (!CookieSize.isZero()) {
1212 llvm::Value *CookieSizeV
1213 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1214 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1215 }
1216
1217 Args.push_back(std::make_pair(RValue::get(Size), size_t));
1218 }
1219
1220 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001221 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
John McCall1e7fe752010-09-02 09:58:18 +00001222 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1223 ReturnValueSlot(), Args, OperatorDelete);
1224 }
1225 };
1226}
1227
1228/// Emit the code for deleting an array of objects.
1229static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001230 const CXXDeleteExpr *E,
John McCall1e7fe752010-09-02 09:58:18 +00001231 llvm::Value *Ptr,
1232 QualType ElementType) {
1233 llvm::Value *NumElements = 0;
1234 llvm::Value *AllocatedPtr = 0;
1235 CharUnits CookieSize;
John McCall6ec278d2011-01-27 09:37:56 +00001236 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, E, ElementType,
John McCall1e7fe752010-09-02 09:58:18 +00001237 NumElements, AllocatedPtr, CookieSize);
1238
1239 assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
1240
1241 // Make sure that we call delete even if one of the dtors throws.
John McCall6ec278d2011-01-27 09:37:56 +00001242 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001243 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1244 AllocatedPtr, OperatorDelete,
1245 NumElements, ElementType,
1246 CookieSize);
1247
1248 if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
1249 if (!RD->hasTrivialDestructor()) {
1250 assert(NumElements && "ReadArrayCookie didn't find element count"
1251 " for a class with destructor");
1252 CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
1253 }
1254 }
1255
1256 CGF.PopCleanupBlock();
1257}
1258
Anders Carlsson16d81b82009-09-22 22:53:17 +00001259void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian72c21532009-11-13 19:27:47 +00001260
Douglas Gregor90916562009-09-29 18:16:17 +00001261 // Get at the argument before we performed the implicit conversion
1262 // to void*.
1263 const Expr *Arg = E->getArgument();
1264 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00001265 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregor90916562009-09-29 18:16:17 +00001266 ICE->getType()->isVoidPointerType())
1267 Arg = ICE->getSubExpr();
Douglas Gregord69dd782009-10-01 05:49:51 +00001268 else
1269 break;
Douglas Gregor90916562009-09-29 18:16:17 +00001270 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001271
Douglas Gregor90916562009-09-29 18:16:17 +00001272 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001273
1274 // Null check the pointer.
1275 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1276 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1277
1278 llvm::Value *IsNull =
1279 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
1280 "isnull");
1281
1282 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1283 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001284
John McCall1e7fe752010-09-02 09:58:18 +00001285 // We might be deleting a pointer to array. If so, GEP down to the
1286 // first non-array element.
1287 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1288 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1289 if (DeleteTy->isConstantArrayType()) {
1290 llvm::Value *Zero = Builder.getInt32(0);
1291 llvm::SmallVector<llvm::Value*,8> GEP;
1292
1293 GEP.push_back(Zero); // point at the outermost array
1294
1295 // For each layer of array type we're pointing at:
1296 while (const ConstantArrayType *Arr
1297 = getContext().getAsConstantArrayType(DeleteTy)) {
1298 // 1. Unpeel the array type.
1299 DeleteTy = Arr->getElementType();
1300
1301 // 2. GEP to the first element of the array.
1302 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001303 }
John McCall1e7fe752010-09-02 09:58:18 +00001304
1305 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001306 }
1307
Douglas Gregoreede61a2010-09-02 17:38:50 +00001308 assert(ConvertTypeForMem(DeleteTy) ==
1309 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001310
1311 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001312 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001313 } else {
1314 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1315 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001316
Anders Carlsson16d81b82009-09-22 22:53:17 +00001317 EmitBlock(DeleteEnd);
1318}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001319
John McCall3ad32c82011-01-28 08:37:24 +00001320llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001321 QualType Ty = E->getType();
1322 const llvm::Type *LTy = ConvertType(Ty)->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001323
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001324 if (E->isTypeOperand()) {
1325 llvm::Constant *TypeInfo =
1326 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
1327 return Builder.CreateBitCast(TypeInfo, LTy);
1328 }
1329
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001330 Expr *subE = E->getExprOperand();
Mike Stump5fae8562009-11-17 22:33:00 +00001331 Ty = subE->getType();
1332 CanQualType CanTy = CGM.getContext().getCanonicalType(Ty);
1333 Ty = CanTy.getUnqualifiedType().getNonReferenceType();
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001334 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1335 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1336 if (RD->isPolymorphic()) {
1337 // FIXME: if subE is an lvalue do
1338 LValue Obj = EmitLValue(subE);
1339 llvm::Value *This = Obj.getAddress();
Mike Stumpf549e892009-11-15 16:52:53 +00001340 // We need to do a zero check for *p, unless it has NonNullAttr.
1341 // FIXME: PointerType->hasAttr<NonNullAttr>()
1342 bool CanBeZero = false;
Mike Stumpdb519a42009-11-17 00:45:21 +00001343 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(subE->IgnoreParens()))
John McCall2de56d12010-08-25 11:45:40 +00001344 if (UO->getOpcode() == UO_Deref)
Mike Stumpf549e892009-11-15 16:52:53 +00001345 CanBeZero = true;
1346 if (CanBeZero) {
1347 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
1348 llvm::BasicBlock *ZeroBlock = createBasicBlock();
1349
Dan Gohman043fb9a2010-10-26 18:44:08 +00001350 llvm::Value *Zero = llvm::Constant::getNullValue(This->getType());
1351 Builder.CreateCondBr(Builder.CreateICmpNE(This, Zero),
Mike Stumpf549e892009-11-15 16:52:53 +00001352 NonZeroBlock, ZeroBlock);
1353 EmitBlock(ZeroBlock);
1354 /// Call __cxa_bad_typeid
John McCalld16c2cf2011-02-08 08:22:06 +00001355 const llvm::Type *ResultType = llvm::Type::getVoidTy(getLLVMContext());
Mike Stumpf549e892009-11-15 16:52:53 +00001356 const llvm::FunctionType *FTy;
1357 FTy = llvm::FunctionType::get(ResultType, false);
1358 llvm::Value *F = CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
Mike Stumpc849c052009-11-16 06:50:58 +00001359 Builder.CreateCall(F)->setDoesNotReturn();
Mike Stumpf549e892009-11-15 16:52:53 +00001360 Builder.CreateUnreachable();
1361 EmitBlock(NonZeroBlock);
1362 }
Dan Gohman043fb9a2010-10-26 18:44:08 +00001363 llvm::Value *V = GetVTablePtr(This, LTy->getPointerTo());
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001364 V = Builder.CreateConstInBoundsGEP1_64(V, -1ULL);
1365 V = Builder.CreateLoad(V);
1366 return V;
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001367 }
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001368 }
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001369 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(Ty), LTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001370}
Mike Stumpc849c052009-11-16 06:50:58 +00001371
1372llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *V,
1373 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001374 QualType SrcTy = DCE->getSubExpr()->getType();
1375 QualType DestTy = DCE->getTypeAsWritten();
1376 QualType InnerType = DestTy->getPointeeType();
1377
Mike Stumpc849c052009-11-16 06:50:58 +00001378 const llvm::Type *LTy = ConvertType(DCE->getType());
Mike Stump2b35baf2009-11-16 22:52:20 +00001379
Mike Stumpc849c052009-11-16 06:50:58 +00001380 bool CanBeZero = false;
Mike Stumpc849c052009-11-16 06:50:58 +00001381 bool ToVoid = false;
Mike Stump2b35baf2009-11-16 22:52:20 +00001382 bool ThrowOnBad = false;
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001383 if (DestTy->isPointerType()) {
Mike Stumpc849c052009-11-16 06:50:58 +00001384 // FIXME: if PointerType->hasAttr<NonNullAttr>(), we don't set this
1385 CanBeZero = true;
1386 if (InnerType->isVoidType())
1387 ToVoid = true;
1388 } else {
1389 LTy = LTy->getPointerTo();
Douglas Gregor485ee322010-05-14 21:14:41 +00001390
1391 // FIXME: What if exceptions are disabled?
Mike Stumpc849c052009-11-16 06:50:58 +00001392 ThrowOnBad = true;
1393 }
1394
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001395 if (SrcTy->isPointerType() || SrcTy->isReferenceType())
1396 SrcTy = SrcTy->getPointeeType();
1397 SrcTy = SrcTy.getUnqualifiedType();
1398
Anders Carlsson6f0e4852009-12-18 14:55:04 +00001399 if (DestTy->isPointerType() || DestTy->isReferenceType())
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001400 DestTy = DestTy->getPointeeType();
1401 DestTy = DestTy.getUnqualifiedType();
Mike Stumpc849c052009-11-16 06:50:58 +00001402
Mike Stumpc849c052009-11-16 06:50:58 +00001403 llvm::BasicBlock *ContBlock = createBasicBlock();
1404 llvm::BasicBlock *NullBlock = 0;
1405 llvm::BasicBlock *NonZeroBlock = 0;
1406 if (CanBeZero) {
1407 NonZeroBlock = createBasicBlock();
1408 NullBlock = createBasicBlock();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001409 Builder.CreateCondBr(Builder.CreateIsNotNull(V), NonZeroBlock, NullBlock);
Mike Stumpc849c052009-11-16 06:50:58 +00001410 EmitBlock(NonZeroBlock);
1411 }
1412
Mike Stumpc849c052009-11-16 06:50:58 +00001413 llvm::BasicBlock *BadCastBlock = 0;
Mike Stumpc849c052009-11-16 06:50:58 +00001414
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001415 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
Mike Stump2b35baf2009-11-16 22:52:20 +00001416
1417 // See if this is a dynamic_cast(void*)
1418 if (ToVoid) {
1419 llvm::Value *This = V;
Dan Gohman043fb9a2010-10-26 18:44:08 +00001420 V = GetVTablePtr(This, PtrDiffTy->getPointerTo());
Mike Stump2b35baf2009-11-16 22:52:20 +00001421 V = Builder.CreateConstInBoundsGEP1_64(V, -2ULL);
1422 V = Builder.CreateLoad(V, "offset to top");
John McCalld16c2cf2011-02-08 08:22:06 +00001423 This = EmitCastToVoidPtr(This);
Mike Stump2b35baf2009-11-16 22:52:20 +00001424 V = Builder.CreateInBoundsGEP(This, V);
1425 V = Builder.CreateBitCast(V, LTy);
1426 } else {
1427 /// Call __dynamic_cast
John McCalld16c2cf2011-02-08 08:22:06 +00001428 const llvm::Type *ResultType = Int8PtrTy;
Mike Stump2b35baf2009-11-16 22:52:20 +00001429 const llvm::FunctionType *FTy;
1430 std::vector<const llvm::Type*> ArgTys;
John McCalld16c2cf2011-02-08 08:22:06 +00001431 ArgTys.push_back(Int8PtrTy);
1432 ArgTys.push_back(Int8PtrTy);
1433 ArgTys.push_back(Int8PtrTy);
Mike Stump2b35baf2009-11-16 22:52:20 +00001434 ArgTys.push_back(PtrDiffTy);
1435 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump2b35baf2009-11-16 22:52:20 +00001436
1437 // FIXME: Calculate better hint.
1438 llvm::Value *hint = llvm::ConstantInt::get(PtrDiffTy, -1ULL);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001439
1440 assert(SrcTy->isRecordType() && "Src type must be record type!");
1441 assert(DestTy->isRecordType() && "Dest type must be record type!");
1442
Douglas Gregor154fe982009-12-23 22:04:40 +00001443 llvm::Value *SrcArg
1444 = CGM.GetAddrOfRTTIDescriptor(SrcTy.getUnqualifiedType());
1445 llvm::Value *DestArg
1446 = CGM.GetAddrOfRTTIDescriptor(DestTy.getUnqualifiedType());
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001447
John McCalld16c2cf2011-02-08 08:22:06 +00001448 V = Builder.CreateBitCast(V, Int8PtrTy);
Mike Stump2b35baf2009-11-16 22:52:20 +00001449 V = Builder.CreateCall4(CGM.CreateRuntimeFunction(FTy, "__dynamic_cast"),
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001450 V, SrcArg, DestArg, hint);
Mike Stump2b35baf2009-11-16 22:52:20 +00001451 V = Builder.CreateBitCast(V, LTy);
1452
1453 if (ThrowOnBad) {
1454 BadCastBlock = createBasicBlock();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001455 Builder.CreateCondBr(Builder.CreateIsNotNull(V), ContBlock, BadCastBlock);
Mike Stump2b35baf2009-11-16 22:52:20 +00001456 EmitBlock(BadCastBlock);
Douglas Gregor485ee322010-05-14 21:14:41 +00001457 /// Invoke __cxa_bad_cast
John McCalld16c2cf2011-02-08 08:22:06 +00001458 ResultType = llvm::Type::getVoidTy(getLLVMContext());
Mike Stump2b35baf2009-11-16 22:52:20 +00001459 const llvm::FunctionType *FBadTy;
Mike Stumpfde17be2009-11-17 03:01:03 +00001460 FBadTy = llvm::FunctionType::get(ResultType, false);
Mike Stump2b35baf2009-11-16 22:52:20 +00001461 llvm::Value *F = CGM.CreateRuntimeFunction(FBadTy, "__cxa_bad_cast");
Douglas Gregor485ee322010-05-14 21:14:41 +00001462 if (llvm::BasicBlock *InvokeDest = getInvokeDest()) {
1463 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
1464 Builder.CreateInvoke(F, Cont, InvokeDest)->setDoesNotReturn();
1465 EmitBlock(Cont);
1466 } else {
1467 // FIXME: Does this ever make sense?
1468 Builder.CreateCall(F)->setDoesNotReturn();
1469 }
Mike Stump8b152b82009-11-17 00:08:50 +00001470 Builder.CreateUnreachable();
Mike Stump2b35baf2009-11-16 22:52:20 +00001471 }
Mike Stumpc849c052009-11-16 06:50:58 +00001472 }
1473
1474 if (CanBeZero) {
1475 Builder.CreateBr(ContBlock);
1476 EmitBlock(NullBlock);
1477 Builder.CreateBr(ContBlock);
1478 }
1479 EmitBlock(ContBlock);
1480 if (CanBeZero) {
1481 llvm::PHINode *PHI = Builder.CreatePHI(LTy);
Mike Stump14431c12009-11-17 00:10:05 +00001482 PHI->reserveOperandSpace(2);
Mike Stumpc849c052009-11-16 06:50:58 +00001483 PHI->addIncoming(V, NonZeroBlock);
1484 PHI->addIncoming(llvm::Constant::getNullValue(LTy), NullBlock);
Mike Stumpc849c052009-11-16 06:50:58 +00001485 V = PHI;
1486 }
1487
1488 return V;
1489}