blob: 77ccdd0d720a12c300488b081217f6ed2f95142f [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlssoncc52f652009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
Devang Patel91bbb552010-09-30 19:05:55 +000014#include "clang/Frontend/CodeGenOptions.h"
Anders Carlssoncc52f652009-09-22 22:53:17 +000015#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Fariborz Jahanian60d215b2010-05-20 21:38:57 +000017#include "CGObjCRuntime.h"
Devang Patel91bbb552010-09-30 19:05:55 +000018#include "CGDebugInfo.h"
Chris Lattner26008e02010-07-20 20:19:24 +000019#include "llvm/Intrinsics.h"
Anders Carlssoncc52f652009-09-22 22:53:17 +000020using namespace clang;
21using namespace CodeGen;
22
Anders Carlsson27da15b2010-01-01 20:29:01 +000023RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
24 llvm::Value *Callee,
25 ReturnValueSlot ReturnValue,
26 llvm::Value *This,
Anders Carlssone36a6b32010-01-02 01:01:18 +000027 llvm::Value *VTT,
Anders Carlsson27da15b2010-01-01 20:29:01 +000028 CallExpr::const_arg_iterator ArgBeg,
29 CallExpr::const_arg_iterator ArgEnd) {
30 assert(MD->isInstance() &&
31 "Trying to emit a member call expr on a static method!");
32
33 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
34
35 CallArgList Args;
36
37 // Push the this ptr.
38 Args.push_back(std::make_pair(RValue::get(This),
39 MD->getThisType(getContext())));
40
Anders Carlssone36a6b32010-01-02 01:01:18 +000041 // If there is a VTT parameter, emit it.
42 if (VTT) {
43 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
44 Args.push_back(std::make_pair(RValue::get(VTT), T));
45 }
46
Anders Carlsson27da15b2010-01-01 20:29:01 +000047 // And the rest of the call args
48 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
49
John McCallab26cfa2010-02-05 21:31:56 +000050 QualType ResultType = FPT->getResultType();
51 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
Rafael Espindolac50c27c2010-03-30 20:24:48 +000052 FPT->getExtInfo()),
53 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000054}
55
56/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
57/// expr can be devirtualized.
Anders Carlssona7911fa2010-10-27 13:28:46 +000058static bool canDevirtualizeMemberFunctionCalls(const Expr *Base,
59 const CXXMethodDecl *MD) {
60
61 // If the member function has the "final" attribute, we know that it can't be
Anders Carlssonb00c2142010-10-27 13:34:43 +000062 // overridden and can therefore devirtualize it.
Anders Carlssona7911fa2010-10-27 13:28:46 +000063 if (MD->hasAttr<FinalAttr>())
64 return true;
Anders Carlssonb00c2142010-10-27 13:34:43 +000065
66 // Similarly, if the class itself has the "final" attribute it can't be
67 // overridden and we can therefore devirtualize the member function call.
68 if (MD->getParent()->hasAttr<FinalAttr>())
69 return true;
70
Anders Carlsson27da15b2010-01-01 20:29:01 +000071 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
72 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
73 // This is a record decl. We know the type and can devirtualize it.
74 return VD->getType()->isRecordType();
75 }
76
77 return false;
78 }
79
80 // We can always devirtualize calls on temporary object expressions.
Eli Friedmana6824272010-01-31 20:58:15 +000081 if (isa<CXXConstructExpr>(Base))
Anders Carlsson27da15b2010-01-01 20:29:01 +000082 return true;
83
84 // And calls on bound temporaries.
85 if (isa<CXXBindTemporaryExpr>(Base))
86 return true;
87
88 // Check if this is a call expr that returns a record type.
89 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
90 return CE->getCallReturnType()->isRecordType();
Anders Carlssona7911fa2010-10-27 13:28:46 +000091
Anders Carlsson27da15b2010-01-01 20:29:01 +000092 // We can't devirtualize the call.
93 return false;
94}
95
96RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
97 ReturnValueSlot ReturnValue) {
98 if (isa<BinaryOperator>(CE->getCallee()->IgnoreParens()))
99 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
100
101 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()->IgnoreParens());
102 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
103
Devang Patel91bbb552010-09-30 19:05:55 +0000104 CGDebugInfo *DI = getDebugInfo();
Devang Patel401c9162010-10-22 18:56:27 +0000105 if (DI && CGM.getCodeGenOpts().LimitDebugInfo
106 && !isa<CallExpr>(ME->getBase())) {
Devang Patel91bbb552010-09-30 19:05:55 +0000107 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
108 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
109 DI->getOrCreateRecordType(PTy->getPointeeType(),
110 MD->getParent()->getLocation());
111 }
112 }
113
Anders Carlsson27da15b2010-01-01 20:29:01 +0000114 if (MD->isStatic()) {
115 // The method is static, emit it as we would a regular call.
116 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
117 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
118 ReturnValue, CE->arg_begin(), CE->arg_end());
119 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000120
John McCall0d635f52010-09-03 01:26:39 +0000121 // Compute the object pointer.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000122 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000123 if (ME->isArrow())
124 This = EmitScalarExpr(ME->getBase());
John McCalle26a8722010-12-04 08:14:53 +0000125 else
126 This = EmitLValue(ME->getBase()).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000127
John McCall0d635f52010-09-03 01:26:39 +0000128 if (MD->isTrivial()) {
129 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
130
Douglas Gregorec3bec02010-09-27 22:37:28 +0000131 assert(MD->isCopyAssignmentOperator() && "unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000132 // We don't like to generate the trivial copy assignment operator when
133 // it isn't necessary; just produce the proper effect here.
134 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
135 EmitAggregateCopy(This, RHS, CE->getType());
136 return RValue::get(This);
137 }
138
John McCall0d635f52010-09-03 01:26:39 +0000139 // Compute the function type we're calling.
140 const CGFunctionInfo &FInfo =
141 (isa<CXXDestructorDecl>(MD)
142 ? CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
143 Dtor_Complete)
144 : CGM.getTypes().getFunctionInfo(MD));
145
146 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
147 const llvm::Type *Ty
148 = CGM.getTypes().GetFunctionType(FInfo, FPT->isVariadic());
149
Anders Carlsson27da15b2010-01-01 20:29:01 +0000150 // C++ [class.virtual]p12:
151 // Explicit qualification with the scope operator (5.1) suppresses the
152 // virtual call mechanism.
153 //
154 // We also don't emit a virtual call if the base expression has a record type
155 // because then we know what the type is.
John McCall0d635f52010-09-03 01:26:39 +0000156 bool UseVirtualCall = MD->isVirtual() && !ME->hasQualifier()
Anders Carlssona7911fa2010-10-27 13:28:46 +0000157 && !canDevirtualizeMemberFunctionCalls(ME->getBase(), MD);
John McCall0d635f52010-09-03 01:26:39 +0000158
Anders Carlsson27da15b2010-01-01 20:29:01 +0000159 llvm::Value *Callee;
John McCall0d635f52010-09-03 01:26:39 +0000160 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
161 if (UseVirtualCall) {
162 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000163 } else {
John McCall0d635f52010-09-03 01:26:39 +0000164 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000165 }
John McCall0d635f52010-09-03 01:26:39 +0000166 } else if (UseVirtualCall) {
Anders Carlsson27da15b2010-01-01 20:29:01 +0000167 Callee = BuildVirtualCall(MD, This, Ty);
168 } else {
169 Callee = CGM.GetAddrOfFunction(MD, Ty);
170 }
171
Anders Carlssone36a6b32010-01-02 01:01:18 +0000172 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000173 CE->arg_begin(), CE->arg_end());
174}
175
176RValue
177CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
178 ReturnValueSlot ReturnValue) {
179 const BinaryOperator *BO =
180 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
181 const Expr *BaseExpr = BO->getLHS();
182 const Expr *MemFnExpr = BO->getRHS();
183
184 const MemberPointerType *MPT =
185 MemFnExpr->getType()->getAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000186
Anders Carlsson27da15b2010-01-01 20:29:01 +0000187 const FunctionProtoType *FPT =
188 MPT->getPointeeType()->getAs<FunctionProtoType>();
189 const CXXRecordDecl *RD =
190 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
191
Anders Carlsson27da15b2010-01-01 20:29:01 +0000192 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000193 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000194
195 // Emit the 'this' pointer.
196 llvm::Value *This;
197
John McCalle3027922010-08-25 11:45:40 +0000198 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000199 This = EmitScalarExpr(BaseExpr);
200 else
201 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000202
John McCall475999d2010-08-22 00:05:51 +0000203 // Ask the ABI to load the callee. Note that This is modified.
204 llvm::Value *Callee =
205 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(CGF, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000206
Anders Carlsson27da15b2010-01-01 20:29:01 +0000207 CallArgList Args;
208
209 QualType ThisType =
210 getContext().getPointerType(getContext().getTagDeclType(RD));
211
212 // Push the this ptr.
213 Args.push_back(std::make_pair(RValue::get(This), ThisType));
214
215 // And the rest of the call args
216 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCallab26cfa2010-02-05 21:31:56 +0000217 const FunctionType *BO_FPT = BO->getType()->getAs<FunctionProtoType>();
218 return EmitCall(CGM.getTypes().getFunctionInfo(Args, BO_FPT), Callee,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000219 ReturnValue, Args);
220}
221
222RValue
223CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
224 const CXXMethodDecl *MD,
225 ReturnValueSlot ReturnValue) {
226 assert(MD->isInstance() &&
227 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000228 LValue LV = EmitLValue(E->getArg(0));
229 llvm::Value *This = LV.getAddress();
230
Douglas Gregorec3bec02010-09-27 22:37:28 +0000231 if (MD->isCopyAssignmentOperator()) {
Anders Carlsson27da15b2010-01-01 20:29:01 +0000232 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext());
233 if (ClassDecl->hasTrivialCopyAssignment()) {
234 assert(!ClassDecl->hasUserDeclaredCopyAssignment() &&
235 "EmitCXXOperatorMemberCallExpr - user declared copy assignment");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000236 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
237 QualType Ty = E->getType();
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000238 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000239 return RValue::get(This);
240 }
241 }
242
243 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
244 const llvm::Type *Ty =
245 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
246 FPT->isVariadic());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000247 llvm::Value *Callee;
Anders Carlssona7911fa2010-10-27 13:28:46 +0000248 if (MD->isVirtual() && !canDevirtualizeMemberFunctionCalls(E->getArg(0), MD))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000249 Callee = BuildVirtualCall(MD, This, Ty);
250 else
251 Callee = CGM.GetAddrOfFunction(MD, Ty);
252
Anders Carlssone36a6b32010-01-02 01:01:18 +0000253 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson27da15b2010-01-01 20:29:01 +0000254 E->arg_begin() + 1, E->arg_end());
255}
256
257void
John McCall7a626f62010-09-15 10:14:12 +0000258CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
259 AggValueSlot Dest) {
260 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000261 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000262
263 // If we require zero initialization before (or instead of) calling the
264 // constructor, as can be the case with a non-user-provided default
265 // constructor, emit the zero initialization now.
266 if (E->requiresZeroInitialization())
John McCall7a626f62010-09-15 10:14:12 +0000267 EmitNullInitialization(Dest.getAddr(), E->getType());
Douglas Gregor630c76e2010-08-22 16:15:35 +0000268
269 // If this is a call to a trivial default constructor, do nothing.
270 if (CD->isTrivial() && CD->isDefaultConstructor())
271 return;
272
John McCall8ea46b62010-09-18 00:58:34 +0000273 // Elide the constructor if we're constructing from a temporary.
274 // The temporary check is required because Sema sets this on NRVO
275 // returns.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000276 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000277 assert(getContext().hasSameUnqualifiedType(E->getType(),
278 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000279 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
280 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000281 return;
282 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000283 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000284
285 const ConstantArrayType *Array
286 = getContext().getAsConstantArrayType(E->getType());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000287 if (Array) {
288 QualType BaseElementTy = getContext().getBaseElementType(Array);
289 const llvm::Type *BasePtr = ConvertType(BaseElementTy);
290 BasePtr = llvm::PointerType::getUnqual(BasePtr);
291 llvm::Value *BaseAddrPtr =
John McCall7a626f62010-09-15 10:14:12 +0000292 Builder.CreateBitCast(Dest.getAddr(), BasePtr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000293
294 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr,
295 E->arg_begin(), E->arg_end());
296 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000297 else {
298 CXXCtorType Type =
299 (E->getConstructionKind() == CXXConstructExpr::CK_Complete)
300 ? Ctor_Complete : Ctor_Base;
301 bool ForVirtualBase =
302 E->getConstructionKind() == CXXConstructExpr::CK_VirtualBase;
303
Anders Carlsson27da15b2010-01-01 20:29:01 +0000304 // Call the constructor.
John McCall7a626f62010-09-15 10:14:12 +0000305 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000306 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000307 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000308}
309
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000310void
311CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
312 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000313 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000314 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000315 Exp = E->getSubExpr();
316 assert(isa<CXXConstructExpr>(Exp) &&
317 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
318 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
319 const CXXConstructorDecl *CD = E->getConstructor();
320 RunCleanupsScope Scope(*this);
321
322 // If we require zero initialization before (or instead of) calling the
323 // constructor, as can be the case with a non-user-provided default
324 // constructor, emit the zero initialization now.
325 // FIXME. Do I still need this for a copy ctor synthesis?
326 if (E->requiresZeroInitialization())
327 EmitNullInitialization(Dest, E->getType());
328
Chandler Carruth99da11c2010-11-15 13:54:43 +0000329 assert(!getContext().getAsConstantArrayType(E->getType())
330 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000331 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
332 E->arg_begin(), E->arg_end());
333}
334
John McCallaa4149a2010-08-23 01:17:59 +0000335/// Check whether the given operator new[] is the global placement
336/// operator new[].
337static bool IsPlacementOperatorNewArray(ASTContext &Ctx,
338 const FunctionDecl *Fn) {
339 // Must be in global scope. Note that allocation functions can't be
340 // declared in namespaces.
Sebastian Redl50c68252010-08-31 00:36:30 +0000341 if (!Fn->getDeclContext()->getRedeclContext()->isFileContext())
John McCallaa4149a2010-08-23 01:17:59 +0000342 return false;
343
344 // Signature must be void *operator new[](size_t, void*).
345 // The size_t is common to all operator new[]s.
346 if (Fn->getNumParams() != 2)
347 return false;
348
349 CanQualType ParamType = Ctx.getCanonicalType(Fn->getParamDecl(1)->getType());
350 return (ParamType == Ctx.VoidPtrTy);
351}
352
John McCall8ed55a52010-09-02 09:58:18 +0000353static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
354 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000355 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000356 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000357
Anders Carlsson399f4992009-12-13 20:34:34 +0000358 // No cookie is required if the new operator being used is
359 // ::operator new[](size_t, void*).
360 const FunctionDecl *OperatorNew = E->getOperatorNew();
John McCall8ed55a52010-09-02 09:58:18 +0000361 if (IsPlacementOperatorNewArray(CGF.getContext(), OperatorNew))
John McCallaa4149a2010-08-23 01:17:59 +0000362 return CharUnits::Zero();
363
John McCall8ed55a52010-09-02 09:58:18 +0000364 return CGF.CGM.getCXXABI().GetArrayCookieSize(E->getAllocatedType());
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000365}
366
Fariborz Jahanian47b46292010-03-24 16:57:01 +0000367static llvm::Value *EmitCXXNewAllocSize(ASTContext &Context,
Chris Lattnercb46bdc2010-07-20 18:45:57 +0000368 CodeGenFunction &CGF,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000369 const CXXNewExpr *E,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000370 llvm::Value *&NumElements,
371 llvm::Value *&SizeWithoutCookie) {
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000372 QualType ElemType = E->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000373
374 const llvm::IntegerType *SizeTy =
375 cast<llvm::IntegerType>(CGF.ConvertType(CGF.getContext().getSizeType()));
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000376
John McCall8ed55a52010-09-02 09:58:18 +0000377 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(ElemType);
378
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000379 if (!E->isArray()) {
380 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
381 return SizeWithoutCookie;
382 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000383
John McCall8ed55a52010-09-02 09:58:18 +0000384 // Figure out the cookie size.
385 CharUnits CookieSize = CalculateCookiePadding(CGF, E);
386
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000387 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000388 // We multiply the size of all dimensions for NumElements.
389 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000390 NumElements = CGF.EmitScalarExpr(E->getArraySize());
John McCall8ed55a52010-09-02 09:58:18 +0000391 assert(NumElements->getType() == SizeTy && "element count not a size_t");
392
393 uint64_t ArraySizeMultiplier = 1;
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000394 while (const ConstantArrayType *CAT
395 = CGF.getContext().getAsConstantArrayType(ElemType)) {
396 ElemType = CAT->getElementType();
John McCall8ed55a52010-09-02 09:58:18 +0000397 ArraySizeMultiplier *= CAT->getSize().getZExtValue();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000398 }
399
John McCall8ed55a52010-09-02 09:58:18 +0000400 llvm::Value *Size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000401
Chris Lattner32ac5832010-07-20 21:55:52 +0000402 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
403 // Don't bloat the -O0 code.
404 if (llvm::ConstantInt *NumElementsC =
405 dyn_cast<llvm::ConstantInt>(NumElements)) {
Chris Lattner32ac5832010-07-20 21:55:52 +0000406 llvm::APInt NEC = NumElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000407 unsigned SizeWidth = NEC.getBitWidth();
408
409 // Determine if there is an overflow here by doing an extended multiply.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000410 NEC = NEC.zext(SizeWidth*2);
John McCall8ed55a52010-09-02 09:58:18 +0000411 llvm::APInt SC(SizeWidth*2, TypeSize.getQuantity());
Chris Lattner32ac5832010-07-20 21:55:52 +0000412 SC *= NEC;
John McCall8ed55a52010-09-02 09:58:18 +0000413
414 if (!CookieSize.isZero()) {
415 // Save the current size without a cookie. We don't care if an
416 // overflow's already happened because SizeWithoutCookie isn't
417 // used if the allocator returns null or throws, as it should
418 // always do on an overflow.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000419 llvm::APInt SWC = SC.trunc(SizeWidth);
John McCall8ed55a52010-09-02 09:58:18 +0000420 SizeWithoutCookie = llvm::ConstantInt::get(SizeTy, SWC);
421
422 // Add the cookie size.
423 SC += llvm::APInt(SizeWidth*2, CookieSize.getQuantity());
Chris Lattner32ac5832010-07-20 21:55:52 +0000424 }
425
John McCall8ed55a52010-09-02 09:58:18 +0000426 if (SC.countLeadingZeros() >= SizeWidth) {
Jay Foad6d4db0c2010-12-07 08:25:34 +0000427 SC = SC.trunc(SizeWidth);
John McCall8ed55a52010-09-02 09:58:18 +0000428 Size = llvm::ConstantInt::get(SizeTy, SC);
429 } else {
430 // On overflow, produce a -1 so operator new throws.
431 Size = llvm::Constant::getAllOnesValue(SizeTy);
432 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000433
John McCall8ed55a52010-09-02 09:58:18 +0000434 // Scale NumElements while we're at it.
435 uint64_t N = NEC.getZExtValue() * ArraySizeMultiplier;
436 NumElements = llvm::ConstantInt::get(SizeTy, N);
437
438 // Otherwise, we don't need to do an overflow-checked multiplication if
439 // we're multiplying by one.
440 } else if (TypeSize.isOne()) {
441 assert(ArraySizeMultiplier == 1);
442
443 Size = NumElements;
444
445 // If we need a cookie, add its size in with an overflow check.
446 // This is maybe a little paranoid.
447 if (!CookieSize.isZero()) {
448 SizeWithoutCookie = Size;
449
450 llvm::Value *CookieSizeV
451 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
452
453 const llvm::Type *Types[] = { SizeTy };
454 llvm::Value *UAddF
455 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
456 llvm::Value *AddRes
457 = CGF.Builder.CreateCall2(UAddF, Size, CookieSizeV);
458
459 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
460 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
461 Size = CGF.Builder.CreateSelect(DidOverflow,
462 llvm::ConstantInt::get(SizeTy, -1),
463 Size);
464 }
465
466 // Otherwise use the int.umul.with.overflow intrinsic.
467 } else {
468 llvm::Value *OutermostElementSize
469 = llvm::ConstantInt::get(SizeTy, TypeSize.getQuantity());
470
471 llvm::Value *NumOutermostElements = NumElements;
472
473 // Scale NumElements by the array size multiplier. This might
474 // overflow, but only if the multiplication below also overflows,
475 // in which case this multiplication isn't used.
476 if (ArraySizeMultiplier != 1)
477 NumElements = CGF.Builder.CreateMul(NumElements,
478 llvm::ConstantInt::get(SizeTy, ArraySizeMultiplier));
479
480 // The requested size of the outermost array is non-constant.
481 // Multiply that by the static size of the elements of that array;
482 // on unsigned overflow, set the size to -1 to trigger an
483 // exception from the allocation routine. This is sufficient to
484 // prevent buffer overruns from the allocator returning a
485 // seemingly valid pointer to insufficient space. This idea comes
486 // originally from MSVC, and GCC has an open bug requesting
487 // similar behavior:
488 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19351
489 //
490 // This will not be sufficient for C++0x, which requires a
491 // specific exception class (std::bad_array_new_length).
492 // That will require ABI support that has not yet been specified.
493 const llvm::Type *Types[] = { SizeTy };
494 llvm::Value *UMulF
495 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, Types, 1);
496 llvm::Value *MulRes = CGF.Builder.CreateCall2(UMulF, NumOutermostElements,
497 OutermostElementSize);
498
499 // The overflow bit.
500 llvm::Value *DidOverflow = CGF.Builder.CreateExtractValue(MulRes, 1);
501
502 // The result of the multiplication.
503 Size = CGF.Builder.CreateExtractValue(MulRes, 0);
504
505 // If we have a cookie, we need to add that size in, too.
506 if (!CookieSize.isZero()) {
507 SizeWithoutCookie = Size;
508
509 llvm::Value *CookieSizeV
510 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
511 llvm::Value *UAddF
512 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, Types, 1);
513 llvm::Value *AddRes
514 = CGF.Builder.CreateCall2(UAddF, SizeWithoutCookie, CookieSizeV);
515
516 Size = CGF.Builder.CreateExtractValue(AddRes, 0);
517
518 llvm::Value *AddDidOverflow = CGF.Builder.CreateExtractValue(AddRes, 1);
519 DidOverflow = CGF.Builder.CreateAnd(DidOverflow, AddDidOverflow);
520 }
521
522 Size = CGF.Builder.CreateSelect(DidOverflow,
523 llvm::ConstantInt::get(SizeTy, -1),
524 Size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000525 }
John McCall8ed55a52010-09-02 09:58:18 +0000526
527 if (CookieSize.isZero())
528 SizeWithoutCookie = Size;
529 else
530 assert(SizeWithoutCookie && "didn't set SizeWithoutCookie?");
531
Chris Lattner32ac5832010-07-20 21:55:52 +0000532 return Size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000533}
534
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000535static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const CXXNewExpr *E,
536 llvm::Value *NewPtr) {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000537
538 assert(E->getNumConstructorArgs() == 1 &&
539 "Can only have one argument to initializer of POD type.");
540
541 const Expr *Init = E->getConstructorArg(0);
542 QualType AllocType = E->getAllocatedType();
Daniel Dunbar03816342010-08-21 02:24:36 +0000543
544 unsigned Alignment =
545 CGF.getContext().getTypeAlignInChars(AllocType).getQuantity();
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000546 if (!CGF.hasAggregateLLVMType(AllocType))
547 CGF.EmitStoreOfScalar(CGF.EmitScalarExpr(Init), NewPtr,
Daniel Dunbar03816342010-08-21 02:24:36 +0000548 AllocType.isVolatileQualified(), Alignment,
549 AllocType);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000550 else if (AllocType->isAnyComplexType())
551 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
552 AllocType.isVolatileQualified());
John McCall7a626f62010-09-15 10:14:12 +0000553 else {
554 AggValueSlot Slot
555 = AggValueSlot::forAddr(NewPtr, AllocType.isVolatileQualified(), true);
556 CGF.EmitAggExpr(Init, Slot);
557 }
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000558}
559
560void
561CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
562 llvm::Value *NewPtr,
563 llvm::Value *NumElements) {
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000564 // We have a POD type.
565 if (E->getNumConstructorArgs() == 0)
566 return;
567
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000568 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
569
570 // Create a temporary for the loop index and initialize it with 0.
571 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
572 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
573 Builder.CreateStore(Zero, IndexPtr);
574
575 // Start the loop with a block that tests the condition.
576 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
577 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
578
579 EmitBlock(CondBlock);
580
581 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
582
583 // Generate: if (loop-index < number-of-elements fall to the loop body,
584 // otherwise, go to the block after the for-loop.
585 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
586 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
587 // If the condition is true, execute the body.
588 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
589
590 EmitBlock(ForBody);
591
592 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
593 // Inside the loop body, emit the constructor call on the array element.
594 Counter = Builder.CreateLoad(IndexPtr);
595 llvm::Value *Address = Builder.CreateInBoundsGEP(NewPtr, Counter,
596 "arrayidx");
597 StoreAnyExprIntoOneUnit(*this, E, Address);
598
599 EmitBlock(ContinueBlock);
600
601 // Emit the increment of the loop counter.
602 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
603 Counter = Builder.CreateLoad(IndexPtr);
604 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
605 Builder.CreateStore(NextVal, IndexPtr);
606
607 // Finally, branch back up to the condition for the next iteration.
608 EmitBranch(CondBlock);
609
610 // Emit the fall-through block.
611 EmitBlock(AfterFor, true);
612}
613
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000614static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
615 llvm::Value *NewPtr, llvm::Value *Size) {
616 llvm::LLVMContext &VMContext = CGF.CGM.getLLVMContext();
617 const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
618 if (NewPtr->getType() != BP)
619 NewPtr = CGF.Builder.CreateBitCast(NewPtr, BP, "tmp");
Benjamin Krameracc6b4e2010-12-30 00:13:21 +0000620
621 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
622 CGF.getContext().getTypeAlign(T)/8, false);
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000623}
624
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000625static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
626 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000627 llvm::Value *NumElements,
628 llvm::Value *AllocSizeWithoutCookie) {
Anders Carlsson3a202f62009-11-24 18:43:52 +0000629 if (E->isArray()) {
Anders Carlssond040e6b2010-05-03 15:09:17 +0000630 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000631 bool RequiresZeroInitialization = false;
632 if (Ctor->getParent()->hasTrivialConstructor()) {
633 // If new expression did not specify value-initialization, then there
634 // is no initialization.
635 if (!E->hasInitializer() || Ctor->getParent()->isEmpty())
636 return;
637
John McCall614dbdc2010-08-22 21:01:12 +0000638 if (CGF.CGM.getTypes().isZeroInitializable(E->getAllocatedType())) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000639 // Optimization: since zero initialization will just set the memory
640 // to all zeroes, generate a single memset to do it in one shot.
641 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
642 AllocSizeWithoutCookie);
643 return;
644 }
645
646 RequiresZeroInitialization = true;
647 }
648
649 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
650 E->constructor_arg_begin(),
651 E->constructor_arg_end(),
652 RequiresZeroInitialization);
Anders Carlssond040e6b2010-05-03 15:09:17 +0000653 return;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000654 } else if (E->getNumConstructorArgs() == 1 &&
655 isa<ImplicitValueInitExpr>(E->getConstructorArg(0))) {
656 // Optimization: since zero initialization will just set the memory
657 // to all zeroes, generate a single memset to do it in one shot.
658 EmitZeroMemSet(CGF, E->getAllocatedType(), NewPtr,
659 AllocSizeWithoutCookie);
660 return;
661 } else {
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000662 CGF.EmitNewArrayInitializer(E, NewPtr, NumElements);
663 return;
664 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000665 }
Anders Carlsson3a202f62009-11-24 18:43:52 +0000666
667 if (CXXConstructorDecl *Ctor = E->getConstructor()) {
Douglas Gregor747eb782010-07-08 06:14:04 +0000668 // Per C++ [expr.new]p15, if we have an initializer, then we're performing
669 // direct initialization. C++ [dcl.init]p5 requires that we
670 // zero-initialize storage if there are no user-declared constructors.
671 if (E->hasInitializer() &&
672 !Ctor->getParent()->hasUserDeclaredConstructor() &&
673 !Ctor->getParent()->isEmpty())
674 CGF.EmitNullInitialization(NewPtr, E->getAllocatedType());
675
Douglas Gregore1823702010-07-07 23:37:33 +0000676 CGF.EmitCXXConstructorCall(Ctor, Ctor_Complete, /*ForVirtualBase=*/false,
677 NewPtr, E->constructor_arg_begin(),
678 E->constructor_arg_end());
Anders Carlsson3a202f62009-11-24 18:43:52 +0000679
680 return;
681 }
Fariborz Jahanianb66b08e2010-06-25 20:01:13 +0000682 // We have a POD type.
683 if (E->getNumConstructorArgs() == 0)
684 return;
685
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000686 StoreAnyExprIntoOneUnit(CGF, E, NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000687}
688
Benjamin Kramerfb5e5842010-10-22 16:48:22 +0000689namespace {
John McCall7f9c92a2010-09-17 00:50:28 +0000690/// A utility class for saving an rvalue.
691class SavedRValue {
692public:
693 enum Kind { ScalarLiteral, ScalarAddress,
694 AggregateLiteral, AggregateAddress,
695 Complex };
696
697private:
698 llvm::Value *Value;
699 Kind K;
700
701 SavedRValue(llvm::Value *V, Kind K) : Value(V), K(K) {}
702
703public:
704 SavedRValue() {}
705
706 static SavedRValue forScalarLiteral(llvm::Value *V) {
707 return SavedRValue(V, ScalarLiteral);
708 }
709
710 static SavedRValue forScalarAddress(llvm::Value *Addr) {
711 return SavedRValue(Addr, ScalarAddress);
712 }
713
714 static SavedRValue forAggregateLiteral(llvm::Value *V) {
715 return SavedRValue(V, AggregateLiteral);
716 }
717
718 static SavedRValue forAggregateAddress(llvm::Value *Addr) {
719 return SavedRValue(Addr, AggregateAddress);
720 }
721
722 static SavedRValue forComplexAddress(llvm::Value *Addr) {
723 return SavedRValue(Addr, Complex);
724 }
725
726 Kind getKind() const { return K; }
727 llvm::Value *getValue() const { return Value; }
728};
Benjamin Kramerfb5e5842010-10-22 16:48:22 +0000729} // end anonymous namespace
John McCall7f9c92a2010-09-17 00:50:28 +0000730
731/// Given an r-value, perform the code necessary to make sure that a
732/// future RestoreRValue will be able to load the value without
733/// domination concerns.
734static SavedRValue SaveRValue(CodeGenFunction &CGF, RValue RV) {
735 if (RV.isScalar()) {
736 llvm::Value *V = RV.getScalarVal();
737
738 // These automatically dominate and don't need to be saved.
739 if (isa<llvm::Constant>(V) || isa<llvm::AllocaInst>(V))
740 return SavedRValue::forScalarLiteral(V);
741
742 // Everything else needs an alloca.
743 llvm::Value *Addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
744 CGF.Builder.CreateStore(V, Addr);
745 return SavedRValue::forScalarAddress(Addr);
746 }
747
748 if (RV.isComplex()) {
749 CodeGenFunction::ComplexPairTy V = RV.getComplexVal();
750 const llvm::Type *ComplexTy =
751 llvm::StructType::get(CGF.getLLVMContext(),
752 V.first->getType(), V.second->getType(),
753 (void*) 0);
754 llvm::Value *Addr = CGF.CreateTempAlloca(ComplexTy, "saved-complex");
755 CGF.StoreComplexToAddr(V, Addr, /*volatile*/ false);
756 return SavedRValue::forComplexAddress(Addr);
757 }
758
759 assert(RV.isAggregate());
760 llvm::Value *V = RV.getAggregateAddr(); // TODO: volatile?
761 if (isa<llvm::Constant>(V) || isa<llvm::AllocaInst>(V))
762 return SavedRValue::forAggregateLiteral(V);
763
764 llvm::Value *Addr = CGF.CreateTempAlloca(V->getType(), "saved-rvalue");
765 CGF.Builder.CreateStore(V, Addr);
766 return SavedRValue::forAggregateAddress(Addr);
767}
768
769/// Given a saved r-value produced by SaveRValue, perform the code
770/// necessary to restore it to usability at the current insertion
771/// point.
772static RValue RestoreRValue(CodeGenFunction &CGF, SavedRValue RV) {
773 switch (RV.getKind()) {
774 case SavedRValue::ScalarLiteral:
775 return RValue::get(RV.getValue());
776 case SavedRValue::ScalarAddress:
777 return RValue::get(CGF.Builder.CreateLoad(RV.getValue()));
778 case SavedRValue::AggregateLiteral:
779 return RValue::getAggregate(RV.getValue());
780 case SavedRValue::AggregateAddress:
781 return RValue::getAggregate(CGF.Builder.CreateLoad(RV.getValue()));
782 case SavedRValue::Complex:
783 return RValue::getComplex(CGF.LoadComplexFromAddr(RV.getValue(), false));
784 }
785
786 llvm_unreachable("bad saved r-value kind");
787 return RValue();
788}
789
John McCall824c2f52010-09-14 07:57:04 +0000790namespace {
791 /// A cleanup to call the given 'operator delete' function upon
792 /// abnormal exit from a new expression.
793 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
794 size_t NumPlacementArgs;
795 const FunctionDecl *OperatorDelete;
796 llvm::Value *Ptr;
797 llvm::Value *AllocSize;
798
799 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
800
801 public:
802 static size_t getExtraSize(size_t NumPlacementArgs) {
803 return NumPlacementArgs * sizeof(RValue);
804 }
805
806 CallDeleteDuringNew(size_t NumPlacementArgs,
807 const FunctionDecl *OperatorDelete,
808 llvm::Value *Ptr,
809 llvm::Value *AllocSize)
810 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
811 Ptr(Ptr), AllocSize(AllocSize) {}
812
813 void setPlacementArg(unsigned I, RValue Arg) {
814 assert(I < NumPlacementArgs && "index out of range");
815 getPlacementArgs()[I] = Arg;
816 }
817
818 void Emit(CodeGenFunction &CGF, bool IsForEH) {
819 const FunctionProtoType *FPT
820 = OperatorDelete->getType()->getAs<FunctionProtoType>();
821 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCalld441b1e2010-09-14 21:45:42 +0000822 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +0000823
824 CallArgList DeleteArgs;
825
826 // The first argument is always a void*.
827 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
828 DeleteArgs.push_back(std::make_pair(RValue::get(Ptr), *AI++));
829
830 // A member 'operator delete' can take an extra 'size_t' argument.
831 if (FPT->getNumArgs() == NumPlacementArgs + 2)
832 DeleteArgs.push_back(std::make_pair(RValue::get(AllocSize), *AI++));
833
834 // Pass the rest of the arguments, which must match exactly.
835 for (unsigned I = 0; I != NumPlacementArgs; ++I)
836 DeleteArgs.push_back(std::make_pair(getPlacementArgs()[I], *AI++));
837
838 // Call 'operator delete'.
839 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
840 CGF.CGM.GetAddrOfFunction(OperatorDelete),
841 ReturnValueSlot(), DeleteArgs, OperatorDelete);
842 }
843 };
John McCall7f9c92a2010-09-17 00:50:28 +0000844
845 /// A cleanup to call the given 'operator delete' function upon
846 /// abnormal exit from a new expression when the new expression is
847 /// conditional.
848 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
849 size_t NumPlacementArgs;
850 const FunctionDecl *OperatorDelete;
851 SavedRValue Ptr;
852 SavedRValue AllocSize;
853
854 SavedRValue *getPlacementArgs() {
855 return reinterpret_cast<SavedRValue*>(this+1);
856 }
857
858 public:
859 static size_t getExtraSize(size_t NumPlacementArgs) {
860 return NumPlacementArgs * sizeof(SavedRValue);
861 }
862
863 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
864 const FunctionDecl *OperatorDelete,
865 SavedRValue Ptr,
866 SavedRValue AllocSize)
867 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
868 Ptr(Ptr), AllocSize(AllocSize) {}
869
870 void setPlacementArg(unsigned I, SavedRValue Arg) {
871 assert(I < NumPlacementArgs && "index out of range");
872 getPlacementArgs()[I] = Arg;
873 }
874
875 void Emit(CodeGenFunction &CGF, bool IsForEH) {
876 const FunctionProtoType *FPT
877 = OperatorDelete->getType()->getAs<FunctionProtoType>();
878 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
879 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
880
881 CallArgList DeleteArgs;
882
883 // The first argument is always a void*.
884 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
885 DeleteArgs.push_back(std::make_pair(RestoreRValue(CGF, Ptr), *AI++));
886
887 // A member 'operator delete' can take an extra 'size_t' argument.
888 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
889 RValue RV = RestoreRValue(CGF, AllocSize);
890 DeleteArgs.push_back(std::make_pair(RV, *AI++));
891 }
892
893 // Pass the rest of the arguments, which must match exactly.
894 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
895 RValue RV = RestoreRValue(CGF, getPlacementArgs()[I]);
896 DeleteArgs.push_back(std::make_pair(RV, *AI++));
897 }
898
899 // Call 'operator delete'.
900 CGF.EmitCall(CGF.CGM.getTypes().getFunctionInfo(DeleteArgs, FPT),
901 CGF.CGM.GetAddrOfFunction(OperatorDelete),
902 ReturnValueSlot(), DeleteArgs, OperatorDelete);
903 }
904 };
905}
906
907/// Enter a cleanup to call 'operator delete' if the initializer in a
908/// new-expression throws.
909static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
910 const CXXNewExpr *E,
911 llvm::Value *NewPtr,
912 llvm::Value *AllocSize,
913 const CallArgList &NewArgs) {
914 // If we're not inside a conditional branch, then the cleanup will
915 // dominate and we can do the easier (and more efficient) thing.
916 if (!CGF.isInConditionalBranch()) {
917 CallDeleteDuringNew *Cleanup = CGF.EHStack
918 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
919 E->getNumPlacementArgs(),
920 E->getOperatorDelete(),
921 NewPtr, AllocSize);
922 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
923 Cleanup->setPlacementArg(I, NewArgs[I+1].first);
924
925 return;
926 }
927
928 // Otherwise, we need to save all this stuff.
929 SavedRValue SavedNewPtr = SaveRValue(CGF, RValue::get(NewPtr));
930 SavedRValue SavedAllocSize = SaveRValue(CGF, RValue::get(AllocSize));
931
932 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
933 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(InactiveEHCleanup,
934 E->getNumPlacementArgs(),
935 E->getOperatorDelete(),
936 SavedNewPtr,
937 SavedAllocSize);
938 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
939 Cleanup->setPlacementArg(I, SaveRValue(CGF, NewArgs[I+1].first));
940
941 CGF.ActivateCleanupBlock(CGF.EHStack.stable_begin());
John McCall824c2f52010-09-14 07:57:04 +0000942}
943
Anders Carlssoncc52f652009-09-22 22:53:17 +0000944llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
Anders Carlssoncc52f652009-09-22 22:53:17 +0000945 QualType AllocType = E->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000946 if (AllocType->isArrayType())
947 while (const ArrayType *AType = getContext().getAsArrayType(AllocType))
948 AllocType = AType->getElementType();
949
Anders Carlssoncc52f652009-09-22 22:53:17 +0000950 FunctionDecl *NewFD = E->getOperatorNew();
951 const FunctionProtoType *NewFTy = NewFD->getType()->getAs<FunctionProtoType>();
952
953 CallArgList NewArgs;
954
955 // The allocation size is the first argument.
956 QualType SizeTy = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +0000957
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000958 llvm::Value *NumElements = 0;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000959 llvm::Value *AllocSizeWithoutCookie = 0;
Fariborz Jahanian47b46292010-03-24 16:57:01 +0000960 llvm::Value *AllocSize = EmitCXXNewAllocSize(getContext(),
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000961 *this, E, NumElements,
962 AllocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000963
Anders Carlssoncc52f652009-09-22 22:53:17 +0000964 NewArgs.push_back(std::make_pair(RValue::get(AllocSize), SizeTy));
965
966 // Emit the rest of the arguments.
967 // FIXME: Ideally, this should just use EmitCallArgs.
968 CXXNewExpr::const_arg_iterator NewArg = E->placement_arg_begin();
969
970 // First, use the types from the function type.
971 // We start at 1 here because the first argument (the allocation size)
972 // has already been emitted.
973 for (unsigned i = 1, e = NewFTy->getNumArgs(); i != e; ++i, ++NewArg) {
974 QualType ArgType = NewFTy->getArgType(i);
975
976 assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
977 getTypePtr() ==
978 getContext().getCanonicalType(NewArg->getType()).getTypePtr() &&
979 "type mismatch in call argument!");
980
981 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
982 ArgType));
983
984 }
985
986 // Either we've emitted all the call args, or we have a call to a
987 // variadic function.
988 assert((NewArg == E->placement_arg_end() || NewFTy->isVariadic()) &&
989 "Extra arguments in non-variadic function!");
990
991 // If we still have any arguments, emit them using the type of the argument.
992 for (CXXNewExpr::const_arg_iterator NewArgEnd = E->placement_arg_end();
993 NewArg != NewArgEnd; ++NewArg) {
994 QualType ArgType = NewArg->getType();
995 NewArgs.push_back(std::make_pair(EmitCallArg(*NewArg, ArgType),
996 ArgType));
997 }
998
999 // Emit the call to new.
1000 RValue RV =
John McCallab26cfa2010-02-05 21:31:56 +00001001 EmitCall(CGM.getTypes().getFunctionInfo(NewArgs, NewFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001002 CGM.GetAddrOfFunction(NewFD), ReturnValueSlot(), NewArgs, NewFD);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001003
1004 // If an allocation function is declared with an empty exception specification
1005 // it returns null to indicate failure to allocate storage. [expr.new]p13.
1006 // (We don't need to check for null when there's no new initializer and
1007 // we're allocating a POD type).
1008 bool NullCheckResult = NewFTy->hasEmptyExceptionSpec() &&
1009 !(AllocType->isPODType() && !E->hasInitializer());
1010
John McCall8ed55a52010-09-02 09:58:18 +00001011 llvm::BasicBlock *NullCheckSource = 0;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001012 llvm::BasicBlock *NewNotNull = 0;
1013 llvm::BasicBlock *NewEnd = 0;
1014
1015 llvm::Value *NewPtr = RV.getScalarVal();
John McCall8ed55a52010-09-02 09:58:18 +00001016 unsigned AS = cast<llvm::PointerType>(NewPtr->getType())->getAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001017
1018 if (NullCheckResult) {
John McCall8ed55a52010-09-02 09:58:18 +00001019 NullCheckSource = Builder.GetInsertBlock();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001020 NewNotNull = createBasicBlock("new.notnull");
1021 NewEnd = createBasicBlock("new.end");
1022
John McCall8ed55a52010-09-02 09:58:18 +00001023 llvm::Value *IsNull = Builder.CreateIsNull(NewPtr, "new.isnull");
1024 Builder.CreateCondBr(IsNull, NewEnd, NewNotNull);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001025 EmitBlock(NewNotNull);
1026 }
Ken Dyck3eb55cf2010-01-26 19:44:24 +00001027
John McCall8ed55a52010-09-02 09:58:18 +00001028 assert((AllocSize == AllocSizeWithoutCookie) ==
1029 CalculateCookiePadding(*this, E).isZero());
1030 if (AllocSize != AllocSizeWithoutCookie) {
1031 assert(E->isArray());
1032 NewPtr = CGM.getCXXABI().InitializeArrayCookie(CGF, NewPtr, NumElements,
1033 AllocType);
1034 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001035
John McCall824c2f52010-09-14 07:57:04 +00001036 // If there's an operator delete, enter a cleanup to call it if an
1037 // exception is thrown.
1038 EHScopeStack::stable_iterator CallOperatorDelete;
1039 if (E->getOperatorDelete()) {
John McCall7f9c92a2010-09-17 00:50:28 +00001040 EnterNewDeleteCleanup(*this, E, NewPtr, AllocSize, NewArgs);
John McCall824c2f52010-09-14 07:57:04 +00001041 CallOperatorDelete = EHStack.stable_begin();
1042 }
1043
Douglas Gregor040ad502010-09-02 23:24:14 +00001044 const llvm::Type *ElementPtrTy
1045 = ConvertTypeForMem(AllocType)->getPointerTo(AS);
John McCall8ed55a52010-09-02 09:58:18 +00001046 NewPtr = Builder.CreateBitCast(NewPtr, ElementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001047
John McCall8ed55a52010-09-02 09:58:18 +00001048 if (E->isArray()) {
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001049 EmitNewInitializer(*this, E, NewPtr, NumElements, AllocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001050
1051 // NewPtr is a pointer to the base element type. If we're
1052 // allocating an array of arrays, we'll need to cast back to the
1053 // array pointer type.
Douglas Gregor040ad502010-09-02 23:24:14 +00001054 const llvm::Type *ResultTy = ConvertTypeForMem(E->getType());
John McCall8ed55a52010-09-02 09:58:18 +00001055 if (NewPtr->getType() != ResultTy)
1056 NewPtr = Builder.CreateBitCast(NewPtr, ResultTy);
1057 } else {
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001058 EmitNewInitializer(*this, E, NewPtr, NumElements, AllocSizeWithoutCookie);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001059 }
John McCall824c2f52010-09-14 07:57:04 +00001060
1061 // Deactivate the 'operator delete' cleanup if we finished
1062 // initialization.
1063 if (CallOperatorDelete.isValid())
1064 DeactivateCleanupBlock(CallOperatorDelete);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001065
Anders Carlssoncc52f652009-09-22 22:53:17 +00001066 if (NullCheckResult) {
1067 Builder.CreateBr(NewEnd);
John McCall8ed55a52010-09-02 09:58:18 +00001068 llvm::BasicBlock *NotNullSource = Builder.GetInsertBlock();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001069 EmitBlock(NewEnd);
1070
1071 llvm::PHINode *PHI = Builder.CreatePHI(NewPtr->getType());
1072 PHI->reserveOperandSpace(2);
John McCall8ed55a52010-09-02 09:58:18 +00001073 PHI->addIncoming(NewPtr, NotNullSource);
1074 PHI->addIncoming(llvm::Constant::getNullValue(NewPtr->getType()),
1075 NullCheckSource);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001076
1077 NewPtr = PHI;
1078 }
John McCall8ed55a52010-09-02 09:58:18 +00001079
Anders Carlssoncc52f652009-09-22 22:53:17 +00001080 return NewPtr;
1081}
1082
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001083void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1084 llvm::Value *Ptr,
1085 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001086 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1087
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001088 const FunctionProtoType *DeleteFTy =
1089 DeleteFD->getType()->getAs<FunctionProtoType>();
1090
1091 CallArgList DeleteArgs;
1092
Anders Carlsson21122cf2009-12-13 20:04:38 +00001093 // Check if we need to pass the size to the delete operator.
1094 llvm::Value *Size = 0;
1095 QualType SizeTy;
1096 if (DeleteFTy->getNumArgs() == 2) {
1097 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001098 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1099 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1100 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001101 }
1102
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001103 QualType ArgTy = DeleteFTy->getArgType(0);
1104 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1105 DeleteArgs.push_back(std::make_pair(RValue::get(DeletePtr), ArgTy));
1106
Anders Carlsson21122cf2009-12-13 20:04:38 +00001107 if (Size)
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001108 DeleteArgs.push_back(std::make_pair(RValue::get(Size), SizeTy));
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001109
1110 // Emit the call to delete.
John McCallab26cfa2010-02-05 21:31:56 +00001111 EmitCall(CGM.getTypes().getFunctionInfo(DeleteArgs, DeleteFTy),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001112 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001113 DeleteArgs, DeleteFD);
1114}
1115
John McCall8ed55a52010-09-02 09:58:18 +00001116namespace {
1117 /// Calls the given 'operator delete' on a single object.
1118 struct CallObjectDelete : EHScopeStack::Cleanup {
1119 llvm::Value *Ptr;
1120 const FunctionDecl *OperatorDelete;
1121 QualType ElementType;
1122
1123 CallObjectDelete(llvm::Value *Ptr,
1124 const FunctionDecl *OperatorDelete,
1125 QualType ElementType)
1126 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1127
1128 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1129 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1130 }
1131 };
1132}
1133
1134/// Emit the code for deleting a single object.
1135static void EmitObjectDelete(CodeGenFunction &CGF,
1136 const FunctionDecl *OperatorDelete,
1137 llvm::Value *Ptr,
1138 QualType ElementType) {
1139 // Find the destructor for the type, if applicable. If the
1140 // destructor is virtual, we'll just emit the vcall and return.
1141 const CXXDestructorDecl *Dtor = 0;
1142 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1143 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1144 if (!RD->hasTrivialDestructor()) {
1145 Dtor = RD->getDestructor();
1146
1147 if (Dtor->isVirtual()) {
1148 const llvm::Type *Ty =
John McCall0d635f52010-09-03 01:26:39 +00001149 CGF.getTypes().GetFunctionType(CGF.getTypes().getFunctionInfo(Dtor,
1150 Dtor_Complete),
John McCall8ed55a52010-09-02 09:58:18 +00001151 /*isVariadic=*/false);
1152
1153 llvm::Value *Callee
1154 = CGF.BuildVirtualCall(Dtor, Dtor_Deleting, Ptr, Ty);
1155 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1156 0, 0);
1157
1158 // The dtor took care of deleting the object.
1159 return;
1160 }
1161 }
1162 }
1163
1164 // Make sure that we call delete even if the dtor throws.
1165 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1166 Ptr, OperatorDelete, ElementType);
1167
1168 if (Dtor)
1169 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1170 /*ForVirtualBase=*/false, Ptr);
1171
1172 CGF.PopCleanupBlock();
1173}
1174
1175namespace {
1176 /// Calls the given 'operator delete' on an array of objects.
1177 struct CallArrayDelete : EHScopeStack::Cleanup {
1178 llvm::Value *Ptr;
1179 const FunctionDecl *OperatorDelete;
1180 llvm::Value *NumElements;
1181 QualType ElementType;
1182 CharUnits CookieSize;
1183
1184 CallArrayDelete(llvm::Value *Ptr,
1185 const FunctionDecl *OperatorDelete,
1186 llvm::Value *NumElements,
1187 QualType ElementType,
1188 CharUnits CookieSize)
1189 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1190 ElementType(ElementType), CookieSize(CookieSize) {}
1191
1192 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1193 const FunctionProtoType *DeleteFTy =
1194 OperatorDelete->getType()->getAs<FunctionProtoType>();
1195 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1196
1197 CallArgList Args;
1198
1199 // Pass the pointer as the first argument.
1200 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1201 llvm::Value *DeletePtr
1202 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
1203 Args.push_back(std::make_pair(RValue::get(DeletePtr), VoidPtrTy));
1204
1205 // Pass the original requested size as the second argument.
1206 if (DeleteFTy->getNumArgs() == 2) {
1207 QualType size_t = DeleteFTy->getArgType(1);
1208 const llvm::IntegerType *SizeTy
1209 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1210
1211 CharUnits ElementTypeSize =
1212 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1213
1214 // The size of an element, multiplied by the number of elements.
1215 llvm::Value *Size
1216 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1217 Size = CGF.Builder.CreateMul(Size, NumElements);
1218
1219 // Plus the size of the cookie if applicable.
1220 if (!CookieSize.isZero()) {
1221 llvm::Value *CookieSizeV
1222 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1223 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1224 }
1225
1226 Args.push_back(std::make_pair(RValue::get(Size), size_t));
1227 }
1228
1229 // Emit the call to delete.
1230 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Args, DeleteFTy),
1231 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1232 ReturnValueSlot(), Args, OperatorDelete);
1233 }
1234 };
1235}
1236
1237/// Emit the code for deleting an array of objects.
1238static void EmitArrayDelete(CodeGenFunction &CGF,
1239 const FunctionDecl *OperatorDelete,
1240 llvm::Value *Ptr,
1241 QualType ElementType) {
1242 llvm::Value *NumElements = 0;
1243 llvm::Value *AllocatedPtr = 0;
1244 CharUnits CookieSize;
1245 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, Ptr, ElementType,
1246 NumElements, AllocatedPtr, CookieSize);
1247
1248 assert(AllocatedPtr && "ReadArrayCookie didn't set AllocatedPtr");
1249
1250 // Make sure that we call delete even if one of the dtors throws.
1251 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1252 AllocatedPtr, OperatorDelete,
1253 NumElements, ElementType,
1254 CookieSize);
1255
1256 if (const CXXRecordDecl *RD = ElementType->getAsCXXRecordDecl()) {
1257 if (!RD->hasTrivialDestructor()) {
1258 assert(NumElements && "ReadArrayCookie didn't find element count"
1259 " for a class with destructor");
1260 CGF.EmitCXXAggrDestructorCall(RD->getDestructor(), NumElements, Ptr);
1261 }
1262 }
1263
1264 CGF.PopCleanupBlock();
1265}
1266
Anders Carlssoncc52f652009-09-22 22:53:17 +00001267void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Fariborz Jahanian6814eaa2009-11-13 19:27:47 +00001268
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001269 // Get at the argument before we performed the implicit conversion
1270 // to void*.
1271 const Expr *Arg = E->getArgument();
1272 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
John McCalle3027922010-08-25 11:45:40 +00001273 if (ICE->getCastKind() != CK_UserDefinedConversion &&
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001274 ICE->getType()->isVoidPointerType())
1275 Arg = ICE->getSubExpr();
Douglas Gregore364e7b2009-10-01 05:49:51 +00001276 else
1277 break;
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001278 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001279
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001280 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001281
1282 // Null check the pointer.
1283 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1284 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1285
1286 llvm::Value *IsNull =
1287 Builder.CreateICmpEQ(Ptr, llvm::Constant::getNullValue(Ptr->getType()),
1288 "isnull");
1289
1290 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1291 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001292
John McCall8ed55a52010-09-02 09:58:18 +00001293 // We might be deleting a pointer to array. If so, GEP down to the
1294 // first non-array element.
1295 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1296 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1297 if (DeleteTy->isConstantArrayType()) {
1298 llvm::Value *Zero = Builder.getInt32(0);
1299 llvm::SmallVector<llvm::Value*,8> GEP;
1300
1301 GEP.push_back(Zero); // point at the outermost array
1302
1303 // For each layer of array type we're pointing at:
1304 while (const ConstantArrayType *Arr
1305 = getContext().getAsConstantArrayType(DeleteTy)) {
1306 // 1. Unpeel the array type.
1307 DeleteTy = Arr->getElementType();
1308
1309 // 2. GEP to the first element of the array.
1310 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001311 }
John McCall8ed55a52010-09-02 09:58:18 +00001312
1313 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP.begin(), GEP.end(), "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001314 }
1315
Douglas Gregor04f36212010-09-02 17:38:50 +00001316 assert(ConvertTypeForMem(DeleteTy) ==
1317 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001318
1319 if (E->isArrayForm()) {
1320 EmitArrayDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1321 } else {
1322 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy);
1323 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001324
Anders Carlssoncc52f652009-09-22 22:53:17 +00001325 EmitBlock(DeleteEnd);
1326}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001327
1328llvm::Value * CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
1329 QualType Ty = E->getType();
1330 const llvm::Type *LTy = ConvertType(Ty)->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001331
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001332 if (E->isTypeOperand()) {
1333 llvm::Constant *TypeInfo =
1334 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
1335 return Builder.CreateBitCast(TypeInfo, LTy);
1336 }
1337
Mike Stumpc9b231c2009-11-15 08:09:41 +00001338 Expr *subE = E->getExprOperand();
Mike Stump6fdfea62009-11-17 22:33:00 +00001339 Ty = subE->getType();
1340 CanQualType CanTy = CGM.getContext().getCanonicalType(Ty);
1341 Ty = CanTy.getUnqualifiedType().getNonReferenceType();
Mike Stumpc9b231c2009-11-15 08:09:41 +00001342 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1343 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1344 if (RD->isPolymorphic()) {
1345 // FIXME: if subE is an lvalue do
1346 LValue Obj = EmitLValue(subE);
1347 llvm::Value *This = Obj.getAddress();
Mike Stump1bf924b2009-11-15 16:52:53 +00001348 // We need to do a zero check for *p, unless it has NonNullAttr.
1349 // FIXME: PointerType->hasAttr<NonNullAttr>()
1350 bool CanBeZero = false;
Mike Stumpc2c03342009-11-17 00:45:21 +00001351 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(subE->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +00001352 if (UO->getOpcode() == UO_Deref)
Mike Stump1bf924b2009-11-15 16:52:53 +00001353 CanBeZero = true;
1354 if (CanBeZero) {
1355 llvm::BasicBlock *NonZeroBlock = createBasicBlock();
1356 llvm::BasicBlock *ZeroBlock = createBasicBlock();
1357
Dan Gohman8fc50c22010-10-26 18:44:08 +00001358 llvm::Value *Zero = llvm::Constant::getNullValue(This->getType());
1359 Builder.CreateCondBr(Builder.CreateICmpNE(This, Zero),
Mike Stump1bf924b2009-11-15 16:52:53 +00001360 NonZeroBlock, ZeroBlock);
1361 EmitBlock(ZeroBlock);
1362 /// Call __cxa_bad_typeid
1363 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1364 const llvm::FunctionType *FTy;
1365 FTy = llvm::FunctionType::get(ResultType, false);
1366 llvm::Value *F = CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
Mike Stump65511702009-11-16 06:50:58 +00001367 Builder.CreateCall(F)->setDoesNotReturn();
Mike Stump1bf924b2009-11-15 16:52:53 +00001368 Builder.CreateUnreachable();
1369 EmitBlock(NonZeroBlock);
1370 }
Dan Gohman8fc50c22010-10-26 18:44:08 +00001371 llvm::Value *V = GetVTablePtr(This, LTy->getPointerTo());
Mike Stumpc9b231c2009-11-15 08:09:41 +00001372 V = Builder.CreateConstInBoundsGEP1_64(V, -1ULL);
1373 V = Builder.CreateLoad(V);
1374 return V;
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001375 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001376 }
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001377 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(Ty), LTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001378}
Mike Stump65511702009-11-16 06:50:58 +00001379
1380llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *V,
1381 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001382 QualType SrcTy = DCE->getSubExpr()->getType();
1383 QualType DestTy = DCE->getTypeAsWritten();
1384 QualType InnerType = DestTy->getPointeeType();
1385
Mike Stump65511702009-11-16 06:50:58 +00001386 const llvm::Type *LTy = ConvertType(DCE->getType());
Mike Stump6ca0e212009-11-16 22:52:20 +00001387
Mike Stump65511702009-11-16 06:50:58 +00001388 bool CanBeZero = false;
Mike Stump65511702009-11-16 06:50:58 +00001389 bool ToVoid = false;
Mike Stump6ca0e212009-11-16 22:52:20 +00001390 bool ThrowOnBad = false;
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001391 if (DestTy->isPointerType()) {
Mike Stump65511702009-11-16 06:50:58 +00001392 // FIXME: if PointerType->hasAttr<NonNullAttr>(), we don't set this
1393 CanBeZero = true;
1394 if (InnerType->isVoidType())
1395 ToVoid = true;
1396 } else {
1397 LTy = LTy->getPointerTo();
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001398
1399 // FIXME: What if exceptions are disabled?
Mike Stump65511702009-11-16 06:50:58 +00001400 ThrowOnBad = true;
1401 }
1402
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001403 if (SrcTy->isPointerType() || SrcTy->isReferenceType())
1404 SrcTy = SrcTy->getPointeeType();
1405 SrcTy = SrcTy.getUnqualifiedType();
1406
Anders Carlsson0087bc82009-12-18 14:55:04 +00001407 if (DestTy->isPointerType() || DestTy->isReferenceType())
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001408 DestTy = DestTy->getPointeeType();
1409 DestTy = DestTy.getUnqualifiedType();
Mike Stump65511702009-11-16 06:50:58 +00001410
Mike Stump65511702009-11-16 06:50:58 +00001411 llvm::BasicBlock *ContBlock = createBasicBlock();
1412 llvm::BasicBlock *NullBlock = 0;
1413 llvm::BasicBlock *NonZeroBlock = 0;
1414 if (CanBeZero) {
1415 NonZeroBlock = createBasicBlock();
1416 NullBlock = createBasicBlock();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001417 Builder.CreateCondBr(Builder.CreateIsNotNull(V), NonZeroBlock, NullBlock);
Mike Stump65511702009-11-16 06:50:58 +00001418 EmitBlock(NonZeroBlock);
1419 }
1420
Mike Stump65511702009-11-16 06:50:58 +00001421 llvm::BasicBlock *BadCastBlock = 0;
Mike Stump65511702009-11-16 06:50:58 +00001422
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001423 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType());
Mike Stump6ca0e212009-11-16 22:52:20 +00001424
1425 // See if this is a dynamic_cast(void*)
1426 if (ToVoid) {
1427 llvm::Value *This = V;
Dan Gohman8fc50c22010-10-26 18:44:08 +00001428 V = GetVTablePtr(This, PtrDiffTy->getPointerTo());
Mike Stump6ca0e212009-11-16 22:52:20 +00001429 V = Builder.CreateConstInBoundsGEP1_64(V, -2ULL);
1430 V = Builder.CreateLoad(V, "offset to top");
1431 This = Builder.CreateBitCast(This, llvm::Type::getInt8PtrTy(VMContext));
1432 V = Builder.CreateInBoundsGEP(This, V);
1433 V = Builder.CreateBitCast(V, LTy);
1434 } else {
1435 /// Call __dynamic_cast
1436 const llvm::Type *ResultType = llvm::Type::getInt8PtrTy(VMContext);
1437 const llvm::FunctionType *FTy;
1438 std::vector<const llvm::Type*> ArgTys;
1439 const llvm::Type *PtrToInt8Ty
1440 = llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1441 ArgTys.push_back(PtrToInt8Ty);
1442 ArgTys.push_back(PtrToInt8Ty);
1443 ArgTys.push_back(PtrToInt8Ty);
1444 ArgTys.push_back(PtrDiffTy);
1445 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump6ca0e212009-11-16 22:52:20 +00001446
1447 // FIXME: Calculate better hint.
1448 llvm::Value *hint = llvm::ConstantInt::get(PtrDiffTy, -1ULL);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001449
1450 assert(SrcTy->isRecordType() && "Src type must be record type!");
1451 assert(DestTy->isRecordType() && "Dest type must be record type!");
1452
Douglas Gregor247894b2009-12-23 22:04:40 +00001453 llvm::Value *SrcArg
1454 = CGM.GetAddrOfRTTIDescriptor(SrcTy.getUnqualifiedType());
1455 llvm::Value *DestArg
1456 = CGM.GetAddrOfRTTIDescriptor(DestTy.getUnqualifiedType());
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001457
Mike Stump6ca0e212009-11-16 22:52:20 +00001458 V = Builder.CreateBitCast(V, PtrToInt8Ty);
1459 V = Builder.CreateCall4(CGM.CreateRuntimeFunction(FTy, "__dynamic_cast"),
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001460 V, SrcArg, DestArg, hint);
Mike Stump6ca0e212009-11-16 22:52:20 +00001461 V = Builder.CreateBitCast(V, LTy);
1462
1463 if (ThrowOnBad) {
1464 BadCastBlock = createBasicBlock();
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001465 Builder.CreateCondBr(Builder.CreateIsNotNull(V), ContBlock, BadCastBlock);
Mike Stump6ca0e212009-11-16 22:52:20 +00001466 EmitBlock(BadCastBlock);
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001467 /// Invoke __cxa_bad_cast
Mike Stump6ca0e212009-11-16 22:52:20 +00001468 ResultType = llvm::Type::getVoidTy(VMContext);
1469 const llvm::FunctionType *FBadTy;
Mike Stump3afea1d2009-11-17 03:01:03 +00001470 FBadTy = llvm::FunctionType::get(ResultType, false);
Mike Stump6ca0e212009-11-16 22:52:20 +00001471 llvm::Value *F = CGM.CreateRuntimeFunction(FBadTy, "__cxa_bad_cast");
Douglas Gregorfa8b4952010-05-14 21:14:41 +00001472 if (llvm::BasicBlock *InvokeDest = getInvokeDest()) {
1473 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
1474 Builder.CreateInvoke(F, Cont, InvokeDest)->setDoesNotReturn();
1475 EmitBlock(Cont);
1476 } else {
1477 // FIXME: Does this ever make sense?
1478 Builder.CreateCall(F)->setDoesNotReturn();
1479 }
Mike Stumpe8cdcc92009-11-17 00:08:50 +00001480 Builder.CreateUnreachable();
Mike Stump6ca0e212009-11-16 22:52:20 +00001481 }
Mike Stump65511702009-11-16 06:50:58 +00001482 }
1483
1484 if (CanBeZero) {
1485 Builder.CreateBr(ContBlock);
1486 EmitBlock(NullBlock);
1487 Builder.CreateBr(ContBlock);
1488 }
1489 EmitBlock(ContBlock);
1490 if (CanBeZero) {
1491 llvm::PHINode *PHI = Builder.CreatePHI(LTy);
Mike Stump4d0e9092009-11-17 00:10:05 +00001492 PHI->reserveOperandSpace(2);
Mike Stump65511702009-11-16 06:50:58 +00001493 PHI->addIncoming(V, NonZeroBlock);
1494 PHI->addIncoming(llvm::Constant::getNullValue(LTy), NullBlock);
Mike Stump65511702009-11-16 06:50:58 +00001495 V = PHI;
1496 }
1497
1498 return V;
1499}