blob: a3e444a3f51d40c1fa704a1b9c86a229b3a4d1bc [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
Anders Carlssoncc52f652009-09-22 22:53:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with code generation of C++ expressions
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Devang Patel91bbb552010-09-30 19:05:55 +000017#include "CGDebugInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGObjCRuntime.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000019#include "clang/CodeGen/CGFunctionInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000021#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000022#include "llvm/IR/Intrinsics.h"
Anders Carlssonbbe277c2011-04-13 02:35:36 +000023
Anders Carlssoncc52f652009-09-22 22:53:17 +000024using namespace clang;
25using namespace CodeGen;
26
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000027RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
28 const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
29 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
30 const CallExpr *CE) {
31 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
32 isa<CXXOperatorCallExpr>(CE));
Anders Carlsson27da15b2010-01-01 20:29:01 +000033 assert(MD->isInstance() &&
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000034 "Trying to emit a member or operator call expr on a static method!");
Anders Carlsson27da15b2010-01-01 20:29:01 +000035
Richard Smith69d0d262012-08-24 00:54:33 +000036 // C++11 [class.mfct.non-static]p2:
37 // If a non-static member function of a class X is called for an object that
38 // is not of type X, or of a type derived from X, the behavior is undefined.
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000039 SourceLocation CallLoc;
40 if (CE)
41 CallLoc = CE->getExprLoc();
Richard Smith4d3110a2012-10-25 02:14:12 +000042 EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall
43 : TCK_MemberCall,
44 CallLoc, This, getContext().getRecordType(MD->getParent()));
Richard Smith69d0d262012-08-24 00:54:33 +000045
Anders Carlsson27da15b2010-01-01 20:29:01 +000046 CallArgList Args;
47
48 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +000049 Args.add(RValue::get(This), MD->getThisType(getContext()));
Anders Carlsson27da15b2010-01-01 20:29:01 +000050
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +000051 // If there is an implicit parameter (e.g. VTT), emit it.
52 if (ImplicitParam) {
53 Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
Anders Carlssone36a6b32010-01-02 01:01:18 +000054 }
John McCalla729c622012-02-17 03:33:10 +000055
56 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
57 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000058
John McCalla729c622012-02-17 03:33:10 +000059 // And the rest of the call args.
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000060 if (CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000061 // Special case: skip first argument of CXXOperatorCall (it is "this").
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000062 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
63 EmitCallArgs(Args, FPT, CE->arg_begin() + ArgsToSkip, CE->arg_end(),
64 CE->getDirectCallee());
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000065 } else {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000066 assert(
67 FPT->getNumParams() == 0 &&
68 "No CallExpr specified for function with non-zero number of arguments");
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000069 }
Anders Carlsson27da15b2010-01-01 20:29:01 +000070
John McCall8dda7b22012-07-07 06:41:13 +000071 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
Rafael Espindolac50c27c2010-03-30 20:24:48 +000072 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000073}
74
Rafael Espindola3b33c4e2012-06-28 14:28:57 +000075static CXXRecordDecl *getCXXRecord(const Expr *E) {
76 QualType T = E->getType();
77 if (const PointerType *PTy = T->getAs<PointerType>())
78 T = PTy->getPointeeType();
79 const RecordType *Ty = T->castAs<RecordType>();
80 return cast<CXXRecordDecl>(Ty->getDecl());
81}
82
Francois Pichet64225792011-01-18 05:04:39 +000083// Note: This function also emit constructor calls to support a MSVC
84// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +000085RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
86 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +000087 const Expr *callee = CE->getCallee()->IgnoreParens();
88
89 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +000090 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +000091
92 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +000093 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
94
95 if (MD->isStatic()) {
96 // The method is static, emit it as we would a regular call.
97 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
Alexey Samsonov70b9c012014-08-21 20:26:47 +000098 return EmitCall(getContext().getPointerType(MD->getType()), Callee, CE,
99 ReturnValue);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000100 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000101
John McCall0d635f52010-09-03 01:26:39 +0000102 // Compute the object pointer.
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000103 const Expr *Base = ME->getBase();
104 bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000105
Craig Topper8a13c412014-05-21 05:09:00 +0000106 const CXXMethodDecl *DevirtualizedMethod = nullptr;
Benjamin Kramer7463ed72013-08-25 22:46:27 +0000107 if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000108 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
109 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
110 assert(DevirtualizedMethod);
111 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
112 const Expr *Inner = Base->ignoreParenBaseCasts();
113 if (getCXXRecord(Inner) == DevirtualizedClass)
114 // If the class of the Inner expression is where the dynamic method
115 // is defined, build the this pointer from it.
116 Base = Inner;
117 else if (getCXXRecord(Base) != DevirtualizedClass) {
118 // If the method is defined in a class that is not the best dynamic
119 // one or the one of the full expression, we would have to build
120 // a derived-to-base cast to compute the correct this pointer, but
121 // we don't have support for that yet, so do a virtual call.
Craig Topper8a13c412014-05-21 05:09:00 +0000122 DevirtualizedMethod = nullptr;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000123 }
Rafael Espindolab27564a2012-06-28 17:57:36 +0000124 // If the return types are not the same, this might be a case where more
125 // code needs to run to compensate for it. For example, the derived
126 // method might return a type that inherits form from the return
127 // type of MD and has a prefix.
128 // For now we just avoid devirtualizing these covariant cases.
129 if (DevirtualizedMethod &&
Alp Toker314cc812014-01-25 16:55:45 +0000130 DevirtualizedMethod->getReturnType().getCanonicalType() !=
131 MD->getReturnType().getCanonicalType())
Craig Topper8a13c412014-05-21 05:09:00 +0000132 DevirtualizedMethod = nullptr;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000133 }
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000134
Anders Carlsson27da15b2010-01-01 20:29:01 +0000135 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000136 if (ME->isArrow())
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000137 This = EmitScalarExpr(Base);
John McCalle26a8722010-12-04 08:14:53 +0000138 else
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000139 This = EmitLValue(Base).getAddress();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000140
Anders Carlsson27da15b2010-01-01 20:29:01 +0000141
John McCall0d635f52010-09-03 01:26:39 +0000142 if (MD->isTrivial()) {
Craig Topper8a13c412014-05-21 05:09:00 +0000143 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
Francois Pichet64225792011-01-18 05:04:39 +0000144 if (isa<CXXConstructorDecl>(MD) &&
145 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
Craig Topper8a13c412014-05-21 05:09:00 +0000146 return RValue::get(nullptr);
John McCall0d635f52010-09-03 01:26:39 +0000147
Sebastian Redl22653ba2011-08-30 19:58:05 +0000148 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
149 // We don't like to generate the trivial copy/move assignment operator
150 // when it isn't necessary; just produce the proper effect here.
Francois Pichet64225792011-01-18 05:04:39 +0000151 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
Benjamin Kramer1ca66912012-09-30 12:43:37 +0000152 EmitAggregateAssign(This, RHS, CE->getType());
Francois Pichet64225792011-01-18 05:04:39 +0000153 return RValue::get(This);
154 }
Alexey Samsonov525bf652014-08-25 21:58:56 +0000155
156 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000157 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
158 // Trivial move and copy ctor are the same.
Alexey Samsonov525bf652014-08-25 21:58:56 +0000159 assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
Francois Pichet64225792011-01-18 05:04:39 +0000160 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
Alexey Samsonov525bf652014-08-25 21:58:56 +0000161 EmitAggregateCopy(This, RHS, CE->arg_begin()->getType());
Francois Pichet64225792011-01-18 05:04:39 +0000162 return RValue::get(This);
163 }
164 llvm_unreachable("unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000165 }
166
John McCall0d635f52010-09-03 01:26:39 +0000167 // Compute the function type we're calling.
Eli Friedmanade60972012-10-25 00:12:49 +0000168 const CXXMethodDecl *CalleeDecl = DevirtualizedMethod ? DevirtualizedMethod : MD;
Craig Topper8a13c412014-05-21 05:09:00 +0000169 const CGFunctionInfo *FInfo = nullptr;
Eli Friedmanade60972012-10-25 00:12:49 +0000170 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000171 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
172 Dtor, StructorType::Complete);
Eli Friedmanade60972012-10-25 00:12:49 +0000173 else if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000174 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
175 Ctor, StructorType::Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000176 else
Eli Friedmanade60972012-10-25 00:12:49 +0000177 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCall0d635f52010-09-03 01:26:39 +0000178
Reid Klecknere7de47e2013-07-22 13:51:44 +0000179 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000180
Anders Carlsson27da15b2010-01-01 20:29:01 +0000181 // C++ [class.virtual]p12:
182 // Explicit qualification with the scope operator (5.1) suppresses the
183 // virtual call mechanism.
184 //
185 // We also don't emit a virtual call if the base expression has a record type
186 // because then we know what the type is.
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000187 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Stephen Lin19cee182013-06-19 23:23:19 +0000188 llvm::Value *Callee;
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000189
John McCall0d635f52010-09-03 01:26:39 +0000190 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000191 assert(CE->arg_begin() == CE->arg_end() &&
192 "Destructor shouldn't have explicit parameters");
193 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
John McCall0d635f52010-09-03 01:26:39 +0000194 if (UseVirtualCall) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000195 CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000196 This, CE);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000197 } else {
Richard Smith9c6890a2012-11-01 22:30:59 +0000198 if (getLangOpts().AppleKext &&
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000199 MD->isVirtual() &&
200 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000201 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000202 else if (!DevirtualizedMethod)
Reid Klecknere7de47e2013-07-22 13:51:44 +0000203 Callee = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete, FInfo, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000204 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000205 const CXXDestructorDecl *DDtor =
206 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000207 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
208 }
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000209 EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
210 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000211 }
Craig Topper8a13c412014-05-21 05:09:00 +0000212 return RValue::get(nullptr);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000213 }
214
215 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Francois Pichet64225792011-01-18 05:04:39 +0000216 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000217 } else if (UseVirtualCall) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000218 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000219 } else {
Richard Smith9c6890a2012-11-01 22:30:59 +0000220 if (getLangOpts().AppleKext &&
Fariborz Jahanian9f9438b2011-01-28 23:42:29 +0000221 MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000222 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000223 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000224 else if (!DevirtualizedMethod)
Rafael Espindola727a7712012-06-26 19:18:25 +0000225 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000226 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000227 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000228 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000229 }
230
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000231 if (MD->isVirtual()) {
232 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
233 *this, MD, This, UseVirtualCall);
234 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000235
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000236 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
237 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000238}
239
240RValue
241CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
242 ReturnValueSlot ReturnValue) {
243 const BinaryOperator *BO =
244 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
245 const Expr *BaseExpr = BO->getLHS();
246 const Expr *MemFnExpr = BO->getRHS();
247
248 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000249 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000250
Anders Carlsson27da15b2010-01-01 20:29:01 +0000251 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000252 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000253 const CXXRecordDecl *RD =
254 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
255
Anders Carlsson27da15b2010-01-01 20:29:01 +0000256 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000257 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000258
259 // Emit the 'this' pointer.
260 llvm::Value *This;
261
John McCalle3027922010-08-25 11:45:40 +0000262 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000263 This = EmitScalarExpr(BaseExpr);
264 else
265 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000266
Richard Smithe30752c2012-10-09 19:52:38 +0000267 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
268 QualType(MPT->getClass(), 0));
Richard Smith69d0d262012-08-24 00:54:33 +0000269
John McCall475999d2010-08-22 00:05:51 +0000270 // Ask the ABI to load the callee. Note that This is modified.
271 llvm::Value *Callee =
David Majnemer2b0d66d2014-02-20 23:22:07 +0000272 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000273
Anders Carlsson27da15b2010-01-01 20:29:01 +0000274 CallArgList Args;
275
276 QualType ThisType =
277 getContext().getPointerType(getContext().getTagDeclType(RD));
278
279 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000280 Args.add(RValue::get(This), ThisType);
John McCall8dda7b22012-07-07 06:41:13 +0000281
282 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000283
284 // And the rest of the call args
Alexey Samsonov8e1162c2014-09-08 17:22:45 +0000285 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getDirectCallee());
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000286 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
287 Callee, ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000288}
289
290RValue
291CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
292 const CXXMethodDecl *MD,
293 ReturnValueSlot ReturnValue) {
294 assert(MD->isInstance() &&
295 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000296 LValue LV = EmitLValue(E->getArg(0));
297 llvm::Value *This = LV.getAddress();
298
Douglas Gregor146b8e92011-09-06 16:26:56 +0000299 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
300 MD->isTrivial()) {
301 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
302 QualType Ty = E->getType();
Benjamin Kramer1ca66912012-09-30 12:43:37 +0000303 EmitAggregateAssign(This, Src, Ty);
Douglas Gregor146b8e92011-09-06 16:26:56 +0000304 return RValue::get(This);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000305 }
306
Anders Carlssonc36783e2011-05-08 20:32:23 +0000307 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000308 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
309 /*ImplicitParam=*/nullptr, QualType(), E);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000310}
311
Peter Collingbournefe883422011-10-06 18:29:37 +0000312RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
313 ReturnValueSlot ReturnValue) {
314 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
315}
316
Eli Friedmanfde961d2011-10-14 02:27:24 +0000317static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
318 llvm::Value *DestPtr,
319 const CXXRecordDecl *Base) {
320 if (Base->isEmpty())
321 return;
322
323 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
324
325 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
326 CharUnits Size = Layout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +0000327 CharUnits Align = Layout.getNonVirtualAlignment();
Eli Friedmanfde961d2011-10-14 02:27:24 +0000328
329 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
330
331 // If the type contains a pointer to data member we can't memset it to zero.
332 // Instead, create a null constant and copy it to the destination.
333 // TODO: there are other patterns besides zero that we can usefully memset,
334 // like -1, which happens to be the pattern used by member-pointers.
335 // TODO: isZeroInitializable can be over-conservative in the case where a
336 // virtual base contains a member pointer.
337 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
338 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
339
340 llvm::GlobalVariable *NullVariable =
341 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
342 /*isConstant=*/true,
343 llvm::GlobalVariable::PrivateLinkage,
344 NullConstant, Twine());
345 NullVariable->setAlignment(Align.getQuantity());
346 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
347
348 // Get and call the appropriate llvm.memcpy overload.
349 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
350 return;
351 }
352
353 // Otherwise, just memset the whole thing to zero. This is legal
354 // because in LLVM, all default initializers (other than the ones we just
355 // handled above) are guaranteed to have a bit pattern of all zeros.
356 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
357 Align.getQuantity());
358}
359
Anders Carlsson27da15b2010-01-01 20:29:01 +0000360void
John McCall7a626f62010-09-15 10:14:12 +0000361CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
362 AggValueSlot Dest) {
363 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000364 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000365
366 // If we require zero initialization before (or instead of) calling the
367 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000368 // constructor, emit the zero initialization now, unless destination is
369 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000370 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
371 switch (E->getConstructionKind()) {
372 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000373 case CXXConstructExpr::CK_Complete:
374 EmitNullInitialization(Dest.getAddr(), E->getType());
375 break;
376 case CXXConstructExpr::CK_VirtualBase:
377 case CXXConstructExpr::CK_NonVirtualBase:
378 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
379 break;
380 }
381 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000382
383 // If this is a call to a trivial default constructor, do nothing.
384 if (CD->isTrivial() && CD->isDefaultConstructor())
385 return;
386
John McCall8ea46b62010-09-18 00:58:34 +0000387 // Elide the constructor if we're constructing from a temporary.
388 // The temporary check is required because Sema sets this on NRVO
389 // returns.
Richard Smith9c6890a2012-11-01 22:30:59 +0000390 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000391 assert(getContext().hasSameUnqualifiedType(E->getType(),
392 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000393 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
394 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000395 return;
396 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000397 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000398
John McCallf677a8e2011-07-13 06:10:41 +0000399 if (const ConstantArrayType *arrayType
400 = getContext().getAsConstantArrayType(E->getType())) {
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000401 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(), E);
John McCallf677a8e2011-07-13 06:10:41 +0000402 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000403 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000404 bool ForVirtualBase = false;
Douglas Gregor61535002013-01-31 05:50:40 +0000405 bool Delegating = false;
406
Alexis Hunt271c3682011-05-03 20:19:28 +0000407 switch (E->getConstructionKind()) {
408 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000409 // We should be emitting a constructor; GlobalDecl will assert this
410 Type = CurGD.getCtorType();
Douglas Gregor61535002013-01-31 05:50:40 +0000411 Delegating = true;
Alexis Hunt271c3682011-05-03 20:19:28 +0000412 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000413
Alexis Hunt271c3682011-05-03 20:19:28 +0000414 case CXXConstructExpr::CK_Complete:
415 Type = Ctor_Complete;
416 break;
417
418 case CXXConstructExpr::CK_VirtualBase:
419 ForVirtualBase = true;
420 // fall-through
421
422 case CXXConstructExpr::CK_NonVirtualBase:
423 Type = Ctor_Base;
424 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000425
Anders Carlsson27da15b2010-01-01 20:29:01 +0000426 // Call the constructor.
Douglas Gregor61535002013-01-31 05:50:40 +0000427 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000428 E);
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000429 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000430}
431
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000432void
433CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
434 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000435 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000436 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000437 Exp = E->getSubExpr();
438 assert(isa<CXXConstructExpr>(Exp) &&
439 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
440 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
441 const CXXConstructorDecl *CD = E->getConstructor();
442 RunCleanupsScope Scope(*this);
443
444 // If we require zero initialization before (or instead of) calling the
445 // constructor, as can be the case with a non-user-provided default
446 // constructor, emit the zero initialization now.
447 // FIXME. Do I still need this for a copy ctor synthesis?
448 if (E->requiresZeroInitialization())
449 EmitNullInitialization(Dest, E->getType());
450
Chandler Carruth99da11c2010-11-15 13:54:43 +0000451 assert(!getContext().getAsConstantArrayType(E->getType())
452 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Alexey Samsonov525bf652014-08-25 21:58:56 +0000453 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000454}
455
John McCall8ed55a52010-09-02 09:58:18 +0000456static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
457 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000458 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000459 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000460
John McCall7ec4b432011-05-16 01:05:12 +0000461 // No cookie is required if the operator new[] being used is the
462 // reserved placement operator new[].
463 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000464 return CharUnits::Zero();
465
John McCall284c48f2011-01-27 09:37:56 +0000466 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000467}
468
John McCall036f2f62011-05-15 07:14:44 +0000469static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
470 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000471 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000472 llvm::Value *&numElements,
473 llvm::Value *&sizeWithoutCookie) {
474 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000475
John McCall036f2f62011-05-15 07:14:44 +0000476 if (!e->isArray()) {
477 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
478 sizeWithoutCookie
479 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
480 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000481 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000482
John McCall036f2f62011-05-15 07:14:44 +0000483 // The width of size_t.
484 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
485
John McCall8ed55a52010-09-02 09:58:18 +0000486 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000487 llvm::APInt cookieSize(sizeWidth,
488 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000489
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000490 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000491 // We multiply the size of all dimensions for NumElements.
492 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000493 numElements = CGF.EmitScalarExpr(e->getArraySize());
494 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000495
John McCall036f2f62011-05-15 07:14:44 +0000496 // The number of elements can be have an arbitrary integer type;
497 // essentially, we need to multiply it by a constant factor, add a
498 // cookie size, and verify that the result is representable as a
499 // size_t. That's just a gloss, though, and it's wrong in one
500 // important way: if the count is negative, it's an error even if
501 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000502 bool isSigned
503 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000504 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000505 = cast<llvm::IntegerType>(numElements->getType());
506 unsigned numElementsWidth = numElementsType->getBitWidth();
507
508 // Compute the constant factor.
509 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000510 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000511 = CGF.getContext().getAsConstantArrayType(type)) {
512 type = CAT->getElementType();
513 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000514 }
515
John McCall036f2f62011-05-15 07:14:44 +0000516 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
517 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
518 typeSizeMultiplier *= arraySizeMultiplier;
519
520 // This will be a size_t.
521 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000522
Chris Lattner32ac5832010-07-20 21:55:52 +0000523 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
524 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000525 if (llvm::ConstantInt *numElementsC =
526 dyn_cast<llvm::ConstantInt>(numElements)) {
527 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000528
John McCall036f2f62011-05-15 07:14:44 +0000529 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000530
John McCall036f2f62011-05-15 07:14:44 +0000531 // If 'count' was a negative number, it's an overflow.
532 if (isSigned && count.isNegative())
533 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000534
John McCall036f2f62011-05-15 07:14:44 +0000535 // We want to do all this arithmetic in size_t. If numElements is
536 // wider than that, check whether it's already too big, and if so,
537 // overflow.
538 else if (numElementsWidth > sizeWidth &&
539 numElementsWidth - sizeWidth > count.countLeadingZeros())
540 hasAnyOverflow = true;
541
542 // Okay, compute a count at the right width.
543 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
544
Sebastian Redlf862eb62012-02-22 17:37:52 +0000545 // If there is a brace-initializer, we cannot allocate fewer elements than
546 // there are initializers. If we do, that's treated like an overflow.
547 if (adjustedCount.ult(minElements))
548 hasAnyOverflow = true;
549
John McCall036f2f62011-05-15 07:14:44 +0000550 // Scale numElements by that. This might overflow, but we don't
551 // care because it only overflows if allocationSize does, too, and
552 // if that overflows then we shouldn't use this.
553 numElements = llvm::ConstantInt::get(CGF.SizeTy,
554 adjustedCount * arraySizeMultiplier);
555
556 // Compute the size before cookie, and track whether it overflowed.
557 bool overflow;
558 llvm::APInt allocationSize
559 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
560 hasAnyOverflow |= overflow;
561
562 // Add in the cookie, and check whether it's overflowed.
563 if (cookieSize != 0) {
564 // Save the current size without a cookie. This shouldn't be
565 // used if there was overflow.
566 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
567
568 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
569 hasAnyOverflow |= overflow;
570 }
571
572 // On overflow, produce a -1 so operator new will fail.
Aaron Ballman455f42c2014-08-28 17:24:14 +0000573 if (hasAnyOverflow) {
574 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
575 } else {
John McCall036f2f62011-05-15 07:14:44 +0000576 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
Aaron Ballman455f42c2014-08-28 17:24:14 +0000577 }
John McCall036f2f62011-05-15 07:14:44 +0000578
579 // Otherwise, we might need to use the overflow intrinsics.
580 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000581 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000582 // 1) if isSigned, we need to check whether numElements is negative;
583 // 2) if numElementsWidth > sizeWidth, we need to check whether
584 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000585 // 3) if minElements > 0, we need to check whether numElements is smaller
586 // than that.
587 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000588 // sizeWithoutCookie := numElements * typeSizeMultiplier
589 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000590 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000591 // size := sizeWithoutCookie + cookieSize
592 // and check whether it overflows.
593
Craig Topper8a13c412014-05-21 05:09:00 +0000594 llvm::Value *hasOverflow = nullptr;
John McCall036f2f62011-05-15 07:14:44 +0000595
596 // If numElementsWidth > sizeWidth, then one way or another, we're
597 // going to have to do a comparison for (2), and this happens to
598 // take care of (1), too.
599 if (numElementsWidth > sizeWidth) {
600 llvm::APInt threshold(numElementsWidth, 1);
601 threshold <<= sizeWidth;
602
603 llvm::Value *thresholdV
604 = llvm::ConstantInt::get(numElementsType, threshold);
605
606 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
607 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
608
609 // Otherwise, if we're signed, we want to sext up to size_t.
610 } else if (isSigned) {
611 if (numElementsWidth < sizeWidth)
612 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
613
614 // If there's a non-1 type size multiplier, then we can do the
615 // signedness check at the same time as we do the multiply
616 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000617 // unsigned overflow. Otherwise, we have to do it here. But at least
618 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000619 if (typeSizeMultiplier == 1)
620 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000621 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000622
623 // Otherwise, zext up to size_t if necessary.
624 } else if (numElementsWidth < sizeWidth) {
625 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
626 }
627
628 assert(numElements->getType() == CGF.SizeTy);
629
Sebastian Redlf862eb62012-02-22 17:37:52 +0000630 if (minElements) {
631 // Don't allow allocation of fewer elements than we have initializers.
632 if (!hasOverflow) {
633 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
634 llvm::ConstantInt::get(CGF.SizeTy, minElements));
635 } else if (numElementsWidth > sizeWidth) {
636 // The other existing overflow subsumes this check.
637 // We do an unsigned comparison, since any signed value < -1 is
638 // taken care of either above or below.
639 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
640 CGF.Builder.CreateICmpULT(numElements,
641 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
642 }
643 }
644
John McCall036f2f62011-05-15 07:14:44 +0000645 size = numElements;
646
647 // Multiply by the type size if necessary. This multiplier
648 // includes all the factors for nested arrays.
649 //
650 // This step also causes numElements to be scaled up by the
651 // nested-array factor if necessary. Overflow on this computation
652 // can be ignored because the result shouldn't be used if
653 // allocation fails.
654 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000655 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000656 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000657
658 llvm::Value *tsmV =
659 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
660 llvm::Value *result =
661 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
662
663 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
664 if (hasOverflow)
665 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
666 else
667 hasOverflow = overflowed;
668
669 size = CGF.Builder.CreateExtractValue(result, 0);
670
671 // Also scale up numElements by the array size multiplier.
672 if (arraySizeMultiplier != 1) {
673 // If the base element type size is 1, then we can re-use the
674 // multiply we just did.
675 if (typeSize.isOne()) {
676 assert(arraySizeMultiplier == typeSizeMultiplier);
677 numElements = size;
678
679 // Otherwise we need a separate multiply.
680 } else {
681 llvm::Value *asmV =
682 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
683 numElements = CGF.Builder.CreateMul(numElements, asmV);
684 }
685 }
686 } else {
687 // numElements doesn't need to be scaled.
688 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000689 }
690
John McCall036f2f62011-05-15 07:14:44 +0000691 // Add in the cookie size if necessary.
692 if (cookieSize != 0) {
693 sizeWithoutCookie = size;
694
John McCall036f2f62011-05-15 07:14:44 +0000695 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000696 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000697
698 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
699 llvm::Value *result =
700 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
701
702 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
703 if (hasOverflow)
704 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
705 else
706 hasOverflow = overflowed;
707
708 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000709 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000710
John McCall036f2f62011-05-15 07:14:44 +0000711 // If we had any possibility of dynamic overflow, make a select to
712 // overwrite 'size' with an all-ones value, which should cause
713 // operator new to throw.
714 if (hasOverflow)
Aaron Ballman455f42c2014-08-28 17:24:14 +0000715 size = CGF.Builder.CreateSelect(hasOverflow,
716 llvm::Constant::getAllOnesValue(CGF.SizeTy),
717 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000718 }
John McCall8ed55a52010-09-02 09:58:18 +0000719
John McCall036f2f62011-05-15 07:14:44 +0000720 if (cookieSize == 0)
721 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000722 else
John McCall036f2f62011-05-15 07:14:44 +0000723 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000724
John McCall036f2f62011-05-15 07:14:44 +0000725 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000726}
727
Sebastian Redlf862eb62012-02-22 17:37:52 +0000728static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
729 QualType AllocType, llvm::Value *NewPtr) {
Richard Smith1c96bc52013-12-11 01:40:16 +0000730 // FIXME: Refactor with EmitExprAsInit.
Eli Friedman38cd36d2011-12-03 02:13:40 +0000731 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall47fb9502013-03-07 21:37:08 +0000732 switch (CGF.getEvaluationKind(AllocType)) {
733 case TEK_Scalar:
Craig Topper8a13c412014-05-21 05:09:00 +0000734 CGF.EmitScalarInit(Init, nullptr, CGF.MakeAddrLValue(NewPtr, AllocType,
735 Alignment),
John McCall1553b192011-06-16 04:16:24 +0000736 false);
John McCall47fb9502013-03-07 21:37:08 +0000737 return;
738 case TEK_Complex:
739 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
740 Alignment),
741 /*isInit*/ true);
742 return;
743 case TEK_Aggregate: {
John McCall7a626f62010-09-15 10:14:12 +0000744 AggValueSlot Slot
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000745 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000746 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000747 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000748 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000749 CGF.EmitAggExpr(Init, Slot);
John McCall47fb9502013-03-07 21:37:08 +0000750 return;
John McCall7a626f62010-09-15 10:14:12 +0000751 }
John McCall47fb9502013-03-07 21:37:08 +0000752 }
753 llvm_unreachable("bad evaluation kind");
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000754}
755
756void
Richard Smith06a67e22014-06-03 06:58:52 +0000757CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
758 QualType ElementType,
759 llvm::Value *BeginPtr,
760 llvm::Value *NumElements,
761 llvm::Value *AllocSizeWithoutCookie) {
762 // If we have a type with trivial initialization and no initializer,
763 // there's nothing to do.
Sebastian Redl6047f072012-02-16 12:22:20 +0000764 if (!E->hasInitializer())
Richard Smith06a67e22014-06-03 06:58:52 +0000765 return;
John McCall99210dc2011-09-15 06:49:18 +0000766
Richard Smith06a67e22014-06-03 06:58:52 +0000767 llvm::Value *CurPtr = BeginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000768
Richard Smith06a67e22014-06-03 06:58:52 +0000769 unsigned InitListElements = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000770
771 const Expr *Init = E->getInitializer();
Richard Smith06a67e22014-06-03 06:58:52 +0000772 llvm::AllocaInst *EndOfInit = nullptr;
773 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
774 EHScopeStack::stable_iterator Cleanup;
775 llvm::Instruction *CleanupDominator = nullptr;
Richard Smith1c96bc52013-12-11 01:40:16 +0000776
Sebastian Redlf862eb62012-02-22 17:37:52 +0000777 // If the initializer is an initializer list, first do the explicit elements.
778 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000779 InitListElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +0000780
Richard Smith1c96bc52013-12-11 01:40:16 +0000781 // If this is a multi-dimensional array new, we will initialize multiple
782 // elements with each init list element.
783 QualType AllocType = E->getAllocatedType();
784 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
785 AllocType->getAsArrayTypeUnsafe())) {
Richard Smith06a67e22014-06-03 06:58:52 +0000786 unsigned AS = CurPtr->getType()->getPointerAddressSpace();
Richard Smith1c96bc52013-12-11 01:40:16 +0000787 llvm::Type *AllocPtrTy = ConvertTypeForMem(AllocType)->getPointerTo(AS);
Richard Smith06a67e22014-06-03 06:58:52 +0000788 CurPtr = Builder.CreateBitCast(CurPtr, AllocPtrTy);
789 InitListElements *= getContext().getConstantArrayElementCount(CAT);
Richard Smith1c96bc52013-12-11 01:40:16 +0000790 }
791
Richard Smith06a67e22014-06-03 06:58:52 +0000792 // Enter a partial-destruction Cleanup if necessary.
793 if (needsEHCleanup(DtorKind)) {
794 // In principle we could tell the Cleanup where we are more
Chad Rosierf62290a2012-02-24 00:13:55 +0000795 // directly, but the control flow can get so varied here that it
796 // would actually be quite complex. Therefore we go through an
797 // alloca.
Richard Smith06a67e22014-06-03 06:58:52 +0000798 EndOfInit = CreateTempAlloca(BeginPtr->getType(), "array.init.end");
799 CleanupDominator = Builder.CreateStore(BeginPtr, EndOfInit);
800 pushIrregularPartialArrayCleanup(BeginPtr, EndOfInit, ElementType,
801 getDestroyer(DtorKind));
802 Cleanup = EHStack.stable_begin();
Chad Rosierf62290a2012-02-24 00:13:55 +0000803 }
804
Sebastian Redlf862eb62012-02-22 17:37:52 +0000805 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +0000806 // Tell the cleanup that it needs to destroy up to this
807 // element. TODO: some of these stores can be trivially
808 // observed to be unnecessary.
Richard Smith06a67e22014-06-03 06:58:52 +0000809 if (EndOfInit)
810 Builder.CreateStore(Builder.CreateBitCast(CurPtr, BeginPtr->getType()),
811 EndOfInit);
812 // FIXME: If the last initializer is an incomplete initializer list for
813 // an array, and we have an array filler, we can fold together the two
814 // initialization loops.
Richard Smith1c96bc52013-12-11 01:40:16 +0000815 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
Richard Smith06a67e22014-06-03 06:58:52 +0000816 ILE->getInit(i)->getType(), CurPtr);
817 CurPtr = Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.exp.next");
Sebastian Redlf862eb62012-02-22 17:37:52 +0000818 }
819
820 // The remaining elements are filled with the array filler expression.
821 Init = ILE->getArrayFiller();
Richard Smith1c96bc52013-12-11 01:40:16 +0000822
Richard Smith06a67e22014-06-03 06:58:52 +0000823 // Extract the initializer for the individual array elements by pulling
824 // out the array filler from all the nested initializer lists. This avoids
825 // generating a nested loop for the initialization.
826 while (Init && Init->getType()->isConstantArrayType()) {
827 auto *SubILE = dyn_cast<InitListExpr>(Init);
828 if (!SubILE)
829 break;
830 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
831 Init = SubILE->getArrayFiller();
832 }
833
834 // Switch back to initializing one base element at a time.
835 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr->getType());
Sebastian Redlf862eb62012-02-22 17:37:52 +0000836 }
837
Richard Smith06a67e22014-06-03 06:58:52 +0000838 // Attempt to perform zero-initialization using memset.
839 auto TryMemsetInitialization = [&]() -> bool {
840 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
841 // we can initialize with a memset to -1.
842 if (!CGM.getTypes().isZeroInitializable(ElementType))
843 return false;
Chandler Carruthe6c980c2014-05-03 09:16:57 +0000844
Richard Smith06a67e22014-06-03 06:58:52 +0000845 // Optimization: since zero initialization will just set the memory
846 // to all zeroes, generate a single memset to do it in one shot.
847
848 // Subtract out the size of any elements we've already initialized.
849 auto *RemainingSize = AllocSizeWithoutCookie;
850 if (InitListElements) {
851 // We know this can't overflow; we check this when doing the allocation.
852 auto *InitializedSize = llvm::ConstantInt::get(
853 RemainingSize->getType(),
854 getContext().getTypeSizeInChars(ElementType).getQuantity() *
855 InitListElements);
856 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
857 }
858
859 // Create the memset.
860 CharUnits Alignment = getContext().getTypeAlignInChars(ElementType);
861 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize,
862 Alignment.getQuantity(), false);
863 return true;
864 };
865
Richard Smith454a7cd2014-06-03 08:26:00 +0000866 // If all elements have already been initialized, skip any further
867 // initialization.
868 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
869 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
870 // If there was a Cleanup, deactivate it.
871 if (CleanupDominator)
872 DeactivateCleanupBlock(Cleanup, CleanupDominator);
873 return;
874 }
875
876 assert(Init && "have trailing elements to initialize but no initializer");
877
Richard Smith06a67e22014-06-03 06:58:52 +0000878 // If this is a constructor call, try to optimize it out, and failing that
879 // emit a single loop to initialize all remaining elements.
Richard Smith454a7cd2014-06-03 08:26:00 +0000880 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000881 CXXConstructorDecl *Ctor = CCE->getConstructor();
882 if (Ctor->isTrivial()) {
883 // If new expression did not specify value-initialization, then there
884 // is no initialization.
885 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
886 return;
887
888 if (TryMemsetInitialization())
889 return;
890 }
891
892 // Store the new Cleanup position for irregular Cleanups.
893 //
894 // FIXME: Share this cleanup with the constructor call emission rather than
895 // having it create a cleanup of its own.
896 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
897
898 // Emit a constructor call loop to initialize the remaining elements.
899 if (InitListElements)
900 NumElements = Builder.CreateSub(
901 NumElements,
902 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000903 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
Richard Smith06a67e22014-06-03 06:58:52 +0000904 CCE->requiresZeroInitialization());
Chandler Carruthe6c980c2014-05-03 09:16:57 +0000905 return;
906 }
907
Richard Smith06a67e22014-06-03 06:58:52 +0000908 // If this is value-initialization, we can usually use memset.
909 ImplicitValueInitExpr IVIE(ElementType);
Richard Smith454a7cd2014-06-03 08:26:00 +0000910 if (isa<ImplicitValueInitExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000911 if (TryMemsetInitialization())
912 return;
913
914 // Switch to an ImplicitValueInitExpr for the element type. This handles
915 // only one case: multidimensional array new of pointers to members. In
916 // all other cases, we already have an initializer for the array element.
917 Init = &IVIE;
918 }
919
920 // At this point we should have found an initializer for the individual
921 // elements of the array.
922 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
923 "got wrong type of element to initialize");
924
Richard Smith454a7cd2014-06-03 08:26:00 +0000925 // If we have an empty initializer list, we can usually use memset.
926 if (auto *ILE = dyn_cast<InitListExpr>(Init))
927 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
928 return;
Richard Smith06a67e22014-06-03 06:58:52 +0000929
930 // Create the loop blocks.
931 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
932 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
933 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
934
935 // Find the end of the array, hoisted out of the loop.
936 llvm::Value *EndPtr =
937 Builder.CreateInBoundsGEP(BeginPtr, NumElements, "array.end");
John McCall99210dc2011-09-15 06:49:18 +0000938
Sebastian Redlf862eb62012-02-22 17:37:52 +0000939 // If the number of elements isn't constant, we have to now check if there is
940 // anything left to initialize.
Richard Smith06a67e22014-06-03 06:58:52 +0000941 if (!ConstNum) {
942 llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr, EndPtr,
John McCall99210dc2011-09-15 06:49:18 +0000943 "array.isempty");
Richard Smith06a67e22014-06-03 06:58:52 +0000944 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
John McCall99210dc2011-09-15 06:49:18 +0000945 }
946
947 // Enter the loop.
Richard Smith06a67e22014-06-03 06:58:52 +0000948 EmitBlock(LoopBB);
John McCall99210dc2011-09-15 06:49:18 +0000949
950 // Set up the current-element phi.
Richard Smith06a67e22014-06-03 06:58:52 +0000951 llvm::PHINode *CurPtrPhi =
952 Builder.CreatePHI(CurPtr->getType(), 2, "array.cur");
953 CurPtrPhi->addIncoming(CurPtr, EntryBB);
954 CurPtr = CurPtrPhi;
John McCall99210dc2011-09-15 06:49:18 +0000955
Richard Smith06a67e22014-06-03 06:58:52 +0000956 // Store the new Cleanup position for irregular Cleanups.
957 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
Chad Rosierf62290a2012-02-24 00:13:55 +0000958
Richard Smith06a67e22014-06-03 06:58:52 +0000959 // Enter a partial-destruction Cleanup if necessary.
960 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
961 pushRegularPartialArrayCleanup(BeginPtr, CurPtr, ElementType,
962 getDestroyer(DtorKind));
963 Cleanup = EHStack.stable_begin();
964 CleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +0000965 }
966
967 // Emit the initializer into this element.
Richard Smith06a67e22014-06-03 06:58:52 +0000968 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
John McCall99210dc2011-09-15 06:49:18 +0000969
Richard Smith06a67e22014-06-03 06:58:52 +0000970 // Leave the Cleanup if we entered one.
971 if (CleanupDominator) {
972 DeactivateCleanupBlock(Cleanup, CleanupDominator);
973 CleanupDominator->eraseFromParent();
John McCallf4beacd2011-11-10 10:43:54 +0000974 }
John McCall99210dc2011-09-15 06:49:18 +0000975
Faisal Vali57ae0562013-12-14 00:40:05 +0000976 // Advance to the next element by adjusting the pointer type as necessary.
Richard Smith06a67e22014-06-03 06:58:52 +0000977 llvm::Value *NextPtr =
978 Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.next");
979
John McCall99210dc2011-09-15 06:49:18 +0000980 // Check whether we've gotten to the end of the array and, if so,
981 // exit the loop.
Richard Smith06a67e22014-06-03 06:58:52 +0000982 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
983 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
984 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
John McCall99210dc2011-09-15 06:49:18 +0000985
Richard Smith06a67e22014-06-03 06:58:52 +0000986 EmitBlock(ContBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000987}
988
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000989static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000990 QualType ElementType,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000991 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000992 llvm::Value *NumElements,
993 llvm::Value *AllocSizeWithoutCookie) {
Richard Smith06a67e22014-06-03 06:58:52 +0000994 if (E->isArray())
995 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements,
996 AllocSizeWithoutCookie);
997 else if (const Expr *Init = E->getInitializer())
998 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000999}
1000
Richard Smith8d0dc312013-07-21 23:12:18 +00001001/// Emit a call to an operator new or operator delete function, as implicitly
1002/// created by new-expressions and delete-expressions.
1003static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1004 const FunctionDecl *Callee,
1005 const FunctionProtoType *CalleeType,
1006 const CallArgList &Args) {
1007 llvm::Instruction *CallOrInvoke;
Richard Smith1235a8d2013-07-29 20:14:16 +00001008 llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
Richard Smith8d0dc312013-07-21 23:12:18 +00001009 RValue RV =
1010 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(Args, CalleeType),
Richard Smith1235a8d2013-07-29 20:14:16 +00001011 CalleeAddr, ReturnValueSlot(), Args,
Richard Smith8d0dc312013-07-21 23:12:18 +00001012 Callee, &CallOrInvoke);
1013
1014 /// C++1y [expr.new]p10:
1015 /// [In a new-expression,] an implementation is allowed to omit a call
1016 /// to a replaceable global allocation function.
1017 ///
1018 /// We model such elidable calls with the 'builtin' attribute.
Rafael Espindola6956d582013-10-22 14:23:09 +00001019 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
Richard Smith1235a8d2013-07-29 20:14:16 +00001020 if (Callee->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola6956d582013-10-22 14:23:09 +00001021 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smith8d0dc312013-07-21 23:12:18 +00001022 // FIXME: Add addAttribute to CallSite.
1023 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1024 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1025 llvm::Attribute::Builtin);
1026 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1027 II->addAttribute(llvm::AttributeSet::FunctionIndex,
1028 llvm::Attribute::Builtin);
1029 else
1030 llvm_unreachable("unexpected kind of call instruction");
1031 }
1032
1033 return RV;
1034}
1035
Richard Smith760520b2014-06-03 23:27:44 +00001036RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1037 const Expr *Arg,
1038 bool IsDelete) {
1039 CallArgList Args;
1040 const Stmt *ArgS = Arg;
1041 EmitCallArgs(Args, *Type->param_type_begin(),
1042 ConstExprIterator(&ArgS), ConstExprIterator(&ArgS + 1));
1043 // Find the allocation or deallocation function that we're calling.
1044 ASTContext &Ctx = getContext();
1045 DeclarationName Name = Ctx.DeclarationNames
1046 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1047 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
Richard Smith599bed72014-06-05 00:43:02 +00001048 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1049 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1050 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
Richard Smith760520b2014-06-03 23:27:44 +00001051 llvm_unreachable("predeclared global operator new/delete is missing");
1052}
1053
John McCall824c2f52010-09-14 07:57:04 +00001054namespace {
1055 /// A cleanup to call the given 'operator delete' function upon
1056 /// abnormal exit from a new expression.
1057 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1058 size_t NumPlacementArgs;
1059 const FunctionDecl *OperatorDelete;
1060 llvm::Value *Ptr;
1061 llvm::Value *AllocSize;
1062
1063 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1064
1065 public:
1066 static size_t getExtraSize(size_t NumPlacementArgs) {
1067 return NumPlacementArgs * sizeof(RValue);
1068 }
1069
1070 CallDeleteDuringNew(size_t NumPlacementArgs,
1071 const FunctionDecl *OperatorDelete,
1072 llvm::Value *Ptr,
1073 llvm::Value *AllocSize)
1074 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1075 Ptr(Ptr), AllocSize(AllocSize) {}
1076
1077 void setPlacementArg(unsigned I, RValue Arg) {
1078 assert(I < NumPlacementArgs && "index out of range");
1079 getPlacementArgs()[I] = Arg;
1080 }
1081
Craig Topper4f12f102014-03-12 06:41:41 +00001082 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall824c2f52010-09-14 07:57:04 +00001083 const FunctionProtoType *FPT
1084 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001085 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1086 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +00001087
1088 CallArgList DeleteArgs;
1089
1090 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001091 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001092 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001093
1094 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001095 if (FPT->getNumParams() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001096 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001097
1098 // Pass the rest of the arguments, which must match exactly.
1099 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001100 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001101
1102 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001103 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall824c2f52010-09-14 07:57:04 +00001104 }
1105 };
John McCall7f9c92a2010-09-17 00:50:28 +00001106
1107 /// A cleanup to call the given 'operator delete' function upon
1108 /// abnormal exit from a new expression when the new expression is
1109 /// conditional.
1110 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1111 size_t NumPlacementArgs;
1112 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +00001113 DominatingValue<RValue>::saved_type Ptr;
1114 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +00001115
John McCallcb5f77f2011-01-28 10:53:53 +00001116 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1117 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +00001118 }
1119
1120 public:
1121 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +00001122 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +00001123 }
1124
1125 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1126 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +00001127 DominatingValue<RValue>::saved_type Ptr,
1128 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +00001129 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1130 Ptr(Ptr), AllocSize(AllocSize) {}
1131
John McCallcb5f77f2011-01-28 10:53:53 +00001132 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +00001133 assert(I < NumPlacementArgs && "index out of range");
1134 getPlacementArgs()[I] = Arg;
1135 }
1136
Craig Topper4f12f102014-03-12 06:41:41 +00001137 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall7f9c92a2010-09-17 00:50:28 +00001138 const FunctionProtoType *FPT
1139 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001140 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1141 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall7f9c92a2010-09-17 00:50:28 +00001142
1143 CallArgList DeleteArgs;
1144
1145 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001146 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001147 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001148
1149 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001150 if (FPT->getNumParams() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +00001151 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001152 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001153 }
1154
1155 // Pass the rest of the arguments, which must match exactly.
1156 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +00001157 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001158 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001159 }
1160
1161 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001162 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7f9c92a2010-09-17 00:50:28 +00001163 }
1164 };
1165}
1166
1167/// Enter a cleanup to call 'operator delete' if the initializer in a
1168/// new-expression throws.
1169static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1170 const CXXNewExpr *E,
1171 llvm::Value *NewPtr,
1172 llvm::Value *AllocSize,
1173 const CallArgList &NewArgs) {
1174 // If we're not inside a conditional branch, then the cleanup will
1175 // dominate and we can do the easier (and more efficient) thing.
1176 if (!CGF.isInConditionalBranch()) {
1177 CallDeleteDuringNew *Cleanup = CGF.EHStack
1178 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1179 E->getNumPlacementArgs(),
1180 E->getOperatorDelete(),
1181 NewPtr, AllocSize);
1182 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001183 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001184
1185 return;
1186 }
1187
1188 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001189 DominatingValue<RValue>::saved_type SavedNewPtr =
1190 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1191 DominatingValue<RValue>::saved_type SavedAllocSize =
1192 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001193
1194 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCallf4beacd2011-11-10 10:43:54 +00001195 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall7f9c92a2010-09-17 00:50:28 +00001196 E->getNumPlacementArgs(),
1197 E->getOperatorDelete(),
1198 SavedNewPtr,
1199 SavedAllocSize);
1200 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001201 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001202 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001203
John McCallf4beacd2011-11-10 10:43:54 +00001204 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001205}
1206
Anders Carlssoncc52f652009-09-22 22:53:17 +00001207llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001208 // The element type being allocated.
1209 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001210
John McCall75f94982011-03-07 03:12:35 +00001211 // 1. Build a call to the allocation function.
1212 FunctionDecl *allocator = E->getOperatorNew();
1213 const FunctionProtoType *allocatorType =
1214 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001215
John McCall75f94982011-03-07 03:12:35 +00001216 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001217
1218 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001219 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001220
Sebastian Redlf862eb62012-02-22 17:37:52 +00001221 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1222 unsigned minElements = 0;
1223 if (E->isArray() && E->hasInitializer()) {
1224 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1225 minElements = ILE->getNumInits();
1226 }
1227
Craig Topper8a13c412014-05-21 05:09:00 +00001228 llvm::Value *numElements = nullptr;
1229 llvm::Value *allocSizeWithoutCookie = nullptr;
John McCall75f94982011-03-07 03:12:35 +00001230 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001231 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1232 allocSizeWithoutCookie);
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00001233
Eli Friedman43dca6a2011-05-02 17:57:46 +00001234 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001235
Anders Carlssoncc52f652009-09-22 22:53:17 +00001236 // We start at 1 here because the first argument (the allocation size)
1237 // has already been emitted.
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00001238 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arg_begin(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001239 E->placement_arg_end(), /* CalleeDecl */ nullptr,
1240 /*ParamsToSkip*/ 1);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001241
John McCall7ec4b432011-05-16 01:05:12 +00001242 // Emit the allocation call. If the allocator is a global placement
1243 // operator, just "inline" it directly.
1244 RValue RV;
1245 if (allocator->isReservedGlobalPlacementOperator()) {
1246 assert(allocatorArgs.size() == 2);
1247 RV = allocatorArgs[1].RV;
1248 // TODO: kill any unnecessary computations done for the size
1249 // argument.
1250 } else {
Richard Smith8d0dc312013-07-21 23:12:18 +00001251 RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
John McCall7ec4b432011-05-16 01:05:12 +00001252 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001253
John McCall75f94982011-03-07 03:12:35 +00001254 // Emit a null check on the allocation result if the allocation
1255 // function is allowed to return null (because it has a non-throwing
1256 // exception spec; for this part, we inline
1257 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1258 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001259 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001260 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001261
Craig Topper8a13c412014-05-21 05:09:00 +00001262 llvm::BasicBlock *nullCheckBB = nullptr;
1263 llvm::BasicBlock *contBB = nullptr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001264
John McCall75f94982011-03-07 03:12:35 +00001265 llvm::Value *allocation = RV.getScalarVal();
Micah Villmowea2fea22012-10-25 15:39:14 +00001266 unsigned AS = allocation->getType()->getPointerAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001267
John McCallf7dcf322011-03-07 01:52:56 +00001268 // The null-check means that the initializer is conditionally
1269 // evaluated.
1270 ConditionalEvaluation conditional(*this);
1271
John McCall75f94982011-03-07 03:12:35 +00001272 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001273 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001274
1275 nullCheckBB = Builder.GetInsertBlock();
1276 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1277 contBB = createBasicBlock("new.cont");
1278
1279 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1280 Builder.CreateCondBr(isNull, contBB, notNullBB);
1281 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001282 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001283
John McCall824c2f52010-09-14 07:57:04 +00001284 // If there's an operator delete, enter a cleanup to call it if an
1285 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001286 EHScopeStack::stable_iterator operatorDeleteCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001287 llvm::Instruction *cleanupDominator = nullptr;
John McCall7ec4b432011-05-16 01:05:12 +00001288 if (E->getOperatorDelete() &&
1289 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCall75f94982011-03-07 03:12:35 +00001290 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1291 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001292 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001293 }
1294
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001295 assert((allocSize == allocSizeWithoutCookie) ==
1296 CalculateCookiePadding(*this, E).isZero());
1297 if (allocSize != allocSizeWithoutCookie) {
1298 assert(E->isArray());
1299 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1300 numElements,
1301 E, allocType);
1302 }
1303
Chris Lattner2192fe52011-07-18 04:24:23 +00001304 llvm::Type *elementPtrTy
John McCall75f94982011-03-07 03:12:35 +00001305 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1306 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001307
John McCall99210dc2011-09-15 06:49:18 +00001308 EmitNewInitializer(*this, E, allocType, result, numElements,
1309 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001310 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001311 // NewPtr is a pointer to the base element type. If we're
1312 // allocating an array of arrays, we'll need to cast back to the
1313 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001314 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall75f94982011-03-07 03:12:35 +00001315 if (result->getType() != resultType)
1316 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001317 }
John McCall824c2f52010-09-14 07:57:04 +00001318
1319 // Deactivate the 'operator delete' cleanup if we finished
1320 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001321 if (operatorDeleteCleanup.isValid()) {
1322 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1323 cleanupDominator->eraseFromParent();
1324 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001325
John McCall75f94982011-03-07 03:12:35 +00001326 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001327 conditional.end(*this);
1328
John McCall75f94982011-03-07 03:12:35 +00001329 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1330 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001331
Jay Foad20c0f022011-03-30 11:28:58 +00001332 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001333 PHI->addIncoming(result, notNullBB);
1334 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1335 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001336
John McCall75f94982011-03-07 03:12:35 +00001337 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001338 }
John McCall8ed55a52010-09-02 09:58:18 +00001339
John McCall75f94982011-03-07 03:12:35 +00001340 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001341}
1342
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001343void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1344 llvm::Value *Ptr,
1345 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001346 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1347
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001348 const FunctionProtoType *DeleteFTy =
1349 DeleteFD->getType()->getAs<FunctionProtoType>();
1350
1351 CallArgList DeleteArgs;
1352
Anders Carlsson21122cf2009-12-13 20:04:38 +00001353 // Check if we need to pass the size to the delete operator.
Craig Topper8a13c412014-05-21 05:09:00 +00001354 llvm::Value *Size = nullptr;
Anders Carlsson21122cf2009-12-13 20:04:38 +00001355 QualType SizeTy;
Alp Toker9cacbab2014-01-20 20:26:09 +00001356 if (DeleteFTy->getNumParams() == 2) {
1357 SizeTy = DeleteFTy->getParamType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001358 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1359 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1360 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001361 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001362
1363 QualType ArgTy = DeleteFTy->getParamType(0);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001364 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001365 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001366
Anders Carlsson21122cf2009-12-13 20:04:38 +00001367 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001368 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001369
1370 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001371 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001372}
1373
John McCall8ed55a52010-09-02 09:58:18 +00001374namespace {
1375 /// Calls the given 'operator delete' on a single object.
1376 struct CallObjectDelete : EHScopeStack::Cleanup {
1377 llvm::Value *Ptr;
1378 const FunctionDecl *OperatorDelete;
1379 QualType ElementType;
1380
1381 CallObjectDelete(llvm::Value *Ptr,
1382 const FunctionDecl *OperatorDelete,
1383 QualType ElementType)
1384 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1385
Craig Topper4f12f102014-03-12 06:41:41 +00001386 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001387 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1388 }
1389 };
1390}
1391
1392/// Emit the code for deleting a single object.
1393static void EmitObjectDelete(CodeGenFunction &CGF,
1394 const FunctionDecl *OperatorDelete,
1395 llvm::Value *Ptr,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001396 QualType ElementType,
1397 bool UseGlobalDelete) {
John McCall8ed55a52010-09-02 09:58:18 +00001398 // Find the destructor for the type, if applicable. If the
1399 // destructor is virtual, we'll just emit the vcall and return.
Craig Topper8a13c412014-05-21 05:09:00 +00001400 const CXXDestructorDecl *Dtor = nullptr;
John McCall8ed55a52010-09-02 09:58:18 +00001401 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1402 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001403 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001404 Dtor = RD->getDestructor();
1405
1406 if (Dtor->isVirtual()) {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001407 if (UseGlobalDelete) {
1408 // If we're supposed to call the global delete, make sure we do so
1409 // even if the destructor throws.
John McCall82fb8922012-09-25 10:10:39 +00001410
1411 // Derive the complete-object pointer, which is what we need
1412 // to pass to the deallocation function.
1413 llvm::Value *completePtr =
1414 CGF.CGM.getCXXABI().adjustToCompleteObject(CGF, Ptr, ElementType);
1415
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001416 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
John McCall82fb8922012-09-25 10:10:39 +00001417 completePtr, OperatorDelete,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001418 ElementType);
1419 }
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001420
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001421 // FIXME: Provide a source location here even though there's no
1422 // CXXMemberCallExpr for dtor call.
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001423 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001424 CGF.CGM.getCXXABI().EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr,
1425 nullptr);
John McCall8ed55a52010-09-02 09:58:18 +00001426
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001427 if (UseGlobalDelete) {
1428 CGF.PopCleanupBlock();
1429 }
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001430
John McCall8ed55a52010-09-02 09:58:18 +00001431 return;
1432 }
1433 }
1434 }
1435
1436 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001437 // This doesn't have to a conditional cleanup because we're going
1438 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001439 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1440 Ptr, OperatorDelete, ElementType);
1441
1442 if (Dtor)
1443 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001444 /*ForVirtualBase=*/false,
1445 /*Delegating=*/false,
1446 Ptr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001447 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001448 ElementType->isObjCLifetimeType()) {
1449 switch (ElementType.getObjCLifetime()) {
1450 case Qualifiers::OCL_None:
1451 case Qualifiers::OCL_ExplicitNone:
1452 case Qualifiers::OCL_Autoreleasing:
1453 break;
John McCall8ed55a52010-09-02 09:58:18 +00001454
John McCall31168b02011-06-15 23:02:42 +00001455 case Qualifiers::OCL_Strong: {
1456 // Load the pointer value.
1457 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1458 ElementType.isVolatileQualified());
1459
John McCallcdda29c2013-03-13 03:10:54 +00001460 CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001461 break;
1462 }
1463
1464 case Qualifiers::OCL_Weak:
1465 CGF.EmitARCDestroyWeak(Ptr);
1466 break;
1467 }
1468 }
1469
John McCall8ed55a52010-09-02 09:58:18 +00001470 CGF.PopCleanupBlock();
1471}
1472
1473namespace {
1474 /// Calls the given 'operator delete' on an array of objects.
1475 struct CallArrayDelete : EHScopeStack::Cleanup {
1476 llvm::Value *Ptr;
1477 const FunctionDecl *OperatorDelete;
1478 llvm::Value *NumElements;
1479 QualType ElementType;
1480 CharUnits CookieSize;
1481
1482 CallArrayDelete(llvm::Value *Ptr,
1483 const FunctionDecl *OperatorDelete,
1484 llvm::Value *NumElements,
1485 QualType ElementType,
1486 CharUnits CookieSize)
1487 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1488 ElementType(ElementType), CookieSize(CookieSize) {}
1489
Craig Topper4f12f102014-03-12 06:41:41 +00001490 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001491 const FunctionProtoType *DeleteFTy =
1492 OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001493 assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
John McCall8ed55a52010-09-02 09:58:18 +00001494
1495 CallArgList Args;
1496
1497 // Pass the pointer as the first argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001498 QualType VoidPtrTy = DeleteFTy->getParamType(0);
John McCall8ed55a52010-09-02 09:58:18 +00001499 llvm::Value *DeletePtr
1500 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001501 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001502
1503 // Pass the original requested size as the second argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001504 if (DeleteFTy->getNumParams() == 2) {
1505 QualType size_t = DeleteFTy->getParamType(1);
Chris Lattner2192fe52011-07-18 04:24:23 +00001506 llvm::IntegerType *SizeTy
John McCall8ed55a52010-09-02 09:58:18 +00001507 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1508
1509 CharUnits ElementTypeSize =
1510 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1511
1512 // The size of an element, multiplied by the number of elements.
1513 llvm::Value *Size
1514 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1515 Size = CGF.Builder.CreateMul(Size, NumElements);
1516
1517 // Plus the size of the cookie if applicable.
1518 if (!CookieSize.isZero()) {
1519 llvm::Value *CookieSizeV
1520 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1521 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1522 }
1523
Eli Friedman43dca6a2011-05-02 17:57:46 +00001524 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001525 }
1526
1527 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001528 EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
John McCall8ed55a52010-09-02 09:58:18 +00001529 }
1530 };
1531}
1532
1533/// Emit the code for deleting an array of objects.
1534static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001535 const CXXDeleteExpr *E,
John McCallca2c56f2011-07-13 01:41:37 +00001536 llvm::Value *deletedPtr,
1537 QualType elementType) {
Craig Topper8a13c412014-05-21 05:09:00 +00001538 llvm::Value *numElements = nullptr;
1539 llvm::Value *allocatedPtr = nullptr;
John McCallca2c56f2011-07-13 01:41:37 +00001540 CharUnits cookieSize;
1541 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1542 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001543
John McCallca2c56f2011-07-13 01:41:37 +00001544 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001545
1546 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001547 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001548 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001549 allocatedPtr, operatorDelete,
1550 numElements, elementType,
1551 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001552
John McCallca2c56f2011-07-13 01:41:37 +00001553 // Destroy the elements.
1554 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1555 assert(numElements && "no element count for a type with a destructor!");
1556
John McCallca2c56f2011-07-13 01:41:37 +00001557 llvm::Value *arrayEnd =
1558 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001559
1560 // Note that it is legal to allocate a zero-length array, and we
1561 // can never fold the check away because the length should always
1562 // come from a cookie.
John McCallca2c56f2011-07-13 01:41:37 +00001563 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1564 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001565 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001566 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001567 }
1568
John McCallca2c56f2011-07-13 01:41:37 +00001569 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001570 CGF.PopCleanupBlock();
1571}
1572
Anders Carlssoncc52f652009-09-22 22:53:17 +00001573void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001574 const Expr *Arg = E->getArgument();
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001575 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001576
1577 // Null check the pointer.
1578 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1579 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1580
Anders Carlsson98981b12011-04-11 00:30:07 +00001581 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001582
1583 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1584 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001585
John McCall8ed55a52010-09-02 09:58:18 +00001586 // We might be deleting a pointer to array. If so, GEP down to the
1587 // first non-array element.
1588 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1589 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1590 if (DeleteTy->isConstantArrayType()) {
1591 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001592 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001593
1594 GEP.push_back(Zero); // point at the outermost array
1595
1596 // For each layer of array type we're pointing at:
1597 while (const ConstantArrayType *Arr
1598 = getContext().getAsConstantArrayType(DeleteTy)) {
1599 // 1. Unpeel the array type.
1600 DeleteTy = Arr->getElementType();
1601
1602 // 2. GEP to the first element of the array.
1603 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001604 }
John McCall8ed55a52010-09-02 09:58:18 +00001605
Jay Foad040dd822011-07-22 08:16:57 +00001606 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001607 }
1608
Douglas Gregor04f36212010-09-02 17:38:50 +00001609 assert(ConvertTypeForMem(DeleteTy) ==
1610 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001611
1612 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001613 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001614 } else {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001615 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1616 E->isGlobalDelete());
John McCall8ed55a52010-09-02 09:58:18 +00001617 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001618
Anders Carlssoncc52f652009-09-22 22:53:17 +00001619 EmitBlock(DeleteEnd);
1620}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001621
David Majnemer1c3d95e2014-07-19 00:17:06 +00001622static bool isGLValueFromPointerDeref(const Expr *E) {
1623 E = E->IgnoreParens();
1624
1625 if (const auto *CE = dyn_cast<CastExpr>(E)) {
1626 if (!CE->getSubExpr()->isGLValue())
1627 return false;
1628 return isGLValueFromPointerDeref(CE->getSubExpr());
1629 }
1630
1631 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
1632 return isGLValueFromPointerDeref(OVE->getSourceExpr());
1633
1634 if (const auto *BO = dyn_cast<BinaryOperator>(E))
1635 if (BO->getOpcode() == BO_Comma)
1636 return isGLValueFromPointerDeref(BO->getRHS());
1637
1638 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
1639 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
1640 isGLValueFromPointerDeref(ACO->getFalseExpr());
1641
1642 // C++11 [expr.sub]p1:
1643 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
1644 if (isa<ArraySubscriptExpr>(E))
1645 return true;
1646
1647 if (const auto *UO = dyn_cast<UnaryOperator>(E))
1648 if (UO->getOpcode() == UO_Deref)
1649 return true;
1650
1651 return false;
1652}
1653
Warren Hunt747e3012014-06-18 21:15:55 +00001654static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001655 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001656 // Get the vtable pointer.
1657 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1658
1659 // C++ [expr.typeid]p2:
1660 // If the glvalue expression is obtained by applying the unary * operator to
1661 // a pointer and the pointer is a null pointer value, the typeid expression
1662 // throws the std::bad_typeid exception.
David Majnemer1c3d95e2014-07-19 00:17:06 +00001663 //
1664 // However, this paragraph's intent is not clear. We choose a very generous
1665 // interpretation which implores us to consider comma operators, conditional
1666 // operators, parentheses and other such constructs.
David Majnemer1162d252014-06-22 19:05:33 +00001667 QualType SrcRecordTy = E->getType();
David Majnemer1c3d95e2014-07-19 00:17:06 +00001668 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
1669 isGLValueFromPointerDeref(E), SrcRecordTy)) {
David Majnemer1162d252014-06-22 19:05:33 +00001670 llvm::BasicBlock *BadTypeidBlock =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001671 CGF.createBasicBlock("typeid.bad_typeid");
David Majnemer1162d252014-06-22 19:05:33 +00001672 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
Anders Carlsson940f02d2011-04-18 00:57:03 +00001673
David Majnemer1162d252014-06-22 19:05:33 +00001674 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1675 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001676
David Majnemer1162d252014-06-22 19:05:33 +00001677 CGF.EmitBlock(BadTypeidBlock);
1678 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1679 CGF.EmitBlock(EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001680 }
1681
David Majnemer1162d252014-06-22 19:05:33 +00001682 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
1683 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001684}
1685
John McCalle4df6c82011-01-28 08:37:24 +00001686llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001687 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001688 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001689
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001690 if (E->isTypeOperand()) {
David Majnemer143c55e2013-09-27 07:04:31 +00001691 llvm::Constant *TypeInfo =
1692 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson940f02d2011-04-18 00:57:03 +00001693 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001694 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001695
Anders Carlsson940f02d2011-04-18 00:57:03 +00001696 // C++ [expr.typeid]p2:
1697 // When typeid is applied to a glvalue expression whose type is a
1698 // polymorphic class type, the result refers to a std::type_info object
1699 // representing the type of the most derived object (that is, the dynamic
1700 // type) to which the glvalue refers.
Richard Smithef8bf432012-08-13 20:08:14 +00001701 if (E->isPotentiallyEvaluated())
1702 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1703 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001704
1705 QualType OperandTy = E->getExprOperand()->getType();
1706 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1707 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001708}
Mike Stump65511702009-11-16 06:50:58 +00001709
Anders Carlssonc1c99712011-04-11 01:45:29 +00001710static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1711 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001712 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001713 if (DestTy->isPointerType())
1714 return llvm::Constant::getNullValue(DestLTy);
1715
1716 /// C++ [expr.dynamic.cast]p9:
1717 /// A failed cast to reference type throws std::bad_cast
David Majnemer1162d252014-06-22 19:05:33 +00001718 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
1719 return nullptr;
Anders Carlssonc1c99712011-04-11 01:45:29 +00001720
1721 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1722 return llvm::UndefValue::get(DestLTy);
1723}
1724
Anders Carlsson882d7902011-04-11 00:46:40 +00001725llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001726 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001727 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001728
Anders Carlssonc1c99712011-04-11 01:45:29 +00001729 if (DCE->isAlwaysNull())
David Majnemer1162d252014-06-22 19:05:33 +00001730 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
1731 return T;
Anders Carlssonc1c99712011-04-11 01:45:29 +00001732
1733 QualType SrcTy = DCE->getSubExpr()->getType();
1734
David Majnemer1162d252014-06-22 19:05:33 +00001735 // C++ [expr.dynamic.cast]p7:
1736 // If T is "pointer to cv void," then the result is a pointer to the most
1737 // derived object pointed to by v.
1738 const PointerType *DestPTy = DestTy->getAs<PointerType>();
1739
1740 bool isDynamicCastToVoid;
1741 QualType SrcRecordTy;
1742 QualType DestRecordTy;
1743 if (DestPTy) {
1744 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
1745 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1746 DestRecordTy = DestPTy->getPointeeType();
1747 } else {
1748 isDynamicCastToVoid = false;
1749 SrcRecordTy = SrcTy;
1750 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1751 }
1752
1753 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1754
Anders Carlsson882d7902011-04-11 00:46:40 +00001755 // C++ [expr.dynamic.cast]p4:
1756 // If the value of v is a null pointer value in the pointer case, the result
1757 // is the null pointer value of type T.
David Majnemer1162d252014-06-22 19:05:33 +00001758 bool ShouldNullCheckSrcValue =
1759 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
1760 SrcRecordTy);
Craig Topper8a13c412014-05-21 05:09:00 +00001761
1762 llvm::BasicBlock *CastNull = nullptr;
1763 llvm::BasicBlock *CastNotNull = nullptr;
Anders Carlsson882d7902011-04-11 00:46:40 +00001764 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001765
Anders Carlsson882d7902011-04-11 00:46:40 +00001766 if (ShouldNullCheckSrcValue) {
1767 CastNull = createBasicBlock("dynamic_cast.null");
1768 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1769
1770 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1771 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1772 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001773 }
1774
David Majnemer1162d252014-06-22 19:05:33 +00001775 if (isDynamicCastToVoid) {
1776 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, Value, SrcRecordTy,
1777 DestTy);
1778 } else {
1779 assert(DestRecordTy->isRecordType() &&
1780 "destination type must be a record type!");
1781 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, Value, SrcRecordTy,
1782 DestTy, DestRecordTy, CastEnd);
1783 }
Anders Carlsson882d7902011-04-11 00:46:40 +00001784
1785 if (ShouldNullCheckSrcValue) {
1786 EmitBranch(CastEnd);
1787
1788 EmitBlock(CastNull);
1789 EmitBranch(CastEnd);
1790 }
1791
1792 EmitBlock(CastEnd);
1793
1794 if (ShouldNullCheckSrcValue) {
1795 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1796 PHI->addIncoming(Value, CastNotNull);
1797 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1798
1799 Value = PHI;
1800 }
1801
1802 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001803}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001804
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001805void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00001806 RunCleanupsScope Scope(*this);
Alexey Bataev39c81e22014-08-28 04:28:19 +00001807 LValue SlotLV =
1808 MakeAddrLValue(Slot.getAddr(), E->getType(), Slot.getAlignment());
Eli Friedman8631f3e82012-02-09 03:47:20 +00001809
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001810 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1811 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1812 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00001813 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001814 // Emit initialization
David Blaikie40ed2972012-06-06 20:45:41 +00001815 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Alexey Bataev39c81e22014-08-28 04:28:19 +00001816 if (CurField->hasCapturedVLAType()) {
1817 auto VAT = CurField->getCapturedVLAType();
1818 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
1819 } else {
1820 ArrayRef<VarDecl *> ArrayIndexes;
1821 if (CurField->getType()->isArrayType())
1822 ArrayIndexes = E->getCaptureInitIndexVars(i);
1823 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
1824 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001825 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001826}