blob: 8c05b466dc6c37ee2ff05ce0fcfc0d2b456e8059 [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"
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000016#include "CGCUDARuntime.h"
John McCall4c40d982010-08-31 07:33:07 +000017#include "CGCXXABI.h"
Fariborz Jahanian842ddd02010-05-20 21:38:57 +000018#include "CGObjCRuntime.h"
Devang Patelc69e1cf2010-09-30 19:05:55 +000019#include "CGDebugInfo.h"
Chris Lattner6c552c12010-07-20 20:19:24 +000020#include "llvm/Intrinsics.h"
Anders Carlssonad3692bb2011-04-13 02:35:36 +000021#include "llvm/Support/CallSite.h"
22
Anders Carlsson16d81b82009-09-22 22:53:17 +000023using namespace clang;
24using namespace CodeGen;
25
Anders Carlsson3b5ad222010-01-01 20:29:01 +000026RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
27 llvm::Value *Callee,
28 ReturnValueSlot ReturnValue,
29 llvm::Value *This,
Anders Carlssonc997d422010-01-02 01:01:18 +000030 llvm::Value *VTT,
Anders Carlsson3b5ad222010-01-01 20:29:01 +000031 CallExpr::const_arg_iterator ArgBeg,
32 CallExpr::const_arg_iterator ArgEnd) {
33 assert(MD->isInstance() &&
34 "Trying to emit a member call expr on a static method!");
35
36 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
37
38 CallArgList Args;
39
40 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +000041 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000042
Anders Carlssonc997d422010-01-02 01:01:18 +000043 // If there is a VTT parameter, emit it.
44 if (VTT) {
45 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +000046 Args.add(RValue::get(VTT), T);
Anders Carlssonc997d422010-01-02 01:01:18 +000047 }
48
Anders Carlsson3b5ad222010-01-01 20:29:01 +000049 // And the rest of the call args
50 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
51
John McCall04a67a62010-02-05 21:31:56 +000052 QualType ResultType = FPT->getResultType();
Tilmann Scheller9c6082f2011-03-02 21:36:49 +000053 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
54 FPT->getExtInfo()),
Rafael Espindola264ba482010-03-30 20:24:48 +000055 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000056}
57
Anders Carlsson1679f5a2011-01-29 03:52:01 +000058static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
Anders Carlsson268ab8c2011-01-29 05:04:11 +000059 const Expr *E = Base;
60
61 while (true) {
62 E = E->IgnoreParens();
63 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
64 if (CE->getCastKind() == CK_DerivedToBase ||
65 CE->getCastKind() == CK_UncheckedDerivedToBase ||
66 CE->getCastKind() == CK_NoOp) {
67 E = CE->getSubExpr();
68 continue;
69 }
70 }
71
72 break;
73 }
74
75 QualType DerivedType = E->getType();
Anders Carlsson1679f5a2011-01-29 03:52:01 +000076 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
77 DerivedType = PTy->getPointeeType();
78
79 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
80}
81
Anders Carlssoncd0b32e2011-04-10 18:20:53 +000082// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
83// quite what we want.
84static const Expr *skipNoOpCastsAndParens(const Expr *E) {
85 while (true) {
86 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
87 E = PE->getSubExpr();
88 continue;
89 }
90
91 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
92 if (CE->getCastKind() == CK_NoOp) {
93 E = CE->getSubExpr();
94 continue;
95 }
96 }
97 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
98 if (UO->getOpcode() == UO_Extension) {
99 E = UO->getSubExpr();
100 continue;
101 }
102 }
103 return E;
104 }
105}
106
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000107/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
108/// expr can be devirtualized.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000109static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
110 const Expr *Base,
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000111 const CXXMethodDecl *MD) {
112
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000113 // When building with -fapple-kext, all calls must go through the vtable since
114 // the kernel linker can do runtime patching of vtables.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000115 if (Context.getLangOptions().AppleKext)
116 return false;
117
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000118 // If the most derived class is marked final, we know that no subclass can
119 // override this member function and so we can devirtualize it. For example:
120 //
121 // struct A { virtual void f(); }
122 // struct B final : A { };
123 //
124 // void f(B *b) {
125 // b->f();
126 // }
127 //
128 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
129 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
130 return true;
131
Anders Carlssonf89e0422011-01-23 21:07:30 +0000132 // If the member function is marked 'final', we know that it can't be
Anders Carlssond66f4282010-10-27 13:34:43 +0000133 // overridden and can therefore devirtualize it.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000134 if (MD->hasAttr<FinalAttr>())
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000135 return true;
Anders Carlssond66f4282010-10-27 13:34:43 +0000136
Anders Carlssonf89e0422011-01-23 21:07:30 +0000137 // Similarly, if the class itself is marked 'final' it can't be overridden
138 // and we can therefore devirtualize the member function call.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000139 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssond66f4282010-10-27 13:34:43 +0000140 return true;
141
Anders Carlssoncd0b32e2011-04-10 18:20:53 +0000142 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000143 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
144 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
145 // This is a record decl. We know the type and can devirtualize it.
146 return VD->getType()->isRecordType();
147 }
148
149 return false;
150 }
151
152 // We can always devirtualize calls on temporary object expressions.
Eli Friedman6997aae2010-01-31 20:58:15 +0000153 if (isa<CXXConstructExpr>(Base))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000154 return true;
155
156 // And calls on bound temporaries.
157 if (isa<CXXBindTemporaryExpr>(Base))
158 return true;
159
160 // Check if this is a call expr that returns a record type.
161 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
162 return CE->getCallReturnType()->isRecordType();
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000163
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000164 // We can't devirtualize the call.
165 return false;
166}
167
Francois Pichetdbee3412011-01-18 05:04:39 +0000168// Note: This function also emit constructor calls to support a MSVC
169// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000170RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
171 ReturnValueSlot ReturnValue) {
John McCall379b5152011-04-11 07:02:50 +0000172 const Expr *callee = CE->getCallee()->IgnoreParens();
173
174 if (isa<BinaryOperator>(callee))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000175 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall379b5152011-04-11 07:02:50 +0000176
177 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000178 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
179
Devang Patelc69e1cf2010-09-30 19:05:55 +0000180 CGDebugInfo *DI = getDebugInfo();
Devang Patel68020272010-10-22 18:56:27 +0000181 if (DI && CGM.getCodeGenOpts().LimitDebugInfo
182 && !isa<CallExpr>(ME->getBase())) {
Devang Patelc69e1cf2010-09-30 19:05:55 +0000183 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
184 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
185 DI->getOrCreateRecordType(PTy->getPointeeType(),
186 MD->getParent()->getLocation());
187 }
188 }
189
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000190 if (MD->isStatic()) {
191 // The method is static, emit it as we would a regular call.
192 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
193 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
194 ReturnValue, CE->arg_begin(), CE->arg_end());
195 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000196
John McCallfc400282010-09-03 01:26:39 +0000197 // Compute the object pointer.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000198 llvm::Value *This;
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000199 if (ME->isArrow())
200 This = EmitScalarExpr(ME->getBase());
John McCall0e800c92010-12-04 08:14:53 +0000201 else
202 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000203
John McCallfc400282010-09-03 01:26:39 +0000204 if (MD->isTrivial()) {
205 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichetdbee3412011-01-18 05:04:39 +0000206 if (isa<CXXConstructorDecl>(MD) &&
207 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
208 return RValue::get(0);
John McCallfc400282010-09-03 01:26:39 +0000209
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000210 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
211 // We don't like to generate the trivial copy/move assignment operator
212 // when it isn't necessary; just produce the proper effect here.
Francois Pichetdbee3412011-01-18 05:04:39 +0000213 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
214 EmitAggregateCopy(This, RHS, CE->getType());
215 return RValue::get(This);
216 }
217
218 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000219 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
220 // Trivial move and copy ctor are the same.
Francois Pichetdbee3412011-01-18 05:04:39 +0000221 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
222 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
223 CE->arg_begin(), CE->arg_end());
224 return RValue::get(This);
225 }
226 llvm_unreachable("unknown trivial member function");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000227 }
228
John McCallfc400282010-09-03 01:26:39 +0000229 // Compute the function type we're calling.
Francois Pichetdbee3412011-01-18 05:04:39 +0000230 const CGFunctionInfo *FInfo = 0;
231 if (isa<CXXDestructorDecl>(MD))
232 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
233 Dtor_Complete);
234 else if (isa<CXXConstructorDecl>(MD))
235 FInfo = &CGM.getTypes().getFunctionInfo(cast<CXXConstructorDecl>(MD),
236 Ctor_Complete);
237 else
238 FInfo = &CGM.getTypes().getFunctionInfo(MD);
John McCallfc400282010-09-03 01:26:39 +0000239
240 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000241 llvm::Type *Ty
Francois Pichetdbee3412011-01-18 05:04:39 +0000242 = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
John McCallfc400282010-09-03 01:26:39 +0000243
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000244 // C++ [class.virtual]p12:
245 // Explicit qualification with the scope operator (5.1) suppresses the
246 // virtual call mechanism.
247 //
248 // We also don't emit a virtual call if the base expression has a record type
249 // because then we know what the type is.
Fariborz Jahanian27262672011-01-20 17:19:02 +0000250 bool UseVirtualCall;
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000251 UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
252 && !canDevirtualizeMemberFunctionCalls(getContext(),
253 ME->getBase(), MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000254 llvm::Value *Callee;
John McCallfc400282010-09-03 01:26:39 +0000255 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
256 if (UseVirtualCall) {
257 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000258 } else {
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000259 if (getContext().getLangOptions().AppleKext &&
260 MD->isVirtual() &&
261 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000262 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000263 else
264 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000265 }
Francois Pichetdbee3412011-01-18 05:04:39 +0000266 } else if (const CXXConstructorDecl *Ctor =
267 dyn_cast<CXXConstructorDecl>(MD)) {
268 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000269 } else if (UseVirtualCall) {
Fariborz Jahanian27262672011-01-20 17:19:02 +0000270 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000271 } else {
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000272 if (getContext().getLangOptions().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000273 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000274 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000275 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000276 else
277 Callee = CGM.GetAddrOfFunction(MD, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000278 }
279
Anders Carlssonc997d422010-01-02 01:01:18 +0000280 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000281 CE->arg_begin(), CE->arg_end());
282}
283
284RValue
285CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
286 ReturnValueSlot ReturnValue) {
287 const BinaryOperator *BO =
288 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
289 const Expr *BaseExpr = BO->getLHS();
290 const Expr *MemFnExpr = BO->getRHS();
291
292 const MemberPointerType *MPT =
John McCall864c0412011-04-26 20:42:42 +0000293 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000294
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000295 const FunctionProtoType *FPT =
John McCall864c0412011-04-26 20:42:42 +0000296 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000297 const CXXRecordDecl *RD =
298 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
299
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000300 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000301 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000302
303 // Emit the 'this' pointer.
304 llvm::Value *This;
305
John McCall2de56d12010-08-25 11:45:40 +0000306 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000307 This = EmitScalarExpr(BaseExpr);
308 else
309 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000310
John McCall93d557b2010-08-22 00:05:51 +0000311 // Ask the ABI to load the callee. Note that This is modified.
312 llvm::Value *Callee =
John McCalld16c2cf2011-02-08 08:22:06 +0000313 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000314
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000315 CallArgList Args;
316
317 QualType ThisType =
318 getContext().getPointerType(getContext().getTagDeclType(RD));
319
320 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +0000321 Args.add(RValue::get(This), ThisType);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000322
323 // And the rest of the call args
324 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall864c0412011-04-26 20:42:42 +0000325 return EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000326 ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000327}
328
329RValue
330CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
331 const CXXMethodDecl *MD,
332 ReturnValueSlot ReturnValue) {
333 assert(MD->isInstance() &&
334 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000335 LValue LV = EmitLValue(E->getArg(0));
336 llvm::Value *This = LV.getAddress();
337
Douglas Gregorb2b56582011-09-06 16:26:56 +0000338 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
339 MD->isTrivial()) {
340 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
341 QualType Ty = E->getType();
342 EmitAggregateCopy(This, Src, Ty);
343 return RValue::get(This);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000344 }
345
Anders Carlssona2447e02011-05-08 20:32:23 +0000346 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Anders Carlssonc997d422010-01-02 01:01:18 +0000347 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000348 E->arg_begin() + 1, E->arg_end());
349}
350
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000351RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
352 ReturnValueSlot ReturnValue) {
353 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
354}
355
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000356void
John McCall558d2ab2010-09-15 10:14:12 +0000357CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
358 AggValueSlot Dest) {
359 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000360 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000361
362 // If we require zero initialization before (or instead of) calling the
363 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +0000364 // constructor, emit the zero initialization now, unless destination is
365 // already zeroed.
366 if (E->requiresZeroInitialization() && !Dest.isZeroed())
John McCall558d2ab2010-09-15 10:14:12 +0000367 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor759e41b2010-08-22 16:15:35 +0000368
369 // If this is a call to a trivial default constructor, do nothing.
370 if (CD->isTrivial() && CD->isDefaultConstructor())
371 return;
372
John McCallfc1e6c72010-09-18 00:58:34 +0000373 // Elide the constructor if we're constructing from a temporary.
374 // The temporary check is required because Sema sets this on NRVO
375 // returns.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000376 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000377 assert(getContext().hasSameUnqualifiedType(E->getType(),
378 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000379 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
380 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000381 return;
382 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000383 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000384
John McCallc3c07662011-07-13 06:10:41 +0000385 if (const ConstantArrayType *arrayType
386 = getContext().getAsConstantArrayType(E->getType())) {
387 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000388 E->arg_begin(), E->arg_end());
John McCallc3c07662011-07-13 06:10:41 +0000389 } else {
Cameron Esfahani6bd2f6a2011-05-06 21:28:42 +0000390 CXXCtorType Type = Ctor_Complete;
Sean Huntd49bd552011-05-03 20:19:28 +0000391 bool ForVirtualBase = false;
392
393 switch (E->getConstructionKind()) {
394 case CXXConstructExpr::CK_Delegating:
Sean Hunt059ce0d2011-05-01 07:04:31 +0000395 // We should be emitting a constructor; GlobalDecl will assert this
396 Type = CurGD.getCtorType();
Sean Huntd49bd552011-05-03 20:19:28 +0000397 break;
Sean Hunt059ce0d2011-05-01 07:04:31 +0000398
Sean Huntd49bd552011-05-03 20:19:28 +0000399 case CXXConstructExpr::CK_Complete:
400 Type = Ctor_Complete;
401 break;
402
403 case CXXConstructExpr::CK_VirtualBase:
404 ForVirtualBase = true;
405 // fall-through
406
407 case CXXConstructExpr::CK_NonVirtualBase:
408 Type = Ctor_Base;
409 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000410
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000411 // Call the constructor.
John McCall558d2ab2010-09-15 10:14:12 +0000412 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000413 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000414 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000415}
416
Fariborz Jahanian34999872010-11-13 21:53:34 +0000417void
418CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
419 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000420 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000421 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000422 Exp = E->getSubExpr();
423 assert(isa<CXXConstructExpr>(Exp) &&
424 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
425 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
426 const CXXConstructorDecl *CD = E->getConstructor();
427 RunCleanupsScope Scope(*this);
428
429 // If we require zero initialization before (or instead of) calling the
430 // constructor, as can be the case with a non-user-provided default
431 // constructor, emit the zero initialization now.
432 // FIXME. Do I still need this for a copy ctor synthesis?
433 if (E->requiresZeroInitialization())
434 EmitNullInitialization(Dest, E->getType());
435
Chandler Carruth858a5462010-11-15 13:54:43 +0000436 assert(!getContext().getAsConstantArrayType(E->getType())
437 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000438 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
439 E->arg_begin(), E->arg_end());
440}
441
John McCall1e7fe752010-09-02 09:58:18 +0000442static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
443 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000444 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000445 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000446
John McCallb1c98a32011-05-16 01:05:12 +0000447 // No cookie is required if the operator new[] being used is the
448 // reserved placement operator new[].
449 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCall5172ed92010-08-23 01:17:59 +0000450 return CharUnits::Zero();
451
John McCall6ec278d2011-01-27 09:37:56 +0000452 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000453}
454
John McCall7d166272011-05-15 07:14:44 +0000455static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
456 const CXXNewExpr *e,
457 llvm::Value *&numElements,
458 llvm::Value *&sizeWithoutCookie) {
459 QualType type = e->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000460
John McCall7d166272011-05-15 07:14:44 +0000461 if (!e->isArray()) {
462 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
463 sizeWithoutCookie
464 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
465 return sizeWithoutCookie;
Douglas Gregor59174c02010-07-21 01:10:17 +0000466 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000467
John McCall7d166272011-05-15 07:14:44 +0000468 // The width of size_t.
469 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
470
John McCall1e7fe752010-09-02 09:58:18 +0000471 // Figure out the cookie size.
John McCall7d166272011-05-15 07:14:44 +0000472 llvm::APInt cookieSize(sizeWidth,
473 CalculateCookiePadding(CGF, e).getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000474
Anders Carlssona4d4c012009-09-23 16:07:23 +0000475 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000476 // We multiply the size of all dimensions for NumElements.
477 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall7d166272011-05-15 07:14:44 +0000478 numElements = CGF.EmitScalarExpr(e->getArraySize());
479 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall1e7fe752010-09-02 09:58:18 +0000480
John McCall7d166272011-05-15 07:14:44 +0000481 // The number of elements can be have an arbitrary integer type;
482 // essentially, we need to multiply it by a constant factor, add a
483 // cookie size, and verify that the result is representable as a
484 // size_t. That's just a gloss, though, and it's wrong in one
485 // important way: if the count is negative, it's an error even if
486 // the cookie size would bring the total size >= 0.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000487 bool isSigned
488 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000489 llvm::IntegerType *numElementsType
John McCall7d166272011-05-15 07:14:44 +0000490 = cast<llvm::IntegerType>(numElements->getType());
491 unsigned numElementsWidth = numElementsType->getBitWidth();
492
493 // Compute the constant factor.
494 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000495 while (const ConstantArrayType *CAT
John McCall7d166272011-05-15 07:14:44 +0000496 = CGF.getContext().getAsConstantArrayType(type)) {
497 type = CAT->getElementType();
498 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000499 }
500
John McCall7d166272011-05-15 07:14:44 +0000501 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
502 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
503 typeSizeMultiplier *= arraySizeMultiplier;
504
505 // This will be a size_t.
506 llvm::Value *size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000507
Chris Lattner806941e2010-07-20 21:55:52 +0000508 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
509 // Don't bloat the -O0 code.
John McCall7d166272011-05-15 07:14:44 +0000510 if (llvm::ConstantInt *numElementsC =
511 dyn_cast<llvm::ConstantInt>(numElements)) {
512 const llvm::APInt &count = numElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000513
John McCall7d166272011-05-15 07:14:44 +0000514 bool hasAnyOverflow = false;
John McCall1e7fe752010-09-02 09:58:18 +0000515
John McCall7d166272011-05-15 07:14:44 +0000516 // If 'count' was a negative number, it's an overflow.
517 if (isSigned && count.isNegative())
518 hasAnyOverflow = true;
John McCall1e7fe752010-09-02 09:58:18 +0000519
John McCall7d166272011-05-15 07:14:44 +0000520 // We want to do all this arithmetic in size_t. If numElements is
521 // wider than that, check whether it's already too big, and if so,
522 // overflow.
523 else if (numElementsWidth > sizeWidth &&
524 numElementsWidth - sizeWidth > count.countLeadingZeros())
525 hasAnyOverflow = true;
526
527 // Okay, compute a count at the right width.
528 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
529
530 // Scale numElements by that. This might overflow, but we don't
531 // care because it only overflows if allocationSize does, too, and
532 // if that overflows then we shouldn't use this.
533 numElements = llvm::ConstantInt::get(CGF.SizeTy,
534 adjustedCount * arraySizeMultiplier);
535
536 // Compute the size before cookie, and track whether it overflowed.
537 bool overflow;
538 llvm::APInt allocationSize
539 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
540 hasAnyOverflow |= overflow;
541
542 // Add in the cookie, and check whether it's overflowed.
543 if (cookieSize != 0) {
544 // Save the current size without a cookie. This shouldn't be
545 // used if there was overflow.
546 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
547
548 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
549 hasAnyOverflow |= overflow;
550 }
551
552 // On overflow, produce a -1 so operator new will fail.
553 if (hasAnyOverflow) {
554 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
555 } else {
556 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
557 }
558
559 // Otherwise, we might need to use the overflow intrinsics.
560 } else {
561 // There are up to four conditions we need to test for:
562 // 1) if isSigned, we need to check whether numElements is negative;
563 // 2) if numElementsWidth > sizeWidth, we need to check whether
564 // numElements is larger than something representable in size_t;
565 // 3) we need to compute
566 // sizeWithoutCookie := numElements * typeSizeMultiplier
567 // and check whether it overflows; and
568 // 4) if we need a cookie, we need to compute
569 // size := sizeWithoutCookie + cookieSize
570 // and check whether it overflows.
571
572 llvm::Value *hasOverflow = 0;
573
574 // If numElementsWidth > sizeWidth, then one way or another, we're
575 // going to have to do a comparison for (2), and this happens to
576 // take care of (1), too.
577 if (numElementsWidth > sizeWidth) {
578 llvm::APInt threshold(numElementsWidth, 1);
579 threshold <<= sizeWidth;
580
581 llvm::Value *thresholdV
582 = llvm::ConstantInt::get(numElementsType, threshold);
583
584 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
585 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
586
587 // Otherwise, if we're signed, we want to sext up to size_t.
588 } else if (isSigned) {
589 if (numElementsWidth < sizeWidth)
590 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
591
592 // If there's a non-1 type size multiplier, then we can do the
593 // signedness check at the same time as we do the multiply
594 // because a negative number times anything will cause an
595 // unsigned overflow. Otherwise, we have to do it here.
596 if (typeSizeMultiplier == 1)
597 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
598 llvm::ConstantInt::get(CGF.SizeTy, 0));
599
600 // Otherwise, zext up to size_t if necessary.
601 } else if (numElementsWidth < sizeWidth) {
602 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
603 }
604
605 assert(numElements->getType() == CGF.SizeTy);
606
607 size = numElements;
608
609 // Multiply by the type size if necessary. This multiplier
610 // includes all the factors for nested arrays.
611 //
612 // This step also causes numElements to be scaled up by the
613 // nested-array factor if necessary. Overflow on this computation
614 // can be ignored because the result shouldn't be used if
615 // allocation fails.
616 if (typeSizeMultiplier != 1) {
John McCall7d166272011-05-15 07:14:44 +0000617 llvm::Value *umul_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000618 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000619
620 llvm::Value *tsmV =
621 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
622 llvm::Value *result =
623 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
624
625 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
626 if (hasOverflow)
627 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
628 else
629 hasOverflow = overflowed;
630
631 size = CGF.Builder.CreateExtractValue(result, 0);
632
633 // Also scale up numElements by the array size multiplier.
634 if (arraySizeMultiplier != 1) {
635 // If the base element type size is 1, then we can re-use the
636 // multiply we just did.
637 if (typeSize.isOne()) {
638 assert(arraySizeMultiplier == typeSizeMultiplier);
639 numElements = size;
640
641 // Otherwise we need a separate multiply.
642 } else {
643 llvm::Value *asmV =
644 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
645 numElements = CGF.Builder.CreateMul(numElements, asmV);
646 }
647 }
648 } else {
649 // numElements doesn't need to be scaled.
650 assert(arraySizeMultiplier == 1);
Chris Lattner806941e2010-07-20 21:55:52 +0000651 }
652
John McCall7d166272011-05-15 07:14:44 +0000653 // Add in the cookie size if necessary.
654 if (cookieSize != 0) {
655 sizeWithoutCookie = size;
656
John McCall7d166272011-05-15 07:14:44 +0000657 llvm::Value *uadd_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000658 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000659
660 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
661 llvm::Value *result =
662 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
663
664 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
665 if (hasOverflow)
666 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
667 else
668 hasOverflow = overflowed;
669
670 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall1e7fe752010-09-02 09:58:18 +0000671 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000672
John McCall7d166272011-05-15 07:14:44 +0000673 // If we had any possibility of dynamic overflow, make a select to
674 // overwrite 'size' with an all-ones value, which should cause
675 // operator new to throw.
676 if (hasOverflow)
677 size = CGF.Builder.CreateSelect(hasOverflow,
678 llvm::Constant::getAllOnesValue(CGF.SizeTy),
679 size);
Chris Lattner806941e2010-07-20 21:55:52 +0000680 }
John McCall1e7fe752010-09-02 09:58:18 +0000681
John McCall7d166272011-05-15 07:14:44 +0000682 if (cookieSize == 0)
683 sizeWithoutCookie = size;
John McCall1e7fe752010-09-02 09:58:18 +0000684 else
John McCall7d166272011-05-15 07:14:44 +0000685 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall1e7fe752010-09-02 09:58:18 +0000686
John McCall7d166272011-05-15 07:14:44 +0000687 return size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000688}
689
Fariborz Jahanianef668722010-06-25 18:26:07 +0000690static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
691 llvm::Value *NewPtr) {
Fariborz Jahanianef668722010-06-25 18:26:07 +0000692
693 assert(E->getNumConstructorArgs() == 1 &&
694 "Can only have one argument to initializer of POD type.");
695
696 const Expr *Init = E->getConstructorArg(0);
697 QualType AllocType = E->getAllocatedType();
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000698
699 unsigned Alignment =
700 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
John McCalla07398e2011-06-16 04:16:24 +0000701 if (!CGF.hasAggregateLLVMType(AllocType))
702 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType, Alignment),
703 false);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000704 else if (AllocType->isAnyComplexType())
705 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
706 AllocType.isVolatileQualified());
John McCall558d2ab2010-09-15 10:14:12 +0000707 else {
708 AggValueSlot Slot
John McCall7c2349b2011-08-25 20:40:09 +0000709 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
710 AggValueSlot::IsDestructed,
John McCall44184392011-08-26 07:31:35 +0000711 AggValueSlot::DoesNotNeedGCBarriers,
712 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000713 CGF.EmitAggExpr(Init, Slot);
714 }
Fariborz Jahanianef668722010-06-25 18:26:07 +0000715}
716
717void
718CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000719 QualType elementType,
720 llvm::Value *beginPtr,
721 llvm::Value *numElements) {
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000722 // We have a POD type.
723 if (E->getNumConstructorArgs() == 0)
724 return;
John McCall19705672011-09-15 06:49:18 +0000725
726 // Check if the number of elements is constant.
727 bool checkZero = true;
728 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) {
729 // If it's constant zero, skip the whole loop.
730 if (constNum->isZero()) return;
731
732 checkZero = false;
733 }
734
735 // Find the end of the array, hoisted out of the loop.
736 llvm::Value *endPtr =
737 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
738
739 // Create the continuation block.
740 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end");
741
742 // If we need to check for zero, do so now.
743 if (checkZero) {
744 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty");
745 llvm::Value *isEmpty = Builder.CreateICmpEQ(beginPtr, endPtr,
746 "array.isempty");
747 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
748 EmitBlock(nonEmptyBB);
749 }
750
751 // Enter the loop.
752 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
753 llvm::BasicBlock *loopBB = createBasicBlock("new.loop");
754
755 EmitBlock(loopBB);
756
757 // Set up the current-element phi.
758 llvm::PHINode *curPtr =
759 Builder.CreatePHI(beginPtr->getType(), 2, "array.cur");
760 curPtr->addIncoming(beginPtr, entryBB);
761
762 // Enter a partial-destruction cleanup if necessary.
763 QualType::DestructionKind dtorKind = elementType.isDestructedType();
764 EHScopeStack::stable_iterator cleanup;
765 if (needsEHCleanup(dtorKind)) {
766 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
767 getDestroyer(dtorKind));
768 cleanup = EHStack.stable_begin();
769 }
770
771 // Emit the initializer into this element.
772 StoreAnyExprIntoOneUnit(*this, E, curPtr);
773
774 // Leave the cleanup if we entered one.
775 if (cleanup != EHStack.stable_end())
776 DeactivateCleanupBlock(cleanup);
777
778 // Advance to the next element.
779 llvm::Value *nextPtr = Builder.CreateConstGEP1_32(curPtr, 1, "array.next");
780
781 // Check whether we've gotten to the end of the array and, if so,
782 // exit the loop.
783 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend");
784 Builder.CreateCondBr(isEnd, contBB, loopBB);
785 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock());
786
787 EmitBlock(contBB);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000788}
789
Douglas Gregor59174c02010-07-21 01:10:17 +0000790static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
791 llvm::Value *NewPtr, llvm::Value *Size) {
John McCalld16c2cf2011-02-08 08:22:06 +0000792 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyckfe710082011-01-19 01:58:38 +0000793 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000794 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000795 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000796}
797
Anders Carlssona4d4c012009-09-23 16:07:23 +0000798static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000799 QualType ElementType,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000800 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000801 llvm::Value *NumElements,
802 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000803 if (E->isArray()) {
Anders Carlssone99bdb62010-05-03 15:09:17 +0000804 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000805 bool RequiresZeroInitialization = false;
Sean Hunt023df372011-05-09 18:22:59 +0000806 if (Ctor->getParent()->hasTrivialDefaultConstructor()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000807 // If new expression did not specify value-initialization, then there
808 // is no initialization.
809 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
810 return;
811
John McCall19705672011-09-15 06:49:18 +0000812 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000813 // Optimization: since zero initialization will just set the memory
814 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +0000815 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
Douglas Gregor59174c02010-07-21 01:10:17 +0000816 return;
817 }
818
819 RequiresZeroInitialization = true;
820 }
John McCallc3c07662011-07-13 06:10:41 +0000821
Douglas Gregor59174c02010-07-21 01:10:17 +0000822 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
823 E->constructor_arg_begin(),
824 E->constructor_arg_end(),
825 RequiresZeroInitialization);
Anders Carlssone99bdb62010-05-03 15:09:17 +0000826 return;
Douglas Gregor59174c02010-07-21 01:10:17 +0000827 } else if (E->getNumConstructorArgs() == 1 &&
828 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
829 // Optimization: since zero initialization will just set the memory
830 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +0000831 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
832 return;
Douglas Gregor59174c02010-07-21 01:10:17 +0000833 } else {
John McCall19705672011-09-15 06:49:18 +0000834 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000835 return;
836 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000837 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000838
839 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregored8abf12010-07-08 06:14:04 +0000840 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
841 // direct initialization. C++ [dcl.init]p5 requires that we
842 // zero-initialize storage if there are no user-declared constructors.
843 if (E->hasInitializer() &&
844 !Ctor->getParent()->hasUserDeclaredConstructor() &&
845 !Ctor->getParent()->isEmpty())
John McCall19705672011-09-15 06:49:18 +0000846 CGF.EmitNullInitialization(NewPtr, ElementType);
Douglas Gregored8abf12010-07-08 06:14:04 +0000847
Douglas Gregor84745672010-07-07 23:37:33 +0000848 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
849 NewPtr, E->constructor_arg_begin(),
850 E->constructor_arg_end());
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000851
852 return;
853 }
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000854 // We have a POD type.
855 if (E->getNumConstructorArgs() == 0)
856 return;
857
Fariborz Jahanianef668722010-06-25 18:26:07 +0000858 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000859}
860
John McCall7d8647f2010-09-14 07:57:04 +0000861namespace {
862 /// A cleanup to call the given 'operator delete' function upon
863 /// abnormal exit from a new expression.
864 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
865 size_t NumPlacementArgs;
866 const FunctionDecl *OperatorDelete;
867 llvm::Value *Ptr;
868 llvm::Value *AllocSize;
869
870 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
871
872 public:
873 static size_t getExtraSize(size_t NumPlacementArgs) {
874 return NumPlacementArgs * sizeof(RValue);
875 }
876
877 CallDeleteDuringNew(size_t NumPlacementArgs,
878 const FunctionDecl *OperatorDelete,
879 llvm::Value *Ptr,
880 llvm::Value *AllocSize)
881 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
882 Ptr(Ptr), AllocSize(AllocSize) {}
883
884 void setPlacementArg(unsigned I, RValue Arg) {
885 assert(I < NumPlacementArgs && "index out of range");
886 getPlacementArgs()[I] = Arg;
887 }
888
John McCallad346f42011-07-12 20:27:29 +0000889 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7d8647f2010-09-14 07:57:04 +0000890 const FunctionProtoType *FPT
891 = OperatorDelete->getType()->getAs<FunctionProtoType>();
892 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +0000893 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +0000894
895 CallArgList DeleteArgs;
896
897 // The first argument is always a void*.
898 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +0000899 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000900
901 // A member 'operator delete' can take an extra 'size_t' argument.
902 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman04c9a492011-05-02 17:57:46 +0000903 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000904
905 // Pass the rest of the arguments, which must match exactly.
906 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman04c9a492011-05-02 17:57:46 +0000907 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall7d8647f2010-09-14 07:57:04 +0000908
909 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000910 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall7d8647f2010-09-14 07:57:04 +0000911 CGF.CGM.GetAddrOfFunction(OperatorDelete),
912 ReturnValueSlot(), DeleteArgs, OperatorDelete);
913 }
914 };
John McCall3019c442010-09-17 00:50:28 +0000915
916 /// A cleanup to call the given 'operator delete' function upon
917 /// abnormal exit from a new expression when the new expression is
918 /// conditional.
919 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
920 size_t NumPlacementArgs;
921 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +0000922 DominatingValue<RValue>::saved_type Ptr;
923 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +0000924
John McCall804b8072011-01-28 10:53:53 +0000925 DominatingValue<RValue>::saved_type *getPlacementArgs() {
926 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +0000927 }
928
929 public:
930 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +0000931 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +0000932 }
933
934 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
935 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +0000936 DominatingValue<RValue>::saved_type Ptr,
937 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +0000938 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
939 Ptr(Ptr), AllocSize(AllocSize) {}
940
John McCall804b8072011-01-28 10:53:53 +0000941 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +0000942 assert(I < NumPlacementArgs && "index out of range");
943 getPlacementArgs()[I] = Arg;
944 }
945
John McCallad346f42011-07-12 20:27:29 +0000946 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall3019c442010-09-17 00:50:28 +0000947 const FunctionProtoType *FPT
948 = OperatorDelete->getType()->getAs<FunctionProtoType>();
949 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
950 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
951
952 CallArgList DeleteArgs;
953
954 // The first argument is always a void*.
955 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +0000956 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall3019c442010-09-17 00:50:28 +0000957
958 // A member 'operator delete' can take an extra 'size_t' argument.
959 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +0000960 RValue RV = AllocSize.restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +0000961 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +0000962 }
963
964 // Pass the rest of the arguments, which must match exactly.
965 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +0000966 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +0000967 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +0000968 }
969
970 // Call 'operator delete'.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000971 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
John McCall3019c442010-09-17 00:50:28 +0000972 CGF.CGM.GetAddrOfFunction(OperatorDelete),
973 ReturnValueSlot(), DeleteArgs, OperatorDelete);
974 }
975 };
976}
977
978/// Enter a cleanup to call 'operator delete' if the initializer in a
979/// new-expression throws.
980static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
981 const CXXNewExpr *E,
982 llvm::Value *NewPtr,
983 llvm::Value *AllocSize,
984 const CallArgList &NewArgs) {
985 // If we're not inside a conditional branch, then the cleanup will
986 // dominate and we can do the easier (and more efficient) thing.
987 if (!CGF.isInConditionalBranch()) {
988 CallDeleteDuringNew *Cleanup = CGF.EHStack
989 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
990 E->getNumPlacementArgs(),
991 E->getOperatorDelete(),
992 NewPtr, AllocSize);
993 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanc6d07822011-05-02 18:05:27 +0000994 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall3019c442010-09-17 00:50:28 +0000995
996 return;
997 }
998
999 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +00001000 DominatingValue<RValue>::saved_type SavedNewPtr =
1001 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1002 DominatingValue<RValue>::saved_type SavedAllocSize =
1003 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +00001004
1005 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
1006 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
1007 E->getNumPlacementArgs(),
1008 E->getOperatorDelete(),
1009 SavedNewPtr,
1010 SavedAllocSize);
1011 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +00001012 Cleanup->setPlacementArg(I,
Eli Friedmanc6d07822011-05-02 18:05:27 +00001013 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall3019c442010-09-17 00:50:28 +00001014
1015 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall7d8647f2010-09-14 07:57:04 +00001016}
1017
Anders Carlsson16d81b82009-09-22 22:53:17 +00001018llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001019 // The element type being allocated.
1020 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +00001021
John McCallc2f3e7f2011-03-07 03:12:35 +00001022 // 1. Build a call to the allocation function.
1023 FunctionDecl *allocator = E->getOperatorNew();
1024 const FunctionProtoType *allocatorType =
1025 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001026
John McCallc2f3e7f2011-03-07 03:12:35 +00001027 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001028
1029 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001030 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001031
John McCallc2f3e7f2011-03-07 03:12:35 +00001032 llvm::Value *numElements = 0;
1033 llvm::Value *allocSizeWithoutCookie = 0;
1034 llvm::Value *allocSize =
John McCall7d166272011-05-15 07:14:44 +00001035 EmitCXXNewAllocSize(*this, E, numElements, allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +00001036
Eli Friedman04c9a492011-05-02 17:57:46 +00001037 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001038
1039 // Emit the rest of the arguments.
1040 // FIXME: Ideally, this should just use EmitCallArgs.
John McCallc2f3e7f2011-03-07 03:12:35 +00001041 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001042
1043 // First, use the types from the function type.
1044 // We start at 1 here because the first argument (the allocation size)
1045 // has already been emitted.
John McCallc2f3e7f2011-03-07 03:12:35 +00001046 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1047 ++i, ++placementArg) {
1048 QualType argType = allocatorType->getArgType(i);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001049
John McCallc2f3e7f2011-03-07 03:12:35 +00001050 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1051 placementArg->getType()) &&
Anders Carlsson16d81b82009-09-22 22:53:17 +00001052 "type mismatch in call argument!");
1053
John McCall413ebdb2011-03-11 20:59:21 +00001054 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001055 }
1056
1057 // Either we've emitted all the call args, or we have a call to a
1058 // variadic function.
John McCallc2f3e7f2011-03-07 03:12:35 +00001059 assert((placementArg == E->placement_arg_end() ||
1060 allocatorType->isVariadic()) &&
1061 "Extra arguments to non-variadic function!");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001062
1063 // If we still have any arguments, emit them using the type of the argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001064 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1065 placementArg != placementArgsEnd; ++placementArg) {
John McCall413ebdb2011-03-11 20:59:21 +00001066 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001067 }
1068
John McCallb1c98a32011-05-16 01:05:12 +00001069 // Emit the allocation call. If the allocator is a global placement
1070 // operator, just "inline" it directly.
1071 RValue RV;
1072 if (allocator->isReservedGlobalPlacementOperator()) {
1073 assert(allocatorArgs.size() == 2);
1074 RV = allocatorArgs[1].RV;
1075 // TODO: kill any unnecessary computations done for the size
1076 // argument.
1077 } else {
1078 RV = EmitCall(CGM.getTypes().getFunctionInfo(allocatorArgs, allocatorType),
1079 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1080 allocatorArgs, allocator);
1081 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001082
John McCallc2f3e7f2011-03-07 03:12:35 +00001083 // Emit a null check on the allocation result if the allocation
1084 // function is allowed to return null (because it has a non-throwing
1085 // exception spec; for this part, we inline
1086 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1087 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001088 bool nullCheck = allocatorType->isNothrow(getContext()) &&
John McCallf85e1932011-06-15 23:02:42 +00001089 !(allocType.isPODType(getContext()) && !E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001090
John McCallc2f3e7f2011-03-07 03:12:35 +00001091 llvm::BasicBlock *nullCheckBB = 0;
1092 llvm::BasicBlock *contBB = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001093
John McCallc2f3e7f2011-03-07 03:12:35 +00001094 llvm::Value *allocation = RV.getScalarVal();
1095 unsigned AS =
1096 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001097
John McCalla7f633f2011-03-07 01:52:56 +00001098 // The null-check means that the initializer is conditionally
1099 // evaluated.
1100 ConditionalEvaluation conditional(*this);
1101
John McCallc2f3e7f2011-03-07 03:12:35 +00001102 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001103 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001104
1105 nullCheckBB = Builder.GetInsertBlock();
1106 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1107 contBB = createBasicBlock("new.cont");
1108
1109 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1110 Builder.CreateCondBr(isNull, contBB, notNullBB);
1111 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001112 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001113
John McCall7d8647f2010-09-14 07:57:04 +00001114 // If there's an operator delete, enter a cleanup to call it if an
1115 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001116 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCallb1c98a32011-05-16 01:05:12 +00001117 if (E->getOperatorDelete() &&
1118 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001119 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1120 operatorDeleteCleanup = EHStack.stable_begin();
John McCall7d8647f2010-09-14 07:57:04 +00001121 }
1122
Eli Friedman576cf172011-09-06 18:53:03 +00001123 assert((allocSize == allocSizeWithoutCookie) ==
1124 CalculateCookiePadding(*this, E).isZero());
1125 if (allocSize != allocSizeWithoutCookie) {
1126 assert(E->isArray());
1127 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1128 numElements,
1129 E, allocType);
1130 }
1131
Chris Lattner2acc6e32011-07-18 04:24:23 +00001132 llvm::Type *elementPtrTy
John McCallc2f3e7f2011-03-07 03:12:35 +00001133 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1134 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001135
John McCall19705672011-09-15 06:49:18 +00001136 EmitNewInitializer(*this, E, allocType, result, numElements,
1137 allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001138 if (E->isArray()) {
John McCall1e7fe752010-09-02 09:58:18 +00001139 // NewPtr is a pointer to the base element type. If we're
1140 // allocating an array of arrays, we'll need to cast back to the
1141 // array pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001142 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCallc2f3e7f2011-03-07 03:12:35 +00001143 if (result->getType() != resultType)
1144 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001145 }
John McCall7d8647f2010-09-14 07:57:04 +00001146
1147 // Deactivate the 'operator delete' cleanup if we finished
1148 // initialization.
John McCallc2f3e7f2011-03-07 03:12:35 +00001149 if (operatorDeleteCleanup.isValid())
1150 DeactivateCleanupBlock(operatorDeleteCleanup);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001151
John McCallc2f3e7f2011-03-07 03:12:35 +00001152 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001153 conditional.end(*this);
1154
John McCallc2f3e7f2011-03-07 03:12:35 +00001155 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1156 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001157
Jay Foadbbf3bac2011-03-30 11:28:58 +00001158 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001159 PHI->addIncoming(result, notNullBB);
1160 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1161 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001162
John McCallc2f3e7f2011-03-07 03:12:35 +00001163 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001164 }
John McCall1e7fe752010-09-02 09:58:18 +00001165
John McCallc2f3e7f2011-03-07 03:12:35 +00001166 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001167}
1168
Eli Friedman5fe05982009-11-18 00:50:08 +00001169void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1170 llvm::Value *Ptr,
1171 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001172 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1173
Eli Friedman5fe05982009-11-18 00:50:08 +00001174 const FunctionProtoType *DeleteFTy =
1175 DeleteFD->getType()->getAs<FunctionProtoType>();
1176
1177 CallArgList DeleteArgs;
1178
Anders Carlsson871d0782009-12-13 20:04:38 +00001179 // Check if we need to pass the size to the delete operator.
1180 llvm::Value *Size = 0;
1181 QualType SizeTy;
1182 if (DeleteFTy->getNumArgs() == 2) {
1183 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001184 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1185 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1186 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001187 }
1188
Eli Friedman5fe05982009-11-18 00:50:08 +00001189 QualType ArgTy = DeleteFTy->getArgType(0);
1190 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001191 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001192
Anders Carlsson871d0782009-12-13 20:04:38 +00001193 if (Size)
Eli Friedman04c9a492011-05-02 17:57:46 +00001194 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001195
1196 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001197 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001198 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +00001199 DeleteArgs, DeleteFD);
1200}
1201
John McCall1e7fe752010-09-02 09:58:18 +00001202namespace {
1203 /// Calls the given 'operator delete' on a single object.
1204 struct CallObjectDelete : EHScopeStack::Cleanup {
1205 llvm::Value *Ptr;
1206 const FunctionDecl *OperatorDelete;
1207 QualType ElementType;
1208
1209 CallObjectDelete(llvm::Value *Ptr,
1210 const FunctionDecl *OperatorDelete,
1211 QualType ElementType)
1212 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1213
John McCallad346f42011-07-12 20:27:29 +00001214 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001215 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1216 }
1217 };
1218}
1219
1220/// Emit the code for deleting a single object.
1221static void EmitObjectDelete(CodeGenFunction &CGF,
1222 const FunctionDecl *OperatorDelete,
1223 llvm::Value *Ptr,
Douglas Gregora8b20f72011-07-13 00:54:47 +00001224 QualType ElementType,
1225 bool UseGlobalDelete) {
John McCall1e7fe752010-09-02 09:58:18 +00001226 // Find the destructor for the type, if applicable. If the
1227 // destructor is virtual, we'll just emit the vcall and return.
1228 const CXXDestructorDecl *Dtor = 0;
1229 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1230 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanaebab722011-08-02 18:05:30 +00001231 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall1e7fe752010-09-02 09:58:18 +00001232 Dtor = RD->getDestructor();
1233
1234 if (Dtor->isVirtual()) {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001235 if (UseGlobalDelete) {
1236 // If we're supposed to call the global delete, make sure we do so
1237 // even if the destructor throws.
1238 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1239 Ptr, OperatorDelete,
1240 ElementType);
1241 }
1242
Chris Lattner2acc6e32011-07-18 04:24:23 +00001243 llvm::Type *Ty =
John McCallfc400282010-09-03 01:26:39 +00001244 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1245 Dtor_Complete),
John McCall1e7fe752010-09-02 09:58:18 +00001246 /*isVariadic=*/false);
1247
1248 llvm::Value *Callee
Douglas Gregora8b20f72011-07-13 00:54:47 +00001249 = CGF.BuildVirtualCall(Dtor,
1250 UseGlobalDelete? Dtor_Complete : Dtor_Deleting,
1251 Ptr, Ty);
John McCall1e7fe752010-09-02 09:58:18 +00001252 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1253 0, 0);
1254
Douglas Gregora8b20f72011-07-13 00:54:47 +00001255 if (UseGlobalDelete) {
1256 CGF.PopCleanupBlock();
1257 }
1258
John McCall1e7fe752010-09-02 09:58:18 +00001259 return;
1260 }
1261 }
1262 }
1263
1264 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001265 // This doesn't have to a conditional cleanup because we're going
1266 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001267 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1268 Ptr, OperatorDelete, ElementType);
1269
1270 if (Dtor)
1271 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1272 /*ForVirtualBase=*/false, Ptr);
John McCallf85e1932011-06-15 23:02:42 +00001273 else if (CGF.getLangOptions().ObjCAutoRefCount &&
1274 ElementType->isObjCLifetimeType()) {
1275 switch (ElementType.getObjCLifetime()) {
1276 case Qualifiers::OCL_None:
1277 case Qualifiers::OCL_ExplicitNone:
1278 case Qualifiers::OCL_Autoreleasing:
1279 break;
John McCall1e7fe752010-09-02 09:58:18 +00001280
John McCallf85e1932011-06-15 23:02:42 +00001281 case Qualifiers::OCL_Strong: {
1282 // Load the pointer value.
1283 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1284 ElementType.isVolatileQualified());
1285
1286 CGF.EmitARCRelease(PtrValue, /*precise*/ true);
1287 break;
1288 }
1289
1290 case Qualifiers::OCL_Weak:
1291 CGF.EmitARCDestroyWeak(Ptr);
1292 break;
1293 }
1294 }
1295
John McCall1e7fe752010-09-02 09:58:18 +00001296 CGF.PopCleanupBlock();
1297}
1298
1299namespace {
1300 /// Calls the given 'operator delete' on an array of objects.
1301 struct CallArrayDelete : EHScopeStack::Cleanup {
1302 llvm::Value *Ptr;
1303 const FunctionDecl *OperatorDelete;
1304 llvm::Value *NumElements;
1305 QualType ElementType;
1306 CharUnits CookieSize;
1307
1308 CallArrayDelete(llvm::Value *Ptr,
1309 const FunctionDecl *OperatorDelete,
1310 llvm::Value *NumElements,
1311 QualType ElementType,
1312 CharUnits CookieSize)
1313 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1314 ElementType(ElementType), CookieSize(CookieSize) {}
1315
John McCallad346f42011-07-12 20:27:29 +00001316 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001317 const FunctionProtoType *DeleteFTy =
1318 OperatorDelete->getType()->getAs<FunctionProtoType>();
1319 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1320
1321 CallArgList Args;
1322
1323 // Pass the pointer as the first argument.
1324 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1325 llvm::Value *DeletePtr
1326 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001327 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall1e7fe752010-09-02 09:58:18 +00001328
1329 // Pass the original requested size as the second argument.
1330 if (DeleteFTy->getNumArgs() == 2) {
1331 QualType size_t = DeleteFTy->getArgType(1);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001332 llvm::IntegerType *SizeTy
John McCall1e7fe752010-09-02 09:58:18 +00001333 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1334
1335 CharUnits ElementTypeSize =
1336 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1337
1338 // The size of an element, multiplied by the number of elements.
1339 llvm::Value *Size
1340 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1341 Size = CGF.Builder.CreateMul(Size, NumElements);
1342
1343 // Plus the size of the cookie if applicable.
1344 if (!CookieSize.isZero()) {
1345 llvm::Value *CookieSizeV
1346 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1347 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1348 }
1349
Eli Friedman04c9a492011-05-02 17:57:46 +00001350 Args.add(RValue::get(Size), size_t);
John McCall1e7fe752010-09-02 09:58:18 +00001351 }
1352
1353 // Emit the call to delete.
Tilmann Scheller9c6082f2011-03-02 21:36:49 +00001354 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
John McCall1e7fe752010-09-02 09:58:18 +00001355 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1356 ReturnValueSlot(), Args, OperatorDelete);
1357 }
1358 };
1359}
1360
1361/// Emit the code for deleting an array of objects.
1362static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001363 const CXXDeleteExpr *E,
John McCall7cfd76c2011-07-13 01:41:37 +00001364 llvm::Value *deletedPtr,
1365 QualType elementType) {
1366 llvm::Value *numElements = 0;
1367 llvm::Value *allocatedPtr = 0;
1368 CharUnits cookieSize;
1369 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1370 numElements, allocatedPtr, cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001371
John McCall7cfd76c2011-07-13 01:41:37 +00001372 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall1e7fe752010-09-02 09:58:18 +00001373
1374 // Make sure that we call delete even if one of the dtors throws.
John McCall7cfd76c2011-07-13 01:41:37 +00001375 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001376 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCall7cfd76c2011-07-13 01:41:37 +00001377 allocatedPtr, operatorDelete,
1378 numElements, elementType,
1379 cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001380
John McCall7cfd76c2011-07-13 01:41:37 +00001381 // Destroy the elements.
1382 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1383 assert(numElements && "no element count for a type with a destructor!");
1384
John McCall7cfd76c2011-07-13 01:41:37 +00001385 llvm::Value *arrayEnd =
1386 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCallfbf780a2011-07-13 08:09:46 +00001387
1388 // Note that it is legal to allocate a zero-length array, and we
1389 // can never fold the check away because the length should always
1390 // come from a cookie.
John McCall7cfd76c2011-07-13 01:41:37 +00001391 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1392 CGF.getDestroyer(dtorKind),
John McCallfbf780a2011-07-13 08:09:46 +00001393 /*checkZeroLength*/ true,
John McCall7cfd76c2011-07-13 01:41:37 +00001394 CGF.needsEHCleanup(dtorKind));
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);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001431 SmallVector<llvm::Value*,8> GEP;
John McCall1e7fe752010-09-02 09:58:18 +00001432
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
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001445 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "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
Chris Lattner2acc6e32011-07-18 04:24:23 +00001464 llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1465 llvm::FunctionType *FTy =
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001466 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);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001473 CGF.EmitCallOrInvoke(Fn).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,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001479 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001480 // 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) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001512 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001513 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
Chris Lattner2acc6e32011-07-18 04:24:23 +00001553 llvm::FunctionType *FTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001554 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
Chris Lattner2acc6e32011-07-18 04:24:23 +00001562 llvm::Type *VoidTy = llvm::Type::getVoidTy(CGF.getLLVMContext());
1563 llvm::FunctionType *FTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001564 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);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001571 CGF.EmitCallOrInvoke(Fn).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) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001579 llvm::Type *PtrDiffLTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001580 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001581 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001582
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) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001651 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001652 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}