blob: 6ee9bc1033e29aecf988161687fc76e30f4c8793 [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlssoncc52f652009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
Devang Patel91bbb552010-09-30 19:05:55 +000014#include "clang/Frontend/CodeGenOptions.h"
Anders Carlssoncc52f652009-09-22 22:53:17 +000015#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Fariborz Jahanian60d215b2010-05-20 21:38:57 +000017#include "CGObjCRuntime.h"
Devang Patel91bbb552010-09-30 19:05:55 +000018#include "CGDebugInfo.h"
Chris Lattner26008e02010-07-20 20:19:24 +000019#include "llvm/Intrinsics.h"
Anders Carlssonbbe277c2011-04-13 02:35:36 +000020#include "llvm/Support/CallSite.h"
21
Anders Carlssoncc52f652009-09-22 22:53:17 +000022using namespace clang;
23using namespace CodeGen;
24
Anders Carlsson27da15b2010-01-01 20:29:01 +000025RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
26 llvm::Value *Callee,
27 ReturnValueSlot ReturnValue,
28 llvm::Value *This,
Anders Carlssone36a6b32010-01-02 01:01:18 +000029 llvm::Value *VTT,
Anders Carlsson27da15b2010-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 Friedman43dca6a2011-05-02 17:57:46 +000040 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson27da15b2010-01-01 20:29:01 +000041
Anders Carlssone36a6b32010-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 Friedman43dca6a2011-05-02 17:57:46 +000045 Args.add(RValue::get(VTT), T);
Anders Carlssone36a6b32010-01-02 01:01:18 +000046 }
47
Anders Carlsson27da15b2010-01-01 20:29:01 +000048 // And the rest of the call args
49 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
50
John McCallab26cfa2010-02-05 21:31:56 +000051 QualType ResultType = FPT->getResultType();
Tilmann Scheller99cc30c2011-03-02 21:36:49 +000052 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
53 FPT->getExtInfo()),
Rafael Espindolac50c27c2010-03-30 20:24:48 +000054 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000055}
56
Anders Carlsson1ae64c52011-01-29 03:52:01 +000057static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
Anders Carlsson6b3afd72011-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 Carlsson1ae64c52011-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 Carlssonc53d9e82011-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 Carlsson27da15b2010-01-01 20:29:01 +0000106/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
107/// expr can be devirtualized.
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000108static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
109 const Expr *Base,
Anders Carlssona7911fa2010-10-27 13:28:46 +0000110 const CXXMethodDecl *MD) {
111
Anders Carlsson1ae64c52011-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 Jahanian252a47f2011-01-21 01:04:41 +0000114 if (Context.getLangOptions().AppleKext)
115 return false;
116
Anders Carlsson1ae64c52011-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 Carlsson19588aa2011-01-23 21:07:30 +0000131 // If the member function is marked 'final', we know that it can't be
Anders Carlssonb00c2142010-10-27 13:34:43 +0000132 // overridden and can therefore devirtualize it.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000133 if (MD->hasAttr<FinalAttr>())
Anders Carlssona7911fa2010-10-27 13:28:46 +0000134 return true;
Anders Carlssonb00c2142010-10-27 13:34:43 +0000135
Anders Carlsson19588aa2011-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 Carlsson1eb95962011-01-24 16:26:15 +0000138 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssonb00c2142010-10-27 13:34:43 +0000139 return true;
140
Anders Carlssonc53d9e82011-04-10 18:20:53 +0000141 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson27da15b2010-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 Friedmana6824272010-01-31 20:58:15 +0000152 if (isa<CXXConstructExpr>(Base))
Anders Carlsson27da15b2010-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 Carlssona7911fa2010-10-27 13:28:46 +0000162
Anders Carlsson27da15b2010-01-01 20:29:01 +0000163 // We can't devirtualize the call.
164 return false;
165}
166
Francois Pichet64225792011-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 Carlsson27da15b2010-01-01 20:29:01 +0000169RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
170 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +0000171 const Expr *callee = CE->getCallee()->IgnoreParens();
172
173 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000174 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +0000175
176 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000177 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
178
Devang Patel91bbb552010-09-30 19:05:55 +0000179 CGDebugInfo *DI = getDebugInfo();
Devang Patel401c9162010-10-22 18:56:27 +0000180 if (DI && CGM.getCodeGenOpts().LimitDebugInfo
181 && !isa<CallExpr>(ME->getBase())) {
Devang Patel91bbb552010-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 Carlsson27da15b2010-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 Carlsson27da15b2010-01-01 20:29:01 +0000195
John McCall0d635f52010-09-03 01:26:39 +0000196 // Compute the object pointer.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000197 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000198 if (ME->isArrow())
199 This = EmitScalarExpr(ME->getBase());
John McCalle26a8722010-12-04 08:14:53 +0000200 else
201 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000202
John McCall0d635f52010-09-03 01:26:39 +0000203 if (MD->isTrivial()) {
204 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichet64225792011-01-18 05:04:39 +0000205 if (isa<CXXConstructorDecl>(MD) &&
206 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
207 return RValue::get(0);
John McCall0d635f52010-09-03 01:26:39 +0000208
Francois Pichet64225792011-01-18 05:04:39 +0000209 if (MD->isCopyAssignmentOperator()) {
210 // We don't like to generate the trivial copy assignment operator when
211 // it isn't necessary; just produce the proper effect here.
212 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) &&
218 cast<CXXConstructorDecl>(MD)->isCopyConstructor()) {
219 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
220 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
221 CE->arg_begin(), CE->arg_end());
222 return RValue::get(This);
223 }
224 llvm_unreachable("unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000225 }
226
John McCall0d635f52010-09-03 01:26:39 +0000227 // Compute the function type we're calling.
Francois Pichet64225792011-01-18 05:04:39 +0000228 const CGFunctionInfo *FInfo = 0;
229 if (isa<CXXDestructorDecl>(MD))
230 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
231 Dtor_Complete);
232 else if (isa<CXXConstructorDecl>(MD))
233 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXConstructorDecl>(MD),
234 Ctor_Complete);
235 else
236 FInfo = &CGM.getTypes().getFunctionInfo(MD);
John McCall0d635f52010-09-03 01:26:39 +0000237
238 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
239 const llvm::Type *Ty
Francois Pichet64225792011-01-18 05:04:39 +0000240 = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
John McCall0d635f52010-09-03 01:26:39 +0000241
Anders Carlsson27da15b2010-01-01 20:29:01 +0000242 // C++ [class.virtual]p12:
243 // Explicit qualification with the scope operator (5.1) suppresses the
244 // virtual call mechanism.
245 //
246 // We also don't emit a virtual call if the base expression has a record type
247 // because then we know what the type is.
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000248 bool UseVirtualCall;
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000249 UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
250 && !canDevirtualizeMemberFunctionCalls(getContext(),
251 ME->getBase(), MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000252 llvm::Value *Callee;
John McCall0d635f52010-09-03 01:26:39 +0000253 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
254 if (UseVirtualCall) {
255 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000256 } else {
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000257 if (getContext().getLangOptions().AppleKext &&
258 MD->isVirtual() &&
259 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000260 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000261 else
262 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000263 }
Francois Pichet64225792011-01-18 05:04:39 +0000264 } else if (const CXXConstructorDecl *Ctor =
265 dyn_cast<CXXConstructorDecl>(MD)) {
266 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000267 } else if (UseVirtualCall) {
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000268 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000269 } else {
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000270 if (getContext().getLangOptions().AppleKext &&
Fariborz Jahanian9f9438b2011-01-28 23:42:29 +0000271 MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000272 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000273 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000274 else
275 Callee = CGM.GetAddrOfFunction(MD, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000276 }
277
Anders Carlssone36a6b32010-01-02 01:01:18 +0000278 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000279 CE->arg_begin(), CE->arg_end());
280}
281
282RValue
283CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
284 ReturnValueSlot ReturnValue) {
285 const BinaryOperator *BO =
286 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
287 const Expr *BaseExpr = BO->getLHS();
288 const Expr *MemFnExpr = BO->getRHS();
289
290 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000291 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000292
Anders Carlsson27da15b2010-01-01 20:29:01 +0000293 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000294 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000295 const CXXRecordDecl *RD =
296 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
297
Anders Carlsson27da15b2010-01-01 20:29:01 +0000298 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000299 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000300
301 // Emit the 'this' pointer.
302 llvm::Value *This;
303
John McCalle3027922010-08-25 11:45:40 +0000304 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000305 This = EmitScalarExpr(BaseExpr);
306 else
307 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000308
John McCall475999d2010-08-22 00:05:51 +0000309 // Ask the ABI to load the callee. Note that This is modified.
310 llvm::Value *Callee =
John McCallad7c5c12011-02-08 08:22:06 +0000311 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000312
Anders Carlsson27da15b2010-01-01 20:29:01 +0000313 CallArgList Args;
314
315 QualType ThisType =
316 getContext().getPointerType(getContext().getTagDeclType(RD));
317
318 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000319 Args.add(RValue::get(This), ThisType);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000320
321 // And the rest of the call args
322 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall0009fcc2011-04-26 20:42:42 +0000323 return EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee,
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000324 ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000325}
326
327RValue
328CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
329 const CXXMethodDecl *MD,
330 ReturnValueSlot ReturnValue) {
331 assert(MD->isInstance() &&
332 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000333 LValue LV = EmitLValue(E->getArg(0));
334 llvm::Value *This = LV.getAddress();
335
Douglas Gregorec3bec02010-09-27 22:37:28 +0000336 if (MD->isCopyAssignmentOperator()) {
Anders Carlsson27da15b2010-01-01 20:29:01 +0000337 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
338 if (ClassDecl->hasTrivialCopyAssignment()) {
339 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
340 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000341 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
342 QualType Ty = E->getType();
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000343 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000344 return RValue::get(This);
345 }
346 }
347
Anders Carlssonc36783e2011-05-08 20:32:23 +0000348 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000349 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000350 E->arg_begin() + 1, E->arg_end());
351}
352
353void
John McCall7a626f62010-09-15 10:14:12 +0000354CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
355 AggValueSlot Dest) {
356 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000357 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000358
359 // If we require zero initialization before (or instead of) calling the
360 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000361 // constructor, emit the zero initialization now, unless destination is
362 // already zeroed.
363 if (E->requiresZeroInitialization() && !Dest.isZeroed())
John McCall7a626f62010-09-15 10:14:12 +0000364 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor630c76e2010-08-22 16:15:35 +0000365
366 // If this is a call to a trivial default constructor, do nothing.
367 if (CD->isTrivial() && CD->isDefaultConstructor())
368 return;
369
John McCall8ea46b62010-09-18 00:58:34 +0000370 // Elide the constructor if we're constructing from a temporary.
371 // The temporary check is required because Sema sets this on NRVO
372 // returns.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000373 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000374 assert(getContext().hasSameUnqualifiedType(E->getType(),
375 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000376 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
377 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000378 return;
379 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000380 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000381
382 const ConstantArrayType *Array
383 = getContext().getAsConstantArrayType(E->getType());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000384 if (Array) {
385 QualType BaseElementTy = getContext().getBaseElementType(Array);
386 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
387 BasePtr = llvm::PointerType::getUnqual(BasePtr);
388 llvm::Value *BaseAddrPtr =
John McCall7a626f62010-09-15 10:14:12 +0000389 Builder.CreateBitCast(Dest.getAddr(), BasePtr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000390
391 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
392 E->arg_begin(), E->arg_end());
393 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000394 else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000395 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000396 bool ForVirtualBase = false;
397
398 switch (E->getConstructionKind()) {
399 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000400 // We should be emitting a constructor; GlobalDecl will assert this
401 Type = CurGD.getCtorType();
Alexis Hunt271c3682011-05-03 20:19:28 +0000402 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000403
Alexis Hunt271c3682011-05-03 20:19:28 +0000404 case CXXConstructExpr::CK_Complete:
405 Type = Ctor_Complete;
406 break;
407
408 case CXXConstructExpr::CK_VirtualBase:
409 ForVirtualBase = true;
410 // fall-through
411
412 case CXXConstructExpr::CK_NonVirtualBase:
413 Type = Ctor_Base;
414 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000415
Anders Carlsson27da15b2010-01-01 20:29:01 +0000416 // Call the constructor.
John McCall7a626f62010-09-15 10:14:12 +0000417 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000418 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000419 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000420}
421
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000422void
423CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
424 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000425 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000426 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000427 Exp = E->getSubExpr();
428 assert(isa<CXXConstructExpr>(Exp) &&
429 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
430 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
431 const CXXConstructorDecl *CD = E->getConstructor();
432 RunCleanupsScope Scope(*this);
433
434 // If we require zero initialization before (or instead of) calling the
435 // constructor, as can be the case with a non-user-provided default
436 // constructor, emit the zero initialization now.
437 // FIXME. Do I still need this for a copy ctor synthesis?
438 if (E->requiresZeroInitialization())
439 EmitNullInitialization(Dest, E->getType());
440
Chandler Carruth99da11c2010-11-15 13:54:43 +0000441 assert(!getContext().getAsConstantArrayType(E->getType())
442 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000443 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
444 E->arg_begin(), E->arg_end());
445}
446
John McCallaa4149a2010-08-23 01:17:59 +0000447/// Check whether the given operator new[] is the global placement
448/// operator new[].
449static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
450 const FunctionDecl *Fn) {
451 // Must be in global scope. Note that allocation functions can't be
452 // declared in namespaces.
Sebastian Redl50c68252010-08-31 00:36:30 +0000453 if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
John McCallaa4149a2010-08-23 01:17:59 +0000454 return false;
455
456 // Signature must be void *operator new[](size_t, void*).
457 // The size_t is common to all operator new[]s.
458 if (Fn->getNumParams() != 2)
459 return false;
460
461 CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
462 return (ParamType == Ctx.VoidPtrTy);
463}
464
John McCall8ed55a52010-09-02 09:58:18 +0000465static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
466 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000467 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000468 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000469
Anders Carlsson399f4992009-12-13 20:34:34 +0000470 // No cookie is required if the new operator being used is
471 // ::operator new[](size_t, void*).
472 const FunctionDecl *OperatorNew = E->getOperatorNew();
John McCall8ed55a52010-09-02 09:58:18 +0000473 if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
John McCallaa4149a2010-08-23 01:17:59 +0000474 return CharUnits::Zero();
475
John McCall284c48f2011-01-27 09:37:56 +0000476 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000477}
478
Fariborz Jahanian47b46292010-03-24 16:57:01 +0000479static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
Chris Lattnercb46bdc2010-07-20 18:45:57 +0000480 CodeGenFunction &CGF,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000481 const CXXNewExpr *E,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000482 llvm::Value *&NumElements,
483 llvm::Value *&SizeWithoutCookie) {
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000484 QualType ElemType = E->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000485
486 const llvm::IntegerType *SizeTy =
487 cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000488
John McCall8ed55a52010-09-02 09:58:18 +0000489 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
490
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000491 if (!E->isArray()) {
492 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
493 return SizeWithoutCookie;
494 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000495
John McCall8ed55a52010-09-02 09:58:18 +0000496 // Figure out the cookie size.
497 CharUnits CookieSize = CalculateCookiePadding(CGF, E);
498
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000499 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000500 // We multiply the size of all dimensions for NumElements.
501 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000502 NumElements = CGF.EmitScalarExpr(E->getArraySize());
John McCall8ed55a52010-09-02 09:58:18 +0000503 assert(NumElements->getType() == SizeTy && "element count not a size_t");
504
505 uint64_t ArraySizeMultiplier = 1;
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000506 while (const ConstantArrayType *CAT
507 = CGF.getContext().getAsConstantArrayType(ElemType)) {
508 ElemType = CAT->getElementType();
John McCall8ed55a52010-09-02 09:58:18 +0000509 ArraySizeMultiplier *= CAT->getSize().getZExtValue();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000510 }
511
John McCall8ed55a52010-09-02 09:58:18 +0000512 llvm::Value *Size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000513
Chris Lattner32ac5832010-07-20 21:55:52 +0000514 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
515 // Don't bloat the -O0 code.
516 if (llvm::ConstantInt *NumElementsC =
517 dyn_cast<llvm::ConstantInt>(NumElements)) {
Chris Lattner32ac5832010-07-20 21:55:52 +0000518 llvm::APInt NEC = NumElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000519 unsigned SizeWidth = NEC.getBitWidth();
520
521 // Determine if there is an overflow here by doing an extended multiply.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000522 NEC = NEC.zext(SizeWidth*2);
John McCall8ed55a52010-09-02 09:58:18 +0000523 llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
Chris Lattner32ac5832010-07-20 21:55:52 +0000524 SC *= NEC;
John McCall8ed55a52010-09-02 09:58:18 +0000525
526 if (!CookieSize.isZero()) {
527 // Save the current size without a cookie. We don't care if an
528 // overflow's already happened because SizeWithoutCookie isn't
529 // used if the allocator returns null or throws, as it should
530 // always do on an overflow.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000531 llvm::APInt SWC = SC.trunc(SizeWidth);
John McCall8ed55a52010-09-02 09:58:18 +0000532 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
533
534 // Add the cookie size.
535 SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
Chris Lattner32ac5832010-07-20 21:55:52 +0000536 }
537
John McCall8ed55a52010-09-02 09:58:18 +0000538 if (SC.countLeadingZeros() >= SizeWidth) {
Jay Foad6d4db0c2010-12-07 08:25:34 +0000539 SC = SC.trunc(SizeWidth);
John McCall8ed55a52010-09-02 09:58:18 +0000540 Size = llvm::ConstantInt::get(SizeTy, SC);
541 } else {
542 // On overflow, produce a -1 so operator new throws.
543 Size = llvm::Constant::getAllOnesValue(SizeTy);
544 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000545
John McCall8ed55a52010-09-02 09:58:18 +0000546 // Scale NumElements while we're at it.
547 uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
548 NumElements = llvm::ConstantInt::get(SizeTy, N);
549
550 // Otherwise, we don't need to do an overflow-checked multiplication if
551 // we're multiplying by one.
552 } else if (TypeSize.isOne()) {
553 assert(ArraySizeMultiplier == 1);
554
555 Size = NumElements;
556
557 // If we need a cookie, add its size in with an overflow check.
558 // This is maybe a little paranoid.
559 if (!CookieSize.isZero()) {
560 SizeWithoutCookie = Size;
561
562 llvm::Value *CookieSizeV
563 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
564
565 const llvm::Type *Types[] = { SizeTy };
566 llvm::Value *UAddF
567 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
568 llvm::Value *AddRes
569 = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
570
571 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
572 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
573 Size = CGF.Builder.CreateSelect(DidOverflow,
574 llvm::ConstantInt::get(SizeTy, -1),
575 Size);
576 }
577
578 // Otherwise use the int.umul.with.overflow intrinsic.
579 } else {
580 llvm::Value *OutermostElementSize
581 = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
582
583 llvm::Value *NumOutermostElements = NumElements;
584
585 // Scale NumElements by the array size multiplier. This might
586 // overflow, but only if the multiplication below also overflows,
587 // in which case this multiplication isn't used.
588 if (ArraySizeMultiplier != 1)
589 NumElements = CGF.Builder.CreateMul(NumElements,
590 llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
591
592 // The requested size of the outermost array is non-constant.
593 // Multiply that by the static size of the elements of that array;
594 // on unsigned overflow, set the size to -1 to trigger an
595 // exception from the allocation routine. This is sufficient to
596 // prevent buffer overruns from the allocator returning a
597 // seemingly valid pointer to insufficient space. This idea comes
598 // originally from MSVC, and GCC has an open bug requesting
599 // similar behavior:
600 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
601 //
602 // This will not be sufficient for C++0x, which requires a
603 // specific exception class (std::bad_array_new_length).
604 // That will require ABI support that has not yet been specified.
605 const llvm::Type *Types[] = { SizeTy };
606 llvm::Value *UMulF
607 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
608 llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
609 OutermostElementSize);
610
611 // The overflow bit.
612 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
613
614 // The result of the multiplication.
615 Size = CGF.Builder.CreateExtractValue(MulRes, 0);
616
617 // If we have a cookie, we need to add that size in, too.
618 if (!CookieSize.isZero()) {
619 SizeWithoutCookie = Size;
620
621 llvm::Value *CookieSizeV
622 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
623 llvm::Value *UAddF
624 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
625 llvm::Value *AddRes
626 = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
627
628 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
629
630 llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
Eli Friedmandb42a3e2011-04-09 19:54:33 +0000631 DidOverflow = CGF.Builder.CreateOr(DidOverflow, AddDidOverflow);
John McCall8ed55a52010-09-02 09:58:18 +0000632 }
633
634 Size = CGF.Builder.CreateSelect(DidOverflow,
635 llvm::ConstantInt::get(SizeTy, -1),
636 Size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000637 }
John McCall8ed55a52010-09-02 09:58:18 +0000638
639 if (CookieSize.isZero())
640 SizeWithoutCookie = Size;
641 else
642 assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
643
Chris Lattner32ac5832010-07-20 21:55:52 +0000644 return Size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000645}
646
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000647static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
648 llvm::Value *NewPtr) {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000649
650 assert(E->getNumConstructorArgs() == 1 &&
651 "Can only have one argument to initializer of POD type.");
652
653 const Expr *Init = E->getConstructorArg(0);
654 QualType AllocType = E->getAllocatedType();
Daniel Dunbar03816342010-08-21 02:24:36 +0000655
656 unsigned Alignment =
657 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000658 if (!CGF.hasAggregateLLVMType(AllocType))
659 CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
Daniel Dunbar03816342010-08-21 02:24:36 +0000660 AllocType.isVolatileQualified(), Alignment,
661 AllocType);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000662 else if (AllocType->isAnyComplexType())
663 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
664 AllocType.isVolatileQualified());
John McCall7a626f62010-09-15 10:14:12 +0000665 else {
666 AggValueSlot Slot
667 = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
668 CGF.EmitAggExpr(Init, Slot);
669 }
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000670}
671
672void
673CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
674 llvm::Value *NewPtr,
675 llvm::Value *NumElements) {
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000676 // We have a POD type.
677 if (E->getNumConstructorArgs() == 0)
678 return;
679
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000680 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
681
682 // Create a temporary for the loop index and initialize it with 0.
683 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
684 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
685 Builder.CreateStore(Zero, IndexPtr);
686
687 // Start the loop with a block that tests the condition.
688 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
689 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
690
691 EmitBlock(CondBlock);
692
693 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
694
695 // Generate: if (loop-index < number-of-elements fall to the loop body,
696 // otherwise, go to the block after the for-loop.
697 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
698 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
699 // If the condition is true, execute the body.
700 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
701
702 EmitBlock(ForBody);
703
704 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
705 // Inside the loop body, emit the constructor call on the array element.
706 Counter = Builder.CreateLoad(IndexPtr);
707 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
708 "arrayidx");
709 StoreAnyExprIntoOneUnit(*this, E, Address);
710
711 EmitBlock(ContinueBlock);
712
713 // Emit the increment of the loop counter.
714 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
715 Counter = Builder.CreateLoad(IndexPtr);
716 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
717 Builder.CreateStore(NextVal, IndexPtr);
718
719 // Finally, branch back up to the condition for the next iteration.
720 EmitBranch(CondBlock);
721
722 // Emit the fall-through block.
723 EmitBlock(AfterFor, true);
724}
725
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000726static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
727 llvm::Value *NewPtr, llvm::Value *Size) {
John McCallad7c5c12011-02-08 08:22:06 +0000728 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyck705ba072011-01-19 01:58:38 +0000729 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000730 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyck705ba072011-01-19 01:58:38 +0000731 Alignment.getQuantity(), false);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000732}
733
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000734static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
735 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000736 llvm::Value *NumElements,
737 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson3a202f62009-11-24 18:43:52 +0000738 if (E->isArray()) {
Anders Carlssond040e6b2010-05-03 15:09:17 +0000739 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000740 bool RequiresZeroInitialization = false;
741 if (Ctor->getParent()->hasTrivialConstructor()) {
742 // If new expression did not specify value-initialization, then there
743 // is no initialization.
744 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
745 return;
746
John McCall614dbdc2010-08-22 21:01:12 +0000747 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000748 // Optimization: since zero initialization will just set the memory
749 // to all zeroes, generate a single memset to do it in one shot.
750 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
751 AllocSizeWithoutCookie);
752 return;
753 }
754
755 RequiresZeroInitialization = true;
756 }
757
758 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
759 E->constructor_arg_begin(),
760 E->constructor_arg_end(),
761 RequiresZeroInitialization);
Anders Carlssond040e6b2010-05-03 15:09:17 +0000762 return;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000763 } else if (E->getNumConstructorArgs() == 1 &&
764 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
765 // Optimization: since zero initialization will just set the memory
766 // to all zeroes, generate a single memset to do it in one shot.
767 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
768 AllocSizeWithoutCookie);
769 return;
770 } else {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000771 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
772 return;
773 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000774 }
Anders Carlsson3a202f62009-11-24 18:43:52 +0000775
776 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor747eb782010-07-08 06:14:04 +0000777 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
778 // direct initialization. C++ [dcl.init]p5 requires that we
779 // zero-initialize storage if there are no user-declared constructors.
780 if (E->hasInitializer() &&
781 !Ctor->getParent()->hasUserDeclaredConstructor() &&
782 !Ctor->getParent()->isEmpty())
783 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
784
Douglas Gregore1823702010-07-07 23:37:33 +0000785 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
786 NewPtr, E->constructor_arg_begin(),
787 E->constructor_arg_end());
Anders Carlsson3a202f62009-11-24 18:43:52 +0000788
789 return;
790 }
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000791 // We have a POD type.
792 if (E->getNumConstructorArgs() == 0)
793 return;
794
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000795 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000796}
797
John McCall824c2f52010-09-14 07:57:04 +0000798namespace {
799 /// A cleanup to call the given 'operator delete' function upon
800 /// abnormal exit from a new expression.
801 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
802 size_t NumPlacementArgs;
803 const FunctionDecl *OperatorDelete;
804 llvm::Value *Ptr;
805 llvm::Value *AllocSize;
806
807 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
808
809 public:
810 static size_t getExtraSize(size_t NumPlacementArgs) {
811 return NumPlacementArgs * sizeof(RValue);
812 }
813
814 CallDeleteDuringNew(size_t NumPlacementArgs,
815 const FunctionDecl *OperatorDelete,
816 llvm::Value *Ptr,
817 llvm::Value *AllocSize)
818 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
819 Ptr(Ptr), AllocSize(AllocSize) {}
820
821 void setPlacementArg(unsigned I, RValue Arg) {
822 assert(I < NumPlacementArgs && "index out of range");
823 getPlacementArgs()[I] = Arg;
824 }
825
826 void Emit(CodeGenFunction &CGF, bool IsForEH) {
827 const FunctionProtoType *FPT
828 = OperatorDelete->getType()->getAs<FunctionProtoType>();
829 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCalld441b1e2010-09-14 21:45:42 +0000830 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +0000831
832 CallArgList DeleteArgs;
833
834 // The first argument is always a void*.
835 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +0000836 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000837
838 // A member 'operator delete' can take an extra 'size_t' argument.
839 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +0000840 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000841
842 // Pass the rest of the arguments, which must match exactly.
843 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +0000844 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +0000845
846 // Call 'operator delete'.
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000847 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall824c2f52010-09-14 07:57:04 +0000848 CGF.CGM.GetAddrOfFunction(OperatorDelete),
849 ReturnValueSlot(), DeleteArgs, OperatorDelete);
850 }
851 };
John McCall7f9c92a2010-09-17 00:50:28 +0000852
853 /// A cleanup to call the given 'operator delete' function upon
854 /// abnormal exit from a new expression when the new expression is
855 /// conditional.
856 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
857 size_t NumPlacementArgs;
858 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +0000859 DominatingValue<RValue>::saved_type Ptr;
860 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +0000861
John McCallcb5f77f2011-01-28 10:53:53 +0000862 DominatingValue<RValue>::saved_type *getPlacementArgs() {
863 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +0000864 }
865
866 public:
867 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +0000868 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +0000869 }
870
871 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
872 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +0000873 DominatingValue<RValue>::saved_type Ptr,
874 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +0000875 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
876 Ptr(Ptr), AllocSize(AllocSize) {}
877
John McCallcb5f77f2011-01-28 10:53:53 +0000878 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +0000879 assert(I < NumPlacementArgs && "index out of range");
880 getPlacementArgs()[I] = Arg;
881 }
882
883 void Emit(CodeGenFunction &CGF, bool IsForEH) {
884 const FunctionProtoType *FPT
885 = OperatorDelete->getType()->getAs<FunctionProtoType>();
886 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
887 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
888
889 CallArgList DeleteArgs;
890
891 // The first argument is always a void*.
892 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +0000893 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +0000894
895 // A member 'operator delete' can take an extra 'size_t' argument.
896 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +0000897 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +0000898 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +0000899 }
900
901 // Pass the rest of the arguments, which must match exactly.
902 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +0000903 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +0000904 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +0000905 }
906
907 // Call 'operator delete'.
Tilmann Scheller99cc30c2011-03-02 21:36:49 +0000908 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall7f9c92a2010-09-17 00:50:28 +0000909 CGF.CGM.GetAddrOfFunction(OperatorDelete),
910 ReturnValueSlot(), DeleteArgs, OperatorDelete);
911 }
912 };
913}
914
915/// Enter a cleanup to call 'operator delete' if the initializer in a
916/// new-expression throws.
917static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
918 const CXXNewExpr *E,
919 llvm::Value *NewPtr,
920 llvm::Value *AllocSize,
921 const CallArgList &NewArgs) {
922 // If we're not inside a conditional branch, then the cleanup will
923 // dominate and we can do the easier (and more efficient) thing.
924 if (!CGF.isInConditionalBranch()) {
925 CallDeleteDuringNew *Cleanup = CGF.EHStack
926 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
927 E->getNumPlacementArgs(),
928 E->getOperatorDelete(),
929 NewPtr, AllocSize);
930 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +0000931 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +0000932
933 return;
934 }
935
936 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +0000937 DominatingValue<RValue>::saved_type SavedNewPtr =
938 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
939 DominatingValue<RValue>::saved_type SavedAllocSize =
940 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +0000941
942 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
943 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
944 E->getNumPlacementArgs(),
945 E->getOperatorDelete(),
946 SavedNewPtr,
947 SavedAllocSize);
948 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +0000949 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +0000950 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +0000951
952 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall824c2f52010-09-14 07:57:04 +0000953}
954
Anders Carlssoncc52f652009-09-22 22:53:17 +0000955llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +0000956 // The element type being allocated.
957 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +0000958
John McCall75f94982011-03-07 03:12:35 +0000959 // 1. Build a call to the allocation function.
960 FunctionDecl *allocator = E->getOperatorNew();
961 const FunctionProtoType *allocatorType =
962 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +0000963
John McCall75f94982011-03-07 03:12:35 +0000964 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +0000965
966 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +0000967 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +0000968
John McCall75f94982011-03-07 03:12:35 +0000969 llvm::Value *numElements = 0;
970 llvm::Value *allocSizeWithoutCookie = 0;
971 llvm::Value *allocSize =
972 EmitCXXNewAllocSize(getContext(), *this, E, numElements,
973 allocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000974
Eli Friedman43dca6a2011-05-02 17:57:46 +0000975 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +0000976
977 // Emit the rest of the arguments.
978 // FIXME: Ideally, this should just use EmitCallArgs.
John McCall75f94982011-03-07 03:12:35 +0000979 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlssoncc52f652009-09-22 22:53:17 +0000980
981 // First, use the types from the function type.
982 // We start at 1 here because the first argument (the allocation size)
983 // has already been emitted.
John McCall75f94982011-03-07 03:12:35 +0000984 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
985 ++i, ++placementArg) {
986 QualType argType = allocatorType->getArgType(i);
Anders Carlssoncc52f652009-09-22 22:53:17 +0000987
John McCall75f94982011-03-07 03:12:35 +0000988 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
989 placementArg->getType()) &&
Anders Carlssoncc52f652009-09-22 22:53:17 +0000990 "type mismatch in call argument!");
991
John McCall32ea9692011-03-11 20:59:21 +0000992 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlssoncc52f652009-09-22 22:53:17 +0000993 }
994
995 // Either we've emitted all the call args, or we have a call to a
996 // variadic function.
John McCall75f94982011-03-07 03:12:35 +0000997 assert((placementArg == E->placement_arg_end() ||
998 allocatorType->isVariadic()) &&
999 "Extra arguments to non-variadic function!");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001000
1001 // If we still have any arguments, emit them using the type of the argument.
John McCall75f94982011-03-07 03:12:35 +00001002 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1003 placementArg != placementArgsEnd; ++placementArg) {
John McCall32ea9692011-03-11 20:59:21 +00001004 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001005 }
1006
John McCall75f94982011-03-07 03:12:35 +00001007 // Emit the allocation call.
Anders Carlssoncc52f652009-09-22 22:53:17 +00001008 RValue RV =
John McCall75f94982011-03-07 03:12:35 +00001009 EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocatorType),
1010 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1011 allocatorArgs, allocator);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001012
John McCall75f94982011-03-07 03:12:35 +00001013 // Emit a null check on the allocation result if the allocation
1014 // function is allowed to return null (because it has a non-throwing
1015 // exception spec; for this part, we inline
1016 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1017 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001018 bool nullCheck = allocatorType->isNothrow(getContext()) &&
John McCall75f94982011-03-07 03:12:35 +00001019 !(allocType->isPODType() && !E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001020
John McCall75f94982011-03-07 03:12:35 +00001021 llvm::BasicBlock *nullCheckBB = 0;
1022 llvm::BasicBlock *contBB = 0;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001023
John McCall75f94982011-03-07 03:12:35 +00001024 llvm::Value *allocation = RV.getScalarVal();
1025 unsigned AS =
1026 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001027
John McCallf7dcf322011-03-07 01:52:56 +00001028 // The null-check means that the initializer is conditionally
1029 // evaluated.
1030 ConditionalEvaluation conditional(*this);
1031
John McCall75f94982011-03-07 03:12:35 +00001032 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001033 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001034
1035 nullCheckBB = Builder.GetInsertBlock();
1036 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1037 contBB = createBasicBlock("new.cont");
1038
1039 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1040 Builder.CreateCondBr(isNull, contBB, notNullBB);
1041 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001042 }
Ken Dyck3eb55cf2010-01-26 19:44:24 +00001043
John McCall75f94982011-03-07 03:12:35 +00001044 assert((allocSize == allocSizeWithoutCookie) ==
John McCall8ed55a52010-09-02 09:58:18 +00001045 CalculateCookiePadding(*this, E).isZero());
John McCall75f94982011-03-07 03:12:35 +00001046 if (allocSize != allocSizeWithoutCookie) {
John McCall8ed55a52010-09-02 09:58:18 +00001047 assert(E->isArray());
John McCall75f94982011-03-07 03:12:35 +00001048 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1049 numElements,
1050 E, allocType);
John McCall8ed55a52010-09-02 09:58:18 +00001051 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001052
John McCall824c2f52010-09-14 07:57:04 +00001053 // If there's an operator delete, enter a cleanup to call it if an
1054 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001055 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCall824c2f52010-09-14 07:57:04 +00001056 if (E->getOperatorDelete()) {
John McCall75f94982011-03-07 03:12:35 +00001057 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1058 operatorDeleteCleanup = EHStack.stable_begin();
John McCall824c2f52010-09-14 07:57:04 +00001059 }
1060
John McCall75f94982011-03-07 03:12:35 +00001061 const llvm::Type *elementPtrTy
1062 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1063 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001064
John McCall8ed55a52010-09-02 09:58:18 +00001065 if (E->isArray()) {
John McCall75f94982011-03-07 03:12:35 +00001066 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001067
1068 // NewPtr is a pointer to the base element type. If we're
1069 // allocating an array of arrays, we'll need to cast back to the
1070 // array pointer type.
John McCall75f94982011-03-07 03:12:35 +00001071 const llvm::Type *resultType = ConvertTypeForMem(E->getType());
1072 if (result->getType() != resultType)
1073 result = Builder.CreateBitCast(result, resultType);
John McCall8ed55a52010-09-02 09:58:18 +00001074 } else {
John McCall75f94982011-03-07 03:12:35 +00001075 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001076 }
John McCall824c2f52010-09-14 07:57:04 +00001077
1078 // Deactivate the 'operator delete' cleanup if we finished
1079 // initialization.
John McCall75f94982011-03-07 03:12:35 +00001080 if (operatorDeleteCleanup.isValid())
1081 DeactivateCleanupBlock(operatorDeleteCleanup);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001082
John McCall75f94982011-03-07 03:12:35 +00001083 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001084 conditional.end(*this);
1085
John McCall75f94982011-03-07 03:12:35 +00001086 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1087 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001088
Jay Foad20c0f022011-03-30 11:28:58 +00001089 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001090 PHI->addIncoming(result, notNullBB);
1091 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1092 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001093
John McCall75f94982011-03-07 03:12:35 +00001094 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001095 }
John McCall8ed55a52010-09-02 09:58:18 +00001096
John McCall75f94982011-03-07 03:12:35 +00001097 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001098}
1099
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001100void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1101 llvm::Value *Ptr,
1102 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001103 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1104
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001105 const FunctionProtoType *DeleteFTy =
1106 DeleteFD->getType()->getAs<FunctionProtoType>();
1107
1108 CallArgList DeleteArgs;
1109
Anders Carlsson21122cf2009-12-13 20:04:38 +00001110 // Check if we need to pass the size to the delete operator.
1111 llvm::Value *Size = 0;
1112 QualType SizeTy;
1113 if (DeleteFTy->getNumArgs() == 2) {
1114 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001115 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1116 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1117 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001118 }
1119
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001120 QualType ArgTy = DeleteFTy->getArgType(0);
1121 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001122 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001123
Anders Carlsson21122cf2009-12-13 20:04:38 +00001124 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001125 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001126
1127 // Emit the call to delete.
Tilmann Scheller99cc30c2011-03-02 21:36:49 +00001128 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001129 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001130 DeleteArgs, DeleteFD);
1131}
1132
John McCall8ed55a52010-09-02 09:58:18 +00001133namespace {
1134 /// Calls the given 'operator delete' on a single object.
1135 struct CallObjectDelete : EHScopeStack::Cleanup {
1136 llvm::Value *Ptr;
1137 const FunctionDecl *OperatorDelete;
1138 QualType ElementType;
1139
1140 CallObjectDelete(llvm::Value *Ptr,
1141 const FunctionDecl *OperatorDelete,
1142 QualType ElementType)
1143 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1144
1145 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1146 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1147 }
1148 };
1149}
1150
1151/// Emit the code for deleting a single object.
1152static void EmitObjectDelete(CodeGenFunction &CGF,
1153 const FunctionDecl *OperatorDelete,
1154 llvm::Value *Ptr,
1155 QualType ElementType) {
1156 // Find the destructor for the type, if applicable. If the
1157 // destructor is virtual, we'll just emit the vcall and return.
1158 const CXXDestructorDecl *Dtor = 0;
1159 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1160 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1161 if (!RD->hasTrivialDestructor()) {
1162 Dtor = RD->getDestructor();
1163
1164 if (Dtor->isVirtual()) {
1165 const llvm::Type *Ty =
John McCall0d635f52010-09-03 01:26:39 +00001166 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1167 Dtor_Complete),
John McCall8ed55a52010-09-02 09:58:18 +00001168 /*isVariadic=*/false);
1169
1170 llvm::Value *Callee
1171 = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
1172 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1173 0, 0);
1174
1175 // The dtor took care of deleting the object.
1176 return;
1177 }
1178 }
1179 }
1180
1181 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001182 // This doesn't have to a conditional cleanup because we're going
1183 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001184 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1185 Ptr, OperatorDelete, ElementType);
1186
1187 if (Dtor)
1188 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1189 /*ForVirtualBase=*/false, Ptr);
1190
1191 CGF.PopCleanupBlock();
1192}
1193
1194namespace {
1195 /// Calls the given 'operator delete' on an array of objects.
1196 struct CallArrayDelete : EHScopeStack::Cleanup {
1197 llvm::Value *Ptr;
1198 const FunctionDecl *OperatorDelete;
1199 llvm::Value *NumElements;
1200 QualType ElementType;
1201 CharUnits CookieSize;
1202
1203 CallArrayDelete(llvm::Value *Ptr,
1204 const FunctionDecl *OperatorDelete,
1205 llvm::Value *NumElements,
1206 QualType ElementType,
1207 CharUnits CookieSize)
1208 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1209 ElementType(ElementType), CookieSize(CookieSize) {}
1210
1211 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1212 const FunctionProtoType *DeleteFTy =
1213 OperatorDelete->getType()->getAs<FunctionProtoType>();
1214 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1215
1216 CallArgList Args;
1217
1218 // Pass the pointer as the first argument.
1219 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1220 llvm::Value *DeletePtr
1221 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001222 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001223
1224 // Pass the original requested size as the second argument.
1225 if (DeleteFTy->getNumArgs() == 2) {
1226 QualType size_t = DeleteFTy->getArgType(1);
1227 const llvm::IntegerType *SizeTy
1228 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1229
1230 CharUnits ElementTypeSize =
1231 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1232
1233 // The size of an element, multiplied by the number of elements.
1234 llvm::Value *Size
1235 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1236 Size = CGF.Builder.CreateMul(Size, NumElements);
1237
1238 // Plus the size of the cookie if applicable.
1239 if (!CookieSize.isZero()) {
1240 llvm::Value *CookieSizeV
1241 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1242 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1243 }
1244
Eli Friedman43dca6a2011-05-02 17:57:46 +00001245 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001246 }
1247
1248 // Emit the call to delete.
Tilmann Scheller99cc30c2011-03-02 21:36:49 +00001249 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
John McCall8ed55a52010-09-02 09:58:18 +00001250 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1251 ReturnValueSlot(), Args, OperatorDelete);
1252 }
1253 };
1254}
1255
1256/// Emit the code for deleting an array of objects.
1257static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001258 const CXXDeleteExpr *E,
John McCall8ed55a52010-09-02 09:58:18 +00001259 llvm::Value *Ptr,
1260 QualType ElementType) {
1261 llvm::Value *NumElements = 0;
1262 llvm::Value *AllocatedPtr = 0;
1263 CharUnits CookieSize;
John McCall284c48f2011-01-27 09:37:56 +00001264 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, E, ElementType,
John McCall8ed55a52010-09-02 09:58:18 +00001265 NumElements, AllocatedPtr, CookieSize);
1266
1267 assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
1268
1269 // Make sure that we call delete even if one of the dtors throws.
John McCall284c48f2011-01-27 09:37:56 +00001270 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001271 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1272 AllocatedPtr, OperatorDelete,
1273 NumElements, ElementType,
1274 CookieSize);
1275
1276 if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
1277 if (!RD->hasTrivialDestructor()) {
1278 assert(NumElements && "ReadArrayCookie didn't find element count"
1279 " for a class with destructor");
1280 CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
1281 }
1282 }
1283
1284 CGF.PopCleanupBlock();
1285}
1286
Anders Carlssoncc52f652009-09-22 22:53:17 +00001287void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +00001288
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001289 // Get at the argument before we performed the implicit conversion
1290 // to void*.
1291 const Expr *Arg = E->getArgument();
1292 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00001293 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001294 ICE->getType()->isVoidPointerType())
1295 Arg = ICE->getSubExpr();
Douglas Gregore364e7b2009-10-01 05:49:51 +00001296 else
1297 break;
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001298 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001299
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001300 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001301
1302 // Null check the pointer.
1303 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1304 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1305
Anders Carlsson98981b12011-04-11 00:30:07 +00001306 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001307
1308 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1309 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001310
John McCall8ed55a52010-09-02 09:58:18 +00001311 // We might be deleting a pointer to array. If so, GEP down to the
1312 // first non-array element.
1313 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1314 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1315 if (DeleteTy->isConstantArrayType()) {
1316 llvm::Value *Zero = Builder.getInt32(0);
1317 llvm::SmallVector<llvm::Value*,8> GEP;
1318
1319 GEP.push_back(Zero); // point at the outermost array
1320
1321 // For each layer of array type we're pointing at:
1322 while (const ConstantArrayType *Arr
1323 = getContext().getAsConstantArrayType(DeleteTy)) {
1324 // 1. Unpeel the array type.
1325 DeleteTy = Arr->getElementType();
1326
1327 // 2. GEP to the first element of the array.
1328 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001329 }
John McCall8ed55a52010-09-02 09:58:18 +00001330
1331 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001332 }
1333
Douglas Gregor04f36212010-09-02 17:38:50 +00001334 assert(ConvertTypeForMem(DeleteTy) ==
1335 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001336
1337 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001338 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001339 } else {
1340 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1341 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001342
Anders Carlssoncc52f652009-09-22 22:53:17 +00001343 EmitBlock(DeleteEnd);
1344}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001345
Anders Carlsson0c633502011-04-11 14:13:40 +00001346static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1347 // void __cxa_bad_typeid();
1348
1349 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1350 const llvm::FunctionType *FTy =
1351 llvm::FunctionType::get(VoidTy, false);
1352
1353 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1354}
1355
1356static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001357 llvm::Value *Fn = getBadTypeidFn(CGF);
1358 CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
Anders Carlsson0c633502011-04-11 14:13:40 +00001359 CGF.Builder.CreateUnreachable();
1360}
1361
Anders Carlsson940f02d2011-04-18 00:57:03 +00001362static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1363 const Expr *E,
1364 const llvm::Type *StdTypeInfoPtrTy) {
1365 // Get the vtable pointer.
1366 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1367
1368 // C++ [expr.typeid]p2:
1369 // If the glvalue expression is obtained by applying the unary * operator to
1370 // a pointer and the pointer is a null pointer value, the typeid expression
1371 // throws the std::bad_typeid exception.
1372 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1373 if (UO->getOpcode() == UO_Deref) {
1374 llvm::BasicBlock *BadTypeidBlock =
1375 CGF.createBasicBlock("typeid.bad_typeid");
1376 llvm::BasicBlock *EndBlock =
1377 CGF.createBasicBlock("typeid.end");
1378
1379 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1380 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1381
1382 CGF.EmitBlock(BadTypeidBlock);
1383 EmitBadTypeidCall(CGF);
1384 CGF.EmitBlock(EndBlock);
1385 }
1386 }
1387
1388 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1389 StdTypeInfoPtrTy->getPointerTo());
1390
1391 // Load the type info.
1392 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1393 return CGF.Builder.CreateLoad(Value);
1394}
1395
John McCalle4df6c82011-01-28 08:37:24 +00001396llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001397 const llvm::Type *StdTypeInfoPtrTy =
1398 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001399
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001400 if (E->isTypeOperand()) {
1401 llvm::Constant *TypeInfo =
1402 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson940f02d2011-04-18 00:57:03 +00001403 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001404 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001405
Anders Carlsson940f02d2011-04-18 00:57:03 +00001406 // C++ [expr.typeid]p2:
1407 // When typeid is applied to a glvalue expression whose type is a
1408 // polymorphic class type, the result refers to a std::type_info object
1409 // representing the type of the most derived object (that is, the dynamic
1410 // type) to which the glvalue refers.
1411 if (E->getExprOperand()->isGLValue()) {
1412 if (const RecordType *RT =
1413 E->getExprOperand()->getType()->getAs<RecordType>()) {
1414 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1415 if (RD->isPolymorphic())
1416 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1417 StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001418 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001419 }
Anders Carlsson940f02d2011-04-18 00:57:03 +00001420
1421 QualType OperandTy = E->getExprOperand()->getType();
1422 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1423 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001424}
Mike Stump65511702009-11-16 06:50:58 +00001425
Anders Carlsson882d7902011-04-11 00:46:40 +00001426static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1427 // void *__dynamic_cast(const void *sub,
1428 // const abi::__class_type_info *src,
1429 // const abi::__class_type_info *dst,
1430 // std::ptrdiff_t src2dst_offset);
1431
1432 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1433 const llvm::Type *PtrDiffTy =
1434 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1435
1436 const llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1437
1438 const llvm::FunctionType *FTy =
1439 llvm::FunctionType::get(Int8PtrTy, Args, false);
1440
1441 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1442}
1443
1444static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1445 // void __cxa_bad_cast();
1446
1447 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1448 const llvm::FunctionType *FTy =
1449 llvm::FunctionType::get(VoidTy, false);
1450
1451 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1452}
1453
Anders Carlssonc1c99712011-04-11 01:45:29 +00001454static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001455 llvm::Value *Fn = getBadCastFn(CGF);
1456 CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
Anders Carlssonc1c99712011-04-11 01:45:29 +00001457 CGF.Builder.CreateUnreachable();
1458}
1459
Anders Carlsson882d7902011-04-11 00:46:40 +00001460static llvm::Value *
1461EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1462 QualType SrcTy, QualType DestTy,
1463 llvm::BasicBlock *CastEnd) {
1464 const llvm::Type *PtrDiffLTy =
1465 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1466 const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1467
1468 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1469 if (PTy->getPointeeType()->isVoidType()) {
1470 // C++ [expr.dynamic.cast]p7:
1471 // If T is "pointer to cv void," then the result is a pointer to the
1472 // most derived object pointed to by v.
1473
1474 // Get the vtable pointer.
1475 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1476
1477 // Get the offset-to-top from the vtable.
1478 llvm::Value *OffsetToTop =
1479 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1480 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1481
1482 // Finally, add the offset to the pointer.
1483 Value = CGF.EmitCastToVoidPtr(Value);
1484 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1485
1486 return CGF.Builder.CreateBitCast(Value, DestLTy);
1487 }
1488 }
1489
1490 QualType SrcRecordTy;
1491 QualType DestRecordTy;
1492
1493 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1494 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1495 DestRecordTy = DestPTy->getPointeeType();
1496 } else {
1497 SrcRecordTy = SrcTy;
1498 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1499 }
1500
1501 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1502 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1503
1504 llvm::Value *SrcRTTI =
1505 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1506 llvm::Value *DestRTTI =
1507 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1508
1509 // FIXME: Actually compute a hint here.
1510 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1511
1512 // Emit the call to __dynamic_cast.
1513 Value = CGF.EmitCastToVoidPtr(Value);
1514 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1515 SrcRTTI, DestRTTI, OffsetHint);
1516 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1517
1518 /// C++ [expr.dynamic.cast]p9:
1519 /// A failed cast to reference type throws std::bad_cast
1520 if (DestTy->isReferenceType()) {
1521 llvm::BasicBlock *BadCastBlock =
1522 CGF.createBasicBlock("dynamic_cast.bad_cast");
1523
1524 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1525 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1526
1527 CGF.EmitBlock(BadCastBlock);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001528 EmitBadCastCall(CGF);
Anders Carlsson882d7902011-04-11 00:46:40 +00001529 }
1530
1531 return Value;
1532}
1533
Anders Carlssonc1c99712011-04-11 01:45:29 +00001534static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1535 QualType DestTy) {
1536 const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1537 if (DestTy->isPointerType())
1538 return llvm::Constant::getNullValue(DestLTy);
1539
1540 /// C++ [expr.dynamic.cast]p9:
1541 /// A failed cast to reference type throws std::bad_cast
1542 EmitBadCastCall(CGF);
1543
1544 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1545 return llvm::UndefValue::get(DestLTy);
1546}
1547
Anders Carlsson882d7902011-04-11 00:46:40 +00001548llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001549 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001550 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001551
Anders Carlssonc1c99712011-04-11 01:45:29 +00001552 if (DCE->isAlwaysNull())
1553 return EmitDynamicCastToNull(*this, DestTy);
1554
1555 QualType SrcTy = DCE->getSubExpr()->getType();
1556
Anders Carlsson882d7902011-04-11 00:46:40 +00001557 // C++ [expr.dynamic.cast]p4:
1558 // If the value of v is a null pointer value in the pointer case, the result
1559 // is the null pointer value of type T.
1560 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001561
Anders Carlsson882d7902011-04-11 00:46:40 +00001562 llvm::BasicBlock *CastNull = 0;
1563 llvm::BasicBlock *CastNotNull = 0;
1564 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001565
Anders Carlsson882d7902011-04-11 00:46:40 +00001566 if (ShouldNullCheckSrcValue) {
1567 CastNull = createBasicBlock("dynamic_cast.null");
1568 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1569
1570 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1571 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1572 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001573 }
1574
Anders Carlsson882d7902011-04-11 00:46:40 +00001575 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1576
1577 if (ShouldNullCheckSrcValue) {
1578 EmitBranch(CastEnd);
1579
1580 EmitBlock(CastNull);
1581 EmitBranch(CastEnd);
1582 }
1583
1584 EmitBlock(CastEnd);
1585
1586 if (ShouldNullCheckSrcValue) {
1587 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1588 PHI->addIncoming(Value, CastNotNull);
1589 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1590
1591 Value = PHI;
1592 }
1593
1594 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001595}