blob: 7933007186ee0bad34f761531e1f8d9d892605f0 [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
Francois Pichetdbee3412011-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 Carlsson3b5ad222010-01-01 20:29:01 +0000225 }
226
John McCallfc400282010-09-03 01:26:39 +0000227 // Compute the function type we're calling.
Francois Pichetdbee3412011-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 McCallfc400282010-09-03 01:26:39 +0000237
238 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
239 const llvm::Type *Ty
Francois Pichetdbee3412011-01-18 05:04:39 +0000240 = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
John McCallfc400282010-09-03 01:26:39 +0000241
Anders Carlsson3b5ad222010-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 Jahanian27262672011-01-20 17:19:02 +0000248 bool UseVirtualCall;
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000249 UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
250 && !canDevirtualizeMemberFunctionCalls(getContext(),
251 ME->getBase(), MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000252 llvm::Value *Callee;
John McCallfc400282010-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 Carlsson3b5ad222010-01-01 20:29:01 +0000256 } else {
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000257 if (getContext().getLangOptions().AppleKext &&
258 MD->isVirtual() &&
259 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000260 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000261 else
262 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000263 }
Francois Pichetdbee3412011-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 McCallfc400282010-09-03 01:26:39 +0000267 } else if (UseVirtualCall) {
Fariborz Jahanian27262672011-01-20 17:19:02 +0000268 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000269 } else {
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000270 if (getContext().getLangOptions().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000271 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000272 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000273 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000274 else
275 Callee = CGM.GetAddrOfFunction(MD, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000276 }
277
Anders Carlssonc997d422010-01-02 01:01:18 +0000278 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-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 McCall864c0412011-04-26 20:42:42 +0000291 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000292
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000293 const FunctionProtoType *FPT =
John McCall864c0412011-04-26 20:42:42 +0000294 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000295 const CXXRecordDecl *RD =
296 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
297
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000298 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000299 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000300
301 // Emit the 'this' pointer.
302 llvm::Value *This;
303
John McCall2de56d12010-08-25 11:45:40 +0000304 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000305 This = EmitScalarExpr(BaseExpr);
306 else
307 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000308
John McCall93d557b2010-08-22 00:05:51 +0000309 // Ask the ABI to load the callee. Note that This is modified.
310 llvm::Value *Callee =
John McCalld16c2cf2011-02-08 08:22:06 +0000311 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000312
Anders Carlsson3b5ad222010-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 Friedman04c9a492011-05-02 17:57:46 +0000319 Args.add(RValue::get(This), ThisType);
Anders Carlsson3b5ad222010-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 McCall864c0412011-04-26 20:42:42 +0000323 return EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000324 ReturnValue, Args);
Anders Carlsson3b5ad222010-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 McCall0e800c92010-12-04 08:14:53 +0000333 LValue LV = EmitLValue(E->getArg(0));
334 llvm::Value *This = LV.getAddress();
335
Douglas Gregor3e9438b2010-09-27 22:37:28 +0000336 if (MD->isCopyAssignmentOperator()) {
Anders Carlsson3b5ad222010-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 Carlsson3b5ad222010-01-01 20:29:01 +0000341 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
342 QualType Ty = E->getType();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000343 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000344 return RValue::get(This);
345 }
346 }
347
348 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
349 const llvm::Type *Ty =
350 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
351 FPT->isVariadic());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000352 llvm::Value *Callee;
Fariborz Jahanian27262672011-01-20 17:19:02 +0000353 if (MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000354 !canDevirtualizeMemberFunctionCalls(getContext(),
355 E->getArg(0), MD))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000356 Callee = BuildVirtualCall(MD, This, Ty);
357 else
358 Callee = CGM.GetAddrOfFunction(MD, Ty);
359
Anders Carlssonc997d422010-01-02 01:01:18 +0000360 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000361 E->arg_begin() + 1, E->arg_end());
362}
363
364void
John McCall558d2ab2010-09-15 10:14:12 +0000365CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
366 AggValueSlot Dest) {
367 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000368 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000369
370 // If we require zero initialization before (or instead of) calling the
371 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +0000372 // constructor, emit the zero initialization now, unless destination is
373 // already zeroed.
374 if (E->requiresZeroInitialization() && !Dest.isZeroed())
John McCall558d2ab2010-09-15 10:14:12 +0000375 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor759e41b2010-08-22 16:15:35 +0000376
377 // If this is a call to a trivial default constructor, do nothing.
378 if (CD->isTrivial() && CD->isDefaultConstructor())
379 return;
380
John McCallfc1e6c72010-09-18 00:58:34 +0000381 // Elide the constructor if we're constructing from a temporary.
382 // The temporary check is required because Sema sets this on NRVO
383 // returns.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000384 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000385 assert(getContext().hasSameUnqualifiedType(E->getType(),
386 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000387 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
388 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000389 return;
390 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000391 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000392
393 const ConstantArrayType *Array
394 = getContext().getAsConstantArrayType(E->getType());
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000395 if (Array) {
396 QualType BaseElementTy = getContext().getBaseElementType(Array);
397 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
398 BasePtr = llvm::PointerType::getUnqual(BasePtr);
399 llvm::Value *BaseAddrPtr =
John McCall558d2ab2010-09-15 10:14:12 +0000400 Builder.CreateBitCast(Dest.getAddr(), BasePtr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000401
402 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
403 E->arg_begin(), E->arg_end());
404 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000405 else {
Sean Hunt059ce0d2011-05-01 07:04:31 +0000406 CXXCtorType Type;
407 CXXConstructExpr::ConstructionKind K = E->getConstructionKind();
408 if (K == CXXConstructExpr::CK_Delegating) {
409 // We should be emitting a constructor; GlobalDecl will assert this
410 Type = CurGD.getCtorType();
411 } else {
412 Type = (E->getConstructionKind() == CXXConstructExpr::CK_Complete)
413 ? Ctor_Complete : Ctor_Base;
414 }
415
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000416 bool ForVirtualBase =
417 E->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
418
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000419 // Call the constructor.
John McCall558d2ab2010-09-15 10:14:12 +0000420 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000421 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000422 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000423}
424
Fariborz Jahanian34999872010-11-13 21:53:34 +0000425void
426CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
427 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000428 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000429 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000430 Exp = E->getSubExpr();
431 assert(isa<CXXConstructExpr>(Exp) &&
432 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
433 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
434 const CXXConstructorDecl *CD = E->getConstructor();
435 RunCleanupsScope Scope(*this);
436
437 // If we require zero initialization before (or instead of) calling the
438 // constructor, as can be the case with a non-user-provided default
439 // constructor, emit the zero initialization now.
440 // FIXME. Do I still need this for a copy ctor synthesis?
441 if (E->requiresZeroInitialization())
442 EmitNullInitialization(Dest, E->getType());
443
Chandler Carruth858a5462010-11-15 13:54:43 +0000444 assert(!getContext().getAsConstantArrayType(E->getType())
445 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000446 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
447 E->arg_begin(), E->arg_end());
448}
449
John McCall5172ed92010-08-23 01:17:59 +0000450/// Check whether the given operator new[] is the global placement
451/// operator new[].
452static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
453 const FunctionDecl *Fn) {
454 // Must be in global scope. Note that allocation functions can't be
455 // declared in namespaces.
Sebastian Redl7a126a42010-08-31 00:36:30 +0000456 if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
John McCall5172ed92010-08-23 01:17:59 +0000457 return false;
458
459 // Signature must be void *operator new[](size_t, void*).
460 // The size_t is common to all operator new[]s.
461 if (Fn->getNumParams() != 2)
462 return false;
463
464 CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
465 return (ParamType == Ctx.VoidPtrTy);
466}
467
John McCall1e7fe752010-09-02 09:58:18 +0000468static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
469 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000470 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000471 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000472
Anders Carlssondd937552009-12-13 20:34:34 +0000473 // No cookie is required if the new operator being used is
474 // ::operator new[](size_t, void*).
475 const FunctionDecl *OperatorNew = E->getOperatorNew();
John McCall1e7fe752010-09-02 09:58:18 +0000476 if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
John McCall5172ed92010-08-23 01:17:59 +0000477 return CharUnits::Zero();
478
John McCall6ec278d2011-01-27 09:37:56 +0000479 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000480}
481
Fariborz Jahanianceb43b62010-03-24 16:57:01 +0000482static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
Chris Lattnerdefe8b22010-07-20 18:45:57 +0000483 CodeGenFunction &CGF,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000484 const CXXNewExpr *E,
Douglas Gregor59174c02010-07-21 01:10:17 +0000485 llvm::Value *&NumElements,
486 llvm::Value *&SizeWithoutCookie) {
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000487 QualType ElemType = E->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000488
489 const llvm::IntegerType *SizeTy =
490 cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
Anders Carlssona4d4c012009-09-23 16:07:23 +0000491
John McCall1e7fe752010-09-02 09:58:18 +0000492 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
493
Douglas Gregor59174c02010-07-21 01:10:17 +0000494 if (!E->isArray()) {
495 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
496 return SizeWithoutCookie;
497 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000498
John McCall1e7fe752010-09-02 09:58:18 +0000499 // Figure out the cookie size.
500 CharUnits CookieSize = CalculateCookiePadding(CGF, E);
501
Anders Carlssona4d4c012009-09-23 16:07:23 +0000502 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000503 // We multiply the size of all dimensions for NumElements.
504 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
Anders Carlssona4d4c012009-09-23 16:07:23 +0000505 NumElements = CGF.EmitScalarExpr(E->getArraySize());
John McCall1e7fe752010-09-02 09:58:18 +0000506 assert(NumElements->getType() == SizeTy && "element count not a size_t");
507
508 uint64_t ArraySizeMultiplier = 1;
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000509 while (const ConstantArrayType *CAT
510 = CGF.getContext().getAsConstantArrayType(ElemType)) {
511 ElemType = CAT->getElementType();
John McCall1e7fe752010-09-02 09:58:18 +0000512 ArraySizeMultiplier *= CAT->getSize().getZExtValue();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000513 }
514
John McCall1e7fe752010-09-02 09:58:18 +0000515 llvm::Value *Size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000516
Chris Lattner806941e2010-07-20 21:55:52 +0000517 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
518 // Don't bloat the -O0 code.
519 if (llvm::ConstantInt *NumElementsC =
520 dyn_cast<llvm::ConstantInt>(NumElements)) {
Chris Lattner806941e2010-07-20 21:55:52 +0000521 llvm::APInt NEC = NumElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000522 unsigned SizeWidth = NEC.getBitWidth();
523
524 // Determine if there is an overflow here by doing an extended multiply.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000525 NEC = NEC.zext(SizeWidth*2);
John McCall1e7fe752010-09-02 09:58:18 +0000526 llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
Chris Lattner806941e2010-07-20 21:55:52 +0000527 SC *= NEC;
John McCall1e7fe752010-09-02 09:58:18 +0000528
529 if (!CookieSize.isZero()) {
530 // Save the current size without a cookie. We don't care if an
531 // overflow's already happened because SizeWithoutCookie isn't
532 // used if the allocator returns null or throws, as it should
533 // always do on an overflow.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000534 llvm::APInt SWC = SC.trunc(SizeWidth);
John McCall1e7fe752010-09-02 09:58:18 +0000535 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
536
537 // Add the cookie size.
538 SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
Chris Lattner806941e2010-07-20 21:55:52 +0000539 }
540
John McCall1e7fe752010-09-02 09:58:18 +0000541 if (SC.countLeadingZeros() >= SizeWidth) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000542 SC = SC.trunc(SizeWidth);
John McCall1e7fe752010-09-02 09:58:18 +0000543 Size = llvm::ConstantInt::get(SizeTy, SC);
544 } else {
545 // On overflow, produce a -1 so operator new throws.
546 Size = llvm::Constant::getAllOnesValue(SizeTy);
547 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000548
John McCall1e7fe752010-09-02 09:58:18 +0000549 // Scale NumElements while we're at it.
550 uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
551 NumElements = llvm::ConstantInt::get(SizeTy, N);
552
553 // Otherwise, we don't need to do an overflow-checked multiplication if
554 // we're multiplying by one.
555 } else if (TypeSize.isOne()) {
556 assert(ArraySizeMultiplier == 1);
557
558 Size = NumElements;
559
560 // If we need a cookie, add its size in with an overflow check.
561 // This is maybe a little paranoid.
562 if (!CookieSize.isZero()) {
563 SizeWithoutCookie = Size;
564
565 llvm::Value *CookieSizeV
566 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
567
568 const llvm::Type *Types[] = { SizeTy };
569 llvm::Value *UAddF
570 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
571 llvm::Value *AddRes
572 = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
573
574 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
575 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
576 Size = CGF.Builder.CreateSelect(DidOverflow,
577 llvm::ConstantInt::get(SizeTy, -1),
578 Size);
579 }
580
581 // Otherwise use the int.umul.with.overflow intrinsic.
582 } else {
583 llvm::Value *OutermostElementSize
584 = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
585
586 llvm::Value *NumOutermostElements = NumElements;
587
588 // Scale NumElements by the array size multiplier. This might
589 // overflow, but only if the multiplication below also overflows,
590 // in which case this multiplication isn't used.
591 if (ArraySizeMultiplier != 1)
592 NumElements = CGF.Builder.CreateMul(NumElements,
593 llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
594
595 // The requested size of the outermost array is non-constant.
596 // Multiply that by the static size of the elements of that array;
597 // on unsigned overflow, set the size to -1 to trigger an
598 // exception from the allocation routine. This is sufficient to
599 // prevent buffer overruns from the allocator returning a
600 // seemingly valid pointer to insufficient space. This idea comes
601 // originally from MSVC, and GCC has an open bug requesting
602 // similar behavior:
603 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
604 //
605 // This will not be sufficient for C++0x, which requires a
606 // specific exception class (std::bad_array_new_length).
607 // That will require ABI support that has not yet been specified.
608 const llvm::Type *Types[] = { SizeTy };
609 llvm::Value *UMulF
610 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
611 llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
612 OutermostElementSize);
613
614 // The overflow bit.
615 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
616
617 // The result of the multiplication.
618 Size = CGF.Builder.CreateExtractValue(MulRes, 0);
619
620 // If we have a cookie, we need to add that size in, too.
621 if (!CookieSize.isZero()) {
622 SizeWithoutCookie = Size;
623
624 llvm::Value *CookieSizeV
625 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
626 llvm::Value *UAddF
627 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
628 llvm::Value *AddRes
629 = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
630
631 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
632
633 llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
Eli Friedman5536daa2011-04-09 19:54:33 +0000634 DidOverflow = CGF.Builder.CreateOr(DidOverflow, AddDidOverflow);
John McCall1e7fe752010-09-02 09:58:18 +0000635 }
636
637 Size = CGF.Builder.CreateSelect(DidOverflow,
638 llvm::ConstantInt::get(SizeTy, -1),
639 Size);
Chris Lattner806941e2010-07-20 21:55:52 +0000640 }
John McCall1e7fe752010-09-02 09:58:18 +0000641
642 if (CookieSize.isZero())
643 SizeWithoutCookie = Size;
644 else
645 assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
646
Chris Lattner806941e2010-07-20 21:55:52 +0000647 return Size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000648}
649
Fariborz Jahanianef668722010-06-25 18:26:07 +0000650static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
651 llvm::Value *NewPtr) {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000652
653 assert(E->getNumConstructorArgs() == 1 &&
654 "Can only have one argument to initializer of POD type.");
655
656 const Expr *Init = E->getConstructorArg(0);
657 QualType AllocType = E->getAllocatedType();
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000658
659 unsigned Alignment =
660 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
Fariborz Jahanianef668722010-06-25 18:26:07 +0000661 if (!CGF.hasAggregateLLVMType(AllocType))
662 CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000663 AllocType.isVolatileQualified(), Alignment,
664 AllocType);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000665 else if (AllocType->isAnyComplexType())
666 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
667 AllocType.isVolatileQualified());
John McCall558d2ab2010-09-15 10:14:12 +0000668 else {
669 AggValueSlot Slot
670 = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
671 CGF.EmitAggExpr(Init, Slot);
672 }
Fariborz Jahanianef668722010-06-25 18:26:07 +0000673}
674
675void
676CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
677 llvm::Value *NewPtr,
678 llvm::Value *NumElements) {
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000679 // We have a POD type.
680 if (E->getNumConstructorArgs() == 0)
681 return;
682
Fariborz Jahanianef668722010-06-25 18:26:07 +0000683 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
684
685 // Create a temporary for the loop index and initialize it with 0.
686 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
687 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
688 Builder.CreateStore(Zero, IndexPtr);
689
690 // Start the loop with a block that tests the condition.
691 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
692 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
693
694 EmitBlock(CondBlock);
695
696 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
697
698 // Generate: if (loop-index < number-of-elements fall to the loop body,
699 // otherwise, go to the block after the for-loop.
700 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
701 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
702 // If the condition is true, execute the body.
703 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
704
705 EmitBlock(ForBody);
706
707 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
708 // Inside the loop body, emit the constructor call on the array element.
709 Counter = Builder.CreateLoad(IndexPtr);
710 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
711 "arrayidx");
712 StoreAnyExprIntoOneUnit(*this, E, Address);
713
714 EmitBlock(ContinueBlock);
715
716 // Emit the increment of the loop counter.
717 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
718 Counter = Builder.CreateLoad(IndexPtr);
719 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
720 Builder.CreateStore(NextVal, IndexPtr);
721
722 // Finally, branch back up to the condition for the next iteration.
723 EmitBranch(CondBlock);
724
725 // Emit the fall-through block.
726 EmitBlock(AfterFor, true);
727}
728
Douglas Gregor59174c02010-07-21 01:10:17 +0000729static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
730 llvm::Value *NewPtr, llvm::Value *Size) {
John McCalld16c2cf2011-02-08 08:22:06 +0000731 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyckfe710082011-01-19 01:58:38 +0000732 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000733 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000734 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000735}
736
Anders Carlssona4d4c012009-09-23 16:07:23 +0000737static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
738 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000739 llvm::Value *NumElements,
740 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000741 if (E->isArray()) {
Anders Carlssone99bdb62010-05-03 15:09:17 +0000742 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000743 bool RequiresZeroInitialization = false;
744 if (Ctor->getParent()->hasTrivialConstructor()) {
745 // If new expression did not specify value-initialization, then there
746 // is no initialization.
747 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
748 return;
749
John McCallf16aa102010-08-22 21:01:12 +0000750 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000751 // Optimization: since zero initialization will just set the memory
752 // to all zeroes, generate a single memset to do it in one shot.
753 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
754 AllocSizeWithoutCookie);
755 return;
756 }
757
758 RequiresZeroInitialization = true;
759 }
760
761 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
762 E->constructor_arg_begin(),
763 E->constructor_arg_end(),
764 RequiresZeroInitialization);
Anders Carlssone99bdb62010-05-03 15:09:17 +0000765 return;
Douglas Gregor59174c02010-07-21 01:10:17 +0000766 } else if (E->getNumConstructorArgs() == 1 &&
767 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
768 // Optimization: since zero initialization will just set the memory
769 // to all zeroes, generate a single memset to do it in one shot.
770 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
771 AllocSizeWithoutCookie);
772 return;
773 } else {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000774 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
775 return;
776 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000777 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000778
779 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregored8abf12010-07-08 06:14:04 +0000780 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
781 // direct initialization. C++ [dcl.init]p5 requires that we
782 // zero-initialize storage if there are no user-declared constructors.
783 if (E->hasInitializer() &&
784 !Ctor->getParent()->hasUserDeclaredConstructor() &&
785 !Ctor->getParent()->isEmpty())
786 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
787
Douglas Gregor84745672010-07-07 23:37:33 +0000788 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
789 NewPtr, E->constructor_arg_begin(),
790 E->constructor_arg_end());
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000791
792 return;
793 }
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000794 // We have a POD type.
795 if (E->getNumConstructorArgs() == 0)
796 return;
797
Fariborz Jahanianef668722010-06-25 18:26:07 +0000798 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000799}
800
John McCall7d8647f2010-09-14 07:57:04 +0000801namespace {
802 /// A cleanup to call the given 'operator delete' function upon
803 /// abnormal exit from a new expression.
804 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
805 size_t NumPlacementArgs;
806 const FunctionDecl *OperatorDelete;
807 llvm::Value *Ptr;
808 llvm::Value *AllocSize;
809
810 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
811
812 public:
813 static size_t getExtraSize(size_t NumPlacementArgs) {
814 return NumPlacementArgs * sizeof(RValue);
815 }
816
817 CallDeleteDuringNew(size_t NumPlacementArgs,
818 const FunctionDecl *OperatorDelete,
819 llvm::Value *Ptr,
820 llvm::Value *AllocSize)
821 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
822 Ptr(Ptr), AllocSize(AllocSize) {}
823
824 void setPlacementArg(unsigned I, RValue Arg) {
825 assert(I < NumPlacementArgs && "index out of range");
826 getPlacementArgs()[I] = Arg;
827 }
828
829 void Emit(CodeGenFunction &CGF, bool IsForEH) {
830 const FunctionProtoType *FPT
831 = OperatorDelete->getType()->getAs<FunctionProtoType>();
832 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +0000833 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +0000834
835 CallArgList DeleteArgs;
836
837 // The first argument is always a void*.
838 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +0000839 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000840
841 // A member 'operator delete' can take an extra 'size_t' argument.
842 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman04c9a492011-05-02 17:57:46 +0000843 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000844
845 // Pass the rest of the arguments, which must match exactly.
846 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman04c9a492011-05-02 17:57:46 +0000847 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000848
849 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000850 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall7d8647f2010-09-14 07:57:04 +0000851 CGF.CGM.GetAddrOfFunction(OperatorDelete),
852 ReturnValueSlot(), DeleteArgs, OperatorDelete);
853 }
854 };
John McCall3019c442010-09-17 00:50:28 +0000855
856 /// A cleanup to call the given 'operator delete' function upon
857 /// abnormal exit from a new expression when the new expression is
858 /// conditional.
859 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
860 size_t NumPlacementArgs;
861 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +0000862 DominatingValue<RValue>::saved_type Ptr;
863 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +0000864
John McCall804b8072011-01-28 10:53:53 +0000865 DominatingValue<RValue>::saved_type *getPlacementArgs() {
866 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +0000867 }
868
869 public:
870 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +0000871 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +0000872 }
873
874 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
875 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +0000876 DominatingValue<RValue>::saved_type Ptr,
877 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +0000878 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
879 Ptr(Ptr), AllocSize(AllocSize) {}
880
John McCall804b8072011-01-28 10:53:53 +0000881 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +0000882 assert(I < NumPlacementArgs && "index out of range");
883 getPlacementArgs()[I] = Arg;
884 }
885
886 void Emit(CodeGenFunction &CGF, bool IsForEH) {
887 const FunctionProtoType *FPT
888 = OperatorDelete->getType()->getAs<FunctionProtoType>();
889 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
890 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
891
892 CallArgList DeleteArgs;
893
894 // The first argument is always a void*.
895 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +0000896 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall3019c442010-09-17 00:50:28 +0000897
898 // A member 'operator delete' can take an extra 'size_t' argument.
899 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +0000900 RValue RV = AllocSize.restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +0000901 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +0000902 }
903
904 // Pass the rest of the arguments, which must match exactly.
905 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +0000906 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +0000907 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +0000908 }
909
910 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000911 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall3019c442010-09-17 00:50:28 +0000912 CGF.CGM.GetAddrOfFunction(OperatorDelete),
913 ReturnValueSlot(), DeleteArgs, OperatorDelete);
914 }
915 };
916}
917
918/// Enter a cleanup to call 'operator delete' if the initializer in a
919/// new-expression throws.
920static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
921 const CXXNewExpr *E,
922 llvm::Value *NewPtr,
923 llvm::Value *AllocSize,
924 const CallArgList &NewArgs) {
925 // If we're not inside a conditional branch, then the cleanup will
926 // dominate and we can do the easier (and more efficient) thing.
927 if (!CGF.isInConditionalBranch()) {
928 CallDeleteDuringNew *Cleanup = CGF.EHStack
929 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
930 E->getNumPlacementArgs(),
931 E->getOperatorDelete(),
932 NewPtr, AllocSize);
933 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
934 Cleanup->setPlacementArg(I, NewArgs[I+1].first);
935
936 return;
937 }
938
939 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +0000940 DominatingValue<RValue>::saved_type SavedNewPtr =
941 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
942 DominatingValue<RValue>::saved_type SavedAllocSize =
943 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +0000944
945 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
946 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
947 E->getNumPlacementArgs(),
948 E->getOperatorDelete(),
949 SavedNewPtr,
950 SavedAllocSize);
951 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +0000952 Cleanup->setPlacementArg(I,
953 DominatingValue<RValue>::save(CGF, NewArgs[I+1].first));
John McCall3019c442010-09-17 00:50:28 +0000954
955 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall7d8647f2010-09-14 07:57:04 +0000956}
957
Anders Carlsson16d81b82009-09-22 22:53:17 +0000958llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +0000959 // The element type being allocated.
960 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +0000961
John McCallc2f3e7f2011-03-07 03:12:35 +0000962 // 1. Build a call to the allocation function.
963 FunctionDecl *allocator = E->getOperatorNew();
964 const FunctionProtoType *allocatorType =
965 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000966
John McCallc2f3e7f2011-03-07 03:12:35 +0000967 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +0000968
969 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +0000970 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000971
John McCallc2f3e7f2011-03-07 03:12:35 +0000972 llvm::Value *numElements = 0;
973 llvm::Value *allocSizeWithoutCookie = 0;
974 llvm::Value *allocSize =
975 EmitCXXNewAllocSize(getContext(), *this, E, numElements,
976 allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000977
Eli Friedman04c9a492011-05-02 17:57:46 +0000978 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000979
980 // Emit the rest of the arguments.
981 // FIXME: Ideally, this should just use EmitCallArgs.
John McCallc2f3e7f2011-03-07 03:12:35 +0000982 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlsson16d81b82009-09-22 22:53:17 +0000983
984 // First, use the types from the function type.
985 // We start at 1 here because the first argument (the allocation size)
986 // has already been emitted.
John McCallc2f3e7f2011-03-07 03:12:35 +0000987 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
988 ++i, ++placementArg) {
989 QualType argType = allocatorType->getArgType(i);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000990
John McCallc2f3e7f2011-03-07 03:12:35 +0000991 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
992 placementArg->getType()) &&
Anders Carlsson16d81b82009-09-22 22:53:17 +0000993 "type mismatch in call argument!");
994
John McCall413ebdb2011-03-11 20:59:21 +0000995 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlsson16d81b82009-09-22 22:53:17 +0000996 }
997
998 // Either we've emitted all the call args, or we have a call to a
999 // variadic function.
John McCallc2f3e7f2011-03-07 03:12:35 +00001000 assert((placementArg == E->placement_arg_end() ||
1001 allocatorType->isVariadic()) &&
1002 "Extra arguments to non-variadic function!");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001003
1004 // If we still have any arguments, emit them using the type of the argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001005 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1006 placementArg != placementArgsEnd; ++placementArg) {
John McCall413ebdb2011-03-11 20:59:21 +00001007 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001008 }
1009
John McCallc2f3e7f2011-03-07 03:12:35 +00001010 // Emit the allocation call.
Anders Carlsson16d81b82009-09-22 22:53:17 +00001011 RValue RV =
John McCallc2f3e7f2011-03-07 03:12:35 +00001012 EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocatorType),
1013 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1014 allocatorArgs, allocator);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001015
John McCallc2f3e7f2011-03-07 03:12:35 +00001016 // Emit a null check on the allocation result if the allocation
1017 // function is allowed to return null (because it has a non-throwing
1018 // exception spec; for this part, we inline
1019 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1020 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001021 bool nullCheck = allocatorType->isNothrow(getContext()) &&
John McCallc2f3e7f2011-03-07 03:12:35 +00001022 !(allocType->isPODType() && !E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001023
John McCallc2f3e7f2011-03-07 03:12:35 +00001024 llvm::BasicBlock *nullCheckBB = 0;
1025 llvm::BasicBlock *contBB = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001026
John McCallc2f3e7f2011-03-07 03:12:35 +00001027 llvm::Value *allocation = RV.getScalarVal();
1028 unsigned AS =
1029 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001030
John McCalla7f633f2011-03-07 01:52:56 +00001031 // The null-check means that the initializer is conditionally
1032 // evaluated.
1033 ConditionalEvaluation conditional(*this);
1034
John McCallc2f3e7f2011-03-07 03:12:35 +00001035 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001036 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001037
1038 nullCheckBB = Builder.GetInsertBlock();
1039 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1040 contBB = createBasicBlock("new.cont");
1041
1042 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1043 Builder.CreateCondBr(isNull, contBB, notNullBB);
1044 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001045 }
Ken Dyckcaf647c2010-01-26 19:44:24 +00001046
John McCallc2f3e7f2011-03-07 03:12:35 +00001047 assert((allocSize == allocSizeWithoutCookie) ==
John McCall1e7fe752010-09-02 09:58:18 +00001048 CalculateCookiePadding(*this, E).isZero());
John McCallc2f3e7f2011-03-07 03:12:35 +00001049 if (allocSize != allocSizeWithoutCookie) {
John McCall1e7fe752010-09-02 09:58:18 +00001050 assert(E->isArray());
John McCallc2f3e7f2011-03-07 03:12:35 +00001051 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1052 numElements,
1053 E, allocType);
John McCall1e7fe752010-09-02 09:58:18 +00001054 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001055
John McCall7d8647f2010-09-14 07:57:04 +00001056 // If there's an operator delete, enter a cleanup to call it if an
1057 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001058 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCall7d8647f2010-09-14 07:57:04 +00001059 if (E->getOperatorDelete()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001060 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1061 operatorDeleteCleanup = EHStack.stable_begin();
John McCall7d8647f2010-09-14 07:57:04 +00001062 }
1063
John McCallc2f3e7f2011-03-07 03:12:35 +00001064 const llvm::Type *elementPtrTy
1065 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1066 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001067
John McCall1e7fe752010-09-02 09:58:18 +00001068 if (E->isArray()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001069 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001070
1071 // NewPtr is a pointer to the base element type. If we're
1072 // allocating an array of arrays, we'll need to cast back to the
1073 // array pointer type.
John McCallc2f3e7f2011-03-07 03:12:35 +00001074 const llvm::Type *resultType = ConvertTypeForMem(E->getType());
1075 if (result->getType() != resultType)
1076 result = Builder.CreateBitCast(result, resultType);
John McCall1e7fe752010-09-02 09:58:18 +00001077 } else {
John McCallc2f3e7f2011-03-07 03:12:35 +00001078 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001079 }
John McCall7d8647f2010-09-14 07:57:04 +00001080
1081 // Deactivate the 'operator delete' cleanup if we finished
1082 // initialization.
John McCallc2f3e7f2011-03-07 03:12:35 +00001083 if (operatorDeleteCleanup.isValid())
1084 DeactivateCleanupBlock(operatorDeleteCleanup);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001085
John McCallc2f3e7f2011-03-07 03:12:35 +00001086 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001087 conditional.end(*this);
1088
John McCallc2f3e7f2011-03-07 03:12:35 +00001089 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1090 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001091
Jay Foadbbf3bac2011-03-30 11:28:58 +00001092 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001093 PHI->addIncoming(result, notNullBB);
1094 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1095 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001096
John McCallc2f3e7f2011-03-07 03:12:35 +00001097 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001098 }
John McCall1e7fe752010-09-02 09:58:18 +00001099
John McCallc2f3e7f2011-03-07 03:12:35 +00001100 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001101}
1102
Eli Friedman5fe05982009-11-18 00:50:08 +00001103void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1104 llvm::Value *Ptr,
1105 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001106 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1107
Eli Friedman5fe05982009-11-18 00:50:08 +00001108 const FunctionProtoType *DeleteFTy =
1109 DeleteFD->getType()->getAs<FunctionProtoType>();
1110
1111 CallArgList DeleteArgs;
1112
Anders Carlsson871d0782009-12-13 20:04:38 +00001113 // Check if we need to pass the size to the delete operator.
1114 llvm::Value *Size = 0;
1115 QualType SizeTy;
1116 if (DeleteFTy->getNumArgs() == 2) {
1117 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001118 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1119 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1120 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001121 }
1122
Eli Friedman5fe05982009-11-18 00:50:08 +00001123 QualType ArgTy = DeleteFTy->getArgType(0);
1124 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001125 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001126
Anders Carlsson871d0782009-12-13 20:04:38 +00001127 if (Size)
Eli Friedman04c9a492011-05-02 17:57:46 +00001128 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001129
1130 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001131 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001132 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +00001133 DeleteArgs, DeleteFD);
1134}
1135
John McCall1e7fe752010-09-02 09:58:18 +00001136namespace {
1137 /// Calls the given 'operator delete' on a single object.
1138 struct CallObjectDelete : EHScopeStack::Cleanup {
1139 llvm::Value *Ptr;
1140 const FunctionDecl *OperatorDelete;
1141 QualType ElementType;
1142
1143 CallObjectDelete(llvm::Value *Ptr,
1144 const FunctionDecl *OperatorDelete,
1145 QualType ElementType)
1146 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1147
1148 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1149 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1150 }
1151 };
1152}
1153
1154/// Emit the code for deleting a single object.
1155static void EmitObjectDelete(CodeGenFunction &CGF,
1156 const FunctionDecl *OperatorDelete,
1157 llvm::Value *Ptr,
1158 QualType ElementType) {
1159 // Find the destructor for the type, if applicable. If the
1160 // destructor is virtual, we'll just emit the vcall and return.
1161 const CXXDestructorDecl *Dtor = 0;
1162 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1163 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1164 if (!RD->hasTrivialDestructor()) {
1165 Dtor = RD->getDestructor();
1166
1167 if (Dtor->isVirtual()) {
1168 const llvm::Type *Ty =
John McCallfc400282010-09-03 01:26:39 +00001169 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1170 Dtor_Complete),
John McCall1e7fe752010-09-02 09:58:18 +00001171 /*isVariadic=*/false);
1172
1173 llvm::Value *Callee
1174 = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
1175 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1176 0, 0);
1177
1178 // The dtor took care of deleting the object.
1179 return;
1180 }
1181 }
1182 }
1183
1184 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001185 // This doesn't have to a conditional cleanup because we're going
1186 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001187 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1188 Ptr, OperatorDelete, ElementType);
1189
1190 if (Dtor)
1191 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1192 /*ForVirtualBase=*/false, Ptr);
1193
1194 CGF.PopCleanupBlock();
1195}
1196
1197namespace {
1198 /// Calls the given 'operator delete' on an array of objects.
1199 struct CallArrayDelete : EHScopeStack::Cleanup {
1200 llvm::Value *Ptr;
1201 const FunctionDecl *OperatorDelete;
1202 llvm::Value *NumElements;
1203 QualType ElementType;
1204 CharUnits CookieSize;
1205
1206 CallArrayDelete(llvm::Value *Ptr,
1207 const FunctionDecl *OperatorDelete,
1208 llvm::Value *NumElements,
1209 QualType ElementType,
1210 CharUnits CookieSize)
1211 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1212 ElementType(ElementType), CookieSize(CookieSize) {}
1213
1214 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1215 const FunctionProtoType *DeleteFTy =
1216 OperatorDelete->getType()->getAs<FunctionProtoType>();
1217 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1218
1219 CallArgList Args;
1220
1221 // Pass the pointer as the first argument.
1222 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1223 llvm::Value *DeletePtr
1224 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001225 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall1e7fe752010-09-02 09:58:18 +00001226
1227 // Pass the original requested size as the second argument.
1228 if (DeleteFTy->getNumArgs() == 2) {
1229 QualType size_t = DeleteFTy->getArgType(1);
1230 const llvm::IntegerType *SizeTy
1231 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1232
1233 CharUnits ElementTypeSize =
1234 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1235
1236 // The size of an element, multiplied by the number of elements.
1237 llvm::Value *Size
1238 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1239 Size = CGF.Builder.CreateMul(Size, NumElements);
1240
1241 // Plus the size of the cookie if applicable.
1242 if (!CookieSize.isZero()) {
1243 llvm::Value *CookieSizeV
1244 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1245 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1246 }
1247
Eli Friedman04c9a492011-05-02 17:57:46 +00001248 Args.add(RValue::get(Size), size_t);
John McCall1e7fe752010-09-02 09:58:18 +00001249 }
1250
1251 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001252 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
John McCall1e7fe752010-09-02 09:58:18 +00001253 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1254 ReturnValueSlot(), Args, OperatorDelete);
1255 }
1256 };
1257}
1258
1259/// Emit the code for deleting an array of objects.
1260static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001261 const CXXDeleteExpr *E,
John McCall1e7fe752010-09-02 09:58:18 +00001262 llvm::Value *Ptr,
1263 QualType ElementType) {
1264 llvm::Value *NumElements = 0;
1265 llvm::Value *AllocatedPtr = 0;
1266 CharUnits CookieSize;
John McCall6ec278d2011-01-27 09:37:56 +00001267 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, E, ElementType,
John McCall1e7fe752010-09-02 09:58:18 +00001268 NumElements, AllocatedPtr, CookieSize);
1269
1270 assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
1271
1272 // Make sure that we call delete even if one of the dtors throws.
John McCall6ec278d2011-01-27 09:37:56 +00001273 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001274 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1275 AllocatedPtr, OperatorDelete,
1276 NumElements, ElementType,
1277 CookieSize);
1278
1279 if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
1280 if (!RD->hasTrivialDestructor()) {
1281 assert(NumElements && "ReadArrayCookie didn't find element count"
1282 " for a class with destructor");
1283 CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
1284 }
1285 }
1286
1287 CGF.PopCleanupBlock();
1288}
1289
Anders Carlsson16d81b82009-09-22 22:53:17 +00001290void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian72c21532009-11-13 19:27:47 +00001291
Douglas Gregor90916562009-09-29 18:16:17 +00001292 // Get at the argument before we performed the implicit conversion
1293 // to void*.
1294 const Expr *Arg = E->getArgument();
1295 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00001296 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregor90916562009-09-29 18:16:17 +00001297 ICE->getType()->isVoidPointerType())
1298 Arg = ICE->getSubExpr();
Douglas Gregord69dd782009-10-01 05:49:51 +00001299 else
1300 break;
Douglas Gregor90916562009-09-29 18:16:17 +00001301 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001302
Douglas Gregor90916562009-09-29 18:16:17 +00001303 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001304
1305 // Null check the pointer.
1306 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1307 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1308
Anders Carlssonb9241242011-04-11 00:30:07 +00001309 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001310
1311 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1312 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001313
John McCall1e7fe752010-09-02 09:58:18 +00001314 // We might be deleting a pointer to array. If so, GEP down to the
1315 // first non-array element.
1316 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1317 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1318 if (DeleteTy->isConstantArrayType()) {
1319 llvm::Value *Zero = Builder.getInt32(0);
1320 llvm::SmallVector<llvm::Value*,8> GEP;
1321
1322 GEP.push_back(Zero); // point at the outermost array
1323
1324 // For each layer of array type we're pointing at:
1325 while (const ConstantArrayType *Arr
1326 = getContext().getAsConstantArrayType(DeleteTy)) {
1327 // 1. Unpeel the array type.
1328 DeleteTy = Arr->getElementType();
1329
1330 // 2. GEP to the first element of the array.
1331 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001332 }
John McCall1e7fe752010-09-02 09:58:18 +00001333
1334 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001335 }
1336
Douglas Gregoreede61a2010-09-02 17:38:50 +00001337 assert(ConvertTypeForMem(DeleteTy) ==
1338 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001339
1340 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001341 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001342 } else {
1343 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1344 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001345
Anders Carlsson16d81b82009-09-22 22:53:17 +00001346 EmitBlock(DeleteEnd);
1347}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001348
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001349static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1350 // void __cxa_bad_typeid();
1351
1352 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1353 const llvm::FunctionType *FTy =
1354 llvm::FunctionType::get(VoidTy, false);
1355
1356 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1357}
1358
1359static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001360 llvm::Value *Fn = getBadTypeidFn(CGF);
1361 CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001362 CGF.Builder.CreateUnreachable();
1363}
1364
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001365static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1366 const Expr *E,
1367 const llvm::Type *StdTypeInfoPtrTy) {
1368 // Get the vtable pointer.
1369 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1370
1371 // C++ [expr.typeid]p2:
1372 // If the glvalue expression is obtained by applying the unary * operator to
1373 // a pointer and the pointer is a null pointer value, the typeid expression
1374 // throws the std::bad_typeid exception.
1375 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1376 if (UO->getOpcode() == UO_Deref) {
1377 llvm::BasicBlock *BadTypeidBlock =
1378 CGF.createBasicBlock("typeid.bad_typeid");
1379 llvm::BasicBlock *EndBlock =
1380 CGF.createBasicBlock("typeid.end");
1381
1382 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1383 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1384
1385 CGF.EmitBlock(BadTypeidBlock);
1386 EmitBadTypeidCall(CGF);
1387 CGF.EmitBlock(EndBlock);
1388 }
1389 }
1390
1391 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1392 StdTypeInfoPtrTy->getPointerTo());
1393
1394 // Load the type info.
1395 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1396 return CGF.Builder.CreateLoad(Value);
1397}
1398
John McCall3ad32c82011-01-28 08:37:24 +00001399llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001400 const llvm::Type *StdTypeInfoPtrTy =
1401 ConvertType(E->getType())->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001402
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001403 if (E->isTypeOperand()) {
1404 llvm::Constant *TypeInfo =
1405 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001406 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001407 }
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001408
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001409 // C++ [expr.typeid]p2:
1410 // When typeid is applied to a glvalue expression whose type is a
1411 // polymorphic class type, the result refers to a std::type_info object
1412 // representing the type of the most derived object (that is, the dynamic
1413 // type) to which the glvalue refers.
1414 if (E->getExprOperand()->isGLValue()) {
1415 if (const RecordType *RT =
1416 E->getExprOperand()->getType()->getAs<RecordType>()) {
1417 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1418 if (RD->isPolymorphic())
1419 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1420 StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001421 }
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001422 }
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001423
1424 QualType OperandTy = E->getExprOperand()->getType();
1425 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1426 StdTypeInfoPtrTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001427}
Mike Stumpc849c052009-11-16 06:50:58 +00001428
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001429static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1430 // void *__dynamic_cast(const void *sub,
1431 // const abi::__class_type_info *src,
1432 // const abi::__class_type_info *dst,
1433 // std::ptrdiff_t src2dst_offset);
1434
1435 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1436 const llvm::Type *PtrDiffTy =
1437 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1438
1439 const llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
1440
1441 const llvm::FunctionType *FTy =
1442 llvm::FunctionType::get(Int8PtrTy, Args, false);
1443
1444 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1445}
1446
1447static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1448 // void __cxa_bad_cast();
1449
1450 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1451 const llvm::FunctionType *FTy =
1452 llvm::FunctionType::get(VoidTy, false);
1453
1454 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1455}
1456
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001457static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001458 llvm::Value *Fn = getBadCastFn(CGF);
1459 CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001460 CGF.Builder.CreateUnreachable();
1461}
1462
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001463static llvm::Value *
1464EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1465 QualType SrcTy, QualType DestTy,
1466 llvm::BasicBlock *CastEnd) {
1467 const llvm::Type *PtrDiffLTy =
1468 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1469 const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1470
1471 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1472 if (PTy->getPointeeType()->isVoidType()) {
1473 // C++ [expr.dynamic.cast]p7:
1474 // If T is "pointer to cv void," then the result is a pointer to the
1475 // most derived object pointed to by v.
1476
1477 // Get the vtable pointer.
1478 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1479
1480 // Get the offset-to-top from the vtable.
1481 llvm::Value *OffsetToTop =
1482 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1483 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1484
1485 // Finally, add the offset to the pointer.
1486 Value = CGF.EmitCastToVoidPtr(Value);
1487 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1488
1489 return CGF.Builder.CreateBitCast(Value, DestLTy);
1490 }
1491 }
1492
1493 QualType SrcRecordTy;
1494 QualType DestRecordTy;
1495
1496 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1497 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1498 DestRecordTy = DestPTy->getPointeeType();
1499 } else {
1500 SrcRecordTy = SrcTy;
1501 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1502 }
1503
1504 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1505 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1506
1507 llvm::Value *SrcRTTI =
1508 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1509 llvm::Value *DestRTTI =
1510 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1511
1512 // FIXME: Actually compute a hint here.
1513 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1514
1515 // Emit the call to __dynamic_cast.
1516 Value = CGF.EmitCastToVoidPtr(Value);
1517 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1518 SrcRTTI, DestRTTI, OffsetHint);
1519 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1520
1521 /// C++ [expr.dynamic.cast]p9:
1522 /// A failed cast to reference type throws std::bad_cast
1523 if (DestTy->isReferenceType()) {
1524 llvm::BasicBlock *BadCastBlock =
1525 CGF.createBasicBlock("dynamic_cast.bad_cast");
1526
1527 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1528 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1529
1530 CGF.EmitBlock(BadCastBlock);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001531 EmitBadCastCall(CGF);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001532 }
1533
1534 return Value;
1535}
1536
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001537static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1538 QualType DestTy) {
1539 const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1540 if (DestTy->isPointerType())
1541 return llvm::Constant::getNullValue(DestLTy);
1542
1543 /// C++ [expr.dynamic.cast]p9:
1544 /// A failed cast to reference type throws std::bad_cast
1545 EmitBadCastCall(CGF);
1546
1547 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1548 return llvm::UndefValue::get(DestLTy);
1549}
1550
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001551llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001552 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001553 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001554
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001555 if (DCE->isAlwaysNull())
1556 return EmitDynamicCastToNull(*this, DestTy);
1557
1558 QualType SrcTy = DCE->getSubExpr()->getType();
1559
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001560 // C++ [expr.dynamic.cast]p4:
1561 // If the value of v is a null pointer value in the pointer case, the result
1562 // is the null pointer value of type T.
1563 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001564
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001565 llvm::BasicBlock *CastNull = 0;
1566 llvm::BasicBlock *CastNotNull = 0;
1567 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001568
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001569 if (ShouldNullCheckSrcValue) {
1570 CastNull = createBasicBlock("dynamic_cast.null");
1571 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1572
1573 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1574 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1575 EmitBlock(CastNotNull);
Mike Stumpc849c052009-11-16 06:50:58 +00001576 }
1577
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001578 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1579
1580 if (ShouldNullCheckSrcValue) {
1581 EmitBranch(CastEnd);
1582
1583 EmitBlock(CastNull);
1584 EmitBranch(CastEnd);
1585 }
1586
1587 EmitBlock(CastEnd);
1588
1589 if (ShouldNullCheckSrcValue) {
1590 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1591 PHI->addIncoming(Value, CastNotNull);
1592 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1593
1594 Value = PHI;
1595 }
1596
1597 return Value;
Mike Stumpc849c052009-11-16 06:50:58 +00001598}