blob: 07997e439115eaee7ba204b86e61714bfe08d63c [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
Anders Carlssona2447e02011-05-08 20:32:23 +0000348 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Anders Carlssonc997d422010-01-02 01:01:18 +0000349 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000350 E->arg_begin() + 1, E->arg_end());
351}
352
353void
John McCall558d2ab2010-09-15 10:14:12 +0000354CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
355 AggValueSlot Dest) {
356 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000357 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-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 Kyrtzidis657baf12011-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 McCall558d2ab2010-09-15 10:14:12 +0000364 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor759e41b2010-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 McCallfc1e6c72010-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 Carlsson3b5ad222010-01-01 20:29:01 +0000373 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000374 assert(getContext().hasSameUnqualifiedType(E->getType(),
375 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000376 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
377 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000378 return;
379 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000380 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000381
382 const ConstantArrayType *Array
383 = getContext().getAsConstantArrayType(E->getType());
Anders Carlsson3b5ad222010-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 McCall558d2ab2010-09-15 10:14:12 +0000389 Builder.CreateBitCast(Dest.getAddr(), BasePtr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000390
391 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
392 E->arg_begin(), E->arg_end());
393 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000394 else {
Cameron Esfahani6bd2f6a2011-05-06 21:28:42 +0000395 CXXCtorType Type = Ctor_Complete;
Sean Huntd49bd552011-05-03 20:19:28 +0000396 bool ForVirtualBase = false;
397
398 switch (E->getConstructionKind()) {
399 case CXXConstructExpr::CK_Delegating:
Sean Hunt059ce0d2011-05-01 07:04:31 +0000400 // We should be emitting a constructor; GlobalDecl will assert this
401 Type = CurGD.getCtorType();
Sean Huntd49bd552011-05-03 20:19:28 +0000402 break;
Sean Hunt059ce0d2011-05-01 07:04:31 +0000403
Sean Huntd49bd552011-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 Carlsson155ed4a2010-05-02 23:20:53 +0000415
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000416 // Call the constructor.
John McCall558d2ab2010-09-15 10:14:12 +0000417 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000418 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000419 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000420}
421
Fariborz Jahanian34999872010-11-13 21:53:34 +0000422void
423CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
424 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000425 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000426 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-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 Carruth858a5462010-11-15 13:54:43 +0000441 assert(!getContext().getAsConstantArrayType(E->getType())
442 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000443 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
444 E->arg_begin(), E->arg_end());
445}
446
John McCall1e7fe752010-09-02 09:58:18 +0000447static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
448 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000449 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000450 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000451
John McCallb1c98a32011-05-16 01:05:12 +0000452 // No cookie is required if the operator new[] being used is the
453 // reserved placement operator new[].
454 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCall5172ed92010-08-23 01:17:59 +0000455 return CharUnits::Zero();
456
John McCall6ec278d2011-01-27 09:37:56 +0000457 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000458}
459
John McCall7d166272011-05-15 07:14:44 +0000460static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
461 const CXXNewExpr *e,
462 llvm::Value *&numElements,
463 llvm::Value *&sizeWithoutCookie) {
464 QualType type = e->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000465
John McCall7d166272011-05-15 07:14:44 +0000466 if (!e->isArray()) {
467 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
468 sizeWithoutCookie
469 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
470 return sizeWithoutCookie;
Douglas Gregor59174c02010-07-21 01:10:17 +0000471 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000472
John McCall7d166272011-05-15 07:14:44 +0000473 // The width of size_t.
474 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
475
John McCall1e7fe752010-09-02 09:58:18 +0000476 // Figure out the cookie size.
John McCall7d166272011-05-15 07:14:44 +0000477 llvm::APInt cookieSize(sizeWidth,
478 CalculateCookiePadding(CGF, e).getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000479
Anders Carlssona4d4c012009-09-23 16:07:23 +0000480 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000481 // We multiply the size of all dimensions for NumElements.
482 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall7d166272011-05-15 07:14:44 +0000483 numElements = CGF.EmitScalarExpr(e->getArraySize());
484 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall1e7fe752010-09-02 09:58:18 +0000485
John McCall7d166272011-05-15 07:14:44 +0000486 // The number of elements can be have an arbitrary integer type;
487 // essentially, we need to multiply it by a constant factor, add a
488 // cookie size, and verify that the result is representable as a
489 // size_t. That's just a gloss, though, and it's wrong in one
490 // important way: if the count is negative, it's an error even if
491 // the cookie size would bring the total size >= 0.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000492 bool isSigned
493 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
John McCall7d166272011-05-15 07:14:44 +0000494 const llvm::IntegerType *numElementsType
495 = cast<llvm::IntegerType>(numElements->getType());
496 unsigned numElementsWidth = numElementsType->getBitWidth();
497
498 // Compute the constant factor.
499 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000500 while (const ConstantArrayType *CAT
John McCall7d166272011-05-15 07:14:44 +0000501 = CGF.getContext().getAsConstantArrayType(type)) {
502 type = CAT->getElementType();
503 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000504 }
505
John McCall7d166272011-05-15 07:14:44 +0000506 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
507 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
508 typeSizeMultiplier *= arraySizeMultiplier;
509
510 // This will be a size_t.
511 llvm::Value *size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000512
Chris Lattner806941e2010-07-20 21:55:52 +0000513 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
514 // Don't bloat the -O0 code.
John McCall7d166272011-05-15 07:14:44 +0000515 if (llvm::ConstantInt *numElementsC =
516 dyn_cast<llvm::ConstantInt>(numElements)) {
517 const llvm::APInt &count = numElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000518
John McCall7d166272011-05-15 07:14:44 +0000519 bool hasAnyOverflow = false;
John McCall1e7fe752010-09-02 09:58:18 +0000520
John McCall7d166272011-05-15 07:14:44 +0000521 // If 'count' was a negative number, it's an overflow.
522 if (isSigned && count.isNegative())
523 hasAnyOverflow = true;
John McCall1e7fe752010-09-02 09:58:18 +0000524
John McCall7d166272011-05-15 07:14:44 +0000525 // We want to do all this arithmetic in size_t. If numElements is
526 // wider than that, check whether it's already too big, and if so,
527 // overflow.
528 else if (numElementsWidth > sizeWidth &&
529 numElementsWidth - sizeWidth > count.countLeadingZeros())
530 hasAnyOverflow = true;
531
532 // Okay, compute a count at the right width.
533 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
534
535 // Scale numElements by that. This might overflow, but we don't
536 // care because it only overflows if allocationSize does, too, and
537 // if that overflows then we shouldn't use this.
538 numElements = llvm::ConstantInt::get(CGF.SizeTy,
539 adjustedCount * arraySizeMultiplier);
540
541 // Compute the size before cookie, and track whether it overflowed.
542 bool overflow;
543 llvm::APInt allocationSize
544 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
545 hasAnyOverflow |= overflow;
546
547 // Add in the cookie, and check whether it's overflowed.
548 if (cookieSize != 0) {
549 // Save the current size without a cookie. This shouldn't be
550 // used if there was overflow.
551 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
552
553 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
554 hasAnyOverflow |= overflow;
555 }
556
557 // On overflow, produce a -1 so operator new will fail.
558 if (hasAnyOverflow) {
559 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
560 } else {
561 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
562 }
563
564 // Otherwise, we might need to use the overflow intrinsics.
565 } else {
566 // There are up to four conditions we need to test for:
567 // 1) if isSigned, we need to check whether numElements is negative;
568 // 2) if numElementsWidth > sizeWidth, we need to check whether
569 // numElements is larger than something representable in size_t;
570 // 3) we need to compute
571 // sizeWithoutCookie := numElements * typeSizeMultiplier
572 // and check whether it overflows; and
573 // 4) if we need a cookie, we need to compute
574 // size := sizeWithoutCookie + cookieSize
575 // and check whether it overflows.
576
577 llvm::Value *hasOverflow = 0;
578
579 // If numElementsWidth > sizeWidth, then one way or another, we're
580 // going to have to do a comparison for (2), and this happens to
581 // take care of (1), too.
582 if (numElementsWidth > sizeWidth) {
583 llvm::APInt threshold(numElementsWidth, 1);
584 threshold <<= sizeWidth;
585
586 llvm::Value *thresholdV
587 = llvm::ConstantInt::get(numElementsType, threshold);
588
589 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
590 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
591
592 // Otherwise, if we're signed, we want to sext up to size_t.
593 } else if (isSigned) {
594 if (numElementsWidth < sizeWidth)
595 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
596
597 // If there's a non-1 type size multiplier, then we can do the
598 // signedness check at the same time as we do the multiply
599 // because a negative number times anything will cause an
600 // unsigned overflow. Otherwise, we have to do it here.
601 if (typeSizeMultiplier == 1)
602 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
603 llvm::ConstantInt::get(CGF.SizeTy, 0));
604
605 // Otherwise, zext up to size_t if necessary.
606 } else if (numElementsWidth < sizeWidth) {
607 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
608 }
609
610 assert(numElements->getType() == CGF.SizeTy);
611
612 size = numElements;
613
614 // Multiply by the type size if necessary. This multiplier
615 // includes all the factors for nested arrays.
616 //
617 // This step also causes numElements to be scaled up by the
618 // nested-array factor if necessary. Overflow on this computation
619 // can be ignored because the result shouldn't be used if
620 // allocation fails.
621 if (typeSizeMultiplier != 1) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000622 llvm::Type *intrinsicTypes[] = { CGF.SizeTy };
John McCall7d166272011-05-15 07:14:44 +0000623 llvm::Value *umul_with_overflow
624 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow,
625 intrinsicTypes, 1);
626
627 llvm::Value *tsmV =
628 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
629 llvm::Value *result =
630 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
631
632 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
633 if (hasOverflow)
634 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
635 else
636 hasOverflow = overflowed;
637
638 size = CGF.Builder.CreateExtractValue(result, 0);
639
640 // Also scale up numElements by the array size multiplier.
641 if (arraySizeMultiplier != 1) {
642 // If the base element type size is 1, then we can re-use the
643 // multiply we just did.
644 if (typeSize.isOne()) {
645 assert(arraySizeMultiplier == typeSizeMultiplier);
646 numElements = size;
647
648 // Otherwise we need a separate multiply.
649 } else {
650 llvm::Value *asmV =
651 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
652 numElements = CGF.Builder.CreateMul(numElements, asmV);
653 }
654 }
655 } else {
656 // numElements doesn't need to be scaled.
657 assert(arraySizeMultiplier == 1);
Chris Lattner806941e2010-07-20 21:55:52 +0000658 }
659
John McCall7d166272011-05-15 07:14:44 +0000660 // Add in the cookie size if necessary.
661 if (cookieSize != 0) {
662 sizeWithoutCookie = size;
663
Chris Lattner9cbe4f02011-07-09 17:41:47 +0000664 llvm::Type *intrinsicTypes[] = { CGF.SizeTy };
John McCall7d166272011-05-15 07:14:44 +0000665 llvm::Value *uadd_with_overflow
666 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow,
667 intrinsicTypes, 1);
668
669 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
670 llvm::Value *result =
671 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
672
673 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
674 if (hasOverflow)
675 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
676 else
677 hasOverflow = overflowed;
678
679 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall1e7fe752010-09-02 09:58:18 +0000680 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000681
John McCall7d166272011-05-15 07:14:44 +0000682 // If we had any possibility of dynamic overflow, make a select to
683 // overwrite 'size' with an all-ones value, which should cause
684 // operator new to throw.
685 if (hasOverflow)
686 size = CGF.Builder.CreateSelect(hasOverflow,
687 llvm::Constant::getAllOnesValue(CGF.SizeTy),
688 size);
Chris Lattner806941e2010-07-20 21:55:52 +0000689 }
John McCall1e7fe752010-09-02 09:58:18 +0000690
John McCall7d166272011-05-15 07:14:44 +0000691 if (cookieSize == 0)
692 sizeWithoutCookie = size;
John McCall1e7fe752010-09-02 09:58:18 +0000693 else
John McCall7d166272011-05-15 07:14:44 +0000694 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall1e7fe752010-09-02 09:58:18 +0000695
John McCall7d166272011-05-15 07:14:44 +0000696 return size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000697}
698
Fariborz Jahanianef668722010-06-25 18:26:07 +0000699static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
700 llvm::Value *NewPtr) {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000701
702 assert(E->getNumConstructorArgs() == 1 &&
703 "Can only have one argument to initializer of POD type.");
704
705 const Expr *Init = E->getConstructorArg(0);
706 QualType AllocType = E->getAllocatedType();
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000707
708 unsigned Alignment =
709 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
John McCalla07398e2011-06-16 04:16:24 +0000710 if (!CGF.hasAggregateLLVMType(AllocType))
711 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType, Alignment),
712 false);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000713 else if (AllocType->isAnyComplexType())
714 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
715 AllocType.isVolatileQualified());
John McCall558d2ab2010-09-15 10:14:12 +0000716 else {
717 AggValueSlot Slot
John McCallf85e1932011-06-15 23:02:42 +0000718 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(), true);
John McCall558d2ab2010-09-15 10:14:12 +0000719 CGF.EmitAggExpr(Init, Slot);
720 }
Fariborz Jahanianef668722010-06-25 18:26:07 +0000721}
722
723void
724CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
725 llvm::Value *NewPtr,
726 llvm::Value *NumElements) {
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000727 // We have a POD type.
728 if (E->getNumConstructorArgs() == 0)
729 return;
730
Fariborz Jahanianef668722010-06-25 18:26:07 +0000731 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
732
733 // Create a temporary for the loop index and initialize it with 0.
734 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
735 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
736 Builder.CreateStore(Zero, IndexPtr);
737
738 // Start the loop with a block that tests the condition.
739 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
740 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
741
742 EmitBlock(CondBlock);
743
744 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
745
746 // Generate: if (loop-index < number-of-elements fall to the loop body,
747 // otherwise, go to the block after the for-loop.
748 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
749 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
750 // If the condition is true, execute the body.
751 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
752
753 EmitBlock(ForBody);
754
755 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
756 // Inside the loop body, emit the constructor call on the array element.
757 Counter = Builder.CreateLoad(IndexPtr);
758 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
759 "arrayidx");
760 StoreAnyExprIntoOneUnit(*this, E, Address);
761
762 EmitBlock(ContinueBlock);
763
764 // Emit the increment of the loop counter.
765 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
766 Counter = Builder.CreateLoad(IndexPtr);
767 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
768 Builder.CreateStore(NextVal, IndexPtr);
769
770 // Finally, branch back up to the condition for the next iteration.
771 EmitBranch(CondBlock);
772
773 // Emit the fall-through block.
774 EmitBlock(AfterFor, true);
775}
776
Douglas Gregor59174c02010-07-21 01:10:17 +0000777static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
778 llvm::Value *NewPtr, llvm::Value *Size) {
John McCalld16c2cf2011-02-08 08:22:06 +0000779 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyckfe710082011-01-19 01:58:38 +0000780 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000781 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000782 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000783}
784
Anders Carlssona4d4c012009-09-23 16:07:23 +0000785static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
786 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000787 llvm::Value *NumElements,
788 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000789 if (E->isArray()) {
Anders Carlssone99bdb62010-05-03 15:09:17 +0000790 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000791 bool RequiresZeroInitialization = false;
Sean Hunt023df372011-05-09 18:22:59 +0000792 if (Ctor->getParent()->hasTrivialDefaultConstructor()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000793 // If new expression did not specify value-initialization, then there
794 // is no initialization.
795 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
796 return;
797
John McCallf16aa102010-08-22 21:01:12 +0000798 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000799 // Optimization: since zero initialization will just set the memory
800 // to all zeroes, generate a single memset to do it in one shot.
801 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
802 AllocSizeWithoutCookie);
803 return;
804 }
805
806 RequiresZeroInitialization = true;
807 }
808
809 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
810 E->constructor_arg_begin(),
811 E->constructor_arg_end(),
812 RequiresZeroInitialization);
Anders Carlssone99bdb62010-05-03 15:09:17 +0000813 return;
Douglas Gregor59174c02010-07-21 01:10:17 +0000814 } else if (E->getNumConstructorArgs() == 1 &&
815 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
816 // Optimization: since zero initialization will just set the memory
817 // to all zeroes, generate a single memset to do it in one shot.
818 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
819 AllocSizeWithoutCookie);
820 return;
821 } else {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000822 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
823 return;
824 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000825 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000826
827 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregored8abf12010-07-08 06:14:04 +0000828 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
829 // direct initialization. C++ [dcl.init]p5 requires that we
830 // zero-initialize storage if there are no user-declared constructors.
831 if (E->hasInitializer() &&
832 !Ctor->getParent()->hasUserDeclaredConstructor() &&
833 !Ctor->getParent()->isEmpty())
834 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
835
Douglas Gregor84745672010-07-07 23:37:33 +0000836 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
837 NewPtr, E->constructor_arg_begin(),
838 E->constructor_arg_end());
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000839
840 return;
841 }
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000842 // We have a POD type.
843 if (E->getNumConstructorArgs() == 0)
844 return;
845
Fariborz Jahanianef668722010-06-25 18:26:07 +0000846 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000847}
848
John McCall7d8647f2010-09-14 07:57:04 +0000849namespace {
850 /// A cleanup to call the given 'operator delete' function upon
851 /// abnormal exit from a new expression.
852 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
853 size_t NumPlacementArgs;
854 const FunctionDecl *OperatorDelete;
855 llvm::Value *Ptr;
856 llvm::Value *AllocSize;
857
858 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
859
860 public:
861 static size_t getExtraSize(size_t NumPlacementArgs) {
862 return NumPlacementArgs * sizeof(RValue);
863 }
864
865 CallDeleteDuringNew(size_t NumPlacementArgs,
866 const FunctionDecl *OperatorDelete,
867 llvm::Value *Ptr,
868 llvm::Value *AllocSize)
869 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
870 Ptr(Ptr), AllocSize(AllocSize) {}
871
872 void setPlacementArg(unsigned I, RValue Arg) {
873 assert(I < NumPlacementArgs && "index out of range");
874 getPlacementArgs()[I] = Arg;
875 }
876
John McCallad346f42011-07-12 20:27:29 +0000877 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7d8647f2010-09-14 07:57:04 +0000878 const FunctionProtoType *FPT
879 = OperatorDelete->getType()->getAs<FunctionProtoType>();
880 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +0000881 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +0000882
883 CallArgList DeleteArgs;
884
885 // The first argument is always a void*.
886 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +0000887 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000888
889 // A member 'operator delete' can take an extra 'size_t' argument.
890 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman04c9a492011-05-02 17:57:46 +0000891 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000892
893 // Pass the rest of the arguments, which must match exactly.
894 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman04c9a492011-05-02 17:57:46 +0000895 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000896
897 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000898 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall7d8647f2010-09-14 07:57:04 +0000899 CGF.CGM.GetAddrOfFunction(OperatorDelete),
900 ReturnValueSlot(), DeleteArgs, OperatorDelete);
901 }
902 };
John McCall3019c442010-09-17 00:50:28 +0000903
904 /// A cleanup to call the given 'operator delete' function upon
905 /// abnormal exit from a new expression when the new expression is
906 /// conditional.
907 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
908 size_t NumPlacementArgs;
909 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +0000910 DominatingValue<RValue>::saved_type Ptr;
911 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +0000912
John McCall804b8072011-01-28 10:53:53 +0000913 DominatingValue<RValue>::saved_type *getPlacementArgs() {
914 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +0000915 }
916
917 public:
918 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +0000919 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +0000920 }
921
922 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
923 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +0000924 DominatingValue<RValue>::saved_type Ptr,
925 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +0000926 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
927 Ptr(Ptr), AllocSize(AllocSize) {}
928
John McCall804b8072011-01-28 10:53:53 +0000929 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +0000930 assert(I < NumPlacementArgs && "index out of range");
931 getPlacementArgs()[I] = Arg;
932 }
933
John McCallad346f42011-07-12 20:27:29 +0000934 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall3019c442010-09-17 00:50:28 +0000935 const FunctionProtoType *FPT
936 = OperatorDelete->getType()->getAs<FunctionProtoType>();
937 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
938 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
939
940 CallArgList DeleteArgs;
941
942 // The first argument is always a void*.
943 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +0000944 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall3019c442010-09-17 00:50:28 +0000945
946 // A member 'operator delete' can take an extra 'size_t' argument.
947 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +0000948 RValue RV = AllocSize.restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +0000949 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +0000950 }
951
952 // Pass the rest of the arguments, which must match exactly.
953 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +0000954 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +0000955 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +0000956 }
957
958 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000959 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall3019c442010-09-17 00:50:28 +0000960 CGF.CGM.GetAddrOfFunction(OperatorDelete),
961 ReturnValueSlot(), DeleteArgs, OperatorDelete);
962 }
963 };
964}
965
966/// Enter a cleanup to call 'operator delete' if the initializer in a
967/// new-expression throws.
968static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
969 const CXXNewExpr *E,
970 llvm::Value *NewPtr,
971 llvm::Value *AllocSize,
972 const CallArgList &NewArgs) {
973 // If we're not inside a conditional branch, then the cleanup will
974 // dominate and we can do the easier (and more efficient) thing.
975 if (!CGF.isInConditionalBranch()) {
976 CallDeleteDuringNew *Cleanup = CGF.EHStack
977 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
978 E->getNumPlacementArgs(),
979 E->getOperatorDelete(),
980 NewPtr, AllocSize);
981 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanc6d07822011-05-02 18:05:27 +0000982 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall3019c442010-09-17 00:50:28 +0000983
984 return;
985 }
986
987 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +0000988 DominatingValue<RValue>::saved_type SavedNewPtr =
989 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
990 DominatingValue<RValue>::saved_type SavedAllocSize =
991 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +0000992
993 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
994 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
995 E->getNumPlacementArgs(),
996 E->getOperatorDelete(),
997 SavedNewPtr,
998 SavedAllocSize);
999 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +00001000 Cleanup->setPlacementArg(I,
Eli Friedmanc6d07822011-05-02 18:05:27 +00001001 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall3019c442010-09-17 00:50:28 +00001002
1003 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall7d8647f2010-09-14 07:57:04 +00001004}
1005
Anders Carlsson16d81b82009-09-22 22:53:17 +00001006llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001007 // The element type being allocated.
1008 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +00001009
John McCallc2f3e7f2011-03-07 03:12:35 +00001010 // 1. Build a call to the allocation function.
1011 FunctionDecl *allocator = E->getOperatorNew();
1012 const FunctionProtoType *allocatorType =
1013 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001014
John McCallc2f3e7f2011-03-07 03:12:35 +00001015 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001016
1017 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001018 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001019
John McCallc2f3e7f2011-03-07 03:12:35 +00001020 llvm::Value *numElements = 0;
1021 llvm::Value *allocSizeWithoutCookie = 0;
1022 llvm::Value *allocSize =
John McCall7d166272011-05-15 07:14:44 +00001023 EmitCXXNewAllocSize(*this, E, numElements, allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +00001024
Eli Friedman04c9a492011-05-02 17:57:46 +00001025 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001026
1027 // Emit the rest of the arguments.
1028 // FIXME: Ideally, this should just use EmitCallArgs.
John McCallc2f3e7f2011-03-07 03:12:35 +00001029 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001030
1031 // First, use the types from the function type.
1032 // We start at 1 here because the first argument (the allocation size)
1033 // has already been emitted.
John McCallc2f3e7f2011-03-07 03:12:35 +00001034 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1035 ++i, ++placementArg) {
1036 QualType argType = allocatorType->getArgType(i);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001037
John McCallc2f3e7f2011-03-07 03:12:35 +00001038 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1039 placementArg->getType()) &&
Anders Carlsson16d81b82009-09-22 22:53:17 +00001040 "type mismatch in call argument!");
1041
John McCall413ebdb2011-03-11 20:59:21 +00001042 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001043 }
1044
1045 // Either we've emitted all the call args, or we have a call to a
1046 // variadic function.
John McCallc2f3e7f2011-03-07 03:12:35 +00001047 assert((placementArg == E->placement_arg_end() ||
1048 allocatorType->isVariadic()) &&
1049 "Extra arguments to non-variadic function!");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001050
1051 // If we still have any arguments, emit them using the type of the argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001052 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1053 placementArg != placementArgsEnd; ++placementArg) {
John McCall413ebdb2011-03-11 20:59:21 +00001054 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001055 }
1056
John McCallb1c98a32011-05-16 01:05:12 +00001057 // Emit the allocation call. If the allocator is a global placement
1058 // operator, just "inline" it directly.
1059 RValue RV;
1060 if (allocator->isReservedGlobalPlacementOperator()) {
1061 assert(allocatorArgs.size() == 2);
1062 RV = allocatorArgs[1].RV;
1063 // TODO: kill any unnecessary computations done for the size
1064 // argument.
1065 } else {
1066 RV = EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocatorType),
1067 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1068 allocatorArgs, allocator);
1069 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001070
John McCallc2f3e7f2011-03-07 03:12:35 +00001071 // Emit a null check on the allocation result if the allocation
1072 // function is allowed to return null (because it has a non-throwing
1073 // exception spec; for this part, we inline
1074 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1075 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001076 bool nullCheck = allocatorType->isNothrow(getContext()) &&
John McCallf85e1932011-06-15 23:02:42 +00001077 !(allocType.isPODType(getContext()) && !E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001078
John McCallc2f3e7f2011-03-07 03:12:35 +00001079 llvm::BasicBlock *nullCheckBB = 0;
1080 llvm::BasicBlock *contBB = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001081
John McCallc2f3e7f2011-03-07 03:12:35 +00001082 llvm::Value *allocation = RV.getScalarVal();
1083 unsigned AS =
1084 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001085
John McCalla7f633f2011-03-07 01:52:56 +00001086 // The null-check means that the initializer is conditionally
1087 // evaluated.
1088 ConditionalEvaluation conditional(*this);
1089
John McCallc2f3e7f2011-03-07 03:12:35 +00001090 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001091 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001092
1093 nullCheckBB = Builder.GetInsertBlock();
1094 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1095 contBB = createBasicBlock("new.cont");
1096
1097 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1098 Builder.CreateCondBr(isNull, contBB, notNullBB);
1099 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001100 }
Ken Dyckcaf647c2010-01-26 19:44:24 +00001101
John McCallc2f3e7f2011-03-07 03:12:35 +00001102 assert((allocSize == allocSizeWithoutCookie) ==
John McCall1e7fe752010-09-02 09:58:18 +00001103 CalculateCookiePadding(*this, E).isZero());
John McCallc2f3e7f2011-03-07 03:12:35 +00001104 if (allocSize != allocSizeWithoutCookie) {
John McCall1e7fe752010-09-02 09:58:18 +00001105 assert(E->isArray());
John McCallc2f3e7f2011-03-07 03:12:35 +00001106 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1107 numElements,
1108 E, allocType);
John McCall1e7fe752010-09-02 09:58:18 +00001109 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001110
John McCall7d8647f2010-09-14 07:57:04 +00001111 // If there's an operator delete, enter a cleanup to call it if an
1112 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001113 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCallb1c98a32011-05-16 01:05:12 +00001114 if (E->getOperatorDelete() &&
1115 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001116 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1117 operatorDeleteCleanup = EHStack.stable_begin();
John McCall7d8647f2010-09-14 07:57:04 +00001118 }
1119
John McCallc2f3e7f2011-03-07 03:12:35 +00001120 const llvm::Type *elementPtrTy
1121 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1122 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001123
John McCall1e7fe752010-09-02 09:58:18 +00001124 if (E->isArray()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001125 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001126
1127 // NewPtr is a pointer to the base element type. If we're
1128 // allocating an array of arrays, we'll need to cast back to the
1129 // array pointer type.
John McCallc2f3e7f2011-03-07 03:12:35 +00001130 const llvm::Type *resultType = ConvertTypeForMem(E->getType());
1131 if (result->getType() != resultType)
1132 result = Builder.CreateBitCast(result, resultType);
John McCall1e7fe752010-09-02 09:58:18 +00001133 } else {
John McCallc2f3e7f2011-03-07 03:12:35 +00001134 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001135 }
John McCall7d8647f2010-09-14 07:57:04 +00001136
1137 // Deactivate the 'operator delete' cleanup if we finished
1138 // initialization.
John McCallc2f3e7f2011-03-07 03:12:35 +00001139 if (operatorDeleteCleanup.isValid())
1140 DeactivateCleanupBlock(operatorDeleteCleanup);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001141
John McCallc2f3e7f2011-03-07 03:12:35 +00001142 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001143 conditional.end(*this);
1144
John McCallc2f3e7f2011-03-07 03:12:35 +00001145 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1146 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001147
Jay Foadbbf3bac2011-03-30 11:28:58 +00001148 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001149 PHI->addIncoming(result, notNullBB);
1150 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1151 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001152
John McCallc2f3e7f2011-03-07 03:12:35 +00001153 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001154 }
John McCall1e7fe752010-09-02 09:58:18 +00001155
John McCallc2f3e7f2011-03-07 03:12:35 +00001156 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001157}
1158
Eli Friedman5fe05982009-11-18 00:50:08 +00001159void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1160 llvm::Value *Ptr,
1161 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001162 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1163
Eli Friedman5fe05982009-11-18 00:50:08 +00001164 const FunctionProtoType *DeleteFTy =
1165 DeleteFD->getType()->getAs<FunctionProtoType>();
1166
1167 CallArgList DeleteArgs;
1168
Anders Carlsson871d0782009-12-13 20:04:38 +00001169 // Check if we need to pass the size to the delete operator.
1170 llvm::Value *Size = 0;
1171 QualType SizeTy;
1172 if (DeleteFTy->getNumArgs() == 2) {
1173 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001174 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1175 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1176 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001177 }
1178
Eli Friedman5fe05982009-11-18 00:50:08 +00001179 QualType ArgTy = DeleteFTy->getArgType(0);
1180 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001181 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001182
Anders Carlsson871d0782009-12-13 20:04:38 +00001183 if (Size)
Eli Friedman04c9a492011-05-02 17:57:46 +00001184 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001185
1186 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001187 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001188 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +00001189 DeleteArgs, DeleteFD);
1190}
1191
John McCall1e7fe752010-09-02 09:58:18 +00001192namespace {
1193 /// Calls the given 'operator delete' on a single object.
1194 struct CallObjectDelete : EHScopeStack::Cleanup {
1195 llvm::Value *Ptr;
1196 const FunctionDecl *OperatorDelete;
1197 QualType ElementType;
1198
1199 CallObjectDelete(llvm::Value *Ptr,
1200 const FunctionDecl *OperatorDelete,
1201 QualType ElementType)
1202 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1203
John McCallad346f42011-07-12 20:27:29 +00001204 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001205 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1206 }
1207 };
1208}
1209
1210/// Emit the code for deleting a single object.
1211static void EmitObjectDelete(CodeGenFunction &CGF,
1212 const FunctionDecl *OperatorDelete,
1213 llvm::Value *Ptr,
Douglas Gregora8b20f72011-07-13 00:54:47 +00001214 QualType ElementType,
1215 bool UseGlobalDelete) {
John McCall1e7fe752010-09-02 09:58:18 +00001216 // Find the destructor for the type, if applicable. If the
1217 // destructor is virtual, we'll just emit the vcall and return.
1218 const CXXDestructorDecl *Dtor = 0;
1219 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1220 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1221 if (!RD->hasTrivialDestructor()) {
1222 Dtor = RD->getDestructor();
1223
1224 if (Dtor->isVirtual()) {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001225 if (UseGlobalDelete) {
1226 // If we're supposed to call the global delete, make sure we do so
1227 // even if the destructor throws.
1228 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1229 Ptr, OperatorDelete,
1230 ElementType);
1231 }
1232
John McCall1e7fe752010-09-02 09:58:18 +00001233 const llvm::Type *Ty =
John McCallfc400282010-09-03 01:26:39 +00001234 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1235 Dtor_Complete),
John McCall1e7fe752010-09-02 09:58:18 +00001236 /*isVariadic=*/false);
1237
1238 llvm::Value *Callee
Douglas Gregora8b20f72011-07-13 00:54:47 +00001239 = CGF.BuildVirtualCall(Dtor,
1240 UseGlobalDelete? Dtor_Complete : Dtor_Deleting,
1241 Ptr, Ty);
John McCall1e7fe752010-09-02 09:58:18 +00001242 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1243 0, 0);
1244
Douglas Gregora8b20f72011-07-13 00:54:47 +00001245 if (UseGlobalDelete) {
1246 CGF.PopCleanupBlock();
1247 }
1248
John McCall1e7fe752010-09-02 09:58:18 +00001249 return;
1250 }
1251 }
1252 }
1253
1254 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001255 // This doesn't have to a conditional cleanup because we're going
1256 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001257 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1258 Ptr, OperatorDelete, ElementType);
1259
1260 if (Dtor)
1261 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1262 /*ForVirtualBase=*/false, Ptr);
John McCallf85e1932011-06-15 23:02:42 +00001263 else if (CGF.getLangOptions().ObjCAutoRefCount &&
1264 ElementType->isObjCLifetimeType()) {
1265 switch (ElementType.getObjCLifetime()) {
1266 case Qualifiers::OCL_None:
1267 case Qualifiers::OCL_ExplicitNone:
1268 case Qualifiers::OCL_Autoreleasing:
1269 break;
John McCall1e7fe752010-09-02 09:58:18 +00001270
John McCallf85e1932011-06-15 23:02:42 +00001271 case Qualifiers::OCL_Strong: {
1272 // Load the pointer value.
1273 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1274 ElementType.isVolatileQualified());
1275
1276 CGF.EmitARCRelease(PtrValue, /*precise*/ true);
1277 break;
1278 }
1279
1280 case Qualifiers::OCL_Weak:
1281 CGF.EmitARCDestroyWeak(Ptr);
1282 break;
1283 }
1284 }
1285
John McCall1e7fe752010-09-02 09:58:18 +00001286 CGF.PopCleanupBlock();
1287}
1288
1289namespace {
1290 /// Calls the given 'operator delete' on an array of objects.
1291 struct CallArrayDelete : EHScopeStack::Cleanup {
1292 llvm::Value *Ptr;
1293 const FunctionDecl *OperatorDelete;
1294 llvm::Value *NumElements;
1295 QualType ElementType;
1296 CharUnits CookieSize;
1297
1298 CallArrayDelete(llvm::Value *Ptr,
1299 const FunctionDecl *OperatorDelete,
1300 llvm::Value *NumElements,
1301 QualType ElementType,
1302 CharUnits CookieSize)
1303 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1304 ElementType(ElementType), CookieSize(CookieSize) {}
1305
John McCallad346f42011-07-12 20:27:29 +00001306 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001307 const FunctionProtoType *DeleteFTy =
1308 OperatorDelete->getType()->getAs<FunctionProtoType>();
1309 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1310
1311 CallArgList Args;
1312
1313 // Pass the pointer as the first argument.
1314 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1315 llvm::Value *DeletePtr
1316 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001317 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall1e7fe752010-09-02 09:58:18 +00001318
1319 // Pass the original requested size as the second argument.
1320 if (DeleteFTy->getNumArgs() == 2) {
1321 QualType size_t = DeleteFTy->getArgType(1);
1322 const llvm::IntegerType *SizeTy
1323 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1324
1325 CharUnits ElementTypeSize =
1326 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1327
1328 // The size of an element, multiplied by the number of elements.
1329 llvm::Value *Size
1330 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1331 Size = CGF.Builder.CreateMul(Size, NumElements);
1332
1333 // Plus the size of the cookie if applicable.
1334 if (!CookieSize.isZero()) {
1335 llvm::Value *CookieSizeV
1336 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1337 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1338 }
1339
Eli Friedman04c9a492011-05-02 17:57:46 +00001340 Args.add(RValue::get(Size), size_t);
John McCall1e7fe752010-09-02 09:58:18 +00001341 }
1342
1343 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001344 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
John McCall1e7fe752010-09-02 09:58:18 +00001345 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1346 ReturnValueSlot(), Args, OperatorDelete);
1347 }
1348 };
1349}
1350
1351/// Emit the code for deleting an array of objects.
1352static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001353 const CXXDeleteExpr *E,
John McCall7cfd76c2011-07-13 01:41:37 +00001354 llvm::Value *deletedPtr,
1355 QualType elementType) {
1356 llvm::Value *numElements = 0;
1357 llvm::Value *allocatedPtr = 0;
1358 CharUnits cookieSize;
1359 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1360 numElements, allocatedPtr, cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001361
John McCall7cfd76c2011-07-13 01:41:37 +00001362 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall1e7fe752010-09-02 09:58:18 +00001363
1364 // Make sure that we call delete even if one of the dtors throws.
John McCall7cfd76c2011-07-13 01:41:37 +00001365 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001366 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCall7cfd76c2011-07-13 01:41:37 +00001367 allocatedPtr, operatorDelete,
1368 numElements, elementType,
1369 cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001370
John McCall7cfd76c2011-07-13 01:41:37 +00001371 // Destroy the elements.
1372 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1373 assert(numElements && "no element count for a type with a destructor!");
1374
1375 // It's legal to allocate a zero-length array, but emitArrayDestroy
1376 // won't handle that correctly, so we need to check that here.
1377 llvm::Value *iszero =
1378 CGF.Builder.CreateIsNull(numElements, "delete.isempty");
1379
1380 // We'll patch the 'true' successor of this to lead to the end of
1381 // the emitArrayDestroy loop.
1382 llvm::BasicBlock *destroyBB = CGF.createBasicBlock("delete.destroy");
1383 llvm::BranchInst *br =
1384 CGF.Builder.CreateCondBr(iszero, destroyBB, destroyBB);
1385 CGF.EmitBlock(destroyBB);
1386
1387 llvm::Value *arrayEnd =
1388 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
1389 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1390 CGF.getDestroyer(dtorKind),
1391 CGF.needsEHCleanup(dtorKind));
1392
1393 assert(CGF.Builder.GetInsertBlock()->empty());
1394 br->setSuccessor(0, CGF.Builder.GetInsertBlock());
John McCall1e7fe752010-09-02 09:58:18 +00001395 }
1396
John McCall7cfd76c2011-07-13 01:41:37 +00001397 // Pop the cleanup block.
John McCall1e7fe752010-09-02 09:58:18 +00001398 CGF.PopCleanupBlock();
1399}
1400
Anders Carlsson16d81b82009-09-22 22:53:17 +00001401void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian72c21532009-11-13 19:27:47 +00001402
Douglas Gregor90916562009-09-29 18:16:17 +00001403 // Get at the argument before we performed the implicit conversion
1404 // to void*.
1405 const Expr *Arg = E->getArgument();
1406 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00001407 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregor90916562009-09-29 18:16:17 +00001408 ICE->getType()->isVoidPointerType())
1409 Arg = ICE->getSubExpr();
Douglas Gregord69dd782009-10-01 05:49:51 +00001410 else
1411 break;
Douglas Gregor90916562009-09-29 18:16:17 +00001412 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001413
Douglas Gregor90916562009-09-29 18:16:17 +00001414 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001415
1416 // Null check the pointer.
1417 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1418 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1419
Anders Carlssonb9241242011-04-11 00:30:07 +00001420 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001421
1422 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1423 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001424
John McCall1e7fe752010-09-02 09:58:18 +00001425 // We might be deleting a pointer to array. If so, GEP down to the
1426 // first non-array element.
1427 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1428 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1429 if (DeleteTy->isConstantArrayType()) {
1430 llvm::Value *Zero = Builder.getInt32(0);
1431 llvm::SmallVector<llvm::Value*,8> GEP;
1432
1433 GEP.push_back(Zero); // point at the outermost array
1434
1435 // For each layer of array type we're pointing at:
1436 while (const ConstantArrayType *Arr
1437 = getContext().getAsConstantArrayType(DeleteTy)) {
1438 // 1. Unpeel the array type.
1439 DeleteTy = Arr->getElementType();
1440
1441 // 2. GEP to the first element of the array.
1442 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001443 }
John McCall1e7fe752010-09-02 09:58:18 +00001444
1445 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001446 }
1447
Douglas Gregoreede61a2010-09-02 17:38:50 +00001448 assert(ConvertTypeForMem(DeleteTy) ==
1449 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001450
1451 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001452 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001453 } else {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001454 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1455 E->isGlobalDelete());
John McCall1e7fe752010-09-02 09:58:18 +00001456 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001457
Anders Carlsson16d81b82009-09-22 22:53:17 +00001458 EmitBlock(DeleteEnd);
1459}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001460
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001461static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1462 // void __cxa_bad_typeid();
1463
1464 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1465 const llvm::FunctionType *FTy =
1466 llvm::FunctionType::get(VoidTy, false);
1467
1468 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1469}
1470
1471static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001472 llvm::Value *Fn = getBadTypeidFn(CGF);
1473 CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001474 CGF.Builder.CreateUnreachable();
1475}
1476
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001477static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1478 const Expr *E,
1479 const llvm::Type *StdTypeInfoPtrTy) {
1480 // Get the vtable pointer.
1481 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1482
1483 // C++ [expr.typeid]p2:
1484 // If the glvalue expression is obtained by applying the unary * operator to
1485 // a pointer and the pointer is a null pointer value, the typeid expression
1486 // throws the std::bad_typeid exception.
1487 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1488 if (UO->getOpcode() == UO_Deref) {
1489 llvm::BasicBlock *BadTypeidBlock =
1490 CGF.createBasicBlock("typeid.bad_typeid");
1491 llvm::BasicBlock *EndBlock =
1492 CGF.createBasicBlock("typeid.end");
1493
1494 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1495 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1496
1497 CGF.EmitBlock(BadTypeidBlock);
1498 EmitBadTypeidCall(CGF);
1499 CGF.EmitBlock(EndBlock);
1500 }
1501 }
1502
1503 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1504 StdTypeInfoPtrTy->getPointerTo());
1505
1506 // Load the type info.
1507 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1508 return CGF.Builder.CreateLoad(Value);
1509}
1510
John McCall3ad32c82011-01-28 08:37:24 +00001511llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001512 const llvm::Type *StdTypeInfoPtrTy =
1513 ConvertType(E->getType())->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001514
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001515 if (E->isTypeOperand()) {
1516 llvm::Constant *TypeInfo =
1517 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001518 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001519 }
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001520
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001521 // C++ [expr.typeid]p2:
1522 // When typeid is applied to a glvalue expression whose type is a
1523 // polymorphic class type, the result refers to a std::type_info object
1524 // representing the type of the most derived object (that is, the dynamic
1525 // type) to which the glvalue refers.
1526 if (E->getExprOperand()->isGLValue()) {
1527 if (const RecordType *RT =
1528 E->getExprOperand()->getType()->getAs<RecordType>()) {
1529 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1530 if (RD->isPolymorphic())
1531 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1532 StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001533 }
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001534 }
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001535
1536 QualType OperandTy = E->getExprOperand()->getType();
1537 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1538 StdTypeInfoPtrTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001539}
Mike Stumpc849c052009-11-16 06:50:58 +00001540
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001541static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1542 // void *__dynamic_cast(const void *sub,
1543 // const abi::__class_type_info *src,
1544 // const abi::__class_type_info *dst,
1545 // std::ptrdiff_t src2dst_offset);
1546
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001547 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1548 llvm::Type *PtrDiffTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001549 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1550
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001551 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001552
1553 const llvm::FunctionType *FTy =
1554 llvm::FunctionType::get(Int8PtrTy, Args, false);
1555
1556 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1557}
1558
1559static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1560 // void __cxa_bad_cast();
1561
1562 const llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1563 const llvm::FunctionType *FTy =
1564 llvm::FunctionType::get(VoidTy, false);
1565
1566 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1567}
1568
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001569static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001570 llvm::Value *Fn = getBadCastFn(CGF);
1571 CGF.EmitCallOrInvoke(Fn, 0, 0).setDoesNotReturn();
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001572 CGF.Builder.CreateUnreachable();
1573}
1574
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001575static llvm::Value *
1576EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1577 QualType SrcTy, QualType DestTy,
1578 llvm::BasicBlock *CastEnd) {
1579 const llvm::Type *PtrDiffLTy =
1580 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1581 const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1582
1583 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1584 if (PTy->getPointeeType()->isVoidType()) {
1585 // C++ [expr.dynamic.cast]p7:
1586 // If T is "pointer to cv void," then the result is a pointer to the
1587 // most derived object pointed to by v.
1588
1589 // Get the vtable pointer.
1590 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1591
1592 // Get the offset-to-top from the vtable.
1593 llvm::Value *OffsetToTop =
1594 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1595 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1596
1597 // Finally, add the offset to the pointer.
1598 Value = CGF.EmitCastToVoidPtr(Value);
1599 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1600
1601 return CGF.Builder.CreateBitCast(Value, DestLTy);
1602 }
1603 }
1604
1605 QualType SrcRecordTy;
1606 QualType DestRecordTy;
1607
1608 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1609 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1610 DestRecordTy = DestPTy->getPointeeType();
1611 } else {
1612 SrcRecordTy = SrcTy;
1613 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1614 }
1615
1616 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1617 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1618
1619 llvm::Value *SrcRTTI =
1620 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1621 llvm::Value *DestRTTI =
1622 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1623
1624 // FIXME: Actually compute a hint here.
1625 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1626
1627 // Emit the call to __dynamic_cast.
1628 Value = CGF.EmitCastToVoidPtr(Value);
1629 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1630 SrcRTTI, DestRTTI, OffsetHint);
1631 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1632
1633 /// C++ [expr.dynamic.cast]p9:
1634 /// A failed cast to reference type throws std::bad_cast
1635 if (DestTy->isReferenceType()) {
1636 llvm::BasicBlock *BadCastBlock =
1637 CGF.createBasicBlock("dynamic_cast.bad_cast");
1638
1639 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1640 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1641
1642 CGF.EmitBlock(BadCastBlock);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001643 EmitBadCastCall(CGF);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001644 }
1645
1646 return Value;
1647}
1648
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001649static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1650 QualType DestTy) {
1651 const llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1652 if (DestTy->isPointerType())
1653 return llvm::Constant::getNullValue(DestLTy);
1654
1655 /// C++ [expr.dynamic.cast]p9:
1656 /// A failed cast to reference type throws std::bad_cast
1657 EmitBadCastCall(CGF);
1658
1659 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1660 return llvm::UndefValue::get(DestLTy);
1661}
1662
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001663llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001664 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001665 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001666
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001667 if (DCE->isAlwaysNull())
1668 return EmitDynamicCastToNull(*this, DestTy);
1669
1670 QualType SrcTy = DCE->getSubExpr()->getType();
1671
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001672 // C++ [expr.dynamic.cast]p4:
1673 // If the value of v is a null pointer value in the pointer case, the result
1674 // is the null pointer value of type T.
1675 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001676
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001677 llvm::BasicBlock *CastNull = 0;
1678 llvm::BasicBlock *CastNotNull = 0;
1679 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001680
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001681 if (ShouldNullCheckSrcValue) {
1682 CastNull = createBasicBlock("dynamic_cast.null");
1683 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1684
1685 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1686 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1687 EmitBlock(CastNotNull);
Mike Stumpc849c052009-11-16 06:50:58 +00001688 }
1689
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001690 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1691
1692 if (ShouldNullCheckSrcValue) {
1693 EmitBranch(CastEnd);
1694
1695 EmitBlock(CastNull);
1696 EmitBranch(CastEnd);
1697 }
1698
1699 EmitBlock(CastEnd);
1700
1701 if (ShouldNullCheckSrcValue) {
1702 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1703 PHI->addIncoming(Value, CastNotNull);
1704 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1705
1706 Value = PHI;
1707 }
1708
1709 return Value;
Mike Stumpc849c052009-11-16 06:50:58 +00001710}