blob: acc9a2b03608913966549a4f256cdef8d358ad2f [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlsson16d81b82009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
Devang Patelc69e1cf2010-09-30 19:05:55 +000014#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson16d81b82009-09-22 22:53:17 +000015#include "CodeGenFunction.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Fariborz Jahanian842ddd02010-05-20 21:38:57 +000017#include "CGObjCRuntime.h"
Devang Patelc69e1cf2010-09-30 19:05:55 +000018#include "CGDebugInfo.h"
Chris Lattner6c552c12010-07-20 20:19:24 +000019#include "llvm/Intrinsics.h"
Anders Carlssonad3692bb2011-04-13 02:35:36 +000020#include "llvm/Support/CallSite.h"
21
Anders Carlsson16d81b82009-09-22 22:53:17 +000022using namespace clang;
23using namespace CodeGen;
24
Anders Carlsson3b5ad222010-01-01 20:29:01 +000025RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
26 llvm::Value *Callee,
27 ReturnValueSlot ReturnValue,
28 llvm::Value *This,
Anders Carlssonc997d422010-01-02 01:01:18 +000029 llvm::Value *VTT,
Anders Carlsson3b5ad222010-01-01 20:29:01 +000030 CallExpr::const_arg_iterator ArgBeg,
31 CallExpr::const_arg_iterator ArgEnd) {
32 assert(MD->isInstance() &&
33 "Trying to emit a member call expr on a static method!");
34
35 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
36
37 CallArgList Args;
38
39 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +000040 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000041
Anders Carlssonc997d422010-01-02 01:01:18 +000042 // If there is a VTT parameter, emit it.
43 if (VTT) {
44 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +000045 Args.add(RValue::get(VTT), T);
Anders Carlssonc997d422010-01-02 01:01:18 +000046 }
47
Anders Carlsson3b5ad222010-01-01 20:29:01 +000048 // And the rest of the call args
49 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
50
John McCall04a67a62010-02-05 21:31:56 +000051 QualType ResultType = FPT->getResultType();
Tilmann Scheller9c6082f2011-03-02 21:36:49 +000052 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
53 FPT->getExtInfo()),
Rafael Espindola264ba482010-03-30 20:24:48 +000054 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000055}
56
Anders Carlsson1679f5a2011-01-29 03:52:01 +000057static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
Anders Carlsson268ab8c2011-01-29 05:04:11 +000058 const Expr *E = Base;
59
60 while (true) {
61 E = E->IgnoreParens();
62 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
63 if (CE->getCastKind() == CK_DerivedToBase ||
64 CE->getCastKind() == CK_UncheckedDerivedToBase ||
65 CE->getCastKind() == CK_NoOp) {
66 E = CE->getSubExpr();
67 continue;
68 }
69 }
70
71 break;
72 }
73
74 QualType DerivedType = E->getType();
Anders Carlsson1679f5a2011-01-29 03:52:01 +000075 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
76 DerivedType = PTy->getPointeeType();
77
78 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
79}
80
Anders Carlssoncd0b32e2011-04-10 18:20:53 +000081// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
82// quite what we want.
83static const Expr *skipNoOpCastsAndParens(const Expr *E) {
84 while (true) {
85 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
86 E = PE->getSubExpr();
87 continue;
88 }
89
90 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
91 if (CE->getCastKind() == CK_NoOp) {
92 E = CE->getSubExpr();
93 continue;
94 }
95 }
96 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
97 if (UO->getOpcode() == UO_Extension) {
98 E = UO->getSubExpr();
99 continue;
100 }
101 }
102 return E;
103 }
104}
105
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000106/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
107/// expr can be devirtualized.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000108static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
109 const Expr *Base,
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000110 const CXXMethodDecl *MD) {
111
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000112 // When building with -fapple-kext, all calls must go through the vtable since
113 // the kernel linker can do runtime patching of vtables.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000114 if (Context.getLangOptions().AppleKext)
115 return false;
116
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000117 // If the most derived class is marked final, we know that no subclass can
118 // override this member function and so we can devirtualize it. For example:
119 //
120 // struct A { virtual void f(); }
121 // struct B final : A { };
122 //
123 // void f(B *b) {
124 // b->f();
125 // }
126 //
127 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
128 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
129 return true;
130
Anders Carlssonf89e0422011-01-23 21:07:30 +0000131 // If the member function is marked 'final', we know that it can't be
Anders Carlssond66f4282010-10-27 13:34:43 +0000132 // overridden and can therefore devirtualize it.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000133 if (MD->hasAttr<FinalAttr>())
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000134 return true;
Anders Carlssond66f4282010-10-27 13:34:43 +0000135
Anders Carlssonf89e0422011-01-23 21:07:30 +0000136 // Similarly, if the class itself is marked 'final' it can't be overridden
137 // and we can therefore devirtualize the member function call.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000138 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssond66f4282010-10-27 13:34:43 +0000139 return true;
140
Anders Carlssoncd0b32e2011-04-10 18:20:53 +0000141 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000142 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
143 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
144 // This is a record decl. We know the type and can devirtualize it.
145 return VD->getType()->isRecordType();
146 }
147
148 return false;
149 }
150
151 // We can always devirtualize calls on temporary object expressions.
Eli Friedman6997aae2010-01-31 20:58:15 +0000152 if (isa<CXXConstructExpr>(Base))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000153 return true;
154
155 // And calls on bound temporaries.
156 if (isa<CXXBindTemporaryExpr>(Base))
157 return true;
158
159 // Check if this is a call expr that returns a record type.
160 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
161 return CE->getCallReturnType()->isRecordType();
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000162
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000163 // We can't devirtualize the call.
164 return false;
165}
166
Francois Pichetdbee3412011-01-18 05:04:39 +0000167// Note: This function also emit constructor calls to support a MSVC
168// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000169RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
170 ReturnValueSlot ReturnValue) {
John McCall379b5152011-04-11 07:02:50 +0000171 const Expr *callee = CE->getCallee()->IgnoreParens();
172
173 if (isa<BinaryOperator>(callee))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000174 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall379b5152011-04-11 07:02:50 +0000175
176 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000177 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
178
Devang Patelc69e1cf2010-09-30 19:05:55 +0000179 CGDebugInfo *DI = getDebugInfo();
Devang Patel68020272010-10-22 18:56:27 +0000180 if (DI && CGM.getCodeGenOpts().LimitDebugInfo
181 && !isa<CallExpr>(ME->getBase())) {
Devang Patelc69e1cf2010-09-30 19:05:55 +0000182 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
183 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
184 DI->getOrCreateRecordType(PTy->getPointeeType(),
185 MD->getParent()->getLocation());
186 }
187 }
188
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000189 if (MD->isStatic()) {
190 // The method is static, emit it as we would a regular call.
191 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
192 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
193 ReturnValue, CE->arg_begin(), CE->arg_end());
194 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000195
John McCallfc400282010-09-03 01:26:39 +0000196 // Compute the object pointer.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000197 llvm::Value *This;
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000198 if (ME->isArrow())
199 This = EmitScalarExpr(ME->getBase());
John McCall0e800c92010-12-04 08:14:53 +0000200 else
201 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000202
John McCallfc400282010-09-03 01:26:39 +0000203 if (MD->isTrivial()) {
204 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichetdbee3412011-01-18 05:04:39 +0000205 if (isa<CXXConstructorDecl>(MD) &&
206 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
207 return RValue::get(0);
John McCallfc400282010-09-03 01:26:39 +0000208
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000209 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
210 // We don't like to generate the trivial copy/move assignment operator
211 // when it isn't necessary; just produce the proper effect here.
Francois Pichetdbee3412011-01-18 05:04:39 +0000212 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
213 EmitAggregateCopy(This, RHS, CE->getType());
214 return RValue::get(This);
215 }
216
217 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000218 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
219 // Trivial move and copy ctor are the same.
Francois Pichetdbee3412011-01-18 05:04:39 +0000220 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
221 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
222 CE->arg_begin(), CE->arg_end());
223 return RValue::get(This);
224 }
225 llvm_unreachable("unknown trivial member function");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000226 }
227
John McCallfc400282010-09-03 01:26:39 +0000228 // Compute the function type we're calling.
Francois Pichetdbee3412011-01-18 05:04:39 +0000229 const CGFunctionInfo *FInfo = 0;
230 if (isa<CXXDestructorDecl>(MD))
231 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
232 Dtor_Complete);
233 else if (isa<CXXConstructorDecl>(MD))
234 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXConstructorDecl>(MD),
235 Ctor_Complete);
236 else
237 FInfo = &CGM.getTypes().getFunctionInfo(MD);
John McCallfc400282010-09-03 01:26:39 +0000238
239 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000240 llvm::Type *Ty
Francois Pichetdbee3412011-01-18 05:04:39 +0000241 = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
John McCallfc400282010-09-03 01:26:39 +0000242
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000243 // C++ [class.virtual]p12:
244 // Explicit qualification with the scope operator (5.1) suppresses the
245 // virtual call mechanism.
246 //
247 // We also don't emit a virtual call if the base expression has a record type
248 // because then we know what the type is.
Fariborz Jahanian27262672011-01-20 17:19:02 +0000249 bool UseVirtualCall;
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000250 UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
251 && !canDevirtualizeMemberFunctionCalls(getContext(),
252 ME->getBase(), MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000253 llvm::Value *Callee;
John McCallfc400282010-09-03 01:26:39 +0000254 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
255 if (UseVirtualCall) {
256 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000257 } else {
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000258 if (getContext().getLangOptions().AppleKext &&
259 MD->isVirtual() &&
260 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000261 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000262 else
263 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000264 }
Francois Pichetdbee3412011-01-18 05:04:39 +0000265 } else if (const CXXConstructorDecl *Ctor =
266 dyn_cast<CXXConstructorDecl>(MD)) {
267 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000268 } else if (UseVirtualCall) {
Fariborz Jahanian27262672011-01-20 17:19:02 +0000269 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000270 } else {
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000271 if (getContext().getLangOptions().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000272 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000273 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000274 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000275 else
276 Callee = CGM.GetAddrOfFunction(MD, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000277 }
278
Anders Carlssonc997d422010-01-02 01:01:18 +0000279 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000280 CE->arg_begin(), CE->arg_end());
281}
282
283RValue
284CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
285 ReturnValueSlot ReturnValue) {
286 const BinaryOperator *BO =
287 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
288 const Expr *BaseExpr = BO->getLHS();
289 const Expr *MemFnExpr = BO->getRHS();
290
291 const MemberPointerType *MPT =
John McCall864c0412011-04-26 20:42:42 +0000292 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000293
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000294 const FunctionProtoType *FPT =
John McCall864c0412011-04-26 20:42:42 +0000295 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000296 const CXXRecordDecl *RD =
297 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
298
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000299 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000300 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000301
302 // Emit the 'this' pointer.
303 llvm::Value *This;
304
John McCall2de56d12010-08-25 11:45:40 +0000305 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000306 This = EmitScalarExpr(BaseExpr);
307 else
308 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000309
John McCall93d557b2010-08-22 00:05:51 +0000310 // Ask the ABI to load the callee. Note that This is modified.
311 llvm::Value *Callee =
John McCalld16c2cf2011-02-08 08:22:06 +0000312 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000313
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000314 CallArgList Args;
315
316 QualType ThisType =
317 getContext().getPointerType(getContext().getTagDeclType(RD));
318
319 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +0000320 Args.add(RValue::get(This), ThisType);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000321
322 // And the rest of the call args
323 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall864c0412011-04-26 20:42:42 +0000324 return EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000325 ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000326}
327
328RValue
329CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
330 const CXXMethodDecl *MD,
331 ReturnValueSlot ReturnValue) {
332 assert(MD->isInstance() &&
333 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000334 LValue LV = EmitLValue(E->getArg(0));
335 llvm::Value *This = LV.getAddress();
336
Douglas Gregor3e9438b2010-09-27 22:37:28 +0000337 if (MD->isCopyAssignmentOperator()) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000338 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
339 if (ClassDecl->hasTrivialCopyAssignment()) {
340 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
341 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000342 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
343 QualType Ty = E->getType();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000344 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000345 return RValue::get(This);
346 }
347 }
348
Anders Carlssona2447e02011-05-08 20:32:23 +0000349 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Anders Carlssonc997d422010-01-02 01:01:18 +0000350 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000351 E->arg_begin() + 1, E->arg_end());
352}
353
354void
John McCall558d2ab2010-09-15 10:14:12 +0000355CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
356 AggValueSlot Dest) {
357 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000358 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000359
360 // If we require zero initialization before (or instead of) calling the
361 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +0000362 // constructor, emit the zero initialization now, unless destination is
363 // already zeroed.
364 if (E->requiresZeroInitialization() && !Dest.isZeroed())
John McCall558d2ab2010-09-15 10:14:12 +0000365 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor759e41b2010-08-22 16:15:35 +0000366
367 // If this is a call to a trivial default constructor, do nothing.
368 if (CD->isTrivial() && CD->isDefaultConstructor())
369 return;
370
John McCallfc1e6c72010-09-18 00:58:34 +0000371 // Elide the constructor if we're constructing from a temporary.
372 // The temporary check is required because Sema sets this on NRVO
373 // returns.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000374 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000375 assert(getContext().hasSameUnqualifiedType(E->getType(),
376 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000377 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
378 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000379 return;
380 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000381 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000382
John McCallc3c07662011-07-13 06:10:41 +0000383 if (const ConstantArrayType *arrayType
384 = getContext().getAsConstantArrayType(E->getType())) {
385 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000386 E->arg_begin(), E->arg_end());
John McCallc3c07662011-07-13 06:10:41 +0000387 } else {
Cameron Esfahani6bd2f6a2011-05-06 21:28:42 +0000388 CXXCtorType Type = Ctor_Complete;
Sean Huntd49bd552011-05-03 20:19:28 +0000389 bool ForVirtualBase = false;
390
391 switch (E->getConstructionKind()) {
392 case CXXConstructExpr::CK_Delegating:
Sean Hunt059ce0d2011-05-01 07:04:31 +0000393 // We should be emitting a constructor; GlobalDecl will assert this
394 Type = CurGD.getCtorType();
Sean Huntd49bd552011-05-03 20:19:28 +0000395 break;
Sean Hunt059ce0d2011-05-01 07:04:31 +0000396
Sean Huntd49bd552011-05-03 20:19:28 +0000397 case CXXConstructExpr::CK_Complete:
398 Type = Ctor_Complete;
399 break;
400
401 case CXXConstructExpr::CK_VirtualBase:
402 ForVirtualBase = true;
403 // fall-through
404
405 case CXXConstructExpr::CK_NonVirtualBase:
406 Type = Ctor_Base;
407 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000408
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000409 // Call the constructor.
John McCall558d2ab2010-09-15 10:14:12 +0000410 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000411 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000412 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000413}
414
Fariborz Jahanian34999872010-11-13 21:53:34 +0000415void
416CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
417 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000418 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000419 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000420 Exp = E->getSubExpr();
421 assert(isa<CXXConstructExpr>(Exp) &&
422 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
423 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
424 const CXXConstructorDecl *CD = E->getConstructor();
425 RunCleanupsScope Scope(*this);
426
427 // If we require zero initialization before (or instead of) calling the
428 // constructor, as can be the case with a non-user-provided default
429 // constructor, emit the zero initialization now.
430 // FIXME. Do I still need this for a copy ctor synthesis?
431 if (E->requiresZeroInitialization())
432 EmitNullInitialization(Dest, E->getType());
433
Chandler Carruth858a5462010-11-15 13:54:43 +0000434 assert(!getContext().getAsConstantArrayType(E->getType())
435 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000436 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
437 E->arg_begin(), E->arg_end());
438}
439
John McCall1e7fe752010-09-02 09:58:18 +0000440static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
441 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000442 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000443 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000444
John McCallb1c98a32011-05-16 01:05:12 +0000445 // No cookie is required if the operator new[] being used is the
446 // reserved placement operator new[].
447 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCall5172ed92010-08-23 01:17:59 +0000448 return CharUnits::Zero();
449
John McCall6ec278d2011-01-27 09:37:56 +0000450 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000451}
452
John McCall7d166272011-05-15 07:14:44 +0000453static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
454 const CXXNewExpr *e,
455 llvm::Value *&numElements,
456 llvm::Value *&sizeWithoutCookie) {
457 QualType type = e->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000458
John McCall7d166272011-05-15 07:14:44 +0000459 if (!e->isArray()) {
460 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
461 sizeWithoutCookie
462 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
463 return sizeWithoutCookie;
Douglas Gregor59174c02010-07-21 01:10:17 +0000464 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000465
John McCall7d166272011-05-15 07:14:44 +0000466 // The width of size_t.
467 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
468
John McCall1e7fe752010-09-02 09:58:18 +0000469 // Figure out the cookie size.
John McCall7d166272011-05-15 07:14:44 +0000470 llvm::APInt cookieSize(sizeWidth,
471 CalculateCookiePadding(CGF, e).getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000472
Anders Carlssona4d4c012009-09-23 16:07:23 +0000473 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000474 // We multiply the size of all dimensions for NumElements.
475 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall7d166272011-05-15 07:14:44 +0000476 numElements = CGF.EmitScalarExpr(e->getArraySize());
477 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall1e7fe752010-09-02 09:58:18 +0000478
John McCall7d166272011-05-15 07:14:44 +0000479 // The number of elements can be have an arbitrary integer type;
480 // essentially, we need to multiply it by a constant factor, add a
481 // cookie size, and verify that the result is representable as a
482 // size_t. That's just a gloss, though, and it's wrong in one
483 // important way: if the count is negative, it's an error even if
484 // the cookie size would bring the total size >= 0.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000485 bool isSigned
486 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000487 llvm::IntegerType *numElementsType
John McCall7d166272011-05-15 07:14:44 +0000488 = cast<llvm::IntegerType>(numElements->getType());
489 unsigned numElementsWidth = numElementsType->getBitWidth();
490
491 // Compute the constant factor.
492 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000493 while (const ConstantArrayType *CAT
John McCall7d166272011-05-15 07:14:44 +0000494 = CGF.getContext().getAsConstantArrayType(type)) {
495 type = CAT->getElementType();
496 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000497 }
498
John McCall7d166272011-05-15 07:14:44 +0000499 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
500 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
501 typeSizeMultiplier *= arraySizeMultiplier;
502
503 // This will be a size_t.
504 llvm::Value *size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000505
Chris Lattner806941e2010-07-20 21:55:52 +0000506 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
507 // Don't bloat the -O0 code.
John McCall7d166272011-05-15 07:14:44 +0000508 if (llvm::ConstantInt *numElementsC =
509 dyn_cast<llvm::ConstantInt>(numElements)) {
510 const llvm::APInt &count = numElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000511
John McCall7d166272011-05-15 07:14:44 +0000512 bool hasAnyOverflow = false;
John McCall1e7fe752010-09-02 09:58:18 +0000513
John McCall7d166272011-05-15 07:14:44 +0000514 // If 'count' was a negative number, it's an overflow.
515 if (isSigned && count.isNegative())
516 hasAnyOverflow = true;
John McCall1e7fe752010-09-02 09:58:18 +0000517
John McCall7d166272011-05-15 07:14:44 +0000518 // We want to do all this arithmetic in size_t. If numElements is
519 // wider than that, check whether it's already too big, and if so,
520 // overflow.
521 else if (numElementsWidth > sizeWidth &&
522 numElementsWidth - sizeWidth > count.countLeadingZeros())
523 hasAnyOverflow = true;
524
525 // Okay, compute a count at the right width.
526 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
527
528 // Scale numElements by that. This might overflow, but we don't
529 // care because it only overflows if allocationSize does, too, and
530 // if that overflows then we shouldn't use this.
531 numElements = llvm::ConstantInt::get(CGF.SizeTy,
532 adjustedCount * arraySizeMultiplier);
533
534 // Compute the size before cookie, and track whether it overflowed.
535 bool overflow;
536 llvm::APInt allocationSize
537 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
538 hasAnyOverflow |= overflow;
539
540 // Add in the cookie, and check whether it's overflowed.
541 if (cookieSize != 0) {
542 // Save the current size without a cookie. This shouldn't be
543 // used if there was overflow.
544 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
545
546 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
547 hasAnyOverflow |= overflow;
548 }
549
550 // On overflow, produce a -1 so operator new will fail.
551 if (hasAnyOverflow) {
552 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
553 } else {
554 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
555 }
556
557 // Otherwise, we might need to use the overflow intrinsics.
558 } else {
559 // There are up to four conditions we need to test for:
560 // 1) if isSigned, we need to check whether numElements is negative;
561 // 2) if numElementsWidth > sizeWidth, we need to check whether
562 // numElements is larger than something representable in size_t;
563 // 3) we need to compute
564 // sizeWithoutCookie := numElements * typeSizeMultiplier
565 // and check whether it overflows; and
566 // 4) if we need a cookie, we need to compute
567 // size := sizeWithoutCookie + cookieSize
568 // and check whether it overflows.
569
570 llvm::Value *hasOverflow = 0;
571
572 // If numElementsWidth > sizeWidth, then one way or another, we're
573 // going to have to do a comparison for (2), and this happens to
574 // take care of (1), too.
575 if (numElementsWidth > sizeWidth) {
576 llvm::APInt threshold(numElementsWidth, 1);
577 threshold <<= sizeWidth;
578
579 llvm::Value *thresholdV
580 = llvm::ConstantInt::get(numElementsType, threshold);
581
582 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
583 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
584
585 // Otherwise, if we're signed, we want to sext up to size_t.
586 } else if (isSigned) {
587 if (numElementsWidth < sizeWidth)
588 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
589
590 // If there's a non-1 type size multiplier, then we can do the
591 // signedness check at the same time as we do the multiply
592 // because a negative number times anything will cause an
593 // unsigned overflow. Otherwise, we have to do it here.
594 if (typeSizeMultiplier == 1)
595 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
596 llvm::ConstantInt::get(CGF.SizeTy, 0));
597
598 // Otherwise, zext up to size_t if necessary.
599 } else if (numElementsWidth < sizeWidth) {
600 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
601 }
602
603 assert(numElements->getType() == CGF.SizeTy);
604
605 size = numElements;
606
607 // Multiply by the type size if necessary. This multiplier
608 // includes all the factors for nested arrays.
609 //
610 // This step also causes numElements to be scaled up by the
611 // nested-array factor if necessary. Overflow on this computation
612 // can be ignored because the result shouldn't be used if
613 // allocation fails.
614 if (typeSizeMultiplier != 1) {
John McCall7d166272011-05-15 07:14:44 +0000615 llvm::Value *umul_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000616 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000617
618 llvm::Value *tsmV =
619 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
620 llvm::Value *result =
621 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
622
623 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
624 if (hasOverflow)
625 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
626 else
627 hasOverflow = overflowed;
628
629 size = CGF.Builder.CreateExtractValue(result, 0);
630
631 // Also scale up numElements by the array size multiplier.
632 if (arraySizeMultiplier != 1) {
633 // If the base element type size is 1, then we can re-use the
634 // multiply we just did.
635 if (typeSize.isOne()) {
636 assert(arraySizeMultiplier == typeSizeMultiplier);
637 numElements = size;
638
639 // Otherwise we need a separate multiply.
640 } else {
641 llvm::Value *asmV =
642 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
643 numElements = CGF.Builder.CreateMul(numElements, asmV);
644 }
645 }
646 } else {
647 // numElements doesn't need to be scaled.
648 assert(arraySizeMultiplier == 1);
Chris Lattner806941e2010-07-20 21:55:52 +0000649 }
650
John McCall7d166272011-05-15 07:14:44 +0000651 // Add in the cookie size if necessary.
652 if (cookieSize != 0) {
653 sizeWithoutCookie = size;
654
John McCall7d166272011-05-15 07:14:44 +0000655 llvm::Value *uadd_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000656 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000657
658 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
659 llvm::Value *result =
660 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
661
662 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
663 if (hasOverflow)
664 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
665 else
666 hasOverflow = overflowed;
667
668 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall1e7fe752010-09-02 09:58:18 +0000669 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000670
John McCall7d166272011-05-15 07:14:44 +0000671 // If we had any possibility of dynamic overflow, make a select to
672 // overwrite 'size' with an all-ones value, which should cause
673 // operator new to throw.
674 if (hasOverflow)
675 size = CGF.Builder.CreateSelect(hasOverflow,
676 llvm::Constant::getAllOnesValue(CGF.SizeTy),
677 size);
Chris Lattner806941e2010-07-20 21:55:52 +0000678 }
John McCall1e7fe752010-09-02 09:58:18 +0000679
John McCall7d166272011-05-15 07:14:44 +0000680 if (cookieSize == 0)
681 sizeWithoutCookie = size;
John McCall1e7fe752010-09-02 09:58:18 +0000682 else
John McCall7d166272011-05-15 07:14:44 +0000683 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall1e7fe752010-09-02 09:58:18 +0000684
John McCall7d166272011-05-15 07:14:44 +0000685 return size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000686}
687
Fariborz Jahanianef668722010-06-25 18:26:07 +0000688static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
689 llvm::Value *NewPtr) {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000690
691 assert(E->getNumConstructorArgs() == 1 &&
692 "Can only have one argument to initializer of POD type.");
693
694 const Expr *Init = E->getConstructorArg(0);
695 QualType AllocType = E->getAllocatedType();
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000696
697 unsigned Alignment =
698 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
John McCalla07398e2011-06-16 04:16:24 +0000699 if (!CGF.hasAggregateLLVMType(AllocType))
700 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType, Alignment),
701 false);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000702 else if (AllocType->isAnyComplexType())
703 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
704 AllocType.isVolatileQualified());
John McCall558d2ab2010-09-15 10:14:12 +0000705 else {
706 AggValueSlot Slot
John McCall7c2349b2011-08-25 20:40:09 +0000707 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
708 AggValueSlot::IsDestructed,
John McCall44184392011-08-26 07:31:35 +0000709 AggValueSlot::DoesNotNeedGCBarriers,
710 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000711 CGF.EmitAggExpr(Init, Slot);
712 }
Fariborz Jahanianef668722010-06-25 18:26:07 +0000713}
714
715void
716CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
717 llvm::Value *NewPtr,
718 llvm::Value *NumElements) {
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000719 // We have a POD type.
720 if (E->getNumConstructorArgs() == 0)
721 return;
722
Chris Lattner2acc6e32011-07-18 04:24:23 +0000723 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Fariborz Jahanianef668722010-06-25 18:26:07 +0000724
725 // Create a temporary for the loop index and initialize it with 0.
726 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
727 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
728 Builder.CreateStore(Zero, IndexPtr);
729
730 // Start the loop with a block that tests the condition.
731 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
732 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
733
734 EmitBlock(CondBlock);
735
736 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
737
738 // Generate: if (loop-index < number-of-elements fall to the loop body,
739 // otherwise, go to the block after the for-loop.
740 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
741 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
742 // If the condition is true, execute the body.
743 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
744
745 EmitBlock(ForBody);
746
747 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
748 // Inside the loop body, emit the constructor call on the array element.
749 Counter = Builder.CreateLoad(IndexPtr);
750 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
751 "arrayidx");
752 StoreAnyExprIntoOneUnit(*this, E, Address);
753
754 EmitBlock(ContinueBlock);
755
756 // Emit the increment of the loop counter.
757 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
758 Counter = Builder.CreateLoad(IndexPtr);
759 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
760 Builder.CreateStore(NextVal, IndexPtr);
761
762 // Finally, branch back up to the condition for the next iteration.
763 EmitBranch(CondBlock);
764
765 // Emit the fall-through block.
766 EmitBlock(AfterFor, true);
767}
768
Douglas Gregor59174c02010-07-21 01:10:17 +0000769static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
770 llvm::Value *NewPtr, llvm::Value *Size) {
John McCalld16c2cf2011-02-08 08:22:06 +0000771 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyckfe710082011-01-19 01:58:38 +0000772 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000773 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000774 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000775}
776
Anders Carlssona4d4c012009-09-23 16:07:23 +0000777static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
778 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000779 llvm::Value *NumElements,
780 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000781 if (E->isArray()) {
Anders Carlssone99bdb62010-05-03 15:09:17 +0000782 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000783 bool RequiresZeroInitialization = false;
Sean Hunt023df372011-05-09 18:22:59 +0000784 if (Ctor->getParent()->hasTrivialDefaultConstructor()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000785 // If new expression did not specify value-initialization, then there
786 // is no initialization.
787 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
788 return;
789
John McCallf16aa102010-08-22 21:01:12 +0000790 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000791 // Optimization: since zero initialization will just set the memory
792 // to all zeroes, generate a single memset to do it in one shot.
793 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
794 AllocSizeWithoutCookie);
795 return;
796 }
797
798 RequiresZeroInitialization = true;
799 }
John McCallc3c07662011-07-13 06:10:41 +0000800
Douglas Gregor59174c02010-07-21 01:10:17 +0000801 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
802 E->constructor_arg_begin(),
803 E->constructor_arg_end(),
804 RequiresZeroInitialization);
Anders Carlssone99bdb62010-05-03 15:09:17 +0000805 return;
Douglas Gregor59174c02010-07-21 01:10:17 +0000806 } else if (E->getNumConstructorArgs() == 1 &&
807 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
808 // Optimization: since zero initialization will just set the memory
809 // to all zeroes, generate a single memset to do it in one shot.
810 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
811 AllocSizeWithoutCookie);
812 return;
813 } else {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000814 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
815 return;
816 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000817 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000818
819 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregored8abf12010-07-08 06:14:04 +0000820 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
821 // direct initialization. C++ [dcl.init]p5 requires that we
822 // zero-initialize storage if there are no user-declared constructors.
823 if (E->hasInitializer() &&
824 !Ctor->getParent()->hasUserDeclaredConstructor() &&
825 !Ctor->getParent()->isEmpty())
826 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
827
Douglas Gregor84745672010-07-07 23:37:33 +0000828 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
829 NewPtr, E->constructor_arg_begin(),
830 E->constructor_arg_end());
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000831
832 return;
833 }
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000834 // We have a POD type.
835 if (E->getNumConstructorArgs() == 0)
836 return;
837
Fariborz Jahanianef668722010-06-25 18:26:07 +0000838 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000839}
840
John McCall7d8647f2010-09-14 07:57:04 +0000841namespace {
842 /// A cleanup to call the given 'operator delete' function upon
843 /// abnormal exit from a new expression.
844 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
845 size_t NumPlacementArgs;
846 const FunctionDecl *OperatorDelete;
847 llvm::Value *Ptr;
848 llvm::Value *AllocSize;
849
850 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
851
852 public:
853 static size_t getExtraSize(size_t NumPlacementArgs) {
854 return NumPlacementArgs * sizeof(RValue);
855 }
856
857 CallDeleteDuringNew(size_t NumPlacementArgs,
858 const FunctionDecl *OperatorDelete,
859 llvm::Value *Ptr,
860 llvm::Value *AllocSize)
861 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
862 Ptr(Ptr), AllocSize(AllocSize) {}
863
864 void setPlacementArg(unsigned I, RValue Arg) {
865 assert(I < NumPlacementArgs && "index out of range");
866 getPlacementArgs()[I] = Arg;
867 }
868
John McCallad346f42011-07-12 20:27:29 +0000869 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7d8647f2010-09-14 07:57:04 +0000870 const FunctionProtoType *FPT
871 = OperatorDelete->getType()->getAs<FunctionProtoType>();
872 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +0000873 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +0000874
875 CallArgList DeleteArgs;
876
877 // The first argument is always a void*.
878 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +0000879 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000880
881 // A member 'operator delete' can take an extra 'size_t' argument.
882 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman04c9a492011-05-02 17:57:46 +0000883 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000884
885 // Pass the rest of the arguments, which must match exactly.
886 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman04c9a492011-05-02 17:57:46 +0000887 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000888
889 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000890 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall7d8647f2010-09-14 07:57:04 +0000891 CGF.CGM.GetAddrOfFunction(OperatorDelete),
892 ReturnValueSlot(), DeleteArgs, OperatorDelete);
893 }
894 };
John McCall3019c442010-09-17 00:50:28 +0000895
896 /// A cleanup to call the given 'operator delete' function upon
897 /// abnormal exit from a new expression when the new expression is
898 /// conditional.
899 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
900 size_t NumPlacementArgs;
901 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +0000902 DominatingValue<RValue>::saved_type Ptr;
903 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +0000904
John McCall804b8072011-01-28 10:53:53 +0000905 DominatingValue<RValue>::saved_type *getPlacementArgs() {
906 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +0000907 }
908
909 public:
910 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +0000911 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +0000912 }
913
914 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
915 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +0000916 DominatingValue<RValue>::saved_type Ptr,
917 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +0000918 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
919 Ptr(Ptr), AllocSize(AllocSize) {}
920
John McCall804b8072011-01-28 10:53:53 +0000921 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +0000922 assert(I < NumPlacementArgs && "index out of range");
923 getPlacementArgs()[I] = Arg;
924 }
925
John McCallad346f42011-07-12 20:27:29 +0000926 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall3019c442010-09-17 00:50:28 +0000927 const FunctionProtoType *FPT
928 = OperatorDelete->getType()->getAs<FunctionProtoType>();
929 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
930 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
931
932 CallArgList DeleteArgs;
933
934 // The first argument is always a void*.
935 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +0000936 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall3019c442010-09-17 00:50:28 +0000937
938 // A member 'operator delete' can take an extra 'size_t' argument.
939 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +0000940 RValue RV = AllocSize.restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +0000941 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +0000942 }
943
944 // Pass the rest of the arguments, which must match exactly.
945 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +0000946 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +0000947 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +0000948 }
949
950 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000951 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall3019c442010-09-17 00:50:28 +0000952 CGF.CGM.GetAddrOfFunction(OperatorDelete),
953 ReturnValueSlot(), DeleteArgs, OperatorDelete);
954 }
955 };
956}
957
958/// Enter a cleanup to call 'operator delete' if the initializer in a
959/// new-expression throws.
960static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
961 const CXXNewExpr *E,
962 llvm::Value *NewPtr,
963 llvm::Value *AllocSize,
964 const CallArgList &NewArgs) {
965 // If we're not inside a conditional branch, then the cleanup will
966 // dominate and we can do the easier (and more efficient) thing.
967 if (!CGF.isInConditionalBranch()) {
968 CallDeleteDuringNew *Cleanup = CGF.EHStack
969 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
970 E->getNumPlacementArgs(),
971 E->getOperatorDelete(),
972 NewPtr, AllocSize);
973 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanc6d07822011-05-02 18:05:27 +0000974 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall3019c442010-09-17 00:50:28 +0000975
976 return;
977 }
978
979 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +0000980 DominatingValue<RValue>::saved_type SavedNewPtr =
981 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
982 DominatingValue<RValue>::saved_type SavedAllocSize =
983 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +0000984
985 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
986 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
987 E->getNumPlacementArgs(),
988 E->getOperatorDelete(),
989 SavedNewPtr,
990 SavedAllocSize);
991 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +0000992 Cleanup->setPlacementArg(I,
Eli Friedmanc6d07822011-05-02 18:05:27 +0000993 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall3019c442010-09-17 00:50:28 +0000994
995 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall7d8647f2010-09-14 07:57:04 +0000996}
997
Anders Carlsson16d81b82009-09-22 22:53:17 +0000998llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +0000999 // The element type being allocated.
1000 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +00001001
John McCallc2f3e7f2011-03-07 03:12:35 +00001002 // 1. Build a call to the allocation function.
1003 FunctionDecl *allocator = E->getOperatorNew();
1004 const FunctionProtoType *allocatorType =
1005 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001006
John McCallc2f3e7f2011-03-07 03:12:35 +00001007 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001008
1009 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001010 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001011
John McCallc2f3e7f2011-03-07 03:12:35 +00001012 llvm::Value *numElements = 0;
1013 llvm::Value *allocSizeWithoutCookie = 0;
1014 llvm::Value *allocSize =
John McCall7d166272011-05-15 07:14:44 +00001015 EmitCXXNewAllocSize(*this, E, numElements, allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +00001016
Eli Friedman04c9a492011-05-02 17:57:46 +00001017 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001018
1019 // Emit the rest of the arguments.
1020 // FIXME: Ideally, this should just use EmitCallArgs.
John McCallc2f3e7f2011-03-07 03:12:35 +00001021 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001022
1023 // First, use the types from the function type.
1024 // We start at 1 here because the first argument (the allocation size)
1025 // has already been emitted.
John McCallc2f3e7f2011-03-07 03:12:35 +00001026 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1027 ++i, ++placementArg) {
1028 QualType argType = allocatorType->getArgType(i);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001029
John McCallc2f3e7f2011-03-07 03:12:35 +00001030 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1031 placementArg->getType()) &&
Anders Carlsson16d81b82009-09-22 22:53:17 +00001032 "type mismatch in call argument!");
1033
John McCall413ebdb2011-03-11 20:59:21 +00001034 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001035 }
1036
1037 // Either we've emitted all the call args, or we have a call to a
1038 // variadic function.
John McCallc2f3e7f2011-03-07 03:12:35 +00001039 assert((placementArg == E->placement_arg_end() ||
1040 allocatorType->isVariadic()) &&
1041 "Extra arguments to non-variadic function!");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001042
1043 // If we still have any arguments, emit them using the type of the argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001044 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1045 placementArg != placementArgsEnd; ++placementArg) {
John McCall413ebdb2011-03-11 20:59:21 +00001046 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001047 }
1048
John McCallb1c98a32011-05-16 01:05:12 +00001049 // Emit the allocation call. If the allocator is a global placement
1050 // operator, just "inline" it directly.
1051 RValue RV;
1052 if (allocator->isReservedGlobalPlacementOperator()) {
1053 assert(allocatorArgs.size() == 2);
1054 RV = allocatorArgs[1].RV;
1055 // TODO: kill any unnecessary computations done for the size
1056 // argument.
1057 } else {
1058 RV = EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocatorType),
1059 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1060 allocatorArgs, allocator);
1061 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001062
John McCallc2f3e7f2011-03-07 03:12:35 +00001063 // Emit a null check on the allocation result if the allocation
1064 // function is allowed to return null (because it has a non-throwing
1065 // exception spec; for this part, we inline
1066 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1067 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001068 bool nullCheck = allocatorType->isNothrow(getContext()) &&
John McCallf85e1932011-06-15 23:02:42 +00001069 !(allocType.isPODType(getContext()) && !E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001070
John McCallc2f3e7f2011-03-07 03:12:35 +00001071 llvm::BasicBlock *nullCheckBB = 0;
1072 llvm::BasicBlock *contBB = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001073
John McCallc2f3e7f2011-03-07 03:12:35 +00001074 llvm::Value *allocation = RV.getScalarVal();
1075 unsigned AS =
1076 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001077
John McCalla7f633f2011-03-07 01:52:56 +00001078 // The null-check means that the initializer is conditionally
1079 // evaluated.
1080 ConditionalEvaluation conditional(*this);
1081
John McCallc2f3e7f2011-03-07 03:12:35 +00001082 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001083 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001084
1085 nullCheckBB = Builder.GetInsertBlock();
1086 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1087 contBB = createBasicBlock("new.cont");
1088
1089 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1090 Builder.CreateCondBr(isNull, contBB, notNullBB);
1091 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001092 }
Ken Dyckcaf647c2010-01-26 19:44:24 +00001093
John McCallc2f3e7f2011-03-07 03:12:35 +00001094 assert((allocSize == allocSizeWithoutCookie) ==
John McCall1e7fe752010-09-02 09:58:18 +00001095 CalculateCookiePadding(*this, E).isZero());
John McCallc2f3e7f2011-03-07 03:12:35 +00001096 if (allocSize != allocSizeWithoutCookie) {
John McCall1e7fe752010-09-02 09:58:18 +00001097 assert(E->isArray());
John McCallc2f3e7f2011-03-07 03:12:35 +00001098 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1099 numElements,
1100 E, allocType);
John McCall1e7fe752010-09-02 09:58:18 +00001101 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001102
John McCall7d8647f2010-09-14 07:57:04 +00001103 // If there's an operator delete, enter a cleanup to call it if an
1104 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001105 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCallb1c98a32011-05-16 01:05:12 +00001106 if (E->getOperatorDelete() &&
1107 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001108 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1109 operatorDeleteCleanup = EHStack.stable_begin();
John McCall7d8647f2010-09-14 07:57:04 +00001110 }
1111
Chris Lattner2acc6e32011-07-18 04:24:23 +00001112 llvm::Type *elementPtrTy
John McCallc2f3e7f2011-03-07 03:12:35 +00001113 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1114 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001115
John McCall1e7fe752010-09-02 09:58:18 +00001116 if (E->isArray()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001117 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001118
1119 // NewPtr is a pointer to the base element type. If we're
1120 // allocating an array of arrays, we'll need to cast back to the
1121 // array pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001122 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCallc2f3e7f2011-03-07 03:12:35 +00001123 if (result->getType() != resultType)
1124 result = Builder.CreateBitCast(result, resultType);
John McCall1e7fe752010-09-02 09:58:18 +00001125 } else {
John McCallc2f3e7f2011-03-07 03:12:35 +00001126 EmitNewInitializer(*this, E, result, numElements, allocSizeWithoutCookie);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001127 }
John McCall7d8647f2010-09-14 07:57:04 +00001128
1129 // Deactivate the 'operator delete' cleanup if we finished
1130 // initialization.
John McCallc2f3e7f2011-03-07 03:12:35 +00001131 if (operatorDeleteCleanup.isValid())
1132 DeactivateCleanupBlock(operatorDeleteCleanup);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001133
John McCallc2f3e7f2011-03-07 03:12:35 +00001134 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001135 conditional.end(*this);
1136
John McCallc2f3e7f2011-03-07 03:12:35 +00001137 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1138 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001139
Jay Foadbbf3bac2011-03-30 11:28:58 +00001140 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001141 PHI->addIncoming(result, notNullBB);
1142 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1143 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001144
John McCallc2f3e7f2011-03-07 03:12:35 +00001145 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001146 }
John McCall1e7fe752010-09-02 09:58:18 +00001147
John McCallc2f3e7f2011-03-07 03:12:35 +00001148 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001149}
1150
Eli Friedman5fe05982009-11-18 00:50:08 +00001151void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1152 llvm::Value *Ptr,
1153 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001154 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1155
Eli Friedman5fe05982009-11-18 00:50:08 +00001156 const FunctionProtoType *DeleteFTy =
1157 DeleteFD->getType()->getAs<FunctionProtoType>();
1158
1159 CallArgList DeleteArgs;
1160
Anders Carlsson871d0782009-12-13 20:04:38 +00001161 // Check if we need to pass the size to the delete operator.
1162 llvm::Value *Size = 0;
1163 QualType SizeTy;
1164 if (DeleteFTy->getNumArgs() == 2) {
1165 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001166 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1167 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1168 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001169 }
1170
Eli Friedman5fe05982009-11-18 00:50:08 +00001171 QualType ArgTy = DeleteFTy->getArgType(0);
1172 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001173 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001174
Anders Carlsson871d0782009-12-13 20:04:38 +00001175 if (Size)
Eli Friedman04c9a492011-05-02 17:57:46 +00001176 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001177
1178 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001179 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001180 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +00001181 DeleteArgs, DeleteFD);
1182}
1183
John McCall1e7fe752010-09-02 09:58:18 +00001184namespace {
1185 /// Calls the given 'operator delete' on a single object.
1186 struct CallObjectDelete : EHScopeStack::Cleanup {
1187 llvm::Value *Ptr;
1188 const FunctionDecl *OperatorDelete;
1189 QualType ElementType;
1190
1191 CallObjectDelete(llvm::Value *Ptr,
1192 const FunctionDecl *OperatorDelete,
1193 QualType ElementType)
1194 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1195
John McCallad346f42011-07-12 20:27:29 +00001196 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001197 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1198 }
1199 };
1200}
1201
1202/// Emit the code for deleting a single object.
1203static void EmitObjectDelete(CodeGenFunction &CGF,
1204 const FunctionDecl *OperatorDelete,
1205 llvm::Value *Ptr,
Douglas Gregora8b20f72011-07-13 00:54:47 +00001206 QualType ElementType,
1207 bool UseGlobalDelete) {
John McCall1e7fe752010-09-02 09:58:18 +00001208 // Find the destructor for the type, if applicable. If the
1209 // destructor is virtual, we'll just emit the vcall and return.
1210 const CXXDestructorDecl *Dtor = 0;
1211 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1212 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanaebab722011-08-02 18:05:30 +00001213 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall1e7fe752010-09-02 09:58:18 +00001214 Dtor = RD->getDestructor();
1215
1216 if (Dtor->isVirtual()) {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001217 if (UseGlobalDelete) {
1218 // If we're supposed to call the global delete, make sure we do so
1219 // even if the destructor throws.
1220 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1221 Ptr, OperatorDelete,
1222 ElementType);
1223 }
1224
Chris Lattner2acc6e32011-07-18 04:24:23 +00001225 llvm::Type *Ty =
John McCallfc400282010-09-03 01:26:39 +00001226 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1227 Dtor_Complete),
John McCall1e7fe752010-09-02 09:58:18 +00001228 /*isVariadic=*/false);
1229
1230 llvm::Value *Callee
Douglas Gregora8b20f72011-07-13 00:54:47 +00001231 = CGF.BuildVirtualCall(Dtor,
1232 UseGlobalDelete? Dtor_Complete : Dtor_Deleting,
1233 Ptr, Ty);
John McCall1e7fe752010-09-02 09:58:18 +00001234 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1235 0, 0);
1236
Douglas Gregora8b20f72011-07-13 00:54:47 +00001237 if (UseGlobalDelete) {
1238 CGF.PopCleanupBlock();
1239 }
1240
John McCall1e7fe752010-09-02 09:58:18 +00001241 return;
1242 }
1243 }
1244 }
1245
1246 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001247 // This doesn't have to a conditional cleanup because we're going
1248 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001249 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1250 Ptr, OperatorDelete, ElementType);
1251
1252 if (Dtor)
1253 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1254 /*ForVirtualBase=*/false, Ptr);
John McCallf85e1932011-06-15 23:02:42 +00001255 else if (CGF.getLangOptions().ObjCAutoRefCount &&
1256 ElementType->isObjCLifetimeType()) {
1257 switch (ElementType.getObjCLifetime()) {
1258 case Qualifiers::OCL_None:
1259 case Qualifiers::OCL_ExplicitNone:
1260 case Qualifiers::OCL_Autoreleasing:
1261 break;
John McCall1e7fe752010-09-02 09:58:18 +00001262
John McCallf85e1932011-06-15 23:02:42 +00001263 case Qualifiers::OCL_Strong: {
1264 // Load the pointer value.
1265 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1266 ElementType.isVolatileQualified());
1267
1268 CGF.EmitARCRelease(PtrValue, /*precise*/ true);
1269 break;
1270 }
1271
1272 case Qualifiers::OCL_Weak:
1273 CGF.EmitARCDestroyWeak(Ptr);
1274 break;
1275 }
1276 }
1277
John McCall1e7fe752010-09-02 09:58:18 +00001278 CGF.PopCleanupBlock();
1279}
1280
1281namespace {
1282 /// Calls the given 'operator delete' on an array of objects.
1283 struct CallArrayDelete : EHScopeStack::Cleanup {
1284 llvm::Value *Ptr;
1285 const FunctionDecl *OperatorDelete;
1286 llvm::Value *NumElements;
1287 QualType ElementType;
1288 CharUnits CookieSize;
1289
1290 CallArrayDelete(llvm::Value *Ptr,
1291 const FunctionDecl *OperatorDelete,
1292 llvm::Value *NumElements,
1293 QualType ElementType,
1294 CharUnits CookieSize)
1295 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1296 ElementType(ElementType), CookieSize(CookieSize) {}
1297
John McCallad346f42011-07-12 20:27:29 +00001298 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001299 const FunctionProtoType *DeleteFTy =
1300 OperatorDelete->getType()->getAs<FunctionProtoType>();
1301 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1302
1303 CallArgList Args;
1304
1305 // Pass the pointer as the first argument.
1306 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1307 llvm::Value *DeletePtr
1308 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001309 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall1e7fe752010-09-02 09:58:18 +00001310
1311 // Pass the original requested size as the second argument.
1312 if (DeleteFTy->getNumArgs() == 2) {
1313 QualType size_t = DeleteFTy->getArgType(1);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001314 llvm::IntegerType *SizeTy
John McCall1e7fe752010-09-02 09:58:18 +00001315 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1316
1317 CharUnits ElementTypeSize =
1318 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1319
1320 // The size of an element, multiplied by the number of elements.
1321 llvm::Value *Size
1322 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1323 Size = CGF.Builder.CreateMul(Size, NumElements);
1324
1325 // Plus the size of the cookie if applicable.
1326 if (!CookieSize.isZero()) {
1327 llvm::Value *CookieSizeV
1328 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1329 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1330 }
1331
Eli Friedman04c9a492011-05-02 17:57:46 +00001332 Args.add(RValue::get(Size), size_t);
John McCall1e7fe752010-09-02 09:58:18 +00001333 }
1334
1335 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001336 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
John McCall1e7fe752010-09-02 09:58:18 +00001337 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1338 ReturnValueSlot(), Args, OperatorDelete);
1339 }
1340 };
1341}
1342
1343/// Emit the code for deleting an array of objects.
1344static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001345 const CXXDeleteExpr *E,
John McCall7cfd76c2011-07-13 01:41:37 +00001346 llvm::Value *deletedPtr,
1347 QualType elementType) {
1348 llvm::Value *numElements = 0;
1349 llvm::Value *allocatedPtr = 0;
1350 CharUnits cookieSize;
1351 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1352 numElements, allocatedPtr, cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001353
John McCall7cfd76c2011-07-13 01:41:37 +00001354 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall1e7fe752010-09-02 09:58:18 +00001355
1356 // Make sure that we call delete even if one of the dtors throws.
John McCall7cfd76c2011-07-13 01:41:37 +00001357 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001358 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCall7cfd76c2011-07-13 01:41:37 +00001359 allocatedPtr, operatorDelete,
1360 numElements, elementType,
1361 cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001362
John McCall7cfd76c2011-07-13 01:41:37 +00001363 // Destroy the elements.
1364 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1365 assert(numElements && "no element count for a type with a destructor!");
1366
John McCall7cfd76c2011-07-13 01:41:37 +00001367 llvm::Value *arrayEnd =
1368 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCallfbf780a2011-07-13 08:09:46 +00001369
1370 // Note that it is legal to allocate a zero-length array, and we
1371 // can never fold the check away because the length should always
1372 // come from a cookie.
John McCall7cfd76c2011-07-13 01:41:37 +00001373 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1374 CGF.getDestroyer(dtorKind),
John McCallfbf780a2011-07-13 08:09:46 +00001375 /*checkZeroLength*/ true,
John McCall7cfd76c2011-07-13 01:41:37 +00001376 CGF.needsEHCleanup(dtorKind));
John McCall1e7fe752010-09-02 09:58:18 +00001377 }
1378
John McCall7cfd76c2011-07-13 01:41:37 +00001379 // Pop the cleanup block.
John McCall1e7fe752010-09-02 09:58:18 +00001380 CGF.PopCleanupBlock();
1381}
1382
Anders Carlsson16d81b82009-09-22 22:53:17 +00001383void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian72c21532009-11-13 19:27:47 +00001384
Douglas Gregor90916562009-09-29 18:16:17 +00001385 // Get at the argument before we performed the implicit conversion
1386 // to void*.
1387 const Expr *Arg = E->getArgument();
1388 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00001389 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregor90916562009-09-29 18:16:17 +00001390 ICE->getType()->isVoidPointerType())
1391 Arg = ICE->getSubExpr();
Douglas Gregord69dd782009-10-01 05:49:51 +00001392 else
1393 break;
Douglas Gregor90916562009-09-29 18:16:17 +00001394 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001395
Douglas Gregor90916562009-09-29 18:16:17 +00001396 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001397
1398 // Null check the pointer.
1399 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1400 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1401
Anders Carlssonb9241242011-04-11 00:30:07 +00001402 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001403
1404 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1405 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001406
John McCall1e7fe752010-09-02 09:58:18 +00001407 // We might be deleting a pointer to array. If so, GEP down to the
1408 // first non-array element.
1409 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1410 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1411 if (DeleteTy->isConstantArrayType()) {
1412 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001413 SmallVector<llvm::Value*,8> GEP;
John McCall1e7fe752010-09-02 09:58:18 +00001414
1415 GEP.push_back(Zero); // point at the outermost array
1416
1417 // For each layer of array type we're pointing at:
1418 while (const ConstantArrayType *Arr
1419 = getContext().getAsConstantArrayType(DeleteTy)) {
1420 // 1. Unpeel the array type.
1421 DeleteTy = Arr->getElementType();
1422
1423 // 2. GEP to the first element of the array.
1424 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001425 }
John McCall1e7fe752010-09-02 09:58:18 +00001426
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001427 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001428 }
1429
Douglas Gregoreede61a2010-09-02 17:38:50 +00001430 assert(ConvertTypeForMem(DeleteTy) ==
1431 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001432
1433 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001434 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001435 } else {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001436 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1437 E->isGlobalDelete());
John McCall1e7fe752010-09-02 09:58:18 +00001438 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001439
Anders Carlsson16d81b82009-09-22 22:53:17 +00001440 EmitBlock(DeleteEnd);
1441}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001442
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001443static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1444 // void __cxa_bad_typeid();
1445
Chris Lattner2acc6e32011-07-18 04:24:23 +00001446 llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1447 llvm::FunctionType *FTy =
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001448 llvm::FunctionType::get(VoidTy, false);
1449
1450 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1451}
1452
1453static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001454 llvm::Value *Fn = getBadTypeidFn(CGF);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001455 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001456 CGF.Builder.CreateUnreachable();
1457}
1458
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001459static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1460 const Expr *E,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001461 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001462 // Get the vtable pointer.
1463 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1464
1465 // C++ [expr.typeid]p2:
1466 // If the glvalue expression is obtained by applying the unary * operator to
1467 // a pointer and the pointer is a null pointer value, the typeid expression
1468 // throws the std::bad_typeid exception.
1469 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1470 if (UO->getOpcode() == UO_Deref) {
1471 llvm::BasicBlock *BadTypeidBlock =
1472 CGF.createBasicBlock("typeid.bad_typeid");
1473 llvm::BasicBlock *EndBlock =
1474 CGF.createBasicBlock("typeid.end");
1475
1476 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1477 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1478
1479 CGF.EmitBlock(BadTypeidBlock);
1480 EmitBadTypeidCall(CGF);
1481 CGF.EmitBlock(EndBlock);
1482 }
1483 }
1484
1485 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1486 StdTypeInfoPtrTy->getPointerTo());
1487
1488 // Load the type info.
1489 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1490 return CGF.Builder.CreateLoad(Value);
1491}
1492
John McCall3ad32c82011-01-28 08:37:24 +00001493llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001494 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001495 ConvertType(E->getType())->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001496
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001497 if (E->isTypeOperand()) {
1498 llvm::Constant *TypeInfo =
1499 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001500 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001501 }
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001502
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001503 // C++ [expr.typeid]p2:
1504 // When typeid is applied to a glvalue expression whose type is a
1505 // polymorphic class type, the result refers to a std::type_info object
1506 // representing the type of the most derived object (that is, the dynamic
1507 // type) to which the glvalue refers.
1508 if (E->getExprOperand()->isGLValue()) {
1509 if (const RecordType *RT =
1510 E->getExprOperand()->getType()->getAs<RecordType>()) {
1511 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1512 if (RD->isPolymorphic())
1513 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1514 StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001515 }
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001516 }
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001517
1518 QualType OperandTy = E->getExprOperand()->getType();
1519 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1520 StdTypeInfoPtrTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001521}
Mike Stumpc849c052009-11-16 06:50:58 +00001522
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001523static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1524 // void *__dynamic_cast(const void *sub,
1525 // const abi::__class_type_info *src,
1526 // const abi::__class_type_info *dst,
1527 // std::ptrdiff_t src2dst_offset);
1528
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001529 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
1530 llvm::Type *PtrDiffTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001531 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1532
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001533 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001534
Chris Lattner2acc6e32011-07-18 04:24:23 +00001535 llvm::FunctionType *FTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001536 llvm::FunctionType::get(Int8PtrTy, Args, false);
1537
1538 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1539}
1540
1541static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1542 // void __cxa_bad_cast();
1543
Chris Lattner2acc6e32011-07-18 04:24:23 +00001544 llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1545 llvm::FunctionType *FTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001546 llvm::FunctionType::get(VoidTy, false);
1547
1548 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1549}
1550
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001551static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001552 llvm::Value *Fn = getBadCastFn(CGF);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001553 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001554 CGF.Builder.CreateUnreachable();
1555}
1556
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001557static llvm::Value *
1558EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1559 QualType SrcTy, QualType DestTy,
1560 llvm::BasicBlock *CastEnd) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001561 llvm::Type *PtrDiffLTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001562 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001563 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001564
1565 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1566 if (PTy->getPointeeType()->isVoidType()) {
1567 // C++ [expr.dynamic.cast]p7:
1568 // If T is "pointer to cv void," then the result is a pointer to the
1569 // most derived object pointed to by v.
1570
1571 // Get the vtable pointer.
1572 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1573
1574 // Get the offset-to-top from the vtable.
1575 llvm::Value *OffsetToTop =
1576 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1577 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1578
1579 // Finally, add the offset to the pointer.
1580 Value = CGF.EmitCastToVoidPtr(Value);
1581 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1582
1583 return CGF.Builder.CreateBitCast(Value, DestLTy);
1584 }
1585 }
1586
1587 QualType SrcRecordTy;
1588 QualType DestRecordTy;
1589
1590 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1591 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1592 DestRecordTy = DestPTy->getPointeeType();
1593 } else {
1594 SrcRecordTy = SrcTy;
1595 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1596 }
1597
1598 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1599 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1600
1601 llvm::Value *SrcRTTI =
1602 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1603 llvm::Value *DestRTTI =
1604 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1605
1606 // FIXME: Actually compute a hint here.
1607 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1608
1609 // Emit the call to __dynamic_cast.
1610 Value = CGF.EmitCastToVoidPtr(Value);
1611 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1612 SrcRTTI, DestRTTI, OffsetHint);
1613 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1614
1615 /// C++ [expr.dynamic.cast]p9:
1616 /// A failed cast to reference type throws std::bad_cast
1617 if (DestTy->isReferenceType()) {
1618 llvm::BasicBlock *BadCastBlock =
1619 CGF.createBasicBlock("dynamic_cast.bad_cast");
1620
1621 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1622 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1623
1624 CGF.EmitBlock(BadCastBlock);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001625 EmitBadCastCall(CGF);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001626 }
1627
1628 return Value;
1629}
1630
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001631static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1632 QualType DestTy) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001633 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001634 if (DestTy->isPointerType())
1635 return llvm::Constant::getNullValue(DestLTy);
1636
1637 /// C++ [expr.dynamic.cast]p9:
1638 /// A failed cast to reference type throws std::bad_cast
1639 EmitBadCastCall(CGF);
1640
1641 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1642 return llvm::UndefValue::get(DestLTy);
1643}
1644
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001645llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001646 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001647 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001648
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001649 if (DCE->isAlwaysNull())
1650 return EmitDynamicCastToNull(*this, DestTy);
1651
1652 QualType SrcTy = DCE->getSubExpr()->getType();
1653
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001654 // C++ [expr.dynamic.cast]p4:
1655 // If the value of v is a null pointer value in the pointer case, the result
1656 // is the null pointer value of type T.
1657 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001658
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001659 llvm::BasicBlock *CastNull = 0;
1660 llvm::BasicBlock *CastNotNull = 0;
1661 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001662
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001663 if (ShouldNullCheckSrcValue) {
1664 CastNull = createBasicBlock("dynamic_cast.null");
1665 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1666
1667 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1668 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1669 EmitBlock(CastNotNull);
Mike Stumpc849c052009-11-16 06:50:58 +00001670 }
1671
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001672 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1673
1674 if (ShouldNullCheckSrcValue) {
1675 EmitBranch(CastEnd);
1676
1677 EmitBlock(CastNull);
1678 EmitBranch(CastEnd);
1679 }
1680
1681 EmitBlock(CastEnd);
1682
1683 if (ShouldNullCheckSrcValue) {
1684 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1685 PHI->addIncoming(Value, CastNotNull);
1686 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1687
1688 Value = PHI;
1689 }
1690
1691 return Value;
Mike Stumpc849c052009-11-16 06:50:58 +00001692}