blob: 7d41af40f6a9d10b3f763c229903ffd40e06bb48 [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)
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000203 Callee =
204 CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000205 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000206 const CXXDestructorDecl *DDtor =
207 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000208 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
209 }
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000210 EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
211 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000212 }
Craig Topper8a13c412014-05-21 05:09:00 +0000213 return RValue::get(nullptr);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000214 }
215
216 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Francois Pichet64225792011-01-18 05:04:39 +0000217 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000218 } else if (UseVirtualCall) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000219 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000220 } else {
Richard Smith9c6890a2012-11-01 22:30:59 +0000221 if (getLangOpts().AppleKext &&
Fariborz Jahanian9f9438b2011-01-28 23:42:29 +0000222 MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000223 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000224 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000225 else if (!DevirtualizedMethod)
Rafael Espindola727a7712012-06-26 19:18:25 +0000226 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000227 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000228 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000229 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000230 }
231
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000232 if (MD->isVirtual()) {
233 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
234 *this, MD, This, UseVirtualCall);
235 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000236
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000237 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
238 /*ImplicitParam=*/nullptr, QualType(), CE);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000239}
240
241RValue
242CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
243 ReturnValueSlot ReturnValue) {
244 const BinaryOperator *BO =
245 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
246 const Expr *BaseExpr = BO->getLHS();
247 const Expr *MemFnExpr = BO->getRHS();
248
249 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000250 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000251
Anders Carlsson27da15b2010-01-01 20:29:01 +0000252 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000253 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000254 const CXXRecordDecl *RD =
255 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
256
Anders Carlsson27da15b2010-01-01 20:29:01 +0000257 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000258 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000259
260 // Emit the 'this' pointer.
261 llvm::Value *This;
262
John McCalle3027922010-08-25 11:45:40 +0000263 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000264 This = EmitScalarExpr(BaseExpr);
265 else
266 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000267
Richard Smithe30752c2012-10-09 19:52:38 +0000268 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
269 QualType(MPT->getClass(), 0));
Richard Smith69d0d262012-08-24 00:54:33 +0000270
John McCall475999d2010-08-22 00:05:51 +0000271 // Ask the ABI to load the callee. Note that This is modified.
272 llvm::Value *Callee =
David Majnemer2b0d66d2014-02-20 23:22:07 +0000273 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000274
Anders Carlsson27da15b2010-01-01 20:29:01 +0000275 CallArgList Args;
276
277 QualType ThisType =
278 getContext().getPointerType(getContext().getTagDeclType(RD));
279
280 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000281 Args.add(RValue::get(This), ThisType);
John McCall8dda7b22012-07-07 06:41:13 +0000282
283 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000284
285 // And the rest of the call args
Alexey Samsonov8e1162c2014-09-08 17:22:45 +0000286 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getDirectCallee());
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000287 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
288 Callee, ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000289}
290
291RValue
292CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
293 const CXXMethodDecl *MD,
294 ReturnValueSlot ReturnValue) {
295 assert(MD->isInstance() &&
296 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000297 LValue LV = EmitLValue(E->getArg(0));
298 llvm::Value *This = LV.getAddress();
299
Douglas Gregor146b8e92011-09-06 16:26:56 +0000300 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
301 MD->isTrivial()) {
302 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
303 QualType Ty = E->getType();
Benjamin Kramer1ca66912012-09-30 12:43:37 +0000304 EmitAggregateAssign(This, Src, Ty);
Douglas Gregor146b8e92011-09-06 16:26:56 +0000305 return RValue::get(This);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000306 }
307
Anders Carlssonc36783e2011-05-08 20:32:23 +0000308 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Alexey Samsonova5bf76b2014-08-25 20:17:35 +0000309 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
310 /*ImplicitParam=*/nullptr, QualType(), E);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000311}
312
Peter Collingbournefe883422011-10-06 18:29:37 +0000313RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
314 ReturnValueSlot ReturnValue) {
315 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
316}
317
Eli Friedmanfde961d2011-10-14 02:27:24 +0000318static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
319 llvm::Value *DestPtr,
320 const CXXRecordDecl *Base) {
321 if (Base->isEmpty())
322 return;
323
324 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
325
326 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
327 CharUnits Size = Layout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +0000328 CharUnits Align = Layout.getNonVirtualAlignment();
Eli Friedmanfde961d2011-10-14 02:27:24 +0000329
330 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
331
332 // If the type contains a pointer to data member we can't memset it to zero.
333 // Instead, create a null constant and copy it to the destination.
334 // TODO: there are other patterns besides zero that we can usefully memset,
335 // like -1, which happens to be the pattern used by member-pointers.
336 // TODO: isZeroInitializable can be over-conservative in the case where a
337 // virtual base contains a member pointer.
338 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
339 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
340
341 llvm::GlobalVariable *NullVariable =
342 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
343 /*isConstant=*/true,
344 llvm::GlobalVariable::PrivateLinkage,
345 NullConstant, Twine());
346 NullVariable->setAlignment(Align.getQuantity());
347 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
348
349 // Get and call the appropriate llvm.memcpy overload.
350 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
351 return;
352 }
353
354 // Otherwise, just memset the whole thing to zero. This is legal
355 // because in LLVM, all default initializers (other than the ones we just
356 // handled above) are guaranteed to have a bit pattern of all zeros.
357 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
358 Align.getQuantity());
359}
360
Anders Carlsson27da15b2010-01-01 20:29:01 +0000361void
John McCall7a626f62010-09-15 10:14:12 +0000362CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
363 AggValueSlot Dest) {
364 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000365 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000366
367 // If we require zero initialization before (or instead of) calling the
368 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000369 // constructor, emit the zero initialization now, unless destination is
370 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000371 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
372 switch (E->getConstructionKind()) {
373 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000374 case CXXConstructExpr::CK_Complete:
375 EmitNullInitialization(Dest.getAddr(), E->getType());
376 break;
377 case CXXConstructExpr::CK_VirtualBase:
378 case CXXConstructExpr::CK_NonVirtualBase:
379 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
380 break;
381 }
382 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000383
384 // If this is a call to a trivial default constructor, do nothing.
385 if (CD->isTrivial() && CD->isDefaultConstructor())
386 return;
387
John McCall8ea46b62010-09-18 00:58:34 +0000388 // Elide the constructor if we're constructing from a temporary.
389 // The temporary check is required because Sema sets this on NRVO
390 // returns.
Richard Smith9c6890a2012-11-01 22:30:59 +0000391 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000392 assert(getContext().hasSameUnqualifiedType(E->getType(),
393 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000394 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
395 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000396 return;
397 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000398 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000399
John McCallf677a8e2011-07-13 06:10:41 +0000400 if (const ConstantArrayType *arrayType
401 = getContext().getAsConstantArrayType(E->getType())) {
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000402 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(), E);
John McCallf677a8e2011-07-13 06:10:41 +0000403 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000404 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000405 bool ForVirtualBase = false;
Douglas Gregor61535002013-01-31 05:50:40 +0000406 bool Delegating = false;
407
Alexis Hunt271c3682011-05-03 20:19:28 +0000408 switch (E->getConstructionKind()) {
409 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000410 // We should be emitting a constructor; GlobalDecl will assert this
411 Type = CurGD.getCtorType();
Douglas Gregor61535002013-01-31 05:50:40 +0000412 Delegating = true;
Alexis Hunt271c3682011-05-03 20:19:28 +0000413 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000414
Alexis Hunt271c3682011-05-03 20:19:28 +0000415 case CXXConstructExpr::CK_Complete:
416 Type = Ctor_Complete;
417 break;
418
419 case CXXConstructExpr::CK_VirtualBase:
420 ForVirtualBase = true;
421 // fall-through
422
423 case CXXConstructExpr::CK_NonVirtualBase:
424 Type = Ctor_Base;
425 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000426
Anders Carlsson27da15b2010-01-01 20:29:01 +0000427 // Call the constructor.
Douglas Gregor61535002013-01-31 05:50:40 +0000428 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000429 E);
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000430 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000431}
432
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000433void
434CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
435 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000436 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000437 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000438 Exp = E->getSubExpr();
439 assert(isa<CXXConstructExpr>(Exp) &&
440 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
441 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
442 const CXXConstructorDecl *CD = E->getConstructor();
443 RunCleanupsScope Scope(*this);
444
445 // If we require zero initialization before (or instead of) calling the
446 // constructor, as can be the case with a non-user-provided default
447 // constructor, emit the zero initialization now.
448 // FIXME. Do I still need this for a copy ctor synthesis?
449 if (E->requiresZeroInitialization())
450 EmitNullInitialization(Dest, E->getType());
451
Chandler Carruth99da11c2010-11-15 13:54:43 +0000452 assert(!getContext().getAsConstantArrayType(E->getType())
453 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Alexey Samsonov525bf652014-08-25 21:58:56 +0000454 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000455}
456
John McCall8ed55a52010-09-02 09:58:18 +0000457static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
458 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000459 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000460 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000461
John McCall7ec4b432011-05-16 01:05:12 +0000462 // No cookie is required if the operator new[] being used is the
463 // reserved placement operator new[].
464 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000465 return CharUnits::Zero();
466
John McCall284c48f2011-01-27 09:37:56 +0000467 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000468}
469
John McCall036f2f62011-05-15 07:14:44 +0000470static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
471 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000472 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000473 llvm::Value *&numElements,
474 llvm::Value *&sizeWithoutCookie) {
475 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000476
John McCall036f2f62011-05-15 07:14:44 +0000477 if (!e->isArray()) {
478 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
479 sizeWithoutCookie
480 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
481 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000482 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000483
John McCall036f2f62011-05-15 07:14:44 +0000484 // The width of size_t.
485 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
486
John McCall8ed55a52010-09-02 09:58:18 +0000487 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000488 llvm::APInt cookieSize(sizeWidth,
489 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000490
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000491 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000492 // We multiply the size of all dimensions for NumElements.
493 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000494 numElements = CGF.EmitScalarExpr(e->getArraySize());
495 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000496
John McCall036f2f62011-05-15 07:14:44 +0000497 // The number of elements can be have an arbitrary integer type;
498 // essentially, we need to multiply it by a constant factor, add a
499 // cookie size, and verify that the result is representable as a
500 // size_t. That's just a gloss, though, and it's wrong in one
501 // important way: if the count is negative, it's an error even if
502 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000503 bool isSigned
504 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000505 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000506 = cast<llvm::IntegerType>(numElements->getType());
507 unsigned numElementsWidth = numElementsType->getBitWidth();
508
509 // Compute the constant factor.
510 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000511 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000512 = CGF.getContext().getAsConstantArrayType(type)) {
513 type = CAT->getElementType();
514 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000515 }
516
John McCall036f2f62011-05-15 07:14:44 +0000517 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
518 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
519 typeSizeMultiplier *= arraySizeMultiplier;
520
521 // This will be a size_t.
522 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000523
Chris Lattner32ac5832010-07-20 21:55:52 +0000524 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
525 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000526 if (llvm::ConstantInt *numElementsC =
527 dyn_cast<llvm::ConstantInt>(numElements)) {
528 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000529
John McCall036f2f62011-05-15 07:14:44 +0000530 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000531
John McCall036f2f62011-05-15 07:14:44 +0000532 // If 'count' was a negative number, it's an overflow.
533 if (isSigned && count.isNegative())
534 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000535
John McCall036f2f62011-05-15 07:14:44 +0000536 // We want to do all this arithmetic in size_t. If numElements is
537 // wider than that, check whether it's already too big, and if so,
538 // overflow.
539 else if (numElementsWidth > sizeWidth &&
540 numElementsWidth - sizeWidth > count.countLeadingZeros())
541 hasAnyOverflow = true;
542
543 // Okay, compute a count at the right width.
544 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
545
Sebastian Redlf862eb62012-02-22 17:37:52 +0000546 // If there is a brace-initializer, we cannot allocate fewer elements than
547 // there are initializers. If we do, that's treated like an overflow.
548 if (adjustedCount.ult(minElements))
549 hasAnyOverflow = true;
550
John McCall036f2f62011-05-15 07:14:44 +0000551 // Scale numElements by that. This might overflow, but we don't
552 // care because it only overflows if allocationSize does, too, and
553 // if that overflows then we shouldn't use this.
554 numElements = llvm::ConstantInt::get(CGF.SizeTy,
555 adjustedCount * arraySizeMultiplier);
556
557 // Compute the size before cookie, and track whether it overflowed.
558 bool overflow;
559 llvm::APInt allocationSize
560 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
561 hasAnyOverflow |= overflow;
562
563 // Add in the cookie, and check whether it's overflowed.
564 if (cookieSize != 0) {
565 // Save the current size without a cookie. This shouldn't be
566 // used if there was overflow.
567 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
568
569 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
570 hasAnyOverflow |= overflow;
571 }
572
573 // On overflow, produce a -1 so operator new will fail.
Aaron Ballman455f42c2014-08-28 17:24:14 +0000574 if (hasAnyOverflow) {
575 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
576 } else {
John McCall036f2f62011-05-15 07:14:44 +0000577 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
Aaron Ballman455f42c2014-08-28 17:24:14 +0000578 }
John McCall036f2f62011-05-15 07:14:44 +0000579
580 // Otherwise, we might need to use the overflow intrinsics.
581 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000582 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000583 // 1) if isSigned, we need to check whether numElements is negative;
584 // 2) if numElementsWidth > sizeWidth, we need to check whether
585 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000586 // 3) if minElements > 0, we need to check whether numElements is smaller
587 // than that.
588 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000589 // sizeWithoutCookie := numElements * typeSizeMultiplier
590 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000591 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000592 // size := sizeWithoutCookie + cookieSize
593 // and check whether it overflows.
594
Craig Topper8a13c412014-05-21 05:09:00 +0000595 llvm::Value *hasOverflow = nullptr;
John McCall036f2f62011-05-15 07:14:44 +0000596
597 // If numElementsWidth > sizeWidth, then one way or another, we're
598 // going to have to do a comparison for (2), and this happens to
599 // take care of (1), too.
600 if (numElementsWidth > sizeWidth) {
601 llvm::APInt threshold(numElementsWidth, 1);
602 threshold <<= sizeWidth;
603
604 llvm::Value *thresholdV
605 = llvm::ConstantInt::get(numElementsType, threshold);
606
607 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
608 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
609
610 // Otherwise, if we're signed, we want to sext up to size_t.
611 } else if (isSigned) {
612 if (numElementsWidth < sizeWidth)
613 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
614
615 // If there's a non-1 type size multiplier, then we can do the
616 // signedness check at the same time as we do the multiply
617 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000618 // unsigned overflow. Otherwise, we have to do it here. But at least
619 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000620 if (typeSizeMultiplier == 1)
621 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000622 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000623
624 // Otherwise, zext up to size_t if necessary.
625 } else if (numElementsWidth < sizeWidth) {
626 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
627 }
628
629 assert(numElements->getType() == CGF.SizeTy);
630
Sebastian Redlf862eb62012-02-22 17:37:52 +0000631 if (minElements) {
632 // Don't allow allocation of fewer elements than we have initializers.
633 if (!hasOverflow) {
634 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
635 llvm::ConstantInt::get(CGF.SizeTy, minElements));
636 } else if (numElementsWidth > sizeWidth) {
637 // The other existing overflow subsumes this check.
638 // We do an unsigned comparison, since any signed value < -1 is
639 // taken care of either above or below.
640 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
641 CGF.Builder.CreateICmpULT(numElements,
642 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
643 }
644 }
645
John McCall036f2f62011-05-15 07:14:44 +0000646 size = numElements;
647
648 // Multiply by the type size if necessary. This multiplier
649 // includes all the factors for nested arrays.
650 //
651 // This step also causes numElements to be scaled up by the
652 // nested-array factor if necessary. Overflow on this computation
653 // can be ignored because the result shouldn't be used if
654 // allocation fails.
655 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000656 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000657 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000658
659 llvm::Value *tsmV =
660 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
661 llvm::Value *result =
662 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
663
664 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
665 if (hasOverflow)
666 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
667 else
668 hasOverflow = overflowed;
669
670 size = CGF.Builder.CreateExtractValue(result, 0);
671
672 // Also scale up numElements by the array size multiplier.
673 if (arraySizeMultiplier != 1) {
674 // If the base element type size is 1, then we can re-use the
675 // multiply we just did.
676 if (typeSize.isOne()) {
677 assert(arraySizeMultiplier == typeSizeMultiplier);
678 numElements = size;
679
680 // Otherwise we need a separate multiply.
681 } else {
682 llvm::Value *asmV =
683 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
684 numElements = CGF.Builder.CreateMul(numElements, asmV);
685 }
686 }
687 } else {
688 // numElements doesn't need to be scaled.
689 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000690 }
691
John McCall036f2f62011-05-15 07:14:44 +0000692 // Add in the cookie size if necessary.
693 if (cookieSize != 0) {
694 sizeWithoutCookie = size;
695
John McCall036f2f62011-05-15 07:14:44 +0000696 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000697 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000698
699 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
700 llvm::Value *result =
701 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
702
703 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
704 if (hasOverflow)
705 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
706 else
707 hasOverflow = overflowed;
708
709 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000710 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000711
John McCall036f2f62011-05-15 07:14:44 +0000712 // If we had any possibility of dynamic overflow, make a select to
713 // overwrite 'size' with an all-ones value, which should cause
714 // operator new to throw.
715 if (hasOverflow)
Aaron Ballman455f42c2014-08-28 17:24:14 +0000716 size = CGF.Builder.CreateSelect(hasOverflow,
717 llvm::Constant::getAllOnesValue(CGF.SizeTy),
718 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000719 }
John McCall8ed55a52010-09-02 09:58:18 +0000720
John McCall036f2f62011-05-15 07:14:44 +0000721 if (cookieSize == 0)
722 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000723 else
John McCall036f2f62011-05-15 07:14:44 +0000724 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000725
John McCall036f2f62011-05-15 07:14:44 +0000726 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000727}
728
Sebastian Redlf862eb62012-02-22 17:37:52 +0000729static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
730 QualType AllocType, llvm::Value *NewPtr) {
Richard Smith1c96bc52013-12-11 01:40:16 +0000731 // FIXME: Refactor with EmitExprAsInit.
Eli Friedman38cd36d2011-12-03 02:13:40 +0000732 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall47fb9502013-03-07 21:37:08 +0000733 switch (CGF.getEvaluationKind(AllocType)) {
734 case TEK_Scalar:
Craig Topper8a13c412014-05-21 05:09:00 +0000735 CGF.EmitScalarInit(Init, nullptr, CGF.MakeAddrLValue(NewPtr, AllocType,
736 Alignment),
John McCall1553b192011-06-16 04:16:24 +0000737 false);
John McCall47fb9502013-03-07 21:37:08 +0000738 return;
739 case TEK_Complex:
740 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
741 Alignment),
742 /*isInit*/ true);
743 return;
744 case TEK_Aggregate: {
John McCall7a626f62010-09-15 10:14:12 +0000745 AggValueSlot Slot
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000746 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000747 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000748 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000749 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000750 CGF.EmitAggExpr(Init, Slot);
John McCall47fb9502013-03-07 21:37:08 +0000751 return;
John McCall7a626f62010-09-15 10:14:12 +0000752 }
John McCall47fb9502013-03-07 21:37:08 +0000753 }
754 llvm_unreachable("bad evaluation kind");
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000755}
756
757void
Richard Smith06a67e22014-06-03 06:58:52 +0000758CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
759 QualType ElementType,
760 llvm::Value *BeginPtr,
761 llvm::Value *NumElements,
762 llvm::Value *AllocSizeWithoutCookie) {
763 // If we have a type with trivial initialization and no initializer,
764 // there's nothing to do.
Sebastian Redl6047f072012-02-16 12:22:20 +0000765 if (!E->hasInitializer())
Richard Smith06a67e22014-06-03 06:58:52 +0000766 return;
John McCall99210dc2011-09-15 06:49:18 +0000767
Richard Smith06a67e22014-06-03 06:58:52 +0000768 llvm::Value *CurPtr = BeginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000769
Richard Smith06a67e22014-06-03 06:58:52 +0000770 unsigned InitListElements = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000771
772 const Expr *Init = E->getInitializer();
Richard Smith06a67e22014-06-03 06:58:52 +0000773 llvm::AllocaInst *EndOfInit = nullptr;
774 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
775 EHScopeStack::stable_iterator Cleanup;
776 llvm::Instruction *CleanupDominator = nullptr;
Richard Smith1c96bc52013-12-11 01:40:16 +0000777
Sebastian Redlf862eb62012-02-22 17:37:52 +0000778 // If the initializer is an initializer list, first do the explicit elements.
779 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000780 InitListElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +0000781
Richard Smith1c96bc52013-12-11 01:40:16 +0000782 // If this is a multi-dimensional array new, we will initialize multiple
783 // elements with each init list element.
784 QualType AllocType = E->getAllocatedType();
785 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
786 AllocType->getAsArrayTypeUnsafe())) {
Richard Smith06a67e22014-06-03 06:58:52 +0000787 unsigned AS = CurPtr->getType()->getPointerAddressSpace();
Richard Smith1c96bc52013-12-11 01:40:16 +0000788 llvm::Type *AllocPtrTy = ConvertTypeForMem(AllocType)->getPointerTo(AS);
Richard Smith06a67e22014-06-03 06:58:52 +0000789 CurPtr = Builder.CreateBitCast(CurPtr, AllocPtrTy);
790 InitListElements *= getContext().getConstantArrayElementCount(CAT);
Richard Smith1c96bc52013-12-11 01:40:16 +0000791 }
792
Richard Smith06a67e22014-06-03 06:58:52 +0000793 // Enter a partial-destruction Cleanup if necessary.
794 if (needsEHCleanup(DtorKind)) {
795 // In principle we could tell the Cleanup where we are more
Chad Rosierf62290a2012-02-24 00:13:55 +0000796 // directly, but the control flow can get so varied here that it
797 // would actually be quite complex. Therefore we go through an
798 // alloca.
Richard Smith06a67e22014-06-03 06:58:52 +0000799 EndOfInit = CreateTempAlloca(BeginPtr->getType(), "array.init.end");
800 CleanupDominator = Builder.CreateStore(BeginPtr, EndOfInit);
801 pushIrregularPartialArrayCleanup(BeginPtr, EndOfInit, ElementType,
802 getDestroyer(DtorKind));
803 Cleanup = EHStack.stable_begin();
Chad Rosierf62290a2012-02-24 00:13:55 +0000804 }
805
Sebastian Redlf862eb62012-02-22 17:37:52 +0000806 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +0000807 // Tell the cleanup that it needs to destroy up to this
808 // element. TODO: some of these stores can be trivially
809 // observed to be unnecessary.
Richard Smith06a67e22014-06-03 06:58:52 +0000810 if (EndOfInit)
811 Builder.CreateStore(Builder.CreateBitCast(CurPtr, BeginPtr->getType()),
812 EndOfInit);
813 // FIXME: If the last initializer is an incomplete initializer list for
814 // an array, and we have an array filler, we can fold together the two
815 // initialization loops.
Richard Smith1c96bc52013-12-11 01:40:16 +0000816 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
Richard Smith06a67e22014-06-03 06:58:52 +0000817 ILE->getInit(i)->getType(), CurPtr);
818 CurPtr = Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.exp.next");
Sebastian Redlf862eb62012-02-22 17:37:52 +0000819 }
820
821 // The remaining elements are filled with the array filler expression.
822 Init = ILE->getArrayFiller();
Richard Smith1c96bc52013-12-11 01:40:16 +0000823
Richard Smith06a67e22014-06-03 06:58:52 +0000824 // Extract the initializer for the individual array elements by pulling
825 // out the array filler from all the nested initializer lists. This avoids
826 // generating a nested loop for the initialization.
827 while (Init && Init->getType()->isConstantArrayType()) {
828 auto *SubILE = dyn_cast<InitListExpr>(Init);
829 if (!SubILE)
830 break;
831 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
832 Init = SubILE->getArrayFiller();
833 }
834
835 // Switch back to initializing one base element at a time.
836 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr->getType());
Sebastian Redlf862eb62012-02-22 17:37:52 +0000837 }
838
Richard Smith06a67e22014-06-03 06:58:52 +0000839 // Attempt to perform zero-initialization using memset.
840 auto TryMemsetInitialization = [&]() -> bool {
841 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
842 // we can initialize with a memset to -1.
843 if (!CGM.getTypes().isZeroInitializable(ElementType))
844 return false;
Chandler Carruthe6c980c2014-05-03 09:16:57 +0000845
Richard Smith06a67e22014-06-03 06:58:52 +0000846 // Optimization: since zero initialization will just set the memory
847 // to all zeroes, generate a single memset to do it in one shot.
848
849 // Subtract out the size of any elements we've already initialized.
850 auto *RemainingSize = AllocSizeWithoutCookie;
851 if (InitListElements) {
852 // We know this can't overflow; we check this when doing the allocation.
853 auto *InitializedSize = llvm::ConstantInt::get(
854 RemainingSize->getType(),
855 getContext().getTypeSizeInChars(ElementType).getQuantity() *
856 InitListElements);
857 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
858 }
859
860 // Create the memset.
861 CharUnits Alignment = getContext().getTypeAlignInChars(ElementType);
862 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize,
863 Alignment.getQuantity(), false);
864 return true;
865 };
866
Richard Smith454a7cd2014-06-03 08:26:00 +0000867 // If all elements have already been initialized, skip any further
868 // initialization.
869 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
870 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
871 // If there was a Cleanup, deactivate it.
872 if (CleanupDominator)
873 DeactivateCleanupBlock(Cleanup, CleanupDominator);
874 return;
875 }
876
877 assert(Init && "have trailing elements to initialize but no initializer");
878
Richard Smith06a67e22014-06-03 06:58:52 +0000879 // If this is a constructor call, try to optimize it out, and failing that
880 // emit a single loop to initialize all remaining elements.
Richard Smith454a7cd2014-06-03 08:26:00 +0000881 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000882 CXXConstructorDecl *Ctor = CCE->getConstructor();
883 if (Ctor->isTrivial()) {
884 // If new expression did not specify value-initialization, then there
885 // is no initialization.
886 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
887 return;
888
889 if (TryMemsetInitialization())
890 return;
891 }
892
893 // Store the new Cleanup position for irregular Cleanups.
894 //
895 // FIXME: Share this cleanup with the constructor call emission rather than
896 // having it create a cleanup of its own.
897 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
898
899 // Emit a constructor call loop to initialize the remaining elements.
900 if (InitListElements)
901 NumElements = Builder.CreateSub(
902 NumElements,
903 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000904 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
Richard Smith06a67e22014-06-03 06:58:52 +0000905 CCE->requiresZeroInitialization());
Chandler Carruthe6c980c2014-05-03 09:16:57 +0000906 return;
907 }
908
Richard Smith06a67e22014-06-03 06:58:52 +0000909 // If this is value-initialization, we can usually use memset.
910 ImplicitValueInitExpr IVIE(ElementType);
Richard Smith454a7cd2014-06-03 08:26:00 +0000911 if (isa<ImplicitValueInitExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000912 if (TryMemsetInitialization())
913 return;
914
915 // Switch to an ImplicitValueInitExpr for the element type. This handles
916 // only one case: multidimensional array new of pointers to members. In
917 // all other cases, we already have an initializer for the array element.
918 Init = &IVIE;
919 }
920
921 // At this point we should have found an initializer for the individual
922 // elements of the array.
923 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
924 "got wrong type of element to initialize");
925
Richard Smith454a7cd2014-06-03 08:26:00 +0000926 // If we have an empty initializer list, we can usually use memset.
927 if (auto *ILE = dyn_cast<InitListExpr>(Init))
928 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
929 return;
Richard Smith06a67e22014-06-03 06:58:52 +0000930
931 // Create the loop blocks.
932 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
933 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
934 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
935
936 // Find the end of the array, hoisted out of the loop.
937 llvm::Value *EndPtr =
938 Builder.CreateInBoundsGEP(BeginPtr, NumElements, "array.end");
John McCall99210dc2011-09-15 06:49:18 +0000939
Sebastian Redlf862eb62012-02-22 17:37:52 +0000940 // If the number of elements isn't constant, we have to now check if there is
941 // anything left to initialize.
Richard Smith06a67e22014-06-03 06:58:52 +0000942 if (!ConstNum) {
943 llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr, EndPtr,
John McCall99210dc2011-09-15 06:49:18 +0000944 "array.isempty");
Richard Smith06a67e22014-06-03 06:58:52 +0000945 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
John McCall99210dc2011-09-15 06:49:18 +0000946 }
947
948 // Enter the loop.
Richard Smith06a67e22014-06-03 06:58:52 +0000949 EmitBlock(LoopBB);
John McCall99210dc2011-09-15 06:49:18 +0000950
951 // Set up the current-element phi.
Richard Smith06a67e22014-06-03 06:58:52 +0000952 llvm::PHINode *CurPtrPhi =
953 Builder.CreatePHI(CurPtr->getType(), 2, "array.cur");
954 CurPtrPhi->addIncoming(CurPtr, EntryBB);
955 CurPtr = CurPtrPhi;
John McCall99210dc2011-09-15 06:49:18 +0000956
Richard Smith06a67e22014-06-03 06:58:52 +0000957 // Store the new Cleanup position for irregular Cleanups.
958 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
Chad Rosierf62290a2012-02-24 00:13:55 +0000959
Richard Smith06a67e22014-06-03 06:58:52 +0000960 // Enter a partial-destruction Cleanup if necessary.
961 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
962 pushRegularPartialArrayCleanup(BeginPtr, CurPtr, ElementType,
963 getDestroyer(DtorKind));
964 Cleanup = EHStack.stable_begin();
965 CleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +0000966 }
967
968 // Emit the initializer into this element.
Richard Smith06a67e22014-06-03 06:58:52 +0000969 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
John McCall99210dc2011-09-15 06:49:18 +0000970
Richard Smith06a67e22014-06-03 06:58:52 +0000971 // Leave the Cleanup if we entered one.
972 if (CleanupDominator) {
973 DeactivateCleanupBlock(Cleanup, CleanupDominator);
974 CleanupDominator->eraseFromParent();
John McCallf4beacd2011-11-10 10:43:54 +0000975 }
John McCall99210dc2011-09-15 06:49:18 +0000976
Faisal Vali57ae0562013-12-14 00:40:05 +0000977 // Advance to the next element by adjusting the pointer type as necessary.
Richard Smith06a67e22014-06-03 06:58:52 +0000978 llvm::Value *NextPtr =
979 Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.next");
980
John McCall99210dc2011-09-15 06:49:18 +0000981 // Check whether we've gotten to the end of the array and, if so,
982 // exit the loop.
Richard Smith06a67e22014-06-03 06:58:52 +0000983 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
984 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
985 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
John McCall99210dc2011-09-15 06:49:18 +0000986
Richard Smith06a67e22014-06-03 06:58:52 +0000987 EmitBlock(ContBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000988}
989
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000990static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000991 QualType ElementType,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000992 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000993 llvm::Value *NumElements,
994 llvm::Value *AllocSizeWithoutCookie) {
Richard Smith06a67e22014-06-03 06:58:52 +0000995 if (E->isArray())
996 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements,
997 AllocSizeWithoutCookie);
998 else if (const Expr *Init = E->getInitializer())
999 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001000}
1001
Richard Smith8d0dc312013-07-21 23:12:18 +00001002/// Emit a call to an operator new or operator delete function, as implicitly
1003/// created by new-expressions and delete-expressions.
1004static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1005 const FunctionDecl *Callee,
1006 const FunctionProtoType *CalleeType,
1007 const CallArgList &Args) {
1008 llvm::Instruction *CallOrInvoke;
Richard Smith1235a8d2013-07-29 20:14:16 +00001009 llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
Richard Smith8d0dc312013-07-21 23:12:18 +00001010 RValue RV =
1011 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(Args, CalleeType),
Richard Smith1235a8d2013-07-29 20:14:16 +00001012 CalleeAddr, ReturnValueSlot(), Args,
Richard Smith8d0dc312013-07-21 23:12:18 +00001013 Callee, &CallOrInvoke);
1014
1015 /// C++1y [expr.new]p10:
1016 /// [In a new-expression,] an implementation is allowed to omit a call
1017 /// to a replaceable global allocation function.
1018 ///
1019 /// We model such elidable calls with the 'builtin' attribute.
Rafael Espindola6956d582013-10-22 14:23:09 +00001020 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
Richard Smith1235a8d2013-07-29 20:14:16 +00001021 if (Callee->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola6956d582013-10-22 14:23:09 +00001022 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smith8d0dc312013-07-21 23:12:18 +00001023 // FIXME: Add addAttribute to CallSite.
1024 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1025 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1026 llvm::Attribute::Builtin);
1027 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1028 II->addAttribute(llvm::AttributeSet::FunctionIndex,
1029 llvm::Attribute::Builtin);
1030 else
1031 llvm_unreachable("unexpected kind of call instruction");
1032 }
1033
1034 return RV;
1035}
1036
Richard Smith760520b2014-06-03 23:27:44 +00001037RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1038 const Expr *Arg,
1039 bool IsDelete) {
1040 CallArgList Args;
1041 const Stmt *ArgS = Arg;
1042 EmitCallArgs(Args, *Type->param_type_begin(),
1043 ConstExprIterator(&ArgS), ConstExprIterator(&ArgS + 1));
1044 // Find the allocation or deallocation function that we're calling.
1045 ASTContext &Ctx = getContext();
1046 DeclarationName Name = Ctx.DeclarationNames
1047 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1048 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
Richard Smith599bed72014-06-05 00:43:02 +00001049 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1050 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1051 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
Richard Smith760520b2014-06-03 23:27:44 +00001052 llvm_unreachable("predeclared global operator new/delete is missing");
1053}
1054
John McCall824c2f52010-09-14 07:57:04 +00001055namespace {
1056 /// A cleanup to call the given 'operator delete' function upon
1057 /// abnormal exit from a new expression.
1058 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1059 size_t NumPlacementArgs;
1060 const FunctionDecl *OperatorDelete;
1061 llvm::Value *Ptr;
1062 llvm::Value *AllocSize;
1063
1064 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1065
1066 public:
1067 static size_t getExtraSize(size_t NumPlacementArgs) {
1068 return NumPlacementArgs * sizeof(RValue);
1069 }
1070
1071 CallDeleteDuringNew(size_t NumPlacementArgs,
1072 const FunctionDecl *OperatorDelete,
1073 llvm::Value *Ptr,
1074 llvm::Value *AllocSize)
1075 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1076 Ptr(Ptr), AllocSize(AllocSize) {}
1077
1078 void setPlacementArg(unsigned I, RValue Arg) {
1079 assert(I < NumPlacementArgs && "index out of range");
1080 getPlacementArgs()[I] = Arg;
1081 }
1082
Craig Topper4f12f102014-03-12 06:41:41 +00001083 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall824c2f52010-09-14 07:57:04 +00001084 const FunctionProtoType *FPT
1085 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001086 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1087 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +00001088
1089 CallArgList DeleteArgs;
1090
1091 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001092 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001093 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001094
1095 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001096 if (FPT->getNumParams() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001097 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001098
1099 // Pass the rest of the arguments, which must match exactly.
1100 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001101 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001102
1103 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001104 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall824c2f52010-09-14 07:57:04 +00001105 }
1106 };
John McCall7f9c92a2010-09-17 00:50:28 +00001107
1108 /// A cleanup to call the given 'operator delete' function upon
1109 /// abnormal exit from a new expression when the new expression is
1110 /// conditional.
1111 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1112 size_t NumPlacementArgs;
1113 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +00001114 DominatingValue<RValue>::saved_type Ptr;
1115 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +00001116
John McCallcb5f77f2011-01-28 10:53:53 +00001117 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1118 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +00001119 }
1120
1121 public:
1122 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +00001123 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +00001124 }
1125
1126 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1127 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +00001128 DominatingValue<RValue>::saved_type Ptr,
1129 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +00001130 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1131 Ptr(Ptr), AllocSize(AllocSize) {}
1132
John McCallcb5f77f2011-01-28 10:53:53 +00001133 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +00001134 assert(I < NumPlacementArgs && "index out of range");
1135 getPlacementArgs()[I] = Arg;
1136 }
1137
Craig Topper4f12f102014-03-12 06:41:41 +00001138 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall7f9c92a2010-09-17 00:50:28 +00001139 const FunctionProtoType *FPT
1140 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001141 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1142 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall7f9c92a2010-09-17 00:50:28 +00001143
1144 CallArgList DeleteArgs;
1145
1146 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001147 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001148 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001149
1150 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001151 if (FPT->getNumParams() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +00001152 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001153 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001154 }
1155
1156 // Pass the rest of the arguments, which must match exactly.
1157 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +00001158 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001159 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001160 }
1161
1162 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001163 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7f9c92a2010-09-17 00:50:28 +00001164 }
1165 };
1166}
1167
1168/// Enter a cleanup to call 'operator delete' if the initializer in a
1169/// new-expression throws.
1170static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1171 const CXXNewExpr *E,
1172 llvm::Value *NewPtr,
1173 llvm::Value *AllocSize,
1174 const CallArgList &NewArgs) {
1175 // If we're not inside a conditional branch, then the cleanup will
1176 // dominate and we can do the easier (and more efficient) thing.
1177 if (!CGF.isInConditionalBranch()) {
1178 CallDeleteDuringNew *Cleanup = CGF.EHStack
1179 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1180 E->getNumPlacementArgs(),
1181 E->getOperatorDelete(),
1182 NewPtr, AllocSize);
1183 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001184 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001185
1186 return;
1187 }
1188
1189 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001190 DominatingValue<RValue>::saved_type SavedNewPtr =
1191 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1192 DominatingValue<RValue>::saved_type SavedAllocSize =
1193 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001194
1195 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCallf4beacd2011-11-10 10:43:54 +00001196 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall7f9c92a2010-09-17 00:50:28 +00001197 E->getNumPlacementArgs(),
1198 E->getOperatorDelete(),
1199 SavedNewPtr,
1200 SavedAllocSize);
1201 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001202 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001203 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001204
John McCallf4beacd2011-11-10 10:43:54 +00001205 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001206}
1207
Anders Carlssoncc52f652009-09-22 22:53:17 +00001208llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001209 // The element type being allocated.
1210 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001211
John McCall75f94982011-03-07 03:12:35 +00001212 // 1. Build a call to the allocation function.
1213 FunctionDecl *allocator = E->getOperatorNew();
1214 const FunctionProtoType *allocatorType =
1215 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001216
John McCall75f94982011-03-07 03:12:35 +00001217 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001218
1219 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001220 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001221
Sebastian Redlf862eb62012-02-22 17:37:52 +00001222 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1223 unsigned minElements = 0;
1224 if (E->isArray() && E->hasInitializer()) {
1225 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1226 minElements = ILE->getNumInits();
1227 }
1228
Craig Topper8a13c412014-05-21 05:09:00 +00001229 llvm::Value *numElements = nullptr;
1230 llvm::Value *allocSizeWithoutCookie = nullptr;
John McCall75f94982011-03-07 03:12:35 +00001231 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001232 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1233 allocSizeWithoutCookie);
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00001234
Eli Friedman43dca6a2011-05-02 17:57:46 +00001235 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001236
Anders Carlssoncc52f652009-09-22 22:53:17 +00001237 // We start at 1 here because the first argument (the allocation size)
1238 // has already been emitted.
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00001239 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arg_begin(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001240 E->placement_arg_end(), /* CalleeDecl */ nullptr,
1241 /*ParamsToSkip*/ 1);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001242
John McCall7ec4b432011-05-16 01:05:12 +00001243 // Emit the allocation call. If the allocator is a global placement
1244 // operator, just "inline" it directly.
1245 RValue RV;
1246 if (allocator->isReservedGlobalPlacementOperator()) {
1247 assert(allocatorArgs.size() == 2);
1248 RV = allocatorArgs[1].RV;
1249 // TODO: kill any unnecessary computations done for the size
1250 // argument.
1251 } else {
Richard Smith8d0dc312013-07-21 23:12:18 +00001252 RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
John McCall7ec4b432011-05-16 01:05:12 +00001253 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001254
John McCall75f94982011-03-07 03:12:35 +00001255 // Emit a null check on the allocation result if the allocation
1256 // function is allowed to return null (because it has a non-throwing
1257 // exception spec; for this part, we inline
1258 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1259 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001260 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001261 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001262
Craig Topper8a13c412014-05-21 05:09:00 +00001263 llvm::BasicBlock *nullCheckBB = nullptr;
1264 llvm::BasicBlock *contBB = nullptr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001265
John McCall75f94982011-03-07 03:12:35 +00001266 llvm::Value *allocation = RV.getScalarVal();
Micah Villmowea2fea22012-10-25 15:39:14 +00001267 unsigned AS = allocation->getType()->getPointerAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001268
John McCallf7dcf322011-03-07 01:52:56 +00001269 // The null-check means that the initializer is conditionally
1270 // evaluated.
1271 ConditionalEvaluation conditional(*this);
1272
John McCall75f94982011-03-07 03:12:35 +00001273 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001274 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001275
1276 nullCheckBB = Builder.GetInsertBlock();
1277 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1278 contBB = createBasicBlock("new.cont");
1279
1280 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1281 Builder.CreateCondBr(isNull, contBB, notNullBB);
1282 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001283 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001284
John McCall824c2f52010-09-14 07:57:04 +00001285 // If there's an operator delete, enter a cleanup to call it if an
1286 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001287 EHScopeStack::stable_iterator operatorDeleteCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001288 llvm::Instruction *cleanupDominator = nullptr;
John McCall7ec4b432011-05-16 01:05:12 +00001289 if (E->getOperatorDelete() &&
1290 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCall75f94982011-03-07 03:12:35 +00001291 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1292 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001293 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001294 }
1295
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001296 assert((allocSize == allocSizeWithoutCookie) ==
1297 CalculateCookiePadding(*this, E).isZero());
1298 if (allocSize != allocSizeWithoutCookie) {
1299 assert(E->isArray());
1300 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1301 numElements,
1302 E, allocType);
1303 }
1304
Chris Lattner2192fe52011-07-18 04:24:23 +00001305 llvm::Type *elementPtrTy
John McCall75f94982011-03-07 03:12:35 +00001306 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1307 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001308
John McCall99210dc2011-09-15 06:49:18 +00001309 EmitNewInitializer(*this, E, allocType, result, numElements,
1310 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001311 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001312 // NewPtr is a pointer to the base element type. If we're
1313 // allocating an array of arrays, we'll need to cast back to the
1314 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001315 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall75f94982011-03-07 03:12:35 +00001316 if (result->getType() != resultType)
1317 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001318 }
John McCall824c2f52010-09-14 07:57:04 +00001319
1320 // Deactivate the 'operator delete' cleanup if we finished
1321 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001322 if (operatorDeleteCleanup.isValid()) {
1323 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1324 cleanupDominator->eraseFromParent();
1325 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001326
John McCall75f94982011-03-07 03:12:35 +00001327 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001328 conditional.end(*this);
1329
John McCall75f94982011-03-07 03:12:35 +00001330 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1331 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001332
Jay Foad20c0f022011-03-30 11:28:58 +00001333 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001334 PHI->addIncoming(result, notNullBB);
1335 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1336 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001337
John McCall75f94982011-03-07 03:12:35 +00001338 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001339 }
John McCall8ed55a52010-09-02 09:58:18 +00001340
John McCall75f94982011-03-07 03:12:35 +00001341 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001342}
1343
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001344void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1345 llvm::Value *Ptr,
1346 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001347 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1348
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001349 const FunctionProtoType *DeleteFTy =
1350 DeleteFD->getType()->getAs<FunctionProtoType>();
1351
1352 CallArgList DeleteArgs;
1353
Anders Carlsson21122cf2009-12-13 20:04:38 +00001354 // Check if we need to pass the size to the delete operator.
Craig Topper8a13c412014-05-21 05:09:00 +00001355 llvm::Value *Size = nullptr;
Anders Carlsson21122cf2009-12-13 20:04:38 +00001356 QualType SizeTy;
Alp Toker9cacbab2014-01-20 20:26:09 +00001357 if (DeleteFTy->getNumParams() == 2) {
1358 SizeTy = DeleteFTy->getParamType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001359 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1360 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1361 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001362 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001363
1364 QualType ArgTy = DeleteFTy->getParamType(0);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001365 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001366 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001367
Anders Carlsson21122cf2009-12-13 20:04:38 +00001368 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001369 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001370
1371 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001372 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001373}
1374
John McCall8ed55a52010-09-02 09:58:18 +00001375namespace {
1376 /// Calls the given 'operator delete' on a single object.
1377 struct CallObjectDelete : EHScopeStack::Cleanup {
1378 llvm::Value *Ptr;
1379 const FunctionDecl *OperatorDelete;
1380 QualType ElementType;
1381
1382 CallObjectDelete(llvm::Value *Ptr,
1383 const FunctionDecl *OperatorDelete,
1384 QualType ElementType)
1385 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1386
Craig Topper4f12f102014-03-12 06:41:41 +00001387 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001388 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1389 }
1390 };
1391}
1392
1393/// Emit the code for deleting a single object.
1394static void EmitObjectDelete(CodeGenFunction &CGF,
1395 const FunctionDecl *OperatorDelete,
1396 llvm::Value *Ptr,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001397 QualType ElementType,
1398 bool UseGlobalDelete) {
John McCall8ed55a52010-09-02 09:58:18 +00001399 // Find the destructor for the type, if applicable. If the
1400 // destructor is virtual, we'll just emit the vcall and return.
Craig Topper8a13c412014-05-21 05:09:00 +00001401 const CXXDestructorDecl *Dtor = nullptr;
John McCall8ed55a52010-09-02 09:58:18 +00001402 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1403 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001404 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001405 Dtor = RD->getDestructor();
1406
1407 if (Dtor->isVirtual()) {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001408 if (UseGlobalDelete) {
1409 // If we're supposed to call the global delete, make sure we do so
1410 // even if the destructor throws.
John McCall82fb8922012-09-25 10:10:39 +00001411
1412 // Derive the complete-object pointer, which is what we need
1413 // to pass to the deallocation function.
1414 llvm::Value *completePtr =
1415 CGF.CGM.getCXXABI().adjustToCompleteObject(CGF, Ptr, ElementType);
1416
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001417 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
John McCall82fb8922012-09-25 10:10:39 +00001418 completePtr, OperatorDelete,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001419 ElementType);
1420 }
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001421
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001422 // FIXME: Provide a source location here even though there's no
1423 // CXXMemberCallExpr for dtor call.
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001424 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001425 CGF.CGM.getCXXABI().EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr,
1426 nullptr);
John McCall8ed55a52010-09-02 09:58:18 +00001427
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001428 if (UseGlobalDelete) {
1429 CGF.PopCleanupBlock();
1430 }
Alexey Samsonova5bf76b2014-08-25 20:17:35 +00001431
John McCall8ed55a52010-09-02 09:58:18 +00001432 return;
1433 }
1434 }
1435 }
1436
1437 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001438 // This doesn't have to a conditional cleanup because we're going
1439 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001440 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1441 Ptr, OperatorDelete, ElementType);
1442
1443 if (Dtor)
1444 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001445 /*ForVirtualBase=*/false,
1446 /*Delegating=*/false,
1447 Ptr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001448 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001449 ElementType->isObjCLifetimeType()) {
1450 switch (ElementType.getObjCLifetime()) {
1451 case Qualifiers::OCL_None:
1452 case Qualifiers::OCL_ExplicitNone:
1453 case Qualifiers::OCL_Autoreleasing:
1454 break;
John McCall8ed55a52010-09-02 09:58:18 +00001455
John McCall31168b02011-06-15 23:02:42 +00001456 case Qualifiers::OCL_Strong: {
1457 // Load the pointer value.
1458 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1459 ElementType.isVolatileQualified());
1460
John McCallcdda29c2013-03-13 03:10:54 +00001461 CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001462 break;
1463 }
1464
1465 case Qualifiers::OCL_Weak:
1466 CGF.EmitARCDestroyWeak(Ptr);
1467 break;
1468 }
1469 }
1470
John McCall8ed55a52010-09-02 09:58:18 +00001471 CGF.PopCleanupBlock();
1472}
1473
1474namespace {
1475 /// Calls the given 'operator delete' on an array of objects.
1476 struct CallArrayDelete : EHScopeStack::Cleanup {
1477 llvm::Value *Ptr;
1478 const FunctionDecl *OperatorDelete;
1479 llvm::Value *NumElements;
1480 QualType ElementType;
1481 CharUnits CookieSize;
1482
1483 CallArrayDelete(llvm::Value *Ptr,
1484 const FunctionDecl *OperatorDelete,
1485 llvm::Value *NumElements,
1486 QualType ElementType,
1487 CharUnits CookieSize)
1488 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1489 ElementType(ElementType), CookieSize(CookieSize) {}
1490
Craig Topper4f12f102014-03-12 06:41:41 +00001491 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001492 const FunctionProtoType *DeleteFTy =
1493 OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001494 assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
John McCall8ed55a52010-09-02 09:58:18 +00001495
1496 CallArgList Args;
1497
1498 // Pass the pointer as the first argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001499 QualType VoidPtrTy = DeleteFTy->getParamType(0);
John McCall8ed55a52010-09-02 09:58:18 +00001500 llvm::Value *DeletePtr
1501 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001502 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001503
1504 // Pass the original requested size as the second argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001505 if (DeleteFTy->getNumParams() == 2) {
1506 QualType size_t = DeleteFTy->getParamType(1);
Chris Lattner2192fe52011-07-18 04:24:23 +00001507 llvm::IntegerType *SizeTy
John McCall8ed55a52010-09-02 09:58:18 +00001508 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1509
1510 CharUnits ElementTypeSize =
1511 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1512
1513 // The size of an element, multiplied by the number of elements.
1514 llvm::Value *Size
1515 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1516 Size = CGF.Builder.CreateMul(Size, NumElements);
1517
1518 // Plus the size of the cookie if applicable.
1519 if (!CookieSize.isZero()) {
1520 llvm::Value *CookieSizeV
1521 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1522 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1523 }
1524
Eli Friedman43dca6a2011-05-02 17:57:46 +00001525 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001526 }
1527
1528 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001529 EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
John McCall8ed55a52010-09-02 09:58:18 +00001530 }
1531 };
1532}
1533
1534/// Emit the code for deleting an array of objects.
1535static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001536 const CXXDeleteExpr *E,
John McCallca2c56f2011-07-13 01:41:37 +00001537 llvm::Value *deletedPtr,
1538 QualType elementType) {
Craig Topper8a13c412014-05-21 05:09:00 +00001539 llvm::Value *numElements = nullptr;
1540 llvm::Value *allocatedPtr = nullptr;
John McCallca2c56f2011-07-13 01:41:37 +00001541 CharUnits cookieSize;
1542 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1543 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001544
John McCallca2c56f2011-07-13 01:41:37 +00001545 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001546
1547 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001548 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001549 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001550 allocatedPtr, operatorDelete,
1551 numElements, elementType,
1552 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001553
John McCallca2c56f2011-07-13 01:41:37 +00001554 // Destroy the elements.
1555 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1556 assert(numElements && "no element count for a type with a destructor!");
1557
John McCallca2c56f2011-07-13 01:41:37 +00001558 llvm::Value *arrayEnd =
1559 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001560
1561 // Note that it is legal to allocate a zero-length array, and we
1562 // can never fold the check away because the length should always
1563 // come from a cookie.
John McCallca2c56f2011-07-13 01:41:37 +00001564 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1565 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001566 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001567 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001568 }
1569
John McCallca2c56f2011-07-13 01:41:37 +00001570 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001571 CGF.PopCleanupBlock();
1572}
1573
Anders Carlssoncc52f652009-09-22 22:53:17 +00001574void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001575 const Expr *Arg = E->getArgument();
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001576 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001577
1578 // Null check the pointer.
1579 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1580 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1581
Anders Carlsson98981b12011-04-11 00:30:07 +00001582 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001583
1584 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1585 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001586
John McCall8ed55a52010-09-02 09:58:18 +00001587 // We might be deleting a pointer to array. If so, GEP down to the
1588 // first non-array element.
1589 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1590 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1591 if (DeleteTy->isConstantArrayType()) {
1592 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001593 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001594
1595 GEP.push_back(Zero); // point at the outermost array
1596
1597 // For each layer of array type we're pointing at:
1598 while (const ConstantArrayType *Arr
1599 = getContext().getAsConstantArrayType(DeleteTy)) {
1600 // 1. Unpeel the array type.
1601 DeleteTy = Arr->getElementType();
1602
1603 // 2. GEP to the first element of the array.
1604 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001605 }
John McCall8ed55a52010-09-02 09:58:18 +00001606
Jay Foad040dd822011-07-22 08:16:57 +00001607 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001608 }
1609
Douglas Gregor04f36212010-09-02 17:38:50 +00001610 assert(ConvertTypeForMem(DeleteTy) ==
1611 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001612
1613 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001614 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001615 } else {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001616 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1617 E->isGlobalDelete());
John McCall8ed55a52010-09-02 09:58:18 +00001618 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001619
Anders Carlssoncc52f652009-09-22 22:53:17 +00001620 EmitBlock(DeleteEnd);
1621}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001622
David Majnemer1c3d95e2014-07-19 00:17:06 +00001623static bool isGLValueFromPointerDeref(const Expr *E) {
1624 E = E->IgnoreParens();
1625
1626 if (const auto *CE = dyn_cast<CastExpr>(E)) {
1627 if (!CE->getSubExpr()->isGLValue())
1628 return false;
1629 return isGLValueFromPointerDeref(CE->getSubExpr());
1630 }
1631
1632 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
1633 return isGLValueFromPointerDeref(OVE->getSourceExpr());
1634
1635 if (const auto *BO = dyn_cast<BinaryOperator>(E))
1636 if (BO->getOpcode() == BO_Comma)
1637 return isGLValueFromPointerDeref(BO->getRHS());
1638
1639 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
1640 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
1641 isGLValueFromPointerDeref(ACO->getFalseExpr());
1642
1643 // C++11 [expr.sub]p1:
1644 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
1645 if (isa<ArraySubscriptExpr>(E))
1646 return true;
1647
1648 if (const auto *UO = dyn_cast<UnaryOperator>(E))
1649 if (UO->getOpcode() == UO_Deref)
1650 return true;
1651
1652 return false;
1653}
1654
Warren Hunt747e3012014-06-18 21:15:55 +00001655static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001656 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001657 // Get the vtable pointer.
1658 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1659
1660 // C++ [expr.typeid]p2:
1661 // If the glvalue expression is obtained by applying the unary * operator to
1662 // a pointer and the pointer is a null pointer value, the typeid expression
1663 // throws the std::bad_typeid exception.
David Majnemer1c3d95e2014-07-19 00:17:06 +00001664 //
1665 // However, this paragraph's intent is not clear. We choose a very generous
1666 // interpretation which implores us to consider comma operators, conditional
1667 // operators, parentheses and other such constructs.
David Majnemer1162d252014-06-22 19:05:33 +00001668 QualType SrcRecordTy = E->getType();
David Majnemer1c3d95e2014-07-19 00:17:06 +00001669 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
1670 isGLValueFromPointerDeref(E), SrcRecordTy)) {
David Majnemer1162d252014-06-22 19:05:33 +00001671 llvm::BasicBlock *BadTypeidBlock =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001672 CGF.createBasicBlock("typeid.bad_typeid");
David Majnemer1162d252014-06-22 19:05:33 +00001673 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
Anders Carlsson940f02d2011-04-18 00:57:03 +00001674
David Majnemer1162d252014-06-22 19:05:33 +00001675 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1676 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001677
David Majnemer1162d252014-06-22 19:05:33 +00001678 CGF.EmitBlock(BadTypeidBlock);
1679 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1680 CGF.EmitBlock(EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001681 }
1682
David Majnemer1162d252014-06-22 19:05:33 +00001683 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
1684 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001685}
1686
John McCalle4df6c82011-01-28 08:37:24 +00001687llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001688 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001689 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001690
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001691 if (E->isTypeOperand()) {
David Majnemer143c55e2013-09-27 07:04:31 +00001692 llvm::Constant *TypeInfo =
1693 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson940f02d2011-04-18 00:57:03 +00001694 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001695 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001696
Anders Carlsson940f02d2011-04-18 00:57:03 +00001697 // C++ [expr.typeid]p2:
1698 // When typeid is applied to a glvalue expression whose type is a
1699 // polymorphic class type, the result refers to a std::type_info object
1700 // representing the type of the most derived object (that is, the dynamic
1701 // type) to which the glvalue refers.
Richard Smithef8bf432012-08-13 20:08:14 +00001702 if (E->isPotentiallyEvaluated())
1703 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1704 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001705
1706 QualType OperandTy = E->getExprOperand()->getType();
1707 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1708 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001709}
Mike Stump65511702009-11-16 06:50:58 +00001710
Anders Carlssonc1c99712011-04-11 01:45:29 +00001711static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1712 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001713 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001714 if (DestTy->isPointerType())
1715 return llvm::Constant::getNullValue(DestLTy);
1716
1717 /// C++ [expr.dynamic.cast]p9:
1718 /// A failed cast to reference type throws std::bad_cast
David Majnemer1162d252014-06-22 19:05:33 +00001719 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
1720 return nullptr;
Anders Carlssonc1c99712011-04-11 01:45:29 +00001721
1722 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1723 return llvm::UndefValue::get(DestLTy);
1724}
1725
Anders Carlsson882d7902011-04-11 00:46:40 +00001726llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001727 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001728 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001729
Anders Carlssonc1c99712011-04-11 01:45:29 +00001730 if (DCE->isAlwaysNull())
David Majnemer1162d252014-06-22 19:05:33 +00001731 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
1732 return T;
Anders Carlssonc1c99712011-04-11 01:45:29 +00001733
1734 QualType SrcTy = DCE->getSubExpr()->getType();
1735
David Majnemer1162d252014-06-22 19:05:33 +00001736 // C++ [expr.dynamic.cast]p7:
1737 // If T is "pointer to cv void," then the result is a pointer to the most
1738 // derived object pointed to by v.
1739 const PointerType *DestPTy = DestTy->getAs<PointerType>();
1740
1741 bool isDynamicCastToVoid;
1742 QualType SrcRecordTy;
1743 QualType DestRecordTy;
1744 if (DestPTy) {
1745 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
1746 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1747 DestRecordTy = DestPTy->getPointeeType();
1748 } else {
1749 isDynamicCastToVoid = false;
1750 SrcRecordTy = SrcTy;
1751 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1752 }
1753
1754 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1755
Anders Carlsson882d7902011-04-11 00:46:40 +00001756 // C++ [expr.dynamic.cast]p4:
1757 // If the value of v is a null pointer value in the pointer case, the result
1758 // is the null pointer value of type T.
David Majnemer1162d252014-06-22 19:05:33 +00001759 bool ShouldNullCheckSrcValue =
1760 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
1761 SrcRecordTy);
Craig Topper8a13c412014-05-21 05:09:00 +00001762
1763 llvm::BasicBlock *CastNull = nullptr;
1764 llvm::BasicBlock *CastNotNull = nullptr;
Anders Carlsson882d7902011-04-11 00:46:40 +00001765 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001766
Anders Carlsson882d7902011-04-11 00:46:40 +00001767 if (ShouldNullCheckSrcValue) {
1768 CastNull = createBasicBlock("dynamic_cast.null");
1769 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1770
1771 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1772 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1773 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001774 }
1775
David Majnemer1162d252014-06-22 19:05:33 +00001776 if (isDynamicCastToVoid) {
1777 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, Value, SrcRecordTy,
1778 DestTy);
1779 } else {
1780 assert(DestRecordTy->isRecordType() &&
1781 "destination type must be a record type!");
1782 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, Value, SrcRecordTy,
1783 DestTy, DestRecordTy, CastEnd);
1784 }
Anders Carlsson882d7902011-04-11 00:46:40 +00001785
1786 if (ShouldNullCheckSrcValue) {
1787 EmitBranch(CastEnd);
1788
1789 EmitBlock(CastNull);
1790 EmitBranch(CastEnd);
1791 }
1792
1793 EmitBlock(CastEnd);
1794
1795 if (ShouldNullCheckSrcValue) {
1796 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1797 PHI->addIncoming(Value, CastNotNull);
1798 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1799
1800 Value = PHI;
1801 }
1802
1803 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001804}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001805
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001806void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00001807 RunCleanupsScope Scope(*this);
Alexey Bataev39c81e22014-08-28 04:28:19 +00001808 LValue SlotLV =
1809 MakeAddrLValue(Slot.getAddr(), E->getType(), Slot.getAlignment());
Eli Friedman8631f3e82012-02-09 03:47:20 +00001810
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001811 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1812 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1813 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00001814 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001815 // Emit initialization
David Blaikie40ed2972012-06-06 20:45:41 +00001816 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Alexey Bataev39c81e22014-08-28 04:28:19 +00001817 if (CurField->hasCapturedVLAType()) {
1818 auto VAT = CurField->getCapturedVLAType();
1819 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
1820 } else {
1821 ArrayRef<VarDecl *> ArrayIndexes;
1822 if (CurField->getType()->isArrayType())
1823 ArrayIndexes = E->getCaptureInitIndexVars(i);
1824 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
1825 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001826 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001827}