blob: 31ea1b5448a7f27cc63c7e1f3760f7fcec82e159 [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
Anders Carlsson3b5ad222010-01-01 20:29:01 +000036 CallArgList Args;
37
38 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +000039 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson3b5ad222010-01-01 20:29:01 +000040
Anders Carlssonc997d422010-01-02 01:01:18 +000041 // If there is a VTT parameter, emit it.
42 if (VTT) {
43 QualType T = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +000044 Args.add(RValue::get(VTT), T);
Anders Carlssonc997d422010-01-02 01:01:18 +000045 }
John McCallde5d3c72012-02-17 03:33:10 +000046
47 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
48 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Anders Carlssonc997d422010-01-02 01:01:18 +000049
John McCallde5d3c72012-02-17 03:33:10 +000050 // And the rest of the call args.
Anders Carlsson3b5ad222010-01-01 20:29:01 +000051 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
52
John McCall0f3d0972012-07-07 06:41:13 +000053 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
Rafael Espindola264ba482010-03-30 20:24:48 +000054 Callee, ReturnValue, Args, MD);
Anders Carlsson3b5ad222010-01-01 20:29:01 +000055}
56
Anders Carlssoncd0b32e2011-04-10 18:20:53 +000057// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
58// quite what we want.
59static const Expr *skipNoOpCastsAndParens(const Expr *E) {
60 while (true) {
61 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
62 E = PE->getSubExpr();
63 continue;
64 }
65
66 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
67 if (CE->getCastKind() == CK_NoOp) {
68 E = CE->getSubExpr();
69 continue;
70 }
71 }
72 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
73 if (UO->getOpcode() == UO_Extension) {
74 E = UO->getSubExpr();
75 continue;
76 }
77 }
78 return E;
79 }
80}
81
Anders Carlsson3b5ad222010-01-01 20:29:01 +000082/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
83/// expr can be devirtualized.
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +000084static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context,
85 const Expr *Base,
Anders Carlssonbd2bfae2010-10-27 13:28:46 +000086 const CXXMethodDecl *MD) {
87
Anders Carlsson1679f5a2011-01-29 03:52:01 +000088 // When building with -fapple-kext, all calls must go through the vtable since
89 // the kernel linker can do runtime patching of vtables.
David Blaikie4e4d0842012-03-11 07:00:24 +000090 if (Context.getLangOpts().AppleKext)
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +000091 return false;
92
Anders Carlsson1679f5a2011-01-29 03:52:01 +000093 // If the most derived class is marked final, we know that no subclass can
94 // override this member function and so we can devirtualize it. For example:
95 //
96 // struct A { virtual void f(); }
97 // struct B final : A { };
98 //
99 // void f(B *b) {
100 // b->f();
101 // }
102 //
Rafael Espindola8d852e32012-06-27 18:18:05 +0000103 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlsson1679f5a2011-01-29 03:52:01 +0000104 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
105 return true;
106
Anders Carlssonf89e0422011-01-23 21:07:30 +0000107 // If the member function is marked 'final', we know that it can't be
Anders Carlssond66f4282010-10-27 13:34:43 +0000108 // overridden and can therefore devirtualize it.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000109 if (MD->hasAttr<FinalAttr>())
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000110 return true;
Anders Carlssond66f4282010-10-27 13:34:43 +0000111
Anders Carlssonf89e0422011-01-23 21:07:30 +0000112 // Similarly, if the class itself is marked 'final' it can't be overridden
113 // and we can therefore devirtualize the member function call.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +0000114 if (MD->getParent()->hasAttr<FinalAttr>())
Anders Carlssond66f4282010-10-27 13:34:43 +0000115 return true;
116
Anders Carlssoncd0b32e2011-04-10 18:20:53 +0000117 Base = skipNoOpCastsAndParens(Base);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000118 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
119 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
120 // This is a record decl. We know the type and can devirtualize it.
121 return VD->getType()->isRecordType();
122 }
123
124 return false;
125 }
Richard Smithac452932012-08-15 22:59:28 +0000126
127 // We can devirtualize calls on an object accessed by a class member access
128 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
129 // a derived class object constructed in the same location.
130 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
131 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
132 return VD->getType()->isRecordType();
133
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000134 // We can always devirtualize calls on temporary object expressions.
Eli Friedman6997aae2010-01-31 20:58:15 +0000135 if (isa<CXXConstructExpr>(Base))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000136 return true;
137
138 // And calls on bound temporaries.
139 if (isa<CXXBindTemporaryExpr>(Base))
140 return true;
141
142 // Check if this is a call expr that returns a record type.
143 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
144 return CE->getCallReturnType()->isRecordType();
Anders Carlssonbd2bfae2010-10-27 13:28:46 +0000145
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000146 // We can't devirtualize the call.
147 return false;
148}
149
Rafael Espindolaea01d762012-06-28 14:28:57 +0000150static CXXRecordDecl *getCXXRecord(const Expr *E) {
151 QualType T = E->getType();
152 if (const PointerType *PTy = T->getAs<PointerType>())
153 T = PTy->getPointeeType();
154 const RecordType *Ty = T->castAs<RecordType>();
155 return cast<CXXRecordDecl>(Ty->getDecl());
156}
157
Francois Pichetdbee3412011-01-18 05:04:39 +0000158// Note: This function also emit constructor calls to support a MSVC
159// extensions allowing explicit constructor function call.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000160RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
161 ReturnValueSlot ReturnValue) {
John McCall379b5152011-04-11 07:02:50 +0000162 const Expr *callee = CE->getCallee()->IgnoreParens();
163
164 if (isa<BinaryOperator>(callee))
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000165 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall379b5152011-04-11 07:02:50 +0000166
167 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000168 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
169
Devang Patelc69e1cf2010-09-30 19:05:55 +0000170 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000171 if (DI && CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo
Devang Patel68020272010-10-22 18:56:27 +0000172 && !isa<CallExpr>(ME->getBase())) {
Devang Patelc69e1cf2010-09-30 19:05:55 +0000173 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType();
174 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) {
175 DI->getOrCreateRecordType(PTy->getPointeeType(),
176 MD->getParent()->getLocation());
177 }
178 }
179
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000180 if (MD->isStatic()) {
181 // The method is static, emit it as we would a regular call.
182 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
183 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
184 ReturnValue, CE->arg_begin(), CE->arg_end());
185 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000186
John McCallfc400282010-09-03 01:26:39 +0000187 // Compute the object pointer.
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000188 const Expr *Base = ME->getBase();
189 bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000190
Rafael Espindolaea01d762012-06-28 14:28:57 +0000191 const CXXMethodDecl *DevirtualizedMethod = NULL;
192 if (CanUseVirtualCall &&
193 canDevirtualizeMemberFunctionCalls(getContext(), Base, MD)) {
194 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
195 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
196 assert(DevirtualizedMethod);
197 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
198 const Expr *Inner = Base->ignoreParenBaseCasts();
199 if (getCXXRecord(Inner) == DevirtualizedClass)
200 // If the class of the Inner expression is where the dynamic method
201 // is defined, build the this pointer from it.
202 Base = Inner;
203 else if (getCXXRecord(Base) != DevirtualizedClass) {
204 // If the method is defined in a class that is not the best dynamic
205 // one or the one of the full expression, we would have to build
206 // a derived-to-base cast to compute the correct this pointer, but
207 // we don't have support for that yet, so do a virtual call.
208 DevirtualizedMethod = NULL;
209 }
Rafael Espindola80bc96e2012-06-28 17:57:36 +0000210 // If the return types are not the same, this might be a case where more
211 // code needs to run to compensate for it. For example, the derived
212 // method might return a type that inherits form from the return
213 // type of MD and has a prefix.
214 // For now we just avoid devirtualizing these covariant cases.
215 if (DevirtualizedMethod &&
216 DevirtualizedMethod->getResultType().getCanonicalType() !=
217 MD->getResultType().getCanonicalType())
Rafael Espindola4a889e42012-06-28 15:11:39 +0000218 DevirtualizedMethod = NULL;
Rafael Espindolaea01d762012-06-28 14:28:57 +0000219 }
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000220
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000221 llvm::Value *This;
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000222 if (ME->isArrow())
Rafael Espindolaea01d762012-06-28 14:28:57 +0000223 This = EmitScalarExpr(Base);
John McCall0e800c92010-12-04 08:14:53 +0000224 else
Rafael Espindolaea01d762012-06-28 14:28:57 +0000225 This = EmitLValue(Base).getAddress();
Rafael Espindola632fbaa2012-06-28 01:56:38 +0000226
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000227
John McCallfc400282010-09-03 01:26:39 +0000228 if (MD->isTrivial()) {
229 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0);
Francois Pichetdbee3412011-01-18 05:04:39 +0000230 if (isa<CXXConstructorDecl>(MD) &&
231 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
232 return RValue::get(0);
John McCallfc400282010-09-03 01:26:39 +0000233
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000234 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
235 // We don't like to generate the trivial copy/move assignment operator
236 // when it isn't necessary; just produce the proper effect here.
Francois Pichetdbee3412011-01-18 05:04:39 +0000237 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
238 EmitAggregateCopy(This, RHS, CE->getType());
239 return RValue::get(This);
240 }
241
242 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000243 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
244 // Trivial move and copy ctor are the same.
Francois Pichetdbee3412011-01-18 05:04:39 +0000245 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
246 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
247 CE->arg_begin(), CE->arg_end());
248 return RValue::get(This);
249 }
250 llvm_unreachable("unknown trivial member function");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000251 }
252
John McCallfc400282010-09-03 01:26:39 +0000253 // Compute the function type we're calling.
Francois Pichetdbee3412011-01-18 05:04:39 +0000254 const CGFunctionInfo *FInfo = 0;
255 if (isa<CXXDestructorDecl>(MD))
John McCallde5d3c72012-02-17 03:33:10 +0000256 FInfo = &CGM.getTypes().arrangeCXXDestructor(cast<CXXDestructorDecl>(MD),
257 Dtor_Complete);
Francois Pichetdbee3412011-01-18 05:04:39 +0000258 else if (isa<CXXConstructorDecl>(MD))
John McCallde5d3c72012-02-17 03:33:10 +0000259 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(
260 cast<CXXConstructorDecl>(MD),
261 Ctor_Complete);
Francois Pichetdbee3412011-01-18 05:04:39 +0000262 else
John McCallde5d3c72012-02-17 03:33:10 +0000263 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(MD);
John McCallfc400282010-09-03 01:26:39 +0000264
John McCallde5d3c72012-02-17 03:33:10 +0000265 llvm::Type *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCallfc400282010-09-03 01:26:39 +0000266
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000267 // C++ [class.virtual]p12:
268 // Explicit qualification with the scope operator (5.1) suppresses the
269 // virtual call mechanism.
270 //
271 // We also don't emit a virtual call if the base expression has a record type
272 // because then we know what the type is.
Rafael Espindolaea01d762012-06-28 14:28:57 +0000273 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000274
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000275 llvm::Value *Callee;
John McCallfc400282010-09-03 01:26:39 +0000276 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
277 if (UseVirtualCall) {
278 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000279 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +0000280 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahanianccd52592011-02-01 23:22:34 +0000281 MD->isVirtual() &&
282 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000283 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000284 else if (!DevirtualizedMethod)
Rafael Espindola12582bd2012-06-26 19:18:25 +0000285 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000286 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000287 const CXXDestructorDecl *DDtor =
288 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000289 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
290 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000291 }
Francois Pichetdbee3412011-01-18 05:04:39 +0000292 } else if (const CXXConstructorDecl *Ctor =
293 dyn_cast<CXXConstructorDecl>(MD)) {
294 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCallfc400282010-09-03 01:26:39 +0000295 } else if (UseVirtualCall) {
Fariborz Jahanian27262672011-01-20 17:19:02 +0000296 Callee = BuildVirtualCall(MD, This, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000297 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +0000298 if (getContext().getLangOpts().AppleKext &&
Fariborz Jahaniana50e33e2011-01-28 23:42:29 +0000299 MD->isVirtual() &&
Fariborz Jahanian7ac0ff22011-01-21 01:04:41 +0000300 ME->hasQualifier())
Fariborz Jahanian771c6782011-02-03 19:27:17 +0000301 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindolaea01d762012-06-28 14:28:57 +0000302 else if (!DevirtualizedMethod)
Rafael Espindola12582bd2012-06-26 19:18:25 +0000303 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000304 else {
Rafael Espindolaea01d762012-06-28 14:28:57 +0000305 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola0b4fe502012-06-26 17:45:31 +0000306 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000307 }
308
Anders Carlssonc997d422010-01-02 01:01:18 +0000309 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000310 CE->arg_begin(), CE->arg_end());
311}
312
313RValue
314CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
315 ReturnValueSlot ReturnValue) {
316 const BinaryOperator *BO =
317 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
318 const Expr *BaseExpr = BO->getLHS();
319 const Expr *MemFnExpr = BO->getRHS();
320
321 const MemberPointerType *MPT =
John McCall864c0412011-04-26 20:42:42 +0000322 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall93d557b2010-08-22 00:05:51 +0000323
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000324 const FunctionProtoType *FPT =
John McCall864c0412011-04-26 20:42:42 +0000325 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000326 const CXXRecordDecl *RD =
327 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
328
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000329 // Get the member function pointer.
John McCalld608cdb2010-08-22 10:59:02 +0000330 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000331
332 // Emit the 'this' pointer.
333 llvm::Value *This;
334
John McCall2de56d12010-08-25 11:45:40 +0000335 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000336 This = EmitScalarExpr(BaseExpr);
337 else
338 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000339
John McCall93d557b2010-08-22 00:05:51 +0000340 // Ask the ABI to load the callee. Note that This is modified.
341 llvm::Value *Callee =
John McCalld16c2cf2011-02-08 08:22:06 +0000342 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000343
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000344 CallArgList Args;
345
346 QualType ThisType =
347 getContext().getPointerType(getContext().getTagDeclType(RD));
348
349 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +0000350 Args.add(RValue::get(This), ThisType);
John McCall0f3d0972012-07-07 06:41:13 +0000351
352 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000353
354 // And the rest of the call args
355 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
John McCall0f3d0972012-07-07 06:41:13 +0000356 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required), Callee,
Tilmann Scheller9c6082f2011-03-02 21:36:49 +0000357 ReturnValue, Args);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000358}
359
360RValue
361CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
362 const CXXMethodDecl *MD,
363 ReturnValueSlot ReturnValue) {
364 assert(MD->isInstance() &&
365 "Trying to emit a member call expr on a static method!");
John McCall0e800c92010-12-04 08:14:53 +0000366 LValue LV = EmitLValue(E->getArg(0));
367 llvm::Value *This = LV.getAddress();
368
Douglas Gregorb2b56582011-09-06 16:26:56 +0000369 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
370 MD->isTrivial()) {
371 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
372 QualType Ty = E->getType();
373 EmitAggregateCopy(This, Src, Ty);
374 return RValue::get(This);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000375 }
376
Anders Carlssona2447e02011-05-08 20:32:23 +0000377 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Anders Carlssonc997d422010-01-02 01:01:18 +0000378 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0,
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000379 E->arg_begin() + 1, E->arg_end());
380}
381
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000382RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
383 ReturnValueSlot ReturnValue) {
384 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
385}
386
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000387static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
388 llvm::Value *DestPtr,
389 const CXXRecordDecl *Base) {
390 if (Base->isEmpty())
391 return;
392
393 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
394
395 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
396 CharUnits Size = Layout.getNonVirtualSize();
397 CharUnits Align = Layout.getNonVirtualAlign();
398
399 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
400
401 // If the type contains a pointer to data member we can't memset it to zero.
402 // Instead, create a null constant and copy it to the destination.
403 // TODO: there are other patterns besides zero that we can usefully memset,
404 // like -1, which happens to be the pattern used by member-pointers.
405 // TODO: isZeroInitializable can be over-conservative in the case where a
406 // virtual base contains a member pointer.
407 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
408 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
409
410 llvm::GlobalVariable *NullVariable =
411 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
412 /*isConstant=*/true,
413 llvm::GlobalVariable::PrivateLinkage,
414 NullConstant, Twine());
415 NullVariable->setAlignment(Align.getQuantity());
416 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
417
418 // Get and call the appropriate llvm.memcpy overload.
419 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
420 return;
421 }
422
423 // Otherwise, just memset the whole thing to zero. This is legal
424 // because in LLVM, all default initializers (other than the ones we just
425 // handled above) are guaranteed to have a bit pattern of all zeros.
426 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
427 Align.getQuantity());
428}
429
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000430void
John McCall558d2ab2010-09-15 10:14:12 +0000431CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
432 AggValueSlot Dest) {
433 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000434 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor759e41b2010-08-22 16:15:35 +0000435
436 // If we require zero initialization before (or instead of) calling the
437 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +0000438 // constructor, emit the zero initialization now, unless destination is
439 // already zeroed.
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000440 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
441 switch (E->getConstructionKind()) {
442 case CXXConstructExpr::CK_Delegating:
Eli Friedman2ed7cb62011-10-14 02:27:24 +0000443 case CXXConstructExpr::CK_Complete:
444 EmitNullInitialization(Dest.getAddr(), E->getType());
445 break;
446 case CXXConstructExpr::CK_VirtualBase:
447 case CXXConstructExpr::CK_NonVirtualBase:
448 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
449 break;
450 }
451 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000452
453 // If this is a call to a trivial default constructor, do nothing.
454 if (CD->isTrivial() && CD->isDefaultConstructor())
455 return;
456
John McCallfc1e6c72010-09-18 00:58:34 +0000457 // Elide the constructor if we're constructing from a temporary.
458 // The temporary check is required because Sema sets this on NRVO
459 // returns.
David Blaikie4e4d0842012-03-11 07:00:24 +0000460 if (getContext().getLangOpts().ElideConstructors && E->isElidable()) {
John McCallfc1e6c72010-09-18 00:58:34 +0000461 assert(getContext().hasSameUnqualifiedType(E->getType(),
462 E->getArg(0)->getType()));
John McCall558d2ab2010-09-15 10:14:12 +0000463 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
464 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor3c9034c2010-05-15 00:13:29 +0000465 return;
466 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000467 }
Douglas Gregor759e41b2010-08-22 16:15:35 +0000468
John McCallc3c07662011-07-13 06:10:41 +0000469 if (const ConstantArrayType *arrayType
470 = getContext().getAsConstantArrayType(E->getType())) {
471 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000472 E->arg_begin(), E->arg_end());
John McCallc3c07662011-07-13 06:10:41 +0000473 } else {
Cameron Esfahani6bd2f6a2011-05-06 21:28:42 +0000474 CXXCtorType Type = Ctor_Complete;
Sean Huntd49bd552011-05-03 20:19:28 +0000475 bool ForVirtualBase = false;
476
477 switch (E->getConstructionKind()) {
478 case CXXConstructExpr::CK_Delegating:
Sean Hunt059ce0d2011-05-01 07:04:31 +0000479 // We should be emitting a constructor; GlobalDecl will assert this
480 Type = CurGD.getCtorType();
Sean Huntd49bd552011-05-03 20:19:28 +0000481 break;
Sean Hunt059ce0d2011-05-01 07:04:31 +0000482
Sean Huntd49bd552011-05-03 20:19:28 +0000483 case CXXConstructExpr::CK_Complete:
484 Type = Ctor_Complete;
485 break;
486
487 case CXXConstructExpr::CK_VirtualBase:
488 ForVirtualBase = true;
489 // fall-through
490
491 case CXXConstructExpr::CK_NonVirtualBase:
492 Type = Ctor_Base;
493 }
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000494
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000495 // Call the constructor.
John McCall558d2ab2010-09-15 10:14:12 +0000496 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(),
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000497 E->arg_begin(), E->arg_end());
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000498 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000499}
500
Fariborz Jahanian34999872010-11-13 21:53:34 +0000501void
502CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
503 llvm::Value *Src,
Fariborz Jahanian830937b2010-12-02 17:02:11 +0000504 const Expr *Exp) {
John McCall4765fa02010-12-06 08:20:24 +0000505 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahanian34999872010-11-13 21:53:34 +0000506 Exp = E->getSubExpr();
507 assert(isa<CXXConstructExpr>(Exp) &&
508 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
509 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
510 const CXXConstructorDecl *CD = E->getConstructor();
511 RunCleanupsScope Scope(*this);
512
513 // If we require zero initialization before (or instead of) calling the
514 // constructor, as can be the case with a non-user-provided default
515 // constructor, emit the zero initialization now.
516 // FIXME. Do I still need this for a copy ctor synthesis?
517 if (E->requiresZeroInitialization())
518 EmitNullInitialization(Dest, E->getType());
519
Chandler Carruth858a5462010-11-15 13:54:43 +0000520 assert(!getContext().getAsConstantArrayType(E->getType())
521 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Fariborz Jahanian34999872010-11-13 21:53:34 +0000522 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src,
523 E->arg_begin(), E->arg_end());
524}
525
John McCall1e7fe752010-09-02 09:58:18 +0000526static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
527 const CXXNewExpr *E) {
Anders Carlsson871d0782009-12-13 20:04:38 +0000528 if (!E->isArray())
Ken Dyckcaf647c2010-01-26 19:44:24 +0000529 return CharUnits::Zero();
Anders Carlsson871d0782009-12-13 20:04:38 +0000530
John McCallb1c98a32011-05-16 01:05:12 +0000531 // No cookie is required if the operator new[] being used is the
532 // reserved placement operator new[].
533 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCall5172ed92010-08-23 01:17:59 +0000534 return CharUnits::Zero();
535
John McCall6ec278d2011-01-27 09:37:56 +0000536 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000537}
538
John McCall7d166272011-05-15 07:14:44 +0000539static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
540 const CXXNewExpr *e,
Sebastian Redl92036472012-02-22 17:37:52 +0000541 unsigned minElements,
John McCall7d166272011-05-15 07:14:44 +0000542 llvm::Value *&numElements,
543 llvm::Value *&sizeWithoutCookie) {
544 QualType type = e->getAllocatedType();
John McCall1e7fe752010-09-02 09:58:18 +0000545
John McCall7d166272011-05-15 07:14:44 +0000546 if (!e->isArray()) {
547 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
548 sizeWithoutCookie
549 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
550 return sizeWithoutCookie;
Douglas Gregor59174c02010-07-21 01:10:17 +0000551 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000552
John McCall7d166272011-05-15 07:14:44 +0000553 // The width of size_t.
554 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
555
John McCall1e7fe752010-09-02 09:58:18 +0000556 // Figure out the cookie size.
John McCall7d166272011-05-15 07:14:44 +0000557 llvm::APInt cookieSize(sizeWidth,
558 CalculateCookiePadding(CGF, e).getQuantity());
John McCall1e7fe752010-09-02 09:58:18 +0000559
Anders Carlssona4d4c012009-09-23 16:07:23 +0000560 // Emit the array size expression.
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000561 // We multiply the size of all dimensions for NumElements.
562 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall7d166272011-05-15 07:14:44 +0000563 numElements = CGF.EmitScalarExpr(e->getArraySize());
564 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall1e7fe752010-09-02 09:58:18 +0000565
John McCall7d166272011-05-15 07:14:44 +0000566 // The number of elements can be have an arbitrary integer type;
567 // essentially, we need to multiply it by a constant factor, add a
568 // cookie size, and verify that the result is representable as a
569 // size_t. That's just a gloss, though, and it's wrong in one
570 // important way: if the count is negative, it's an error even if
571 // the cookie size would bring the total size >= 0.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000572 bool isSigned
573 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2acc6e32011-07-18 04:24:23 +0000574 llvm::IntegerType *numElementsType
John McCall7d166272011-05-15 07:14:44 +0000575 = cast<llvm::IntegerType>(numElements->getType());
576 unsigned numElementsWidth = numElementsType->getBitWidth();
577
578 // Compute the constant factor.
579 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000580 while (const ConstantArrayType *CAT
John McCall7d166272011-05-15 07:14:44 +0000581 = CGF.getContext().getAsConstantArrayType(type)) {
582 type = CAT->getElementType();
583 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidise7ab92e2010-08-26 15:23:38 +0000584 }
585
John McCall7d166272011-05-15 07:14:44 +0000586 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
587 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
588 typeSizeMultiplier *= arraySizeMultiplier;
589
590 // This will be a size_t.
591 llvm::Value *size;
Chris Lattner83252dc2010-07-20 21:07:09 +0000592
Chris Lattner806941e2010-07-20 21:55:52 +0000593 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
594 // Don't bloat the -O0 code.
John McCall7d166272011-05-15 07:14:44 +0000595 if (llvm::ConstantInt *numElementsC =
596 dyn_cast<llvm::ConstantInt>(numElements)) {
597 const llvm::APInt &count = numElementsC->getValue();
John McCall1e7fe752010-09-02 09:58:18 +0000598
John McCall7d166272011-05-15 07:14:44 +0000599 bool hasAnyOverflow = false;
John McCall1e7fe752010-09-02 09:58:18 +0000600
John McCall7d166272011-05-15 07:14:44 +0000601 // If 'count' was a negative number, it's an overflow.
602 if (isSigned && count.isNegative())
603 hasAnyOverflow = true;
John McCall1e7fe752010-09-02 09:58:18 +0000604
John McCall7d166272011-05-15 07:14:44 +0000605 // We want to do all this arithmetic in size_t. If numElements is
606 // wider than that, check whether it's already too big, and if so,
607 // overflow.
608 else if (numElementsWidth > sizeWidth &&
609 numElementsWidth - sizeWidth > count.countLeadingZeros())
610 hasAnyOverflow = true;
611
612 // Okay, compute a count at the right width.
613 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
614
Sebastian Redl92036472012-02-22 17:37:52 +0000615 // If there is a brace-initializer, we cannot allocate fewer elements than
616 // there are initializers. If we do, that's treated like an overflow.
617 if (adjustedCount.ult(minElements))
618 hasAnyOverflow = true;
619
John McCall7d166272011-05-15 07:14:44 +0000620 // Scale numElements by that. This might overflow, but we don't
621 // care because it only overflows if allocationSize does, too, and
622 // if that overflows then we shouldn't use this.
623 numElements = llvm::ConstantInt::get(CGF.SizeTy,
624 adjustedCount * arraySizeMultiplier);
625
626 // Compute the size before cookie, and track whether it overflowed.
627 bool overflow;
628 llvm::APInt allocationSize
629 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
630 hasAnyOverflow |= overflow;
631
632 // Add in the cookie, and check whether it's overflowed.
633 if (cookieSize != 0) {
634 // Save the current size without a cookie. This shouldn't be
635 // used if there was overflow.
636 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
637
638 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
639 hasAnyOverflow |= overflow;
640 }
641
642 // On overflow, produce a -1 so operator new will fail.
643 if (hasAnyOverflow) {
644 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
645 } else {
646 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
647 }
648
649 // Otherwise, we might need to use the overflow intrinsics.
650 } else {
Sebastian Redl92036472012-02-22 17:37:52 +0000651 // There are up to five conditions we need to test for:
John McCall7d166272011-05-15 07:14:44 +0000652 // 1) if isSigned, we need to check whether numElements is negative;
653 // 2) if numElementsWidth > sizeWidth, we need to check whether
654 // numElements is larger than something representable in size_t;
Sebastian Redl92036472012-02-22 17:37:52 +0000655 // 3) if minElements > 0, we need to check whether numElements is smaller
656 // than that.
657 // 4) we need to compute
John McCall7d166272011-05-15 07:14:44 +0000658 // sizeWithoutCookie := numElements * typeSizeMultiplier
659 // and check whether it overflows; and
Sebastian Redl92036472012-02-22 17:37:52 +0000660 // 5) if we need a cookie, we need to compute
John McCall7d166272011-05-15 07:14:44 +0000661 // size := sizeWithoutCookie + cookieSize
662 // and check whether it overflows.
663
664 llvm::Value *hasOverflow = 0;
665
666 // If numElementsWidth > sizeWidth, then one way or another, we're
667 // going to have to do a comparison for (2), and this happens to
668 // take care of (1), too.
669 if (numElementsWidth > sizeWidth) {
670 llvm::APInt threshold(numElementsWidth, 1);
671 threshold <<= sizeWidth;
672
673 llvm::Value *thresholdV
674 = llvm::ConstantInt::get(numElementsType, threshold);
675
676 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
677 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
678
679 // Otherwise, if we're signed, we want to sext up to size_t.
680 } else if (isSigned) {
681 if (numElementsWidth < sizeWidth)
682 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
683
684 // If there's a non-1 type size multiplier, then we can do the
685 // signedness check at the same time as we do the multiply
686 // because a negative number times anything will cause an
Sebastian Redl92036472012-02-22 17:37:52 +0000687 // unsigned overflow. Otherwise, we have to do it here. But at least
688 // in this case, we can subsume the >= minElements check.
John McCall7d166272011-05-15 07:14:44 +0000689 if (typeSizeMultiplier == 1)
690 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redl92036472012-02-22 17:37:52 +0000691 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall7d166272011-05-15 07:14:44 +0000692
693 // Otherwise, zext up to size_t if necessary.
694 } else if (numElementsWidth < sizeWidth) {
695 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
696 }
697
698 assert(numElements->getType() == CGF.SizeTy);
699
Sebastian Redl92036472012-02-22 17:37:52 +0000700 if (minElements) {
701 // Don't allow allocation of fewer elements than we have initializers.
702 if (!hasOverflow) {
703 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
704 llvm::ConstantInt::get(CGF.SizeTy, minElements));
705 } else if (numElementsWidth > sizeWidth) {
706 // The other existing overflow subsumes this check.
707 // We do an unsigned comparison, since any signed value < -1 is
708 // taken care of either above or below.
709 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
710 CGF.Builder.CreateICmpULT(numElements,
711 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
712 }
713 }
714
John McCall7d166272011-05-15 07:14:44 +0000715 size = numElements;
716
717 // Multiply by the type size if necessary. This multiplier
718 // includes all the factors for nested arrays.
719 //
720 // This step also causes numElements to be scaled up by the
721 // nested-array factor if necessary. Overflow on this computation
722 // can be ignored because the result shouldn't be used if
723 // allocation fails.
724 if (typeSizeMultiplier != 1) {
John McCall7d166272011-05-15 07:14:44 +0000725 llvm::Value *umul_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000726 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000727
728 llvm::Value *tsmV =
729 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
730 llvm::Value *result =
731 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
732
733 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
734 if (hasOverflow)
735 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
736 else
737 hasOverflow = overflowed;
738
739 size = CGF.Builder.CreateExtractValue(result, 0);
740
741 // Also scale up numElements by the array size multiplier.
742 if (arraySizeMultiplier != 1) {
743 // If the base element type size is 1, then we can re-use the
744 // multiply we just did.
745 if (typeSize.isOne()) {
746 assert(arraySizeMultiplier == typeSizeMultiplier);
747 numElements = size;
748
749 // Otherwise we need a separate multiply.
750 } else {
751 llvm::Value *asmV =
752 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
753 numElements = CGF.Builder.CreateMul(numElements, asmV);
754 }
755 }
756 } else {
757 // numElements doesn't need to be scaled.
758 assert(arraySizeMultiplier == 1);
Chris Lattner806941e2010-07-20 21:55:52 +0000759 }
760
John McCall7d166272011-05-15 07:14:44 +0000761 // Add in the cookie size if necessary.
762 if (cookieSize != 0) {
763 sizeWithoutCookie = size;
764
John McCall7d166272011-05-15 07:14:44 +0000765 llvm::Value *uadd_with_overflow
Benjamin Kramer8dd55a32011-07-14 17:45:50 +0000766 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall7d166272011-05-15 07:14:44 +0000767
768 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
769 llvm::Value *result =
770 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
771
772 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
773 if (hasOverflow)
774 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
775 else
776 hasOverflow = overflowed;
777
778 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall1e7fe752010-09-02 09:58:18 +0000779 }
Anders Carlssona4d4c012009-09-23 16:07:23 +0000780
John McCall7d166272011-05-15 07:14:44 +0000781 // If we had any possibility of dynamic overflow, make a select to
782 // overwrite 'size' with an all-ones value, which should cause
783 // operator new to throw.
784 if (hasOverflow)
785 size = CGF.Builder.CreateSelect(hasOverflow,
786 llvm::Constant::getAllOnesValue(CGF.SizeTy),
787 size);
Chris Lattner806941e2010-07-20 21:55:52 +0000788 }
John McCall1e7fe752010-09-02 09:58:18 +0000789
John McCall7d166272011-05-15 07:14:44 +0000790 if (cookieSize == 0)
791 sizeWithoutCookie = size;
John McCall1e7fe752010-09-02 09:58:18 +0000792 else
John McCall7d166272011-05-15 07:14:44 +0000793 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall1e7fe752010-09-02 09:58:18 +0000794
John McCall7d166272011-05-15 07:14:44 +0000795 return size;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000796}
797
Sebastian Redl92036472012-02-22 17:37:52 +0000798static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
799 QualType AllocType, llvm::Value *NewPtr) {
Daniel Dunbar91a16fa2010-08-21 02:24:36 +0000800
Eli Friedmand7722d92011-12-03 02:13:40 +0000801 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCalla07398e2011-06-16 04:16:24 +0000802 if (!CGF.hasAggregateLLVMType(AllocType))
Eli Friedmand7722d92011-12-03 02:13:40 +0000803 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType,
Eli Friedman6da2c712011-12-03 04:14:32 +0000804 Alignment),
John McCalla07398e2011-06-16 04:16:24 +0000805 false);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000806 else if (AllocType->isAnyComplexType())
807 CGF.EmitComplexExprIntoAddr(Init, NewPtr,
808 AllocType.isVolatileQualified());
John McCall558d2ab2010-09-15 10:14:12 +0000809 else {
810 AggValueSlot Slot
Eli Friedmanf3940782011-12-03 00:54:26 +0000811 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000812 AggValueSlot::IsDestructed,
John McCall44184392011-08-26 07:31:35 +0000813 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000814 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000815 CGF.EmitAggExpr(Init, Slot);
Sebastian Redl972edf02012-02-19 16:03:09 +0000816
817 CGF.MaybeEmitStdInitializerListCleanup(NewPtr, Init);
John McCall558d2ab2010-09-15 10:14:12 +0000818 }
Fariborz Jahanianef668722010-06-25 18:26:07 +0000819}
820
821void
822CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000823 QualType elementType,
824 llvm::Value *beginPtr,
825 llvm::Value *numElements) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000826 if (!E->hasInitializer())
827 return; // We have a POD type.
John McCall19705672011-09-15 06:49:18 +0000828
Sebastian Redl92036472012-02-22 17:37:52 +0000829 llvm::Value *explicitPtr = beginPtr;
John McCall19705672011-09-15 06:49:18 +0000830 // Find the end of the array, hoisted out of the loop.
831 llvm::Value *endPtr =
832 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end");
833
Sebastian Redl92036472012-02-22 17:37:52 +0000834 unsigned initializerElements = 0;
835
836 const Expr *Init = E->getInitializer();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000837 llvm::AllocaInst *endOfInit = 0;
838 QualType::DestructionKind dtorKind = elementType.isDestructedType();
839 EHScopeStack::stable_iterator cleanup;
840 llvm::Instruction *cleanupDominator = 0;
Sebastian Redl92036472012-02-22 17:37:52 +0000841 // If the initializer is an initializer list, first do the explicit elements.
842 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
843 initializerElements = ILE->getNumInits();
Chad Rosier577fb5b2012-02-24 00:13:55 +0000844
845 // Enter a partial-destruction cleanup if necessary.
846 if (needsEHCleanup(dtorKind)) {
847 // In principle we could tell the cleanup where we are more
848 // directly, but the control flow can get so varied here that it
849 // would actually be quite complex. Therefore we go through an
850 // alloca.
851 endOfInit = CreateTempAlloca(beginPtr->getType(), "array.endOfInit");
852 cleanupDominator = Builder.CreateStore(beginPtr, endOfInit);
853 pushIrregularPartialArrayCleanup(beginPtr, endOfInit, elementType,
854 getDestroyer(dtorKind));
855 cleanup = EHStack.stable_begin();
856 }
857
Sebastian Redl92036472012-02-22 17:37:52 +0000858 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosier577fb5b2012-02-24 00:13:55 +0000859 // Tell the cleanup that it needs to destroy up to this
860 // element. TODO: some of these stores can be trivially
861 // observed to be unnecessary.
862 if (endOfInit) Builder.CreateStore(explicitPtr, endOfInit);
Sebastian Redl92036472012-02-22 17:37:52 +0000863 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), elementType, explicitPtr);
864 explicitPtr =Builder.CreateConstGEP1_32(explicitPtr, 1, "array.exp.next");
865 }
866
867 // The remaining elements are filled with the array filler expression.
868 Init = ILE->getArrayFiller();
869 }
870
John McCall19705672011-09-15 06:49:18 +0000871 // Create the continuation block.
872 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end");
873
Sebastian Redl92036472012-02-22 17:37:52 +0000874 // If the number of elements isn't constant, we have to now check if there is
875 // anything left to initialize.
876 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) {
877 // If all elements have already been initialized, skip the whole loop.
Chad Rosier577fb5b2012-02-24 00:13:55 +0000878 if (constNum->getZExtValue() <= initializerElements) {
879 // If there was a cleanup, deactivate it.
880 if (cleanupDominator)
881 DeactivateCleanupBlock(cleanup, cleanupDominator);;
882 return;
883 }
Sebastian Redl92036472012-02-22 17:37:52 +0000884 } else {
John McCall19705672011-09-15 06:49:18 +0000885 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty");
Sebastian Redl92036472012-02-22 17:37:52 +0000886 llvm::Value *isEmpty = Builder.CreateICmpEQ(explicitPtr, endPtr,
John McCall19705672011-09-15 06:49:18 +0000887 "array.isempty");
888 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB);
889 EmitBlock(nonEmptyBB);
890 }
891
892 // Enter the loop.
893 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
894 llvm::BasicBlock *loopBB = createBasicBlock("new.loop");
895
896 EmitBlock(loopBB);
897
898 // Set up the current-element phi.
899 llvm::PHINode *curPtr =
Sebastian Redl92036472012-02-22 17:37:52 +0000900 Builder.CreatePHI(explicitPtr->getType(), 2, "array.cur");
901 curPtr->addIncoming(explicitPtr, entryBB);
John McCall19705672011-09-15 06:49:18 +0000902
Chad Rosier577fb5b2012-02-24 00:13:55 +0000903 // Store the new cleanup position for irregular cleanups.
904 if (endOfInit) Builder.CreateStore(curPtr, endOfInit);
905
John McCall19705672011-09-15 06:49:18 +0000906 // Enter a partial-destruction cleanup if necessary.
Chad Rosier577fb5b2012-02-24 00:13:55 +0000907 if (!cleanupDominator && needsEHCleanup(dtorKind)) {
John McCall19705672011-09-15 06:49:18 +0000908 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType,
909 getDestroyer(dtorKind));
910 cleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +0000911 cleanupDominator = Builder.CreateUnreachable();
John McCall19705672011-09-15 06:49:18 +0000912 }
913
914 // Emit the initializer into this element.
Sebastian Redl92036472012-02-22 17:37:52 +0000915 StoreAnyExprIntoOneUnit(*this, Init, E->getAllocatedType(), curPtr);
John McCall19705672011-09-15 06:49:18 +0000916
917 // Leave the cleanup if we entered one.
Eli Friedman40563cd2011-12-09 23:05:37 +0000918 if (cleanupDominator) {
John McCall6f103ba2011-11-10 10:43:54 +0000919 DeactivateCleanupBlock(cleanup, cleanupDominator);
920 cleanupDominator->eraseFromParent();
921 }
John McCall19705672011-09-15 06:49:18 +0000922
923 // Advance to the next element.
924 llvm::Value *nextPtr = Builder.CreateConstGEP1_32(curPtr, 1, "array.next");
925
926 // Check whether we've gotten to the end of the array and, if so,
927 // exit the loop.
928 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend");
929 Builder.CreateCondBr(isEnd, contBB, loopBB);
930 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock());
931
932 EmitBlock(contBB);
Fariborz Jahanianef668722010-06-25 18:26:07 +0000933}
934
Douglas Gregor59174c02010-07-21 01:10:17 +0000935static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T,
936 llvm::Value *NewPtr, llvm::Value *Size) {
John McCalld16c2cf2011-02-08 08:22:06 +0000937 CGF.EmitCastToVoidPtr(NewPtr);
Ken Dyckfe710082011-01-19 01:58:38 +0000938 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T);
Benjamin Kramer9f0c7cc2010-12-30 00:13:21 +0000939 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size,
Ken Dyckfe710082011-01-19 01:58:38 +0000940 Alignment.getQuantity(), false);
Douglas Gregor59174c02010-07-21 01:10:17 +0000941}
942
Anders Carlssona4d4c012009-09-23 16:07:23 +0000943static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall19705672011-09-15 06:49:18 +0000944 QualType ElementType,
Anders Carlssona4d4c012009-09-23 16:07:23 +0000945 llvm::Value *NewPtr,
Douglas Gregor59174c02010-07-21 01:10:17 +0000946 llvm::Value *NumElements,
947 llvm::Value *AllocSizeWithoutCookie) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000948 const Expr *Init = E->getInitializer();
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000949 if (E->isArray()) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000950 if (const CXXConstructExpr *CCE = dyn_cast_or_null<CXXConstructExpr>(Init)){
951 CXXConstructorDecl *Ctor = CCE->getConstructor();
Douglas Gregor59174c02010-07-21 01:10:17 +0000952 bool RequiresZeroInitialization = false;
Douglas Gregor887ddf32012-02-23 17:07:43 +0000953 if (Ctor->isTrivial()) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000954 // If new expression did not specify value-initialization, then there
955 // is no initialization.
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000956 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
Douglas Gregor59174c02010-07-21 01:10:17 +0000957 return;
958
John McCall19705672011-09-15 06:49:18 +0000959 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000960 // Optimization: since zero initialization will just set the memory
961 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +0000962 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
Douglas Gregor59174c02010-07-21 01:10:17 +0000963 return;
964 }
965
966 RequiresZeroInitialization = true;
967 }
John McCallc3c07662011-07-13 06:10:41 +0000968
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000969 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr,
970 CCE->arg_begin(), CCE->arg_end(),
Douglas Gregor59174c02010-07-21 01:10:17 +0000971 RequiresZeroInitialization);
Anders Carlssone99bdb62010-05-03 15:09:17 +0000972 return;
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000973 } else if (Init && isa<ImplicitValueInitExpr>(Init) &&
Eli Friedman40563cd2011-12-09 23:05:37 +0000974 CGF.CGM.getTypes().isZeroInitializable(ElementType)) {
Douglas Gregor59174c02010-07-21 01:10:17 +0000975 // Optimization: since zero initialization will just set the memory
976 // to all zeroes, generate a single memset to do it in one shot.
John McCall19705672011-09-15 06:49:18 +0000977 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie);
978 return;
Fariborz Jahanianef668722010-06-25 18:26:07 +0000979 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000980 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements);
981 return;
Anders Carlssona4d4c012009-09-23 16:07:23 +0000982 }
Anders Carlsson5d4d9462009-11-24 18:43:52 +0000983
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000984 if (!Init)
Fariborz Jahanian5304c952010-06-25 20:01:13 +0000985 return;
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000986
Sebastian Redl92036472012-02-22 17:37:52 +0000987 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssona4d4c012009-09-23 16:07:23 +0000988}
989
John McCall7d8647f2010-09-14 07:57:04 +0000990namespace {
991 /// A cleanup to call the given 'operator delete' function upon
992 /// abnormal exit from a new expression.
993 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
994 size_t NumPlacementArgs;
995 const FunctionDecl *OperatorDelete;
996 llvm::Value *Ptr;
997 llvm::Value *AllocSize;
998
999 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1000
1001 public:
1002 static size_t getExtraSize(size_t NumPlacementArgs) {
1003 return NumPlacementArgs * sizeof(RValue);
1004 }
1005
1006 CallDeleteDuringNew(size_t NumPlacementArgs,
1007 const FunctionDecl *OperatorDelete,
1008 llvm::Value *Ptr,
1009 llvm::Value *AllocSize)
1010 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1011 Ptr(Ptr), AllocSize(AllocSize) {}
1012
1013 void setPlacementArg(unsigned I, RValue Arg) {
1014 assert(I < NumPlacementArgs && "index out of range");
1015 getPlacementArgs()[I] = Arg;
1016 }
1017
John McCallad346f42011-07-12 20:27:29 +00001018 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall7d8647f2010-09-14 07:57:04 +00001019 const FunctionProtoType *FPT
1020 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1021 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
John McCallc3846362010-09-14 21:45:42 +00001022 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
John McCall7d8647f2010-09-14 07:57:04 +00001023
1024 CallArgList DeleteArgs;
1025
1026 // The first argument is always a void*.
1027 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001028 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001029
1030 // A member 'operator delete' can take an extra 'size_t' argument.
1031 if (FPT->getNumArgs() == NumPlacementArgs + 2)
Eli Friedman04c9a492011-05-02 17:57:46 +00001032 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001033
1034 // Pass the rest of the arguments, which must match exactly.
1035 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman04c9a492011-05-02 17:57:46 +00001036 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall7d8647f2010-09-14 07:57:04 +00001037
1038 // Call 'operator delete'.
John McCall0f3d0972012-07-07 06:41:13 +00001039 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, FPT),
John McCall7d8647f2010-09-14 07:57:04 +00001040 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1041 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1042 }
1043 };
John McCall3019c442010-09-17 00:50:28 +00001044
1045 /// A cleanup to call the given 'operator delete' function upon
1046 /// abnormal exit from a new expression when the new expression is
1047 /// conditional.
1048 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1049 size_t NumPlacementArgs;
1050 const FunctionDecl *OperatorDelete;
John McCall804b8072011-01-28 10:53:53 +00001051 DominatingValue<RValue>::saved_type Ptr;
1052 DominatingValue<RValue>::saved_type AllocSize;
John McCall3019c442010-09-17 00:50:28 +00001053
John McCall804b8072011-01-28 10:53:53 +00001054 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1055 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall3019c442010-09-17 00:50:28 +00001056 }
1057
1058 public:
1059 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCall804b8072011-01-28 10:53:53 +00001060 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall3019c442010-09-17 00:50:28 +00001061 }
1062
1063 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1064 const FunctionDecl *OperatorDelete,
John McCall804b8072011-01-28 10:53:53 +00001065 DominatingValue<RValue>::saved_type Ptr,
1066 DominatingValue<RValue>::saved_type AllocSize)
John McCall3019c442010-09-17 00:50:28 +00001067 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1068 Ptr(Ptr), AllocSize(AllocSize) {}
1069
John McCall804b8072011-01-28 10:53:53 +00001070 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall3019c442010-09-17 00:50:28 +00001071 assert(I < NumPlacementArgs && "index out of range");
1072 getPlacementArgs()[I] = Arg;
1073 }
1074
John McCallad346f42011-07-12 20:27:29 +00001075 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall3019c442010-09-17 00:50:28 +00001076 const FunctionProtoType *FPT
1077 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1078 assert(FPT->getNumArgs() == NumPlacementArgs + 1 ||
1079 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0));
1080
1081 CallArgList DeleteArgs;
1082
1083 // The first argument is always a void*.
1084 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin();
Eli Friedman04c9a492011-05-02 17:57:46 +00001085 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall3019c442010-09-17 00:50:28 +00001086
1087 // A member 'operator delete' can take an extra 'size_t' argument.
1088 if (FPT->getNumArgs() == NumPlacementArgs + 2) {
John McCall804b8072011-01-28 10:53:53 +00001089 RValue RV = AllocSize.restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001090 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001091 }
1092
1093 // Pass the rest of the arguments, which must match exactly.
1094 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCall804b8072011-01-28 10:53:53 +00001095 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman04c9a492011-05-02 17:57:46 +00001096 DeleteArgs.add(RV, *AI++);
John McCall3019c442010-09-17 00:50:28 +00001097 }
1098
1099 // Call 'operator delete'.
John McCall0f3d0972012-07-07 06:41:13 +00001100 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, FPT),
John McCall3019c442010-09-17 00:50:28 +00001101 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1102 ReturnValueSlot(), DeleteArgs, OperatorDelete);
1103 }
1104 };
1105}
1106
1107/// Enter a cleanup to call 'operator delete' if the initializer in a
1108/// new-expression throws.
1109static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1110 const CXXNewExpr *E,
1111 llvm::Value *NewPtr,
1112 llvm::Value *AllocSize,
1113 const CallArgList &NewArgs) {
1114 // If we're not inside a conditional branch, then the cleanup will
1115 // dominate and we can do the easier (and more efficient) thing.
1116 if (!CGF.isInConditionalBranch()) {
1117 CallDeleteDuringNew *Cleanup = CGF.EHStack
1118 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1119 E->getNumPlacementArgs(),
1120 E->getOperatorDelete(),
1121 NewPtr, AllocSize);
1122 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanc6d07822011-05-02 18:05:27 +00001123 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall3019c442010-09-17 00:50:28 +00001124
1125 return;
1126 }
1127
1128 // Otherwise, we need to save all this stuff.
John McCall804b8072011-01-28 10:53:53 +00001129 DominatingValue<RValue>::saved_type SavedNewPtr =
1130 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1131 DominatingValue<RValue>::saved_type SavedAllocSize =
1132 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall3019c442010-09-17 00:50:28 +00001133
1134 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCall6f103ba2011-11-10 10:43:54 +00001135 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall3019c442010-09-17 00:50:28 +00001136 E->getNumPlacementArgs(),
1137 E->getOperatorDelete(),
1138 SavedNewPtr,
1139 SavedAllocSize);
1140 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCall804b8072011-01-28 10:53:53 +00001141 Cleanup->setPlacementArg(I,
Eli Friedmanc6d07822011-05-02 18:05:27 +00001142 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall3019c442010-09-17 00:50:28 +00001143
John McCall6f103ba2011-11-10 10:43:54 +00001144 CGF.initFullExprCleanup();
John McCall7d8647f2010-09-14 07:57:04 +00001145}
1146
Anders Carlsson16d81b82009-09-22 22:53:17 +00001147llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001148 // The element type being allocated.
1149 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall1e7fe752010-09-02 09:58:18 +00001150
John McCallc2f3e7f2011-03-07 03:12:35 +00001151 // 1. Build a call to the allocation function.
1152 FunctionDecl *allocator = E->getOperatorNew();
1153 const FunctionProtoType *allocatorType =
1154 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001155
John McCallc2f3e7f2011-03-07 03:12:35 +00001156 CallArgList allocatorArgs;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001157
1158 // The allocation size is the first argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001159 QualType sizeType = getContext().getSizeType();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001160
Sebastian Redl92036472012-02-22 17:37:52 +00001161 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1162 unsigned minElements = 0;
1163 if (E->isArray() && E->hasInitializer()) {
1164 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1165 minElements = ILE->getNumInits();
1166 }
1167
John McCallc2f3e7f2011-03-07 03:12:35 +00001168 llvm::Value *numElements = 0;
1169 llvm::Value *allocSizeWithoutCookie = 0;
1170 llvm::Value *allocSize =
Sebastian Redl92036472012-02-22 17:37:52 +00001171 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1172 allocSizeWithoutCookie);
Anders Carlssona4d4c012009-09-23 16:07:23 +00001173
Eli Friedman04c9a492011-05-02 17:57:46 +00001174 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001175
1176 // Emit the rest of the arguments.
1177 // FIXME: Ideally, this should just use EmitCallArgs.
John McCallc2f3e7f2011-03-07 03:12:35 +00001178 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001179
1180 // First, use the types from the function type.
1181 // We start at 1 here because the first argument (the allocation size)
1182 // has already been emitted.
John McCallc2f3e7f2011-03-07 03:12:35 +00001183 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e;
1184 ++i, ++placementArg) {
1185 QualType argType = allocatorType->getArgType(i);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001186
John McCallc2f3e7f2011-03-07 03:12:35 +00001187 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(),
1188 placementArg->getType()) &&
Anders Carlsson16d81b82009-09-22 22:53:17 +00001189 "type mismatch in call argument!");
1190
John McCall413ebdb2011-03-11 20:59:21 +00001191 EmitCallArg(allocatorArgs, *placementArg, argType);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001192 }
1193
1194 // Either we've emitted all the call args, or we have a call to a
1195 // variadic function.
John McCallc2f3e7f2011-03-07 03:12:35 +00001196 assert((placementArg == E->placement_arg_end() ||
1197 allocatorType->isVariadic()) &&
1198 "Extra arguments to non-variadic function!");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001199
1200 // If we still have any arguments, emit them using the type of the argument.
John McCallc2f3e7f2011-03-07 03:12:35 +00001201 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end();
1202 placementArg != placementArgsEnd; ++placementArg) {
John McCall413ebdb2011-03-11 20:59:21 +00001203 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001204 }
1205
John McCallb1c98a32011-05-16 01:05:12 +00001206 // Emit the allocation call. If the allocator is a global placement
1207 // operator, just "inline" it directly.
1208 RValue RV;
1209 if (allocator->isReservedGlobalPlacementOperator()) {
1210 assert(allocatorArgs.size() == 2);
1211 RV = allocatorArgs[1].RV;
1212 // TODO: kill any unnecessary computations done for the size
1213 // argument.
1214 } else {
John McCall0f3d0972012-07-07 06:41:13 +00001215 RV = EmitCall(CGM.getTypes().arrangeFreeFunctionCall(allocatorArgs,
1216 allocatorType),
John McCallb1c98a32011-05-16 01:05:12 +00001217 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(),
1218 allocatorArgs, allocator);
1219 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001220
John McCallc2f3e7f2011-03-07 03:12:35 +00001221 // Emit a null check on the allocation result if the allocation
1222 // function is allowed to return null (because it has a non-throwing
1223 // exception spec; for this part, we inline
1224 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1225 // interesting initializer.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001226 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001227 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlsson16d81b82009-09-22 22:53:17 +00001228
John McCallc2f3e7f2011-03-07 03:12:35 +00001229 llvm::BasicBlock *nullCheckBB = 0;
1230 llvm::BasicBlock *contBB = 0;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001231
John McCallc2f3e7f2011-03-07 03:12:35 +00001232 llvm::Value *allocation = RV.getScalarVal();
1233 unsigned AS =
1234 cast<llvm::PointerType>(allocation->getType())->getAddressSpace();
Anders Carlsson16d81b82009-09-22 22:53:17 +00001235
John McCalla7f633f2011-03-07 01:52:56 +00001236 // The null-check means that the initializer is conditionally
1237 // evaluated.
1238 ConditionalEvaluation conditional(*this);
1239
John McCallc2f3e7f2011-03-07 03:12:35 +00001240 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001241 conditional.begin(*this);
John McCallc2f3e7f2011-03-07 03:12:35 +00001242
1243 nullCheckBB = Builder.GetInsertBlock();
1244 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1245 contBB = createBasicBlock("new.cont");
1246
1247 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1248 Builder.CreateCondBr(isNull, contBB, notNullBB);
1249 EmitBlock(notNullBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001250 }
Anders Carlsson6ac5fc42009-09-23 18:59:48 +00001251
John McCall7d8647f2010-09-14 07:57:04 +00001252 // If there's an operator delete, enter a cleanup to call it if an
1253 // exception is thrown.
John McCallc2f3e7f2011-03-07 03:12:35 +00001254 EHScopeStack::stable_iterator operatorDeleteCleanup;
John McCall6f103ba2011-11-10 10:43:54 +00001255 llvm::Instruction *cleanupDominator = 0;
John McCallb1c98a32011-05-16 01:05:12 +00001256 if (E->getOperatorDelete() &&
1257 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCallc2f3e7f2011-03-07 03:12:35 +00001258 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1259 operatorDeleteCleanup = EHStack.stable_begin();
John McCall6f103ba2011-11-10 10:43:54 +00001260 cleanupDominator = Builder.CreateUnreachable();
John McCall7d8647f2010-09-14 07:57:04 +00001261 }
1262
Eli Friedman576cf172011-09-06 18:53:03 +00001263 assert((allocSize == allocSizeWithoutCookie) ==
1264 CalculateCookiePadding(*this, E).isZero());
1265 if (allocSize != allocSizeWithoutCookie) {
1266 assert(E->isArray());
1267 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1268 numElements,
1269 E, allocType);
1270 }
1271
Chris Lattner2acc6e32011-07-18 04:24:23 +00001272 llvm::Type *elementPtrTy
John McCallc2f3e7f2011-03-07 03:12:35 +00001273 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1274 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall7d8647f2010-09-14 07:57:04 +00001275
John McCall19705672011-09-15 06:49:18 +00001276 EmitNewInitializer(*this, E, allocType, result, numElements,
1277 allocSizeWithoutCookie);
John McCall1e7fe752010-09-02 09:58:18 +00001278 if (E->isArray()) {
John McCall1e7fe752010-09-02 09:58:18 +00001279 // NewPtr is a pointer to the base element type. If we're
1280 // allocating an array of arrays, we'll need to cast back to the
1281 // array pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001282 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCallc2f3e7f2011-03-07 03:12:35 +00001283 if (result->getType() != resultType)
1284 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanianceb43b62010-03-24 16:57:01 +00001285 }
John McCall7d8647f2010-09-14 07:57:04 +00001286
1287 // Deactivate the 'operator delete' cleanup if we finished
1288 // initialization.
John McCall6f103ba2011-11-10 10:43:54 +00001289 if (operatorDeleteCleanup.isValid()) {
1290 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1291 cleanupDominator->eraseFromParent();
1292 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001293
John McCallc2f3e7f2011-03-07 03:12:35 +00001294 if (nullCheck) {
John McCalla7f633f2011-03-07 01:52:56 +00001295 conditional.end(*this);
1296
John McCallc2f3e7f2011-03-07 03:12:35 +00001297 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1298 EmitBlock(contBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001299
Jay Foadbbf3bac2011-03-30 11:28:58 +00001300 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCallc2f3e7f2011-03-07 03:12:35 +00001301 PHI->addIncoming(result, notNullBB);
1302 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1303 nullCheckBB);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001304
John McCallc2f3e7f2011-03-07 03:12:35 +00001305 result = PHI;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001306 }
John McCall1e7fe752010-09-02 09:58:18 +00001307
John McCallc2f3e7f2011-03-07 03:12:35 +00001308 return result;
Anders Carlsson16d81b82009-09-22 22:53:17 +00001309}
1310
Eli Friedman5fe05982009-11-18 00:50:08 +00001311void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1312 llvm::Value *Ptr,
1313 QualType DeleteTy) {
John McCall1e7fe752010-09-02 09:58:18 +00001314 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1315
Eli Friedman5fe05982009-11-18 00:50:08 +00001316 const FunctionProtoType *DeleteFTy =
1317 DeleteFD->getType()->getAs<FunctionProtoType>();
1318
1319 CallArgList DeleteArgs;
1320
Anders Carlsson871d0782009-12-13 20:04:38 +00001321 // Check if we need to pass the size to the delete operator.
1322 llvm::Value *Size = 0;
1323 QualType SizeTy;
1324 if (DeleteFTy->getNumArgs() == 2) {
1325 SizeTy = DeleteFTy->getArgType(1);
Ken Dyck4f122ef2010-01-26 19:59:28 +00001326 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1327 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1328 DeleteTypeSize.getQuantity());
Anders Carlsson871d0782009-12-13 20:04:38 +00001329 }
1330
Eli Friedman5fe05982009-11-18 00:50:08 +00001331 QualType ArgTy = DeleteFTy->getArgType(0);
1332 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001333 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001334
Anders Carlsson871d0782009-12-13 20:04:38 +00001335 if (Size)
Eli Friedman04c9a492011-05-02 17:57:46 +00001336 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedman5fe05982009-11-18 00:50:08 +00001337
1338 // Emit the call to delete.
John McCall0f3d0972012-07-07 06:41:13 +00001339 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(DeleteArgs, DeleteFTy),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001340 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(),
Eli Friedman5fe05982009-11-18 00:50:08 +00001341 DeleteArgs, DeleteFD);
1342}
1343
John McCall1e7fe752010-09-02 09:58:18 +00001344namespace {
1345 /// Calls the given 'operator delete' on a single object.
1346 struct CallObjectDelete : EHScopeStack::Cleanup {
1347 llvm::Value *Ptr;
1348 const FunctionDecl *OperatorDelete;
1349 QualType ElementType;
1350
1351 CallObjectDelete(llvm::Value *Ptr,
1352 const FunctionDecl *OperatorDelete,
1353 QualType ElementType)
1354 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1355
John McCallad346f42011-07-12 20:27:29 +00001356 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001357 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1358 }
1359 };
1360}
1361
1362/// Emit the code for deleting a single object.
1363static void EmitObjectDelete(CodeGenFunction &CGF,
1364 const FunctionDecl *OperatorDelete,
1365 llvm::Value *Ptr,
Douglas Gregora8b20f72011-07-13 00:54:47 +00001366 QualType ElementType,
1367 bool UseGlobalDelete) {
John McCall1e7fe752010-09-02 09:58:18 +00001368 // Find the destructor for the type, if applicable. If the
1369 // destructor is virtual, we'll just emit the vcall and return.
1370 const CXXDestructorDecl *Dtor = 0;
1371 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1372 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanaebab722011-08-02 18:05:30 +00001373 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall1e7fe752010-09-02 09:58:18 +00001374 Dtor = RD->getDestructor();
1375
1376 if (Dtor->isVirtual()) {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001377 if (UseGlobalDelete) {
1378 // If we're supposed to call the global delete, make sure we do so
1379 // even if the destructor throws.
1380 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1381 Ptr, OperatorDelete,
1382 ElementType);
1383 }
1384
Chris Lattner2acc6e32011-07-18 04:24:23 +00001385 llvm::Type *Ty =
John McCallde5d3c72012-02-17 03:33:10 +00001386 CGF.getTypes().GetFunctionType(
1387 CGF.getTypes().arrangeCXXDestructor(Dtor, Dtor_Complete));
John McCall1e7fe752010-09-02 09:58:18 +00001388
1389 llvm::Value *Callee
Douglas Gregora8b20f72011-07-13 00:54:47 +00001390 = CGF.BuildVirtualCall(Dtor,
1391 UseGlobalDelete? Dtor_Complete : Dtor_Deleting,
1392 Ptr, Ty);
John McCall1e7fe752010-09-02 09:58:18 +00001393 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0,
1394 0, 0);
1395
Douglas Gregora8b20f72011-07-13 00:54:47 +00001396 if (UseGlobalDelete) {
1397 CGF.PopCleanupBlock();
1398 }
1399
John McCall1e7fe752010-09-02 09:58:18 +00001400 return;
1401 }
1402 }
1403 }
1404
1405 // Make sure that we call delete even if the dtor throws.
John McCall3ad32c82011-01-28 08:37:24 +00001406 // This doesn't have to a conditional cleanup because we're going
1407 // to pop it off in a second.
John McCall1e7fe752010-09-02 09:58:18 +00001408 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1409 Ptr, OperatorDelete, ElementType);
1410
1411 if (Dtor)
1412 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1413 /*ForVirtualBase=*/false, Ptr);
David Blaikie4e4d0842012-03-11 07:00:24 +00001414 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001415 ElementType->isObjCLifetimeType()) {
1416 switch (ElementType.getObjCLifetime()) {
1417 case Qualifiers::OCL_None:
1418 case Qualifiers::OCL_ExplicitNone:
1419 case Qualifiers::OCL_Autoreleasing:
1420 break;
John McCall1e7fe752010-09-02 09:58:18 +00001421
John McCallf85e1932011-06-15 23:02:42 +00001422 case Qualifiers::OCL_Strong: {
1423 // Load the pointer value.
1424 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1425 ElementType.isVolatileQualified());
1426
1427 CGF.EmitARCRelease(PtrValue, /*precise*/ true);
1428 break;
1429 }
1430
1431 case Qualifiers::OCL_Weak:
1432 CGF.EmitARCDestroyWeak(Ptr);
1433 break;
1434 }
1435 }
1436
John McCall1e7fe752010-09-02 09:58:18 +00001437 CGF.PopCleanupBlock();
1438}
1439
1440namespace {
1441 /// Calls the given 'operator delete' on an array of objects.
1442 struct CallArrayDelete : EHScopeStack::Cleanup {
1443 llvm::Value *Ptr;
1444 const FunctionDecl *OperatorDelete;
1445 llvm::Value *NumElements;
1446 QualType ElementType;
1447 CharUnits CookieSize;
1448
1449 CallArrayDelete(llvm::Value *Ptr,
1450 const FunctionDecl *OperatorDelete,
1451 llvm::Value *NumElements,
1452 QualType ElementType,
1453 CharUnits CookieSize)
1454 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1455 ElementType(ElementType), CookieSize(CookieSize) {}
1456
John McCallad346f42011-07-12 20:27:29 +00001457 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1e7fe752010-09-02 09:58:18 +00001458 const FunctionProtoType *DeleteFTy =
1459 OperatorDelete->getType()->getAs<FunctionProtoType>();
1460 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2);
1461
1462 CallArgList Args;
1463
1464 // Pass the pointer as the first argument.
1465 QualType VoidPtrTy = DeleteFTy->getArgType(0);
1466 llvm::Value *DeletePtr
1467 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +00001468 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall1e7fe752010-09-02 09:58:18 +00001469
1470 // Pass the original requested size as the second argument.
1471 if (DeleteFTy->getNumArgs() == 2) {
1472 QualType size_t = DeleteFTy->getArgType(1);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001473 llvm::IntegerType *SizeTy
John McCall1e7fe752010-09-02 09:58:18 +00001474 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1475
1476 CharUnits ElementTypeSize =
1477 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1478
1479 // The size of an element, multiplied by the number of elements.
1480 llvm::Value *Size
1481 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1482 Size = CGF.Builder.CreateMul(Size, NumElements);
1483
1484 // Plus the size of the cookie if applicable.
1485 if (!CookieSize.isZero()) {
1486 llvm::Value *CookieSizeV
1487 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1488 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1489 }
1490
Eli Friedman04c9a492011-05-02 17:57:46 +00001491 Args.add(RValue::get(Size), size_t);
John McCall1e7fe752010-09-02 09:58:18 +00001492 }
1493
1494 // Emit the call to delete.
John McCall0f3d0972012-07-07 06:41:13 +00001495 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Args, DeleteFTy),
John McCall1e7fe752010-09-02 09:58:18 +00001496 CGF.CGM.GetAddrOfFunction(OperatorDelete),
1497 ReturnValueSlot(), Args, OperatorDelete);
1498 }
1499 };
1500}
1501
1502/// Emit the code for deleting an array of objects.
1503static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall6ec278d2011-01-27 09:37:56 +00001504 const CXXDeleteExpr *E,
John McCall7cfd76c2011-07-13 01:41:37 +00001505 llvm::Value *deletedPtr,
1506 QualType elementType) {
1507 llvm::Value *numElements = 0;
1508 llvm::Value *allocatedPtr = 0;
1509 CharUnits cookieSize;
1510 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1511 numElements, allocatedPtr, cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001512
John McCall7cfd76c2011-07-13 01:41:37 +00001513 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall1e7fe752010-09-02 09:58:18 +00001514
1515 // Make sure that we call delete even if one of the dtors throws.
John McCall7cfd76c2011-07-13 01:41:37 +00001516 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall1e7fe752010-09-02 09:58:18 +00001517 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCall7cfd76c2011-07-13 01:41:37 +00001518 allocatedPtr, operatorDelete,
1519 numElements, elementType,
1520 cookieSize);
John McCall1e7fe752010-09-02 09:58:18 +00001521
John McCall7cfd76c2011-07-13 01:41:37 +00001522 // Destroy the elements.
1523 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1524 assert(numElements && "no element count for a type with a destructor!");
1525
John McCall7cfd76c2011-07-13 01:41:37 +00001526 llvm::Value *arrayEnd =
1527 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCallfbf780a2011-07-13 08:09:46 +00001528
1529 // Note that it is legal to allocate a zero-length array, and we
1530 // can never fold the check away because the length should always
1531 // come from a cookie.
John McCall7cfd76c2011-07-13 01:41:37 +00001532 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1533 CGF.getDestroyer(dtorKind),
John McCallfbf780a2011-07-13 08:09:46 +00001534 /*checkZeroLength*/ true,
John McCall7cfd76c2011-07-13 01:41:37 +00001535 CGF.needsEHCleanup(dtorKind));
John McCall1e7fe752010-09-02 09:58:18 +00001536 }
1537
John McCall7cfd76c2011-07-13 01:41:37 +00001538 // Pop the cleanup block.
John McCall1e7fe752010-09-02 09:58:18 +00001539 CGF.PopCleanupBlock();
1540}
1541
Anders Carlsson16d81b82009-09-22 22:53:17 +00001542void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregor90916562009-09-29 18:16:17 +00001543 const Expr *Arg = E->getArgument();
Douglas Gregor90916562009-09-29 18:16:17 +00001544 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001545
1546 // Null check the pointer.
1547 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1548 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1549
Anders Carlssonb9241242011-04-11 00:30:07 +00001550 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001551
1552 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1553 EmitBlock(DeleteNotNull);
Anders Carlsson566abee2009-11-13 04:45:41 +00001554
John McCall1e7fe752010-09-02 09:58:18 +00001555 // We might be deleting a pointer to array. If so, GEP down to the
1556 // first non-array element.
1557 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1558 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1559 if (DeleteTy->isConstantArrayType()) {
1560 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001561 SmallVector<llvm::Value*,8> GEP;
John McCall1e7fe752010-09-02 09:58:18 +00001562
1563 GEP.push_back(Zero); // point at the outermost array
1564
1565 // For each layer of array type we're pointing at:
1566 while (const ConstantArrayType *Arr
1567 = getContext().getAsConstantArrayType(DeleteTy)) {
1568 // 1. Unpeel the array type.
1569 DeleteTy = Arr->getElementType();
1570
1571 // 2. GEP to the first element of the array.
1572 GEP.push_back(Zero);
Anders Carlsson16d81b82009-09-22 22:53:17 +00001573 }
John McCall1e7fe752010-09-02 09:58:18 +00001574
Jay Foad0f6ac7c2011-07-22 08:16:57 +00001575 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlsson16d81b82009-09-22 22:53:17 +00001576 }
1577
Douglas Gregoreede61a2010-09-02 17:38:50 +00001578 assert(ConvertTypeForMem(DeleteTy) ==
1579 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall1e7fe752010-09-02 09:58:18 +00001580
1581 if (E->isArrayForm()) {
John McCall6ec278d2011-01-27 09:37:56 +00001582 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall1e7fe752010-09-02 09:58:18 +00001583 } else {
Douglas Gregora8b20f72011-07-13 00:54:47 +00001584 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1585 E->isGlobalDelete());
John McCall1e7fe752010-09-02 09:58:18 +00001586 }
Anders Carlsson16d81b82009-09-22 22:53:17 +00001587
Anders Carlsson16d81b82009-09-22 22:53:17 +00001588 EmitBlock(DeleteEnd);
1589}
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001590
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001591static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1592 // void __cxa_bad_typeid();
Chris Lattner8b418682012-02-07 00:39:47 +00001593 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001594
1595 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1596}
1597
1598static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001599 llvm::Value *Fn = getBadTypeidFn(CGF);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001600 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001601 CGF.Builder.CreateUnreachable();
1602}
1603
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001604static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1605 const Expr *E,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001606 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001607 // Get the vtable pointer.
1608 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1609
1610 // C++ [expr.typeid]p2:
1611 // If the glvalue expression is obtained by applying the unary * operator to
1612 // a pointer and the pointer is a null pointer value, the typeid expression
1613 // throws the std::bad_typeid exception.
1614 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1615 if (UO->getOpcode() == UO_Deref) {
1616 llvm::BasicBlock *BadTypeidBlock =
1617 CGF.createBasicBlock("typeid.bad_typeid");
1618 llvm::BasicBlock *EndBlock =
1619 CGF.createBasicBlock("typeid.end");
1620
1621 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1622 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1623
1624 CGF.EmitBlock(BadTypeidBlock);
1625 EmitBadTypeidCall(CGF);
1626 CGF.EmitBlock(EndBlock);
1627 }
1628 }
1629
1630 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1631 StdTypeInfoPtrTy->getPointerTo());
1632
1633 // Load the type info.
1634 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1635 return CGF.Builder.CreateLoad(Value);
1636}
1637
John McCall3ad32c82011-01-28 08:37:24 +00001638llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001639 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001640 ConvertType(E->getType())->getPointerTo();
Anders Carlsson31b7f522009-12-11 02:46:30 +00001641
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001642 if (E->isTypeOperand()) {
1643 llvm::Constant *TypeInfo =
1644 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand());
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001645 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001646 }
Anders Carlsson4bdbc0c2011-04-11 14:13:40 +00001647
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001648 // C++ [expr.typeid]p2:
1649 // When typeid is applied to a glvalue expression whose type is a
1650 // polymorphic class type, the result refers to a std::type_info object
1651 // representing the type of the most derived object (that is, the dynamic
1652 // type) to which the glvalue refers.
Richard Smith0d729102012-08-13 20:08:14 +00001653 if (E->isPotentiallyEvaluated())
1654 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1655 StdTypeInfoPtrTy);
Anders Carlsson3f6c5e12011-04-18 00:57:03 +00001656
1657 QualType OperandTy = E->getExprOperand()->getType();
1658 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1659 StdTypeInfoPtrTy);
Mike Stumpc2e84ae2009-11-15 08:09:41 +00001660}
Mike Stumpc849c052009-11-16 06:50:58 +00001661
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001662static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1663 // void *__dynamic_cast(const void *sub,
1664 // const abi::__class_type_info *src,
1665 // const abi::__class_type_info *dst,
1666 // std::ptrdiff_t src2dst_offset);
1667
Chris Lattner8b418682012-02-07 00:39:47 +00001668 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001669 llvm::Type *PtrDiffTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001670 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1671
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001672 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001673
Chris Lattner2acc6e32011-07-18 04:24:23 +00001674 llvm::FunctionType *FTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001675 llvm::FunctionType::get(Int8PtrTy, Args, false);
1676
1677 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast");
1678}
1679
1680static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1681 // void __cxa_bad_cast();
Chris Lattner8b418682012-02-07 00:39:47 +00001682 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001683 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1684}
1685
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001686static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonad3692bb2011-04-13 02:35:36 +00001687 llvm::Value *Fn = getBadCastFn(CGF);
Jay Foad4c7d9f12011-07-15 08:37:34 +00001688 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001689 CGF.Builder.CreateUnreachable();
1690}
1691
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001692static llvm::Value *
1693EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1694 QualType SrcTy, QualType DestTy,
1695 llvm::BasicBlock *CastEnd) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001696 llvm::Type *PtrDiffLTy =
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001697 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001698 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001699
1700 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1701 if (PTy->getPointeeType()->isVoidType()) {
1702 // C++ [expr.dynamic.cast]p7:
1703 // If T is "pointer to cv void," then the result is a pointer to the
1704 // most derived object pointed to by v.
1705
1706 // Get the vtable pointer.
1707 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1708
1709 // Get the offset-to-top from the vtable.
1710 llvm::Value *OffsetToTop =
1711 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1712 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1713
1714 // Finally, add the offset to the pointer.
1715 Value = CGF.EmitCastToVoidPtr(Value);
1716 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1717
1718 return CGF.Builder.CreateBitCast(Value, DestLTy);
1719 }
1720 }
1721
1722 QualType SrcRecordTy;
1723 QualType DestRecordTy;
1724
1725 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1726 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1727 DestRecordTy = DestPTy->getPointeeType();
1728 } else {
1729 SrcRecordTy = SrcTy;
1730 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1731 }
1732
1733 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1734 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1735
1736 llvm::Value *SrcRTTI =
1737 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1738 llvm::Value *DestRTTI =
1739 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1740
1741 // FIXME: Actually compute a hint here.
1742 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL);
1743
1744 // Emit the call to __dynamic_cast.
1745 Value = CGF.EmitCastToVoidPtr(Value);
1746 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value,
1747 SrcRTTI, DestRTTI, OffsetHint);
1748 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1749
1750 /// C++ [expr.dynamic.cast]p9:
1751 /// A failed cast to reference type throws std::bad_cast
1752 if (DestTy->isReferenceType()) {
1753 llvm::BasicBlock *BadCastBlock =
1754 CGF.createBasicBlock("dynamic_cast.bad_cast");
1755
1756 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1757 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1758
1759 CGF.EmitBlock(BadCastBlock);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001760 EmitBadCastCall(CGF);
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001761 }
1762
1763 return Value;
1764}
1765
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001766static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1767 QualType DestTy) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001768 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001769 if (DestTy->isPointerType())
1770 return llvm::Constant::getNullValue(DestLTy);
1771
1772 /// C++ [expr.dynamic.cast]p9:
1773 /// A failed cast to reference type throws std::bad_cast
1774 EmitBadCastCall(CGF);
1775
1776 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1777 return llvm::UndefValue::get(DestLTy);
1778}
1779
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001780llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stumpc849c052009-11-16 06:50:58 +00001781 const CXXDynamicCastExpr *DCE) {
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001782 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001783
Anders Carlsson3ddcdd52011-04-11 01:45:29 +00001784 if (DCE->isAlwaysNull())
1785 return EmitDynamicCastToNull(*this, DestTy);
1786
1787 QualType SrcTy = DCE->getSubExpr()->getType();
1788
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001789 // C++ [expr.dynamic.cast]p4:
1790 // If the value of v is a null pointer value in the pointer case, the result
1791 // is the null pointer value of type T.
1792 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Anders Carlsson1d7088d2009-12-17 07:09:17 +00001793
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001794 llvm::BasicBlock *CastNull = 0;
1795 llvm::BasicBlock *CastNotNull = 0;
1796 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stumpc849c052009-11-16 06:50:58 +00001797
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001798 if (ShouldNullCheckSrcValue) {
1799 CastNull = createBasicBlock("dynamic_cast.null");
1800 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1801
1802 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1803 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1804 EmitBlock(CastNotNull);
Mike Stumpc849c052009-11-16 06:50:58 +00001805 }
1806
Anders Carlssonf0cb4a62011-04-11 00:46:40 +00001807 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1808
1809 if (ShouldNullCheckSrcValue) {
1810 EmitBranch(CastEnd);
1811
1812 EmitBlock(CastNull);
1813 EmitBranch(CastEnd);
1814 }
1815
1816 EmitBlock(CastEnd);
1817
1818 if (ShouldNullCheckSrcValue) {
1819 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1820 PHI->addIncoming(Value, CastNotNull);
1821 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1822
1823 Value = PHI;
1824 }
1825
1826 return Value;
Mike Stumpc849c052009-11-16 06:50:58 +00001827}
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001828
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001829void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedmanf8823e72012-02-09 03:47:20 +00001830 RunCleanupsScope Scope(*this);
Eli Friedman377ecc72012-04-16 03:54:45 +00001831 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1832 Slot.getAlignment());
Eli Friedmanf8823e72012-02-09 03:47:20 +00001833
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001834 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1835 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1836 e = E->capture_init_end();
Eric Christopherc07b18e2012-02-29 03:25:18 +00001837 i != e; ++i, ++CurField) {
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001838 // Emit initialization
Eli Friedman377ecc72012-04-16 03:54:45 +00001839
David Blaikie581deb32012-06-06 20:45:41 +00001840 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Eli Friedmanb74ed082012-02-14 02:31:03 +00001841 ArrayRef<VarDecl *> ArrayIndexes;
1842 if (CurField->getType()->isArrayType())
1843 ArrayIndexes = E->getCaptureInitIndexVars(i);
David Blaikie581deb32012-06-06 20:45:41 +00001844 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001845 }
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001846}