blob: a0699f221147c10c220d82ff026bf5795acc9466 [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 Carlssonad3692bb2011-04-13 02:35:36 +000020#include "llvm/Support/CallSite.h"
21
Anders Carlsson16d81b82009-09-22 22:53:17 +000022using namespace clang;
23using namespace CodeGen;
24
Anders Carlsson3b5ad222010-01-01 20:29:01 +000025RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
26 llvm::Value *Callee,
27 ReturnValueSlot ReturnValue,
28 llvm::Value *This,
Anders Carlssonc997d422010-01-02 01:01:18 +000029 llvm::Value *VTT,
Anders Carlsson3b5ad222010-01-01 20:29:01 +000030 CallExpr::const_arg_iterator ArgBeg,
31 CallExpr::const_arg_iterator ArgEnd) {
32 assert(MD->isInstance() &&
33 "Trying to emit a member call expr on a static method!");
34
35 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
36
37 CallArgList Args;
38
39 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +000040 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000041
Anders Carlssonc997d422010-01-02 01:01:18 +000042 // If there is a VTT parameter, emit it.
43 if (VTT) {
44 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +000045 Args.add(RValue::get(VTT), T);
Anders Carlssonc997d422010-01-02 01:01:18 +000046 }
47
Anders Carlsson3b5ad222010-01-01 20:29:01 +000048 // And the rest of the call args
49 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
50
John McCall04a67a62010-02-05 21:31:56 +000051 QualType ResultType = FPT->getResultType();
Tilmann Scheller9c6082f2011-03-02 21:36:49 +000052 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
53 FPT->getExtInfo()),
Rafael Espindola264ba482010-03-30 20:24:48 +000054 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000055}
56
Anders Carlsson1679f5a2011-01-29 03:52:01 +000057static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
Anders Carlsson268ab8c2011-01-29 05:04:11 +000058 const Expr *E = Base;
59
60 while (true) {
61 E = E->IgnoreParens();
62 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
63 if (CE->getCastKind() == CK_DerivedToBase ||
64 CE->getCastKind() == CK_UncheckedDerivedToBase ||
65 CE->getCastKind() == CK_NoOp) {
66 E = CE->getSubExpr();
67 continue;
68 }
69 }
70
71 break;
72 }
73
74 QualType DerivedType = E->getType();
Anders Carlsson1679f5a2011-01-29 03:52:01 +000075 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
76 DerivedType = PTy->getPointeeType();
77
78 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
79}
80
Anders Carlssoncd0b32e2011-04-10 18:20:53 +000081// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
82// quite what we want.
83static const Expr *skipNoOpCastsAndParens(const Expr *E) {
84 while (true) {
85 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
86 E = PE->getSubExpr();
87 continue;
88 }
89
90 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
91 if (CE->getCastKind() == CK_NoOp) {
92 E = CE->getSubExpr();
93 continue;
94 }
95 }
96 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
97 if (UO->getOpcode() == UO_Extension) {
98 E = UO->getSubExpr();
99 continue;
100 }
101 }
102 return E;
103 }
104}
105
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000106/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
107/// expr can be devirtualized.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000108static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
109 const Expr *Base,
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000110 const CXXMethodDecl *MD) {
111
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000112 // When building with -fapple-kext, all calls must go through the vtable since
113 // the kernel linker can do runtime patching of vtables.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000114 if (Context.getLangOptions().AppleKext)
115 return false;
116
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000117 // If the most derived class is marked final, we know that no subclass can
118 // override this member function and so we can devirtualize it. For example:
119 //
120 // struct A { virtual void f(); }
121 // struct B final : A { };
122 //
123 // void f(B *b) {
124 // b->f();
125 // }
126 //
127 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
128 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
129 return true;
130
Anders Carlssonf89e0422011-01-23 21:07:30 +0000131 // If the member function is marked 'final', we know that it can't be
Anders Carlssond66f4282010-10-27 13:34:43 +0000132 // overridden and can therefore devirtualize it.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000133 if (MD->hasAttr<FinalAttr>())
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000134 return true;
Anders Carlssond66f4282010-10-27 13:34:43 +0000135
Anders Carlssonf89e0422011-01-23 21:07:30 +0000136 // Similarly, if the class itself is marked 'final' it can't be overridden
137 // and we can therefore devirtualize the member function call.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000138 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssond66f4282010-10-27 13:34:43 +0000139 return true;
140
Anders Carlssoncd0b32e2011-04-10 18:20:53 +0000141 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000142 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
143 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
144 // This is a record decl. We know the type and can devirtualize it.
145 return VD->getType()->isRecordType();
146 }
147
148 return false;
149 }
150
151 // We can always devirtualize calls on temporary object expressions.
Eli Friedman6997aae2010-01-31 20:58:15 +0000152 if (isa<CXXConstructExpr>(Base))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000153 return true;
154
155 // And calls on bound temporaries.
156 if (isa<CXXBindTemporaryExpr>(Base))
157 return true;
158
159 // Check if this is a call expr that returns a record type.
160 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
161 return CE->getCallReturnType()->isRecordType();
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000162
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000163 // We can't devirtualize the call.
164 return false;
165}
166
Francois Pichetdbee3412011-01-18 05:04:39 +0000167// Note: This function also emit constructor calls to support a MSVC
168// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000169RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
170 ReturnValueSlot ReturnValue) {
John McCall379b5152011-04-11 07:02:50 +0000171 const Expr *callee = CE->getCallee()->IgnoreParens();
172
173 if (isa<BinaryOperator>(callee))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000174 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall379b5152011-04-11 07:02:50 +0000175
176 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000177 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
178
Devang Patelc69e1cf2010-09-30 19:05:55 +0000179 CGDebugInfo *DI = getDebugInfo();
Devang Patel68020272010-10-22 18:56:27 +0000180 if (DI && CGM.getCodeGenOpts().LimitDebugInfo
181 && !isa<CallExpr>(ME->getBase())) {
Devang Patelc69e1cf2010-09-30 19:05:55 +0000182 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
183 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
184 DI->getOrCreateRecordType(PTy->getPointeeType(),
185 MD->getParent()->getLocation());
186 }
187 }
188
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000189 if (MD->isStatic()) {
190 // The method is static, emit it as we would a regular call.
191 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
192 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
193 ReturnValue, CE->arg_begin(), CE->arg_end());
194 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000195
John McCallfc400282010-09-03 01:26:39 +0000196 // Compute the object pointer.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000197 llvm::Value *This;
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000198 if (ME->isArrow())
199 This = EmitScalarExpr(ME->getBase());
John McCall0e800c92010-12-04 08:14:53 +0000200 else
201 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000202
John McCallfc400282010-09-03 01:26:39 +0000203 if (MD->isTrivial()) {
204 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichetdbee3412011-01-18 05:04:39 +0000205 if (isa<CXXConstructorDecl>(MD) &&
206 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
207 return RValue::get(0);
John McCallfc400282010-09-03 01:26:39 +0000208
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000209 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
210 // We don't like to generate the trivial copy/move assignment operator
211 // when it isn't necessary; just produce the proper effect here.
Francois Pichetdbee3412011-01-18 05:04:39 +0000212 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
213 EmitAggregateCopy(This, RHS, CE->getType());
214 return RValue::get(This);
215 }
216
217 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000218 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
219 // Trivial move and copy ctor are the same.
Francois Pichetdbee3412011-01-18 05:04:39 +0000220 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
221 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
222 CE->arg_begin(), CE->arg_end());
223 return RValue::get(This);
224 }
225 llvm_unreachable("unknown trivial member function");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000226 }
227
John McCallfc400282010-09-03 01:26:39 +0000228 // Compute the function type we're calling.
Francois Pichetdbee3412011-01-18 05:04:39 +0000229 const CGFunctionInfo *FInfo = 0;
230 if (isa<CXXDestructorDecl>(MD))
231 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
232 Dtor_Complete);
233 else if (isa<CXXConstructorDecl>(MD))
234 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXConstructorDecl>(MD),
235 Ctor_Complete);
236 else
237 FInfo = &CGM.getTypes().getFunctionInfo(MD);
John McCallfc400282010-09-03 01:26:39 +0000238
239 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000240 llvm::Type *Ty
Francois Pichetdbee3412011-01-18 05:04:39 +0000241 = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
John McCallfc400282010-09-03 01:26:39 +0000242
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000243 // C++ [class.virtual]p12:
244 // Explicit qualification with the scope operator (5.1) suppresses the
245 // virtual call mechanism.
246 //
247 // We also don't emit a virtual call if the base expression has a record type
248 // because then we know what the type is.
Fariborz Jahanian27262672011-01-20 17:19:02 +0000249 bool UseVirtualCall;
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000250 UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
251 && !canDevirtualizeMemberFunctionCalls(getContext(),
252 ME->getBase(), MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000253 llvm::Value *Callee;
John McCallfc400282010-09-03 01:26:39 +0000254 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
255 if (UseVirtualCall) {
256 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000257 } else {
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000258 if (getContext().getLangOptions().AppleKext &&
259 MD->isVirtual() &&
260 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000261 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000262 else
263 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000264 }
Francois Pichetdbee3412011-01-18 05:04:39 +0000265 } else if (const CXXConstructorDecl *Ctor =
266 dyn_cast<CXXConstructorDecl>(MD)) {
267 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000268 } else if (UseVirtualCall) {
Fariborz Jahanian27262672011-01-20 17:19:02 +0000269 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000270 } else {
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000271 if (getContext().getLangOptions().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000272 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000273 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000274 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000275 else
276 Callee = CGM.GetAddrOfFunction(MD, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000277 }
278
Anders Carlssonc997d422010-01-02 01:01:18 +0000279 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000280 CE->arg_begin(), CE->arg_end());
281}
282
283RValue
284CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
285 ReturnValueSlot ReturnValue) {
286 const BinaryOperator *BO =
287 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
288 const Expr *BaseExpr = BO->getLHS();
289 const Expr *MemFnExpr = BO->getRHS();
290
291 const MemberPointerType *MPT =
John McCall864c0412011-04-26 20:42:42 +0000292 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000293
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000294 const FunctionProtoType *FPT =
John McCall864c0412011-04-26 20:42:42 +0000295 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000296 const CXXRecordDecl *RD =
297 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
298
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000299 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000300 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000301
302 // Emit the 'this' pointer.
303 llvm::Value *This;
304
John McCall2de56d12010-08-25 11:45:40 +0000305 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000306 This = EmitScalarExpr(BaseExpr);
307 else
308 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000309
John McCall93d557b2010-08-22 00:05:51 +0000310 // Ask the ABI to load the callee. Note that This is modified.
311 llvm::Value *Callee =
John McCalld16c2cf2011-02-08 08:22:06 +0000312 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000313
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000314 CallArgList Args;
315
316 QualType ThisType =
317 getContext().getPointerType(getContext().getTagDeclType(RD));
318
319 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +0000320 Args.add(RValue::get(This), ThisType);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000321
322 // And the rest of the call args
323 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall864c0412011-04-26 20:42:42 +0000324 return EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000325 ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000326}
327
328RValue
329CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
330 const CXXMethodDecl *MD,
331 ReturnValueSlot ReturnValue) {
332 assert(MD->isInstance() &&
333 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000334 LValue LV = EmitLValue(E->getArg(0));
335 llvm::Value *This = LV.getAddress();
336
Douglas Gregorb2b56582011-09-06 16:26:56 +0000337 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
338 MD->isTrivial()) {
339 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
340 QualType Ty = E->getType();
341 EmitAggregateCopy(This, Src, Ty);
342 return RValue::get(This);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000343 }
344
Anders Carlssona2447e02011-05-08 20:32:23 +0000345 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Anders Carlssonc997d422010-01-02 01:01:18 +0000346 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000347 E->arg_begin() + 1, E->arg_end());
348}
349
350void
John McCall558d2ab2010-09-15 10:14:12 +0000351CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
352 AggValueSlot Dest) {
353 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000354 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000355
356 // If we require zero initialization before (or instead of) calling the
357 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +0000358 // constructor, emit the zero initialization now, unless destination is
359 // already zeroed.
360 if (E->requiresZeroInitialization() && !Dest.isZeroed())
John McCall558d2ab2010-09-15 10:14:12 +0000361 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor759e41b2010-08-22 16:15:35 +0000362
363 // If this is a call to a trivial default constructor, do nothing.
364 if (CD->isTrivial() && CD->isDefaultConstructor())
365 return;
366
John McCallfc1e6c72010-09-18 00:58:34 +0000367 // Elide the constructor if we're constructing from a temporary.
368 // The temporary check is required because Sema sets this on NRVO
369 // returns.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000370 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000371 assert(getContext().hasSameUnqualifiedType(E->getType(),
372 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000373 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
374 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000375 return;
376 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000377 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000378
John McCallc3c07662011-07-13 06:10:41 +0000379 if (const ConstantArrayType *arrayType
380 = getContext().getAsConstantArrayType(E->getType())) {
381 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000382 E->arg_begin(), E->arg_end());
John McCallc3c07662011-07-13 06:10:41 +0000383 } else {
Cameron Esfahani6bd2f6a2011-05-06 21:28:42 +0000384 CXXCtorType Type = Ctor_Complete;
Sean Huntd49bd552011-05-03 20:19:28 +0000385 bool ForVirtualBase = false;
386
387 switch (E->getConstructionKind()) {
388 case CXXConstructExpr::CK_Delegating:
Sean Hunt059ce0d2011-05-01 07:04:31 +0000389 // We should be emitting a constructor; GlobalDecl will assert this
390 Type = CurGD.getCtorType();
Sean Huntd49bd552011-05-03 20:19:28 +0000391 break;
Sean Hunt059ce0d2011-05-01 07:04:31 +0000392
Sean Huntd49bd552011-05-03 20:19:28 +0000393 case CXXConstructExpr::CK_Complete:
394 Type = Ctor_Complete;
395 break;
396
397 case CXXConstructExpr::CK_VirtualBase:
398 ForVirtualBase = true;
399 // fall-through
400
401 case CXXConstructExpr::CK_NonVirtualBase:
402 Type = Ctor_Base;
403 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000404
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000405 // Call the constructor.
John McCall558d2ab2010-09-15 10:14:12 +0000406 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000407 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000408 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000409}
410
Fariborz Jahanian34999872010-11-13 21:53:34 +0000411void
412CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
413 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000414 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000415 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000416 Exp = E->getSubExpr();
417 assert(isa<CXXConstructExpr>(Exp) &&
418 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
419 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
420 const CXXConstructorDecl *CD = E->getConstructor();
421 RunCleanupsScope Scope(*this);
422
423 // If we require zero initialization before (or instead of) calling the
424 // constructor, as can be the case with a non-user-provided default
425 // constructor, emit the zero initialization now.
426 // FIXME. Do I still need this for a copy ctor synthesis?
427 if (E->requiresZeroInitialization())
428 EmitNullInitialization(Dest, E->getType());
429
Chandler Carruth858a5462010-11-15 13:54:43 +0000430 assert(!getContext().getAsConstantArrayType(E->getType())
431 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000432 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
433 E->arg_begin(), E->arg_end());
434}
435
John McCall1e7fe752010-09-02 09:58:18 +0000436static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
437 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000438 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000439 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000440
John McCallb1c98a32011-05-16 01:05:12 +0000441 // No cookie is required if the operator new[] being used is the
442 // reserved placement operator new[].
443 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCall5172ed92010-08-23 01:17:59 +0000444 return CharUnits::Zero();
445
John McCall6ec278d2011-01-27 09:37:56 +0000446 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000447}
448
John McCall7d166272011-05-15 07:14:44 +0000449static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
450 const CXXNewExpr *e,
451 llvm::Value *&numElements,
452 llvm::Value *&sizeWithoutCookie) {
453 QualType type = e->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000454
John McCall7d166272011-05-15 07:14:44 +0000455 if (!e->isArray()) {
456 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
457 sizeWithoutCookie
458 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
459 return sizeWithoutCookie;
Douglas Gregor59174c02010-07-21 01:10:17 +0000460 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000461
John McCall7d166272011-05-15 07:14:44 +0000462 // The width of size_t.
463 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
464
John McCall1e7fe752010-09-02 09:58:18 +0000465 // Figure out the cookie size.
John McCall7d166272011-05-15 07:14:44 +0000466 llvm::APInt cookieSize(sizeWidth,
467 CalculateCookiePadding(CGF, e).getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000468
Anders Carlssona4d4c012009-09-23 16:07:23 +0000469 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000470 // We multiply the size of all dimensions for NumElements.
471 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall7d166272011-05-15 07:14:44 +0000472 numElements = CGF.EmitScalarExpr(e->getArraySize());
473 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall1e7fe752010-09-02 09:58:18 +0000474
John McCall7d166272011-05-15 07:14:44 +0000475 // The number of elements can be have an arbitrary integer type;
476 // essentially, we need to multiply it by a constant factor, add a
477 // cookie size, and verify that the result is representable as a
478 // size_t. That's just a gloss, though, and it's wrong in one
479 // important way: if the count is negative, it's an error even if
480 // the cookie size would bring the total size >= 0.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000481 bool isSigned
482 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000483 llvm::IntegerType *numElementsType
John McCall7d166272011-05-15 07:14:44 +0000484 = cast<llvm::IntegerType>(numElements->getType());
485 unsigned numElementsWidth = numElementsType->getBitWidth();
486
487 // Compute the constant factor.
488 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000489 while (const ConstantArrayType *CAT
John McCall7d166272011-05-15 07:14:44 +0000490 = CGF.getContext().getAsConstantArrayType(type)) {
491 type = CAT->getElementType();
492 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000493 }
494
John McCall7d166272011-05-15 07:14:44 +0000495 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
496 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
497 typeSizeMultiplier *= arraySizeMultiplier;
498
499 // This will be a size_t.
500 llvm::Value *size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000501
Chris Lattner806941e2010-07-20 21:55:52 +0000502 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
503 // Don't bloat the -O0 code.
John McCall7d166272011-05-15 07:14:44 +0000504 if (llvm::ConstantInt *numElementsC =
505 dyn_cast<llvm::ConstantInt>(numElements)) {
506 const llvm::APInt &count = numElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000507
John McCall7d166272011-05-15 07:14:44 +0000508 bool hasAnyOverflow = false;
John McCall1e7fe752010-09-02 09:58:18 +0000509
John McCall7d166272011-05-15 07:14:44 +0000510 // If 'count' was a negative number, it's an overflow.
511 if (isSigned && count.isNegative())
512 hasAnyOverflow = true;
John McCall1e7fe752010-09-02 09:58:18 +0000513
John McCall7d166272011-05-15 07:14:44 +0000514 // We want to do all this arithmetic in size_t. If numElements is
515 // wider than that, check whether it's already too big, and if so,
516 // overflow.
517 else if (numElementsWidth > sizeWidth &&
518 numElementsWidth - sizeWidth > count.countLeadingZeros())
519 hasAnyOverflow = true;
520
521 // Okay, compute a count at the right width.
522 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
523
524 // Scale numElements by that. This might overflow, but we don't
525 // care because it only overflows if allocationSize does, too, and
526 // if that overflows then we shouldn't use this.
527 numElements = llvm::ConstantInt::get(CGF.SizeTy,
528 adjustedCount * arraySizeMultiplier);
529
530 // Compute the size before cookie, and track whether it overflowed.
531 bool overflow;
532 llvm::APInt allocationSize
533 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
534 hasAnyOverflow |= overflow;
535
536 // Add in the cookie, and check whether it's overflowed.
537 if (cookieSize != 0) {
538 // Save the current size without a cookie. This shouldn't be
539 // used if there was overflow.
540 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
541
542 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
543 hasAnyOverflow |= overflow;
544 }
545
546 // On overflow, produce a -1 so operator new will fail.
547 if (hasAnyOverflow) {
548 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
549 } else {
550 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
551 }
552
553 // Otherwise, we might need to use the overflow intrinsics.
554 } else {
555 // There are up to four conditions we need to test for:
556 // 1) if isSigned, we need to check whether numElements is negative;
557 // 2) if numElementsWidth > sizeWidth, we need to check whether
558 // numElements is larger than something representable in size_t;
559 // 3) we need to compute
560 // sizeWithoutCookie := numElements * typeSizeMultiplier
561 // and check whether it overflows; and
562 // 4) if we need a cookie, we need to compute
563 // size := sizeWithoutCookie + cookieSize
564 // and check whether it overflows.
565
566 llvm::Value *hasOverflow = 0;
567
568 // If numElementsWidth > sizeWidth, then one way or another, we're
569 // going to have to do a comparison for (2), and this happens to
570 // take care of (1), too.
571 if (numElementsWidth > sizeWidth) {
572 llvm::APInt threshold(numElementsWidth, 1);
573 threshold <<= sizeWidth;
574
575 llvm::Value *thresholdV
576 = llvm::ConstantInt::get(numElementsType, threshold);
577
578 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
579 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
580
581 // Otherwise, if we're signed, we want to sext up to size_t.
582 } else if (isSigned) {
583 if (numElementsWidth < sizeWidth)
584 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
585
586 // If there's a non-1 type size multiplier, then we can do the
587 // signedness check at the same time as we do the multiply
588 // because a negative number times anything will cause an
589 // unsigned overflow. Otherwise, we have to do it here.
590 if (typeSizeMultiplier == 1)
591 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
592 llvm::ConstantInt::get(CGF.SizeTy, 0));
593
594 // Otherwise, zext up to size_t if necessary.
595 } else if (numElementsWidth < sizeWidth) {
596 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
597 }
598
599 assert(numElements->getType() == CGF.SizeTy);
600
601 size = numElements;
602
603 // Multiply by the type size if necessary. This multiplier
604 // includes all the factors for nested arrays.
605 //
606 // This step also causes numElements to be scaled up by the
607 // nested-array factor if necessary. Overflow on this computation
608 // can be ignored because the result shouldn't be used if
609 // allocation fails.
610 if (typeSizeMultiplier != 1) {
John McCall7d166272011-05-15 07:14:44 +0000611 llvm::Value *umul_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000612 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000613
614 llvm::Value *tsmV =
615 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
616 llvm::Value *result =
617 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
618
619 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
620 if (hasOverflow)
621 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
622 else
623 hasOverflow = overflowed;
624
625 size = CGF.Builder.CreateExtractValue(result, 0);
626
627 // Also scale up numElements by the array size multiplier.
628 if (arraySizeMultiplier != 1) {
629 // If the base element type size is 1, then we can re-use the
630 // multiply we just did.
631 if (typeSize.isOne()) {
632 assert(arraySizeMultiplier == typeSizeMultiplier);
633 numElements = size;
634
635 // Otherwise we need a separate multiply.
636 } else {
637 llvm::Value *asmV =
638 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
639 numElements = CGF.Builder.CreateMul(numElements, asmV);
640 }
641 }
642 } else {
643 // numElements doesn't need to be scaled.
644 assert(arraySizeMultiplier == 1);
Chris Lattner806941e2010-07-20 21:55:52 +0000645 }
646
John McCall7d166272011-05-15 07:14:44 +0000647 // Add in the cookie size if necessary.
648 if (cookieSize != 0) {
649 sizeWithoutCookie = size;
650
John McCall7d166272011-05-15 07:14:44 +0000651 llvm::Value *uadd_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000652 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000653
654 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
655 llvm::Value *result =
656 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
657
658 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
659 if (hasOverflow)
660 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
661 else
662 hasOverflow = overflowed;
663
664 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall1e7fe752010-09-02 09:58:18 +0000665 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000666
John McCall7d166272011-05-15 07:14:44 +0000667 // If we had any possibility of dynamic overflow, make a select to
668 // overwrite 'size' with an all-ones value, which should cause
669 // operator new to throw.
670 if (hasOverflow)
671 size = CGF.Builder.CreateSelect(hasOverflow,
672 llvm::Constant::getAllOnesValue(CGF.SizeTy),
673 size);
Chris Lattner806941e2010-07-20 21:55:52 +0000674 }
John McCall1e7fe752010-09-02 09:58:18 +0000675
John McCall7d166272011-05-15 07:14:44 +0000676 if (cookieSize == 0)
677 sizeWithoutCookie = size;
John McCall1e7fe752010-09-02 09:58:18 +0000678 else
John McCall7d166272011-05-15 07:14:44 +0000679 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall1e7fe752010-09-02 09:58:18 +0000680
John McCall7d166272011-05-15 07:14:44 +0000681 return size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000682}
683
Fariborz Jahanianef668722010-06-25 18:26:07 +0000684static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
685 llvm::Value *NewPtr) {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000686
687 assert(E->getNumConstructorArgs() == 1 &&
688 "Can only have one argument to initializer of POD type.");
689
690 const Expr *Init = E->getConstructorArg(0);
691 QualType AllocType = E->getAllocatedType();
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000692
693 unsigned Alignment =
694 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
John McCalla07398e2011-06-16 04:16:24 +0000695 if (!CGF.hasAggregateLLVMType(AllocType))
696 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType, Alignment),
697 false);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000698 else if (AllocType->isAnyComplexType())
699 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
700 AllocType.isVolatileQualified());
John McCall558d2ab2010-09-15 10:14:12 +0000701 else {
702 AggValueSlot Slot
John McCall7c2349b2011-08-25 20:40:09 +0000703 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
704 AggValueSlot::IsDestructed,
John McCall44184392011-08-26 07:31:35 +0000705 AggValueSlot::DoesNotNeedGCBarriers,
706 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000707 CGF.EmitAggExpr(Init, Slot);
708 }
Fariborz Jahanianef668722010-06-25 18:26:07 +0000709}
710
711void
712CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000713 QualType elementType,
714 llvm::Value *beginPtr,
715 llvm::Value *numElements) {
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000716 // We have a POD type.
717 if (E->getNumConstructorArgs() == 0)
718 return;
John McCall19705672011-09-15 06:49:18 +0000719
720 // Check if the number of elements is constant.
721 bool checkZero = true;
722 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) {
723 // If it's constant zero, skip the whole loop.
724 if (constNum->isZero()) return;
725
726 checkZero = false;
727 }
728
729 // Find the end of the array, hoisted out of the loop.
730 llvm::Value *endPtr =
731 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
732
733 // Create the continuation block.
734 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end");
735
736 // If we need to check for zero, do so now.
737 if (checkZero) {
738 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty");
739 llvm::Value *isEmpty = Builder.CreateICmpEQ(beginPtr, endPtr,
740 "array.isempty");
741 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
742 EmitBlock(nonEmptyBB);
743 }
744
745 // Enter the loop.
746 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
747 llvm::BasicBlock *loopBB = createBasicBlock("new.loop");
748
749 EmitBlock(loopBB);
750
751 // Set up the current-element phi.
752 llvm::PHINode *curPtr =
753 Builder.CreatePHI(beginPtr->getType(), 2, "array.cur");
754 curPtr->addIncoming(beginPtr, entryBB);
755
756 // Enter a partial-destruction cleanup if necessary.
757 QualType::DestructionKind dtorKind = elementType.isDestructedType();
758 EHScopeStack::stable_iterator cleanup;
759 if (needsEHCleanup(dtorKind)) {
760 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
761 getDestroyer(dtorKind));
762 cleanup = EHStack.stable_begin();
763 }
764
765 // Emit the initializer into this element.
766 StoreAnyExprIntoOneUnit(*this, E, curPtr);
767
768 // Leave the cleanup if we entered one.
769 if (cleanup != EHStack.stable_end())
770 DeactivateCleanupBlock(cleanup);
771
772 // Advance to the next element.
773 llvm::Value *nextPtr = Builder.CreateConstGEP1_32(curPtr, 1, "array.next");
774
775 // Check whether we've gotten to the end of the array and, if so,
776 // exit the loop.
777 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend");
778 Builder.CreateCondBr(isEnd, contBB, loopBB);
779 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock());
780
781 EmitBlock(contBB);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000782}
783
Douglas Gregor59174c02010-07-21 01:10:17 +0000784static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
785 llvm::Value *NewPtr, llvm::Value *Size) {
John McCalld16c2cf2011-02-08 08:22:06 +0000786 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyckfe710082011-01-19 01:58:38 +0000787 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000788 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000789 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000790}
791
Anders Carlssona4d4c012009-09-23 16:07:23 +0000792static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000793 QualType ElementType,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000794 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000795 llvm::Value *NumElements,
796 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000797 if (E->isArray()) {
Anders Carlssone99bdb62010-05-03 15:09:17 +0000798 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000799 bool RequiresZeroInitialization = false;
Sean Hunt023df372011-05-09 18:22:59 +0000800 if (Ctor->getParent()->hasTrivialDefaultConstructor()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000801 // If new expression did not specify value-initialization, then there
802 // is no initialization.
803 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
804 return;
805
John McCall19705672011-09-15 06:49:18 +0000806 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000807 // Optimization: since zero initialization will just set the memory
808 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +0000809 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
Douglas Gregor59174c02010-07-21 01:10:17 +0000810 return;
811 }
812
813 RequiresZeroInitialization = true;
814 }
John McCallc3c07662011-07-13 06:10:41 +0000815
Douglas Gregor59174c02010-07-21 01:10:17 +0000816 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
817 E->constructor_arg_begin(),
818 E->constructor_arg_end(),
819 RequiresZeroInitialization);
Anders Carlssone99bdb62010-05-03 15:09:17 +0000820 return;
Douglas Gregor59174c02010-07-21 01:10:17 +0000821 } else if (E->getNumConstructorArgs() == 1 &&
822 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
823 // Optimization: since zero initialization will just set the memory
824 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +0000825 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
826 return;
Douglas Gregor59174c02010-07-21 01:10:17 +0000827 } else {
John McCall19705672011-09-15 06:49:18 +0000828 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000829 return;
830 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000831 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000832
833 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregored8abf12010-07-08 06:14:04 +0000834 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
835 // direct initialization. C++ [dcl.init]p5 requires that we
836 // zero-initialize storage if there are no user-declared constructors.
837 if (E->hasInitializer() &&
838 !Ctor->getParent()->hasUserDeclaredConstructor() &&
839 !Ctor->getParent()->isEmpty())
John McCall19705672011-09-15 06:49:18 +0000840 CGF.EmitNullInitialization(NewPtr, ElementType);
Douglas Gregored8abf12010-07-08 06:14:04 +0000841
Douglas Gregor84745672010-07-07 23:37:33 +0000842 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
843 NewPtr, E->constructor_arg_begin(),
844 E->constructor_arg_end());
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000845
846 return;
847 }
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000848 // We have a POD type.
849 if (E->getNumConstructorArgs() == 0)
850 return;
851
Fariborz Jahanianef668722010-06-25 18:26:07 +0000852 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000853}
854
John McCall7d8647f2010-09-14 07:57:04 +0000855namespace {
856 /// A cleanup to call the given 'operator delete' function upon
857 /// abnormal exit from a new expression.
858 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
859 size_t NumPlacementArgs;
860 const FunctionDecl *OperatorDelete;
861 llvm::Value *Ptr;
862 llvm::Value *AllocSize;
863
864 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
865
866 public:
867 static size_t getExtraSize(size_t NumPlacementArgs) {
868 return NumPlacementArgs * sizeof(RValue);
869 }
870
871 CallDeleteDuringNew(size_t NumPlacementArgs,
872 const FunctionDecl *OperatorDelete,
873 llvm::Value *Ptr,
874 llvm::Value *AllocSize)
875 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
876 Ptr(Ptr), AllocSize(AllocSize) {}
877
878 void setPlacementArg(unsigned I, RValue Arg) {
879 assert(I < NumPlacementArgs && "index out of range");
880 getPlacementArgs()[I] = Arg;
881 }
882
John McCallad346f42011-07-12 20:27:29 +0000883 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7d8647f2010-09-14 07:57:04 +0000884 const FunctionProtoType *FPT
885 = OperatorDelete->getType()->getAs<FunctionProtoType>();
886 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +0000887 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +0000888
889 CallArgList DeleteArgs;
890
891 // The first argument is always a void*.
892 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +0000893 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000894
895 // A member 'operator delete' can take an extra 'size_t' argument.
896 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman04c9a492011-05-02 17:57:46 +0000897 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000898
899 // Pass the rest of the arguments, which must match exactly.
900 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman04c9a492011-05-02 17:57:46 +0000901 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000902
903 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000904 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall7d8647f2010-09-14 07:57:04 +0000905 CGF.CGM.GetAddrOfFunction(OperatorDelete),
906 ReturnValueSlot(), DeleteArgs, OperatorDelete);
907 }
908 };
John McCall3019c442010-09-17 00:50:28 +0000909
910 /// A cleanup to call the given 'operator delete' function upon
911 /// abnormal exit from a new expression when the new expression is
912 /// conditional.
913 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
914 size_t NumPlacementArgs;
915 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +0000916 DominatingValue<RValue>::saved_type Ptr;
917 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +0000918
John McCall804b8072011-01-28 10:53:53 +0000919 DominatingValue<RValue>::saved_type *getPlacementArgs() {
920 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +0000921 }
922
923 public:
924 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +0000925 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +0000926 }
927
928 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
929 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +0000930 DominatingValue<RValue>::saved_type Ptr,
931 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +0000932 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
933 Ptr(Ptr), AllocSize(AllocSize) {}
934
John McCall804b8072011-01-28 10:53:53 +0000935 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +0000936 assert(I < NumPlacementArgs && "index out of range");
937 getPlacementArgs()[I] = Arg;
938 }
939
John McCallad346f42011-07-12 20:27:29 +0000940 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall3019c442010-09-17 00:50:28 +0000941 const FunctionProtoType *FPT
942 = OperatorDelete->getType()->getAs<FunctionProtoType>();
943 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
944 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
945
946 CallArgList DeleteArgs;
947
948 // The first argument is always a void*.
949 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +0000950 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall3019c442010-09-17 00:50:28 +0000951
952 // A member 'operator delete' can take an extra 'size_t' argument.
953 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +0000954 RValue RV = AllocSize.restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +0000955 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +0000956 }
957
958 // Pass the rest of the arguments, which must match exactly.
959 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +0000960 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +0000961 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +0000962 }
963
964 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000965 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall3019c442010-09-17 00:50:28 +0000966 CGF.CGM.GetAddrOfFunction(OperatorDelete),
967 ReturnValueSlot(), DeleteArgs, OperatorDelete);
968 }
969 };
970}
971
972/// Enter a cleanup to call 'operator delete' if the initializer in a
973/// new-expression throws.
974static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
975 const CXXNewExpr *E,
976 llvm::Value *NewPtr,
977 llvm::Value *AllocSize,
978 const CallArgList &NewArgs) {
979 // If we're not inside a conditional branch, then the cleanup will
980 // dominate and we can do the easier (and more efficient) thing.
981 if (!CGF.isInConditionalBranch()) {
982 CallDeleteDuringNew *Cleanup = CGF.EHStack
983 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
984 E->getNumPlacementArgs(),
985 E->getOperatorDelete(),
986 NewPtr, AllocSize);
987 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanc6d07822011-05-02 18:05:27 +0000988 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall3019c442010-09-17 00:50:28 +0000989
990 return;
991 }
992
993 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +0000994 DominatingValue<RValue>::saved_type SavedNewPtr =
995 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
996 DominatingValue<RValue>::saved_type SavedAllocSize =
997 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +0000998
999 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
1000 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
1001 E->getNumPlacementArgs(),
1002 E->getOperatorDelete(),
1003 SavedNewPtr,
1004 SavedAllocSize);
1005 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +00001006 Cleanup->setPlacementArg(I,
Eli Friedmanc6d07822011-05-02 18:05:27 +00001007 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall3019c442010-09-17 00:50:28 +00001008
1009 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall7d8647f2010-09-14 07:57:04 +00001010}
1011
Anders Carlsson16d81b82009-09-22 22:53:17 +00001012llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001013 // The element type being allocated.
1014 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +00001015
John McCallc2f3e7f2011-03-07 03:12:35 +00001016 // 1. Build a call to the allocation function.
1017 FunctionDecl *allocator = E->getOperatorNew();
1018 const FunctionProtoType *allocatorType =
1019 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001020
John McCallc2f3e7f2011-03-07 03:12:35 +00001021 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001022
1023 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001024 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001025
John McCallc2f3e7f2011-03-07 03:12:35 +00001026 llvm::Value *numElements = 0;
1027 llvm::Value *allocSizeWithoutCookie = 0;
1028 llvm::Value *allocSize =
John McCall7d166272011-05-15 07:14:44 +00001029 EmitCXXNewAllocSize(*this, E, numElements, allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +00001030
Eli Friedman04c9a492011-05-02 17:57:46 +00001031 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001032
1033 // Emit the rest of the arguments.
1034 // FIXME: Ideally, this should just use EmitCallArgs.
John McCallc2f3e7f2011-03-07 03:12:35 +00001035 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001036
1037 // First, use the types from the function type.
1038 // We start at 1 here because the first argument (the allocation size)
1039 // has already been emitted.
John McCallc2f3e7f2011-03-07 03:12:35 +00001040 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1041 ++i, ++placementArg) {
1042 QualType argType = allocatorType->getArgType(i);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001043
John McCallc2f3e7f2011-03-07 03:12:35 +00001044 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1045 placementArg->getType()) &&
Anders Carlsson16d81b82009-09-22 22:53:17 +00001046 "type mismatch in call argument!");
1047
John McCall413ebdb2011-03-11 20:59:21 +00001048 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001049 }
1050
1051 // Either we've emitted all the call args, or we have a call to a
1052 // variadic function.
John McCallc2f3e7f2011-03-07 03:12:35 +00001053 assert((placementArg == E->placement_arg_end() ||
1054 allocatorType->isVariadic()) &&
1055 "Extra arguments to non-variadic function!");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001056
1057 // If we still have any arguments, emit them using the type of the argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001058 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1059 placementArg != placementArgsEnd; ++placementArg) {
John McCall413ebdb2011-03-11 20:59:21 +00001060 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001061 }
1062
John McCallb1c98a32011-05-16 01:05:12 +00001063 // Emit the allocation call. If the allocator is a global placement
1064 // operator, just "inline" it directly.
1065 RValue RV;
1066 if (allocator->isReservedGlobalPlacementOperator()) {
1067 assert(allocatorArgs.size() == 2);
1068 RV = allocatorArgs[1].RV;
1069 // TODO: kill any unnecessary computations done for the size
1070 // argument.
1071 } else {
1072 RV = EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocatorType),
1073 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1074 allocatorArgs, allocator);
1075 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001076
John McCallc2f3e7f2011-03-07 03:12:35 +00001077 // Emit a null check on the allocation result if the allocation
1078 // function is allowed to return null (because it has a non-throwing
1079 // exception spec; for this part, we inline
1080 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1081 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001082 bool nullCheck = allocatorType->isNothrow(getContext()) &&
John McCallf85e1932011-06-15 23:02:42 +00001083 !(allocType.isPODType(getContext()) && !E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001084
John McCallc2f3e7f2011-03-07 03:12:35 +00001085 llvm::BasicBlock *nullCheckBB = 0;
1086 llvm::BasicBlock *contBB = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001087
John McCallc2f3e7f2011-03-07 03:12:35 +00001088 llvm::Value *allocation = RV.getScalarVal();
1089 unsigned AS =
1090 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001091
John McCalla7f633f2011-03-07 01:52:56 +00001092 // The null-check means that the initializer is conditionally
1093 // evaluated.
1094 ConditionalEvaluation conditional(*this);
1095
John McCallc2f3e7f2011-03-07 03:12:35 +00001096 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001097 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001098
1099 nullCheckBB = Builder.GetInsertBlock();
1100 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1101 contBB = createBasicBlock("new.cont");
1102
1103 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1104 Builder.CreateCondBr(isNull, contBB, notNullBB);
1105 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001106 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001107
John McCall7d8647f2010-09-14 07:57:04 +00001108 // If there's an operator delete, enter a cleanup to call it if an
1109 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001110 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCallb1c98a32011-05-16 01:05:12 +00001111 if (E->getOperatorDelete() &&
1112 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001113 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1114 operatorDeleteCleanup = EHStack.stable_begin();
John McCall7d8647f2010-09-14 07:57:04 +00001115 }
1116
Eli Friedman576cf172011-09-06 18:53:03 +00001117 assert((allocSize == allocSizeWithoutCookie) ==
1118 CalculateCookiePadding(*this, E).isZero());
1119 if (allocSize != allocSizeWithoutCookie) {
1120 assert(E->isArray());
1121 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1122 numElements,
1123 E, allocType);
1124 }
1125
Chris Lattner2acc6e32011-07-18 04:24:23 +00001126 llvm::Type *elementPtrTy
John McCallc2f3e7f2011-03-07 03:12:35 +00001127 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1128 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001129
John McCall19705672011-09-15 06:49:18 +00001130 EmitNewInitializer(*this, E, allocType, result, numElements,
1131 allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001132 if (E->isArray()) {
John McCall1e7fe752010-09-02 09:58:18 +00001133 // NewPtr is a pointer to the base element type. If we're
1134 // allocating an array of arrays, we'll need to cast back to the
1135 // array pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001136 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCallc2f3e7f2011-03-07 03:12:35 +00001137 if (result->getType() != resultType)
1138 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001139 }
John McCall7d8647f2010-09-14 07:57:04 +00001140
1141 // Deactivate the 'operator delete' cleanup if we finished
1142 // initialization.
John McCallc2f3e7f2011-03-07 03:12:35 +00001143 if (operatorDeleteCleanup.isValid())
1144 DeactivateCleanupBlock(operatorDeleteCleanup);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001145
John McCallc2f3e7f2011-03-07 03:12:35 +00001146 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001147 conditional.end(*this);
1148
John McCallc2f3e7f2011-03-07 03:12:35 +00001149 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1150 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001151
Jay Foadbbf3bac2011-03-30 11:28:58 +00001152 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001153 PHI->addIncoming(result, notNullBB);
1154 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1155 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001156
John McCallc2f3e7f2011-03-07 03:12:35 +00001157 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001158 }
John McCall1e7fe752010-09-02 09:58:18 +00001159
John McCallc2f3e7f2011-03-07 03:12:35 +00001160 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001161}
1162
Eli Friedman5fe05982009-11-18 00:50:08 +00001163void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1164 llvm::Value *Ptr,
1165 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001166 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1167
Eli Friedman5fe05982009-11-18 00:50:08 +00001168 const FunctionProtoType *DeleteFTy =
1169 DeleteFD->getType()->getAs<FunctionProtoType>();
1170
1171 CallArgList DeleteArgs;
1172
Anders Carlsson871d0782009-12-13 20:04:38 +00001173 // Check if we need to pass the size to the delete operator.
1174 llvm::Value *Size = 0;
1175 QualType SizeTy;
1176 if (DeleteFTy->getNumArgs() == 2) {
1177 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001178 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1179 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1180 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001181 }
1182
Eli Friedman5fe05982009-11-18 00:50:08 +00001183 QualType ArgTy = DeleteFTy->getArgType(0);
1184 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001185 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001186
Anders Carlsson871d0782009-12-13 20:04:38 +00001187 if (Size)
Eli Friedman04c9a492011-05-02 17:57:46 +00001188 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001189
1190 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001191 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001192 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +00001193 DeleteArgs, DeleteFD);
1194}
1195
John McCall1e7fe752010-09-02 09:58:18 +00001196namespace {
1197 /// Calls the given 'operator delete' on a single object.
1198 struct CallObjectDelete : EHScopeStack::Cleanup {
1199 llvm::Value *Ptr;
1200 const FunctionDecl *OperatorDelete;
1201 QualType ElementType;
1202
1203 CallObjectDelete(llvm::Value *Ptr,
1204 const FunctionDecl *OperatorDelete,
1205 QualType ElementType)
1206 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1207
John McCallad346f42011-07-12 20:27:29 +00001208 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001209 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1210 }
1211 };
1212}
1213
1214/// Emit the code for deleting a single object.
1215static void EmitObjectDelete(CodeGenFunction &CGF,
1216 const FunctionDecl *OperatorDelete,
1217 llvm::Value *Ptr,
Douglas Gregora8b20f72011-07-13 00:54:47 +00001218 QualType ElementType,
1219 bool UseGlobalDelete) {
John McCall1e7fe752010-09-02 09:58:18 +00001220 // Find the destructor for the type, if applicable. If the
1221 // destructor is virtual, we'll just emit the vcall and return.
1222 const CXXDestructorDecl *Dtor = 0;
1223 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1224 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanaebab722011-08-02 18:05:30 +00001225 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall1e7fe752010-09-02 09:58:18 +00001226 Dtor = RD->getDestructor();
1227
1228 if (Dtor->isVirtual()) {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001229 if (UseGlobalDelete) {
1230 // If we're supposed to call the global delete, make sure we do so
1231 // even if the destructor throws.
1232 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1233 Ptr, OperatorDelete,
1234 ElementType);
1235 }
1236
Chris Lattner2acc6e32011-07-18 04:24:23 +00001237 llvm::Type *Ty =
John McCallfc400282010-09-03 01:26:39 +00001238 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1239 Dtor_Complete),
John McCall1e7fe752010-09-02 09:58:18 +00001240 /*isVariadic=*/false);
1241
1242 llvm::Value *Callee
Douglas Gregora8b20f72011-07-13 00:54:47 +00001243 = CGF.BuildVirtualCall(Dtor,
1244 UseGlobalDelete? Dtor_Complete : Dtor_Deleting,
1245 Ptr, Ty);
John McCall1e7fe752010-09-02 09:58:18 +00001246 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1247 0, 0);
1248
Douglas Gregora8b20f72011-07-13 00:54:47 +00001249 if (UseGlobalDelete) {
1250 CGF.PopCleanupBlock();
1251 }
1252
John McCall1e7fe752010-09-02 09:58:18 +00001253 return;
1254 }
1255 }
1256 }
1257
1258 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001259 // This doesn't have to a conditional cleanup because we're going
1260 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001261 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1262 Ptr, OperatorDelete, ElementType);
1263
1264 if (Dtor)
1265 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1266 /*ForVirtualBase=*/false, Ptr);
John McCallf85e1932011-06-15 23:02:42 +00001267 else if (CGF.getLangOptions().ObjCAutoRefCount &&
1268 ElementType->isObjCLifetimeType()) {
1269 switch (ElementType.getObjCLifetime()) {
1270 case Qualifiers::OCL_None:
1271 case Qualifiers::OCL_ExplicitNone:
1272 case Qualifiers::OCL_Autoreleasing:
1273 break;
John McCall1e7fe752010-09-02 09:58:18 +00001274
John McCallf85e1932011-06-15 23:02:42 +00001275 case Qualifiers::OCL_Strong: {
1276 // Load the pointer value.
1277 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1278 ElementType.isVolatileQualified());
1279
1280 CGF.EmitARCRelease(PtrValue, /*precise*/ true);
1281 break;
1282 }
1283
1284 case Qualifiers::OCL_Weak:
1285 CGF.EmitARCDestroyWeak(Ptr);
1286 break;
1287 }
1288 }
1289
John McCall1e7fe752010-09-02 09:58:18 +00001290 CGF.PopCleanupBlock();
1291}
1292
1293namespace {
1294 /// Calls the given 'operator delete' on an array of objects.
1295 struct CallArrayDelete : EHScopeStack::Cleanup {
1296 llvm::Value *Ptr;
1297 const FunctionDecl *OperatorDelete;
1298 llvm::Value *NumElements;
1299 QualType ElementType;
1300 CharUnits CookieSize;
1301
1302 CallArrayDelete(llvm::Value *Ptr,
1303 const FunctionDecl *OperatorDelete,
1304 llvm::Value *NumElements,
1305 QualType ElementType,
1306 CharUnits CookieSize)
1307 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1308 ElementType(ElementType), CookieSize(CookieSize) {}
1309
John McCallad346f42011-07-12 20:27:29 +00001310 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001311 const FunctionProtoType *DeleteFTy =
1312 OperatorDelete->getType()->getAs<FunctionProtoType>();
1313 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1314
1315 CallArgList Args;
1316
1317 // Pass the pointer as the first argument.
1318 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1319 llvm::Value *DeletePtr
1320 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001321 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall1e7fe752010-09-02 09:58:18 +00001322
1323 // Pass the original requested size as the second argument.
1324 if (DeleteFTy->getNumArgs() == 2) {
1325 QualType size_t = DeleteFTy->getArgType(1);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001326 llvm::IntegerType *SizeTy
John McCall1e7fe752010-09-02 09:58:18 +00001327 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1328
1329 CharUnits ElementTypeSize =
1330 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1331
1332 // The size of an element, multiplied by the number of elements.
1333 llvm::Value *Size
1334 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1335 Size = CGF.Builder.CreateMul(Size, NumElements);
1336
1337 // Plus the size of the cookie if applicable.
1338 if (!CookieSize.isZero()) {
1339 llvm::Value *CookieSizeV
1340 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1341 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1342 }
1343
Eli Friedman04c9a492011-05-02 17:57:46 +00001344 Args.add(RValue::get(Size), size_t);
John McCall1e7fe752010-09-02 09:58:18 +00001345 }
1346
1347 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001348 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
John McCall1e7fe752010-09-02 09:58:18 +00001349 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1350 ReturnValueSlot(), Args, OperatorDelete);
1351 }
1352 };
1353}
1354
1355/// Emit the code for deleting an array of objects.
1356static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001357 const CXXDeleteExpr *E,
John McCall7cfd76c2011-07-13 01:41:37 +00001358 llvm::Value *deletedPtr,
1359 QualType elementType) {
1360 llvm::Value *numElements = 0;
1361 llvm::Value *allocatedPtr = 0;
1362 CharUnits cookieSize;
1363 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1364 numElements, allocatedPtr, cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001365
John McCall7cfd76c2011-07-13 01:41:37 +00001366 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall1e7fe752010-09-02 09:58:18 +00001367
1368 // Make sure that we call delete even if one of the dtors throws.
John McCall7cfd76c2011-07-13 01:41:37 +00001369 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001370 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCall7cfd76c2011-07-13 01:41:37 +00001371 allocatedPtr, operatorDelete,
1372 numElements, elementType,
1373 cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001374
John McCall7cfd76c2011-07-13 01:41:37 +00001375 // Destroy the elements.
1376 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1377 assert(numElements && "no element count for a type with a destructor!");
1378
John McCall7cfd76c2011-07-13 01:41:37 +00001379 llvm::Value *arrayEnd =
1380 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCallfbf780a2011-07-13 08:09:46 +00001381
1382 // Note that it is legal to allocate a zero-length array, and we
1383 // can never fold the check away because the length should always
1384 // come from a cookie.
John McCall7cfd76c2011-07-13 01:41:37 +00001385 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1386 CGF.getDestroyer(dtorKind),
John McCallfbf780a2011-07-13 08:09:46 +00001387 /*checkZeroLength*/ true,
John McCall7cfd76c2011-07-13 01:41:37 +00001388 CGF.needsEHCleanup(dtorKind));
John McCall1e7fe752010-09-02 09:58:18 +00001389 }
1390
John McCall7cfd76c2011-07-13 01:41:37 +00001391 // Pop the cleanup block.
John McCall1e7fe752010-09-02 09:58:18 +00001392 CGF.PopCleanupBlock();
1393}
1394
Anders Carlsson16d81b82009-09-22 22:53:17 +00001395void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian72c21532009-11-13 19:27:47 +00001396
Douglas Gregor90916562009-09-29 18:16:17 +00001397 // Get at the argument before we performed the implicit conversion
1398 // to void*.
1399 const Expr *Arg = E->getArgument();
1400 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00001401 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregor90916562009-09-29 18:16:17 +00001402 ICE->getType()->isVoidPointerType())
1403 Arg = ICE->getSubExpr();
Douglas Gregord69dd782009-10-01 05:49:51 +00001404 else
1405 break;
Douglas Gregor90916562009-09-29 18:16:17 +00001406 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001407
Douglas Gregor90916562009-09-29 18:16:17 +00001408 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001409
1410 // Null check the pointer.
1411 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1412 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1413
Anders Carlssonb9241242011-04-11 00:30:07 +00001414 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001415
1416 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1417 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001418
John McCall1e7fe752010-09-02 09:58:18 +00001419 // We might be deleting a pointer to array. If so, GEP down to the
1420 // first non-array element.
1421 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1422 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1423 if (DeleteTy->isConstantArrayType()) {
1424 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001425 SmallVector<llvm::Value*,8> GEP;
John McCall1e7fe752010-09-02 09:58:18 +00001426
1427 GEP.push_back(Zero); // point at the outermost array
1428
1429 // For each layer of array type we're pointing at:
1430 while (const ConstantArrayType *Arr
1431 = getContext().getAsConstantArrayType(DeleteTy)) {
1432 // 1. Unpeel the array type.
1433 DeleteTy = Arr->getElementType();
1434
1435 // 2. GEP to the first element of the array.
1436 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001437 }
John McCall1e7fe752010-09-02 09:58:18 +00001438
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001439 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001440 }
1441
Douglas Gregoreede61a2010-09-02 17:38:50 +00001442 assert(ConvertTypeForMem(DeleteTy) ==
1443 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001444
1445 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001446 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001447 } else {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001448 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1449 E->isGlobalDelete());
John McCall1e7fe752010-09-02 09:58:18 +00001450 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001451
Anders Carlsson16d81b82009-09-22 22:53:17 +00001452 EmitBlock(DeleteEnd);
1453}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001454
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001455static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1456 // void __cxa_bad_typeid();
1457
Chris Lattner2acc6e32011-07-18 04:24:23 +00001458 llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1459 llvm::FunctionType *FTy =
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001460 llvm::FunctionType::get(VoidTy, false);
1461
1462 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1463}
1464
1465static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001466 llvm::Value *Fn = getBadTypeidFn(CGF);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001467 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001468 CGF.Builder.CreateUnreachable();
1469}
1470
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001471static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1472 const Expr *E,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001473 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001474 // Get the vtable pointer.
1475 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1476
1477 // C++ [expr.typeid]p2:
1478 // If the glvalue expression is obtained by applying the unary * operator to
1479 // a pointer and the pointer is a null pointer value, the typeid expression
1480 // throws the std::bad_typeid exception.
1481 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1482 if (UO->getOpcode() == UO_Deref) {
1483 llvm::BasicBlock *BadTypeidBlock =
1484 CGF.createBasicBlock("typeid.bad_typeid");
1485 llvm::BasicBlock *EndBlock =
1486 CGF.createBasicBlock("typeid.end");
1487
1488 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1489 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1490
1491 CGF.EmitBlock(BadTypeidBlock);
1492 EmitBadTypeidCall(CGF);
1493 CGF.EmitBlock(EndBlock);
1494 }
1495 }
1496
1497 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1498 StdTypeInfoPtrTy->getPointerTo());
1499
1500 // Load the type info.
1501 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1502 return CGF.Builder.CreateLoad(Value);
1503}
1504
John McCall3ad32c82011-01-28 08:37:24 +00001505llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001506 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001507 ConvertType(E->getType())->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001508
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001509 if (E->isTypeOperand()) {
1510 llvm::Constant *TypeInfo =
1511 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001512 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001513 }
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001514
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001515 // C++ [expr.typeid]p2:
1516 // When typeid is applied to a glvalue expression whose type is a
1517 // polymorphic class type, the result refers to a std::type_info object
1518 // representing the type of the most derived object (that is, the dynamic
1519 // type) to which the glvalue refers.
1520 if (E->getExprOperand()->isGLValue()) {
1521 if (const RecordType *RT =
1522 E->getExprOperand()->getType()->getAs<RecordType>()) {
1523 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1524 if (RD->isPolymorphic())
1525 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1526 StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001527 }
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001528 }
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001529
1530 QualType OperandTy = E->getExprOperand()->getType();
1531 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1532 StdTypeInfoPtrTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001533}
Mike Stumpc849c052009-11-16 06:50:58 +00001534
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001535static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1536 // void *__dynamic_cast(const void *sub,
1537 // const abi::__class_type_info *src,
1538 // const abi::__class_type_info *dst,
1539 // std::ptrdiff_t src2dst_offset);
1540
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001541 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1542 llvm::Type *PtrDiffTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001543 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1544
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001545 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001546
Chris Lattner2acc6e32011-07-18 04:24:23 +00001547 llvm::FunctionType *FTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001548 llvm::FunctionType::get(Int8PtrTy, Args, false);
1549
1550 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1551}
1552
1553static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1554 // void __cxa_bad_cast();
1555
Chris Lattner2acc6e32011-07-18 04:24:23 +00001556 llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1557 llvm::FunctionType *FTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001558 llvm::FunctionType::get(VoidTy, false);
1559
1560 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1561}
1562
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001563static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001564 llvm::Value *Fn = getBadCastFn(CGF);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001565 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001566 CGF.Builder.CreateUnreachable();
1567}
1568
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001569static llvm::Value *
1570EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1571 QualType SrcTy, QualType DestTy,
1572 llvm::BasicBlock *CastEnd) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001573 llvm::Type *PtrDiffLTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001574 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001575 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001576
1577 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1578 if (PTy->getPointeeType()->isVoidType()) {
1579 // C++ [expr.dynamic.cast]p7:
1580 // If T is "pointer to cv void," then the result is a pointer to the
1581 // most derived object pointed to by v.
1582
1583 // Get the vtable pointer.
1584 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1585
1586 // Get the offset-to-top from the vtable.
1587 llvm::Value *OffsetToTop =
1588 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1589 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1590
1591 // Finally, add the offset to the pointer.
1592 Value = CGF.EmitCastToVoidPtr(Value);
1593 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1594
1595 return CGF.Builder.CreateBitCast(Value, DestLTy);
1596 }
1597 }
1598
1599 QualType SrcRecordTy;
1600 QualType DestRecordTy;
1601
1602 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1603 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1604 DestRecordTy = DestPTy->getPointeeType();
1605 } else {
1606 SrcRecordTy = SrcTy;
1607 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1608 }
1609
1610 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1611 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1612
1613 llvm::Value *SrcRTTI =
1614 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1615 llvm::Value *DestRTTI =
1616 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1617
1618 // FIXME: Actually compute a hint here.
1619 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1620
1621 // Emit the call to __dynamic_cast.
1622 Value = CGF.EmitCastToVoidPtr(Value);
1623 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1624 SrcRTTI, DestRTTI, OffsetHint);
1625 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1626
1627 /// C++ [expr.dynamic.cast]p9:
1628 /// A failed cast to reference type throws std::bad_cast
1629 if (DestTy->isReferenceType()) {
1630 llvm::BasicBlock *BadCastBlock =
1631 CGF.createBasicBlock("dynamic_cast.bad_cast");
1632
1633 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1634 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1635
1636 CGF.EmitBlock(BadCastBlock);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001637 EmitBadCastCall(CGF);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001638 }
1639
1640 return Value;
1641}
1642
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001643static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1644 QualType DestTy) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001645 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001646 if (DestTy->isPointerType())
1647 return llvm::Constant::getNullValue(DestLTy);
1648
1649 /// C++ [expr.dynamic.cast]p9:
1650 /// A failed cast to reference type throws std::bad_cast
1651 EmitBadCastCall(CGF);
1652
1653 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1654 return llvm::UndefValue::get(DestLTy);
1655}
1656
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001657llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001658 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001659 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001660
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001661 if (DCE->isAlwaysNull())
1662 return EmitDynamicCastToNull(*this, DestTy);
1663
1664 QualType SrcTy = DCE->getSubExpr()->getType();
1665
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001666 // C++ [expr.dynamic.cast]p4:
1667 // If the value of v is a null pointer value in the pointer case, the result
1668 // is the null pointer value of type T.
1669 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001670
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001671 llvm::BasicBlock *CastNull = 0;
1672 llvm::BasicBlock *CastNotNull = 0;
1673 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001674
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001675 if (ShouldNullCheckSrcValue) {
1676 CastNull = createBasicBlock("dynamic_cast.null");
1677 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1678
1679 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1680 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1681 EmitBlock(CastNotNull);
Mike Stumpc849c052009-11-16 06:50:58 +00001682 }
1683
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001684 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1685
1686 if (ShouldNullCheckSrcValue) {
1687 EmitBranch(CastEnd);
1688
1689 EmitBlock(CastNull);
1690 EmitBranch(CastEnd);
1691 }
1692
1693 EmitBlock(CastEnd);
1694
1695 if (ShouldNullCheckSrcValue) {
1696 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1697 PHI->addIncoming(Value, CastNotNull);
1698 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1699
1700 Value = PHI;
1701 }
1702
1703 return Value;
Mike Stumpc849c052009-11-16 06:50:58 +00001704}