blob: c6995d8a1b29316c06ebff58f19093cb658a171b [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
Anders Carlsson27da15b2010-01-01 20:29:01 +000027RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD,
Richard Smithe30752c2012-10-09 19:52:38 +000028 SourceLocation CallLoc,
Anders Carlsson27da15b2010-01-01 20:29:01 +000029 llvm::Value *Callee,
30 ReturnValueSlot ReturnValue,
31 llvm::Value *This,
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +000032 llvm::Value *ImplicitParam,
33 QualType ImplicitParamTy,
Anders Carlsson27da15b2010-01-01 20:29:01 +000034 CallExpr::const_arg_iterator ArgBeg,
35 CallExpr::const_arg_iterator ArgEnd) {
36 assert(MD->isInstance() &&
37 "Trying to emit a member call expr on a static method!");
38
Richard Smith69d0d262012-08-24 00:54:33 +000039 // C++11 [class.mfct.non-static]p2:
40 // If a non-static member function of a class X is called for an object that
41 // is not of type X, or of a type derived from X, the behavior is undefined.
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());
Anders Carlssone36a6b32010-01-02 01:01:18 +000058
John McCalla729c622012-02-17 03:33:10 +000059 // And the rest of the call args.
Anders Carlsson27da15b2010-01-01 20:29:01 +000060 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
61
John McCall8dda7b22012-07-07 06:41:13 +000062 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
Rafael Espindolac50c27c2010-03-30 20:24:48 +000063 Callee, ReturnValue, Args, MD);
Anders Carlsson27da15b2010-01-01 20:29:01 +000064}
65
Rafael Espindola3b33c4e2012-06-28 14:28:57 +000066static CXXRecordDecl *getCXXRecord(const Expr *E) {
67 QualType T = E->getType();
68 if (const PointerType *PTy = T->getAs<PointerType>())
69 T = PTy->getPointeeType();
70 const RecordType *Ty = T->castAs<RecordType>();
71 return cast<CXXRecordDecl>(Ty->getDecl());
72}
73
Francois Pichet64225792011-01-18 05:04:39 +000074// Note: This function also emit constructor calls to support a MSVC
75// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +000076RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
77 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +000078 const Expr *callee = CE->getCallee()->IgnoreParens();
79
80 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +000081 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +000082
83 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +000084 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
85
86 if (MD->isStatic()) {
87 // The method is static, emit it as we would a regular call.
88 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
89 return EmitCall(getContext().getPointerType(MD->getType()), Callee,
Peter Collingbourneb453cd62013-10-20 21:29:19 +000090 CE->getLocStart(), ReturnValue, CE->arg_begin(),
91 CE->arg_end());
Anders Carlsson27da15b2010-01-01 20:29:01 +000092 }
Anders Carlsson27da15b2010-01-01 20:29:01 +000093
John McCall0d635f52010-09-03 01:26:39 +000094 // Compute the object pointer.
Rafael Espindolaecbe2e92012-06-28 01:56:38 +000095 const Expr *Base = ME->getBase();
96 bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +000097
Craig Topper8a13c412014-05-21 05:09:00 +000098 const CXXMethodDecl *DevirtualizedMethod = nullptr;
Benjamin Kramer7463ed72013-08-25 22:46:27 +000099 if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000100 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
101 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
102 assert(DevirtualizedMethod);
103 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
104 const Expr *Inner = Base->ignoreParenBaseCasts();
105 if (getCXXRecord(Inner) == DevirtualizedClass)
106 // If the class of the Inner expression is where the dynamic method
107 // is defined, build the this pointer from it.
108 Base = Inner;
109 else if (getCXXRecord(Base) != DevirtualizedClass) {
110 // If the method is defined in a class that is not the best dynamic
111 // one or the one of the full expression, we would have to build
112 // a derived-to-base cast to compute the correct this pointer, but
113 // we don't have support for that yet, so do a virtual call.
Craig Topper8a13c412014-05-21 05:09:00 +0000114 DevirtualizedMethod = nullptr;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000115 }
Rafael Espindolab27564a2012-06-28 17:57:36 +0000116 // If the return types are not the same, this might be a case where more
117 // code needs to run to compensate for it. For example, the derived
118 // method might return a type that inherits form from the return
119 // type of MD and has a prefix.
120 // For now we just avoid devirtualizing these covariant cases.
121 if (DevirtualizedMethod &&
Alp Toker314cc812014-01-25 16:55:45 +0000122 DevirtualizedMethod->getReturnType().getCanonicalType() !=
123 MD->getReturnType().getCanonicalType())
Craig Topper8a13c412014-05-21 05:09:00 +0000124 DevirtualizedMethod = nullptr;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000125 }
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000126
Anders Carlsson27da15b2010-01-01 20:29:01 +0000127 llvm::Value *This;
Anders Carlsson27da15b2010-01-01 20:29:01 +0000128 if (ME->isArrow())
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000129 This = EmitScalarExpr(Base);
John McCalle26a8722010-12-04 08:14:53 +0000130 else
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000131 This = EmitLValue(Base).getAddress();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000132
Anders Carlsson27da15b2010-01-01 20:29:01 +0000133
John McCall0d635f52010-09-03 01:26:39 +0000134 if (MD->isTrivial()) {
Craig Topper8a13c412014-05-21 05:09:00 +0000135 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
Francois Pichet64225792011-01-18 05:04:39 +0000136 if (isa<CXXConstructorDecl>(MD) &&
137 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
Craig Topper8a13c412014-05-21 05:09:00 +0000138 return RValue::get(nullptr);
John McCall0d635f52010-09-03 01:26:39 +0000139
Sebastian Redl22653ba2011-08-30 19:58:05 +0000140 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
141 // We don't like to generate the trivial copy/move assignment operator
142 // when it isn't necessary; just produce the proper effect here.
Francois Pichet64225792011-01-18 05:04:39 +0000143 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
Benjamin Kramer1ca66912012-09-30 12:43:37 +0000144 EmitAggregateAssign(This, RHS, CE->getType());
Francois Pichet64225792011-01-18 05:04:39 +0000145 return RValue::get(This);
146 }
147
148 if (isa<CXXConstructorDecl>(MD) &&
Sebastian Redl22653ba2011-08-30 19:58:05 +0000149 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
150 // Trivial move and copy ctor are the same.
Francois Pichet64225792011-01-18 05:04:39 +0000151 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
152 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
153 CE->arg_begin(), CE->arg_end());
154 return RValue::get(This);
155 }
156 llvm_unreachable("unknown trivial member function");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000157 }
158
John McCall0d635f52010-09-03 01:26:39 +0000159 // Compute the function type we're calling.
Eli Friedmanade60972012-10-25 00:12:49 +0000160 const CXXMethodDecl *CalleeDecl = DevirtualizedMethod ? DevirtualizedMethod : MD;
Craig Topper8a13c412014-05-21 05:09:00 +0000161 const CGFunctionInfo *FInfo = nullptr;
Eli Friedmanade60972012-10-25 00:12:49 +0000162 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
163 FInfo = &CGM.getTypes().arrangeCXXDestructor(Dtor,
John McCalla729c622012-02-17 03:33:10 +0000164 Dtor_Complete);
Eli Friedmanade60972012-10-25 00:12:49 +0000165 else if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
166 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor,
167 Ctor_Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000168 else
Eli Friedmanade60972012-10-25 00:12:49 +0000169 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCall0d635f52010-09-03 01:26:39 +0000170
Reid Klecknere7de47e2013-07-22 13:51:44 +0000171 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000172
Anders Carlsson27da15b2010-01-01 20:29:01 +0000173 // C++ [class.virtual]p12:
174 // Explicit qualification with the scope operator (5.1) suppresses the
175 // virtual call mechanism.
176 //
177 // We also don't emit a virtual call if the base expression has a record type
178 // because then we know what the type is.
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000179 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
Stephen Lin19cee182013-06-19 23:23:19 +0000180 llvm::Value *Callee;
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000181
John McCall0d635f52010-09-03 01:26:39 +0000182 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000183 assert(CE->arg_begin() == CE->arg_end() &&
184 "Destructor shouldn't have explicit parameters");
185 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
John McCall0d635f52010-09-03 01:26:39 +0000186 if (UseVirtualCall) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000187 CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
188 CE->getExprLoc(), This);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000189 } else {
Richard Smith9c6890a2012-11-01 22:30:59 +0000190 if (getLangOpts().AppleKext &&
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000191 MD->isVirtual() &&
192 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000193 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000194 else if (!DevirtualizedMethod)
Reid Klecknere7de47e2013-07-22 13:51:44 +0000195 Callee = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete, FInfo, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000196 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000197 const CXXDestructorDecl *DDtor =
198 cast<CXXDestructorDecl>(DevirtualizedMethod);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000199 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
200 }
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000201 EmitCXXMemberCall(MD, CE->getExprLoc(), Callee, ReturnValue, This,
Craig Topper8a13c412014-05-21 05:09:00 +0000202 /*ImplicitParam=*/nullptr, QualType(), nullptr,nullptr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000203 }
Craig Topper8a13c412014-05-21 05:09:00 +0000204 return RValue::get(nullptr);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000205 }
206
207 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
Francois Pichet64225792011-01-18 05:04:39 +0000208 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
John McCall0d635f52010-09-03 01:26:39 +0000209 } else if (UseVirtualCall) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000210 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000211 } else {
Richard Smith9c6890a2012-11-01 22:30:59 +0000212 if (getLangOpts().AppleKext &&
Fariborz Jahanian9f9438b2011-01-28 23:42:29 +0000213 MD->isVirtual() &&
Fariborz Jahanian252a47f2011-01-21 01:04:41 +0000214 ME->hasQualifier())
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +0000215 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000216 else if (!DevirtualizedMethod)
Rafael Espindola727a7712012-06-26 19:18:25 +0000217 Callee = CGM.GetAddrOfFunction(MD, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000218 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000219 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000220 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000221 }
222
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000223 if (MD->isVirtual()) {
224 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
225 *this, MD, This, UseVirtualCall);
226 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000227
Richard Smithe30752c2012-10-09 19:52:38 +0000228 return EmitCXXMemberCall(MD, CE->getExprLoc(), Callee, ReturnValue, This,
Craig Topper8a13c412014-05-21 05:09:00 +0000229 /*ImplicitParam=*/nullptr, QualType(),
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000230 CE->arg_begin(), CE->arg_end());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000231}
232
233RValue
234CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
235 ReturnValueSlot ReturnValue) {
236 const BinaryOperator *BO =
237 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
238 const Expr *BaseExpr = BO->getLHS();
239 const Expr *MemFnExpr = BO->getRHS();
240
241 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000242 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000243
Anders Carlsson27da15b2010-01-01 20:29:01 +0000244 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000245 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000246 const CXXRecordDecl *RD =
247 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
248
Anders Carlsson27da15b2010-01-01 20:29:01 +0000249 // Get the member function pointer.
John McCalla1dee5302010-08-22 10:59:02 +0000250 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000251
252 // Emit the 'this' pointer.
253 llvm::Value *This;
254
John McCalle3027922010-08-25 11:45:40 +0000255 if (BO->getOpcode() == BO_PtrMemI)
Anders Carlsson27da15b2010-01-01 20:29:01 +0000256 This = EmitScalarExpr(BaseExpr);
257 else
258 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000259
Richard Smithe30752c2012-10-09 19:52:38 +0000260 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
261 QualType(MPT->getClass(), 0));
Richard Smith69d0d262012-08-24 00:54:33 +0000262
John McCall475999d2010-08-22 00:05:51 +0000263 // Ask the ABI to load the callee. Note that This is modified.
264 llvm::Value *Callee =
David Majnemer2b0d66d2014-02-20 23:22:07 +0000265 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000266
Anders Carlsson27da15b2010-01-01 20:29:01 +0000267 CallArgList Args;
268
269 QualType ThisType =
270 getContext().getPointerType(getContext().getTagDeclType(RD));
271
272 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +0000273 Args.add(RValue::get(This), ThisType);
John McCall8dda7b22012-07-07 06:41:13 +0000274
275 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000276
277 // And the rest of the call args
278 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000279 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
280 Callee, ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000281}
282
283RValue
284CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
285 const CXXMethodDecl *MD,
286 ReturnValueSlot ReturnValue) {
287 assert(MD->isInstance() &&
288 "Trying to emit a member call expr on a static method!");
John McCalle26a8722010-12-04 08:14:53 +0000289 LValue LV = EmitLValue(E->getArg(0));
290 llvm::Value *This = LV.getAddress();
291
Douglas Gregor146b8e92011-09-06 16:26:56 +0000292 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
293 MD->isTrivial()) {
294 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
295 QualType Ty = E->getType();
Benjamin Kramer1ca66912012-09-30 12:43:37 +0000296 EmitAggregateAssign(This, Src, Ty);
Douglas Gregor146b8e92011-09-06 16:26:56 +0000297 return RValue::get(This);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000298 }
299
Anders Carlssonc36783e2011-05-08 20:32:23 +0000300 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
Richard Smithe30752c2012-10-09 19:52:38 +0000301 return EmitCXXMemberCall(MD, E->getExprLoc(), Callee, ReturnValue, This,
Craig Topper8a13c412014-05-21 05:09:00 +0000302 /*ImplicitParam=*/nullptr, QualType(),
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000303 E->arg_begin() + 1, E->arg_end());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000304}
305
Peter Collingbournefe883422011-10-06 18:29:37 +0000306RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
307 ReturnValueSlot ReturnValue) {
308 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
309}
310
Eli Friedmanfde961d2011-10-14 02:27:24 +0000311static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
312 llvm::Value *DestPtr,
313 const CXXRecordDecl *Base) {
314 if (Base->isEmpty())
315 return;
316
317 DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
318
319 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
320 CharUnits Size = Layout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +0000321 CharUnits Align = Layout.getNonVirtualAlignment();
Eli Friedmanfde961d2011-10-14 02:27:24 +0000322
323 llvm::Value *SizeVal = CGF.CGM.getSize(Size);
324
325 // If the type contains a pointer to data member we can't memset it to zero.
326 // Instead, create a null constant and copy it to the destination.
327 // TODO: there are other patterns besides zero that we can usefully memset,
328 // like -1, which happens to be the pattern used by member-pointers.
329 // TODO: isZeroInitializable can be over-conservative in the case where a
330 // virtual base contains a member pointer.
331 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
332 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
333
334 llvm::GlobalVariable *NullVariable =
335 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
336 /*isConstant=*/true,
337 llvm::GlobalVariable::PrivateLinkage,
338 NullConstant, Twine());
339 NullVariable->setAlignment(Align.getQuantity());
340 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
341
342 // Get and call the appropriate llvm.memcpy overload.
343 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
344 return;
345 }
346
347 // Otherwise, just memset the whole thing to zero. This is legal
348 // because in LLVM, all default initializers (other than the ones we just
349 // handled above) are guaranteed to have a bit pattern of all zeros.
350 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
351 Align.getQuantity());
352}
353
Anders Carlsson27da15b2010-01-01 20:29:01 +0000354void
John McCall7a626f62010-09-15 10:14:12 +0000355CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
356 AggValueSlot Dest) {
357 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000358 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000359
360 // If we require zero initialization before (or instead of) calling the
361 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000362 // constructor, emit the zero initialization now, unless destination is
363 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000364 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
365 switch (E->getConstructionKind()) {
366 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000367 case CXXConstructExpr::CK_Complete:
368 EmitNullInitialization(Dest.getAddr(), E->getType());
369 break;
370 case CXXConstructExpr::CK_VirtualBase:
371 case CXXConstructExpr::CK_NonVirtualBase:
372 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
373 break;
374 }
375 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000376
377 // If this is a call to a trivial default constructor, do nothing.
378 if (CD->isTrivial() && CD->isDefaultConstructor())
379 return;
380
John McCall8ea46b62010-09-18 00:58:34 +0000381 // Elide the constructor if we're constructing from a temporary.
382 // The temporary check is required because Sema sets this on NRVO
383 // returns.
Richard Smith9c6890a2012-11-01 22:30:59 +0000384 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000385 assert(getContext().hasSameUnqualifiedType(E->getType(),
386 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000387 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
388 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000389 return;
390 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000391 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000392
John McCallf677a8e2011-07-13 06:10:41 +0000393 if (const ConstantArrayType *arrayType
394 = getContext().getAsConstantArrayType(E->getType())) {
395 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000396 E->arg_begin(), E->arg_end());
John McCallf677a8e2011-07-13 06:10:41 +0000397 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000398 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000399 bool ForVirtualBase = false;
Douglas Gregor61535002013-01-31 05:50:40 +0000400 bool Delegating = false;
401
Alexis Hunt271c3682011-05-03 20:19:28 +0000402 switch (E->getConstructionKind()) {
403 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000404 // We should be emitting a constructor; GlobalDecl will assert this
405 Type = CurGD.getCtorType();
Douglas Gregor61535002013-01-31 05:50:40 +0000406 Delegating = true;
Alexis Hunt271c3682011-05-03 20:19:28 +0000407 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000408
Alexis Hunt271c3682011-05-03 20:19:28 +0000409 case CXXConstructExpr::CK_Complete:
410 Type = Ctor_Complete;
411 break;
412
413 case CXXConstructExpr::CK_VirtualBase:
414 ForVirtualBase = true;
415 // fall-through
416
417 case CXXConstructExpr::CK_NonVirtualBase:
418 Type = Ctor_Base;
419 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000420
Anders Carlsson27da15b2010-01-01 20:29:01 +0000421 // Call the constructor.
Douglas Gregor61535002013-01-31 05:50:40 +0000422 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
Anders Carlsson27da15b2010-01-01 20:29:01 +0000423 E->arg_begin(), E->arg_end());
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000424 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000425}
426
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000427void
428CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
429 llvm::Value *Src,
Fariborz Jahanian50198092010-12-02 17:02:11 +0000430 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000431 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000432 Exp = E->getSubExpr();
433 assert(isa<CXXConstructExpr>(Exp) &&
434 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
435 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
436 const CXXConstructorDecl *CD = E->getConstructor();
437 RunCleanupsScope Scope(*this);
438
439 // If we require zero initialization before (or instead of) calling the
440 // constructor, as can be the case with a non-user-provided default
441 // constructor, emit the zero initialization now.
442 // FIXME. Do I still need this for a copy ctor synthesis?
443 if (E->requiresZeroInitialization())
444 EmitNullInitialization(Dest, E->getType());
445
Chandler Carruth99da11c2010-11-15 13:54:43 +0000446 assert(!getContext().getAsConstantArrayType(E->getType())
447 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000448 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E->arg_begin(), E->arg_end());
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000449}
450
John McCall8ed55a52010-09-02 09:58:18 +0000451static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
452 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000453 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000454 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000455
John McCall7ec4b432011-05-16 01:05:12 +0000456 // No cookie is required if the operator new[] being used is the
457 // reserved placement operator new[].
458 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000459 return CharUnits::Zero();
460
John McCall284c48f2011-01-27 09:37:56 +0000461 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000462}
463
John McCall036f2f62011-05-15 07:14:44 +0000464static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
465 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000466 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000467 llvm::Value *&numElements,
468 llvm::Value *&sizeWithoutCookie) {
469 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000470
John McCall036f2f62011-05-15 07:14:44 +0000471 if (!e->isArray()) {
472 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
473 sizeWithoutCookie
474 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
475 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000476 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000477
John McCall036f2f62011-05-15 07:14:44 +0000478 // The width of size_t.
479 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
480
John McCall8ed55a52010-09-02 09:58:18 +0000481 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000482 llvm::APInt cookieSize(sizeWidth,
483 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000484
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000485 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000486 // We multiply the size of all dimensions for NumElements.
487 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000488 numElements = CGF.EmitScalarExpr(e->getArraySize());
489 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000490
John McCall036f2f62011-05-15 07:14:44 +0000491 // The number of elements can be have an arbitrary integer type;
492 // essentially, we need to multiply it by a constant factor, add a
493 // cookie size, and verify that the result is representable as a
494 // size_t. That's just a gloss, though, and it's wrong in one
495 // important way: if the count is negative, it's an error even if
496 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000497 bool isSigned
498 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000499 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000500 = cast<llvm::IntegerType>(numElements->getType());
501 unsigned numElementsWidth = numElementsType->getBitWidth();
502
503 // Compute the constant factor.
504 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000505 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000506 = CGF.getContext().getAsConstantArrayType(type)) {
507 type = CAT->getElementType();
508 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000509 }
510
John McCall036f2f62011-05-15 07:14:44 +0000511 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
512 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
513 typeSizeMultiplier *= arraySizeMultiplier;
514
515 // This will be a size_t.
516 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000517
Chris Lattner32ac5832010-07-20 21:55:52 +0000518 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
519 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000520 if (llvm::ConstantInt *numElementsC =
521 dyn_cast<llvm::ConstantInt>(numElements)) {
522 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000523
John McCall036f2f62011-05-15 07:14:44 +0000524 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000525
John McCall036f2f62011-05-15 07:14:44 +0000526 // If 'count' was a negative number, it's an overflow.
527 if (isSigned && count.isNegative())
528 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000529
John McCall036f2f62011-05-15 07:14:44 +0000530 // We want to do all this arithmetic in size_t. If numElements is
531 // wider than that, check whether it's already too big, and if so,
532 // overflow.
533 else if (numElementsWidth > sizeWidth &&
534 numElementsWidth - sizeWidth > count.countLeadingZeros())
535 hasAnyOverflow = true;
536
537 // Okay, compute a count at the right width.
538 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
539
Sebastian Redlf862eb62012-02-22 17:37:52 +0000540 // If there is a brace-initializer, we cannot allocate fewer elements than
541 // there are initializers. If we do, that's treated like an overflow.
542 if (adjustedCount.ult(minElements))
543 hasAnyOverflow = true;
544
John McCall036f2f62011-05-15 07:14:44 +0000545 // Scale numElements by that. This might overflow, but we don't
546 // care because it only overflows if allocationSize does, too, and
547 // if that overflows then we shouldn't use this.
548 numElements = llvm::ConstantInt::get(CGF.SizeTy,
549 adjustedCount * arraySizeMultiplier);
550
551 // Compute the size before cookie, and track whether it overflowed.
552 bool overflow;
553 llvm::APInt allocationSize
554 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
555 hasAnyOverflow |= overflow;
556
557 // Add in the cookie, and check whether it's overflowed.
558 if (cookieSize != 0) {
559 // Save the current size without a cookie. This shouldn't be
560 // used if there was overflow.
561 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
562
563 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
564 hasAnyOverflow |= overflow;
565 }
566
567 // On overflow, produce a -1 so operator new will fail.
568 if (hasAnyOverflow) {
569 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
570 } else {
571 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
572 }
573
574 // Otherwise, we might need to use the overflow intrinsics.
575 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000576 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000577 // 1) if isSigned, we need to check whether numElements is negative;
578 // 2) if numElementsWidth > sizeWidth, we need to check whether
579 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000580 // 3) if minElements > 0, we need to check whether numElements is smaller
581 // than that.
582 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000583 // sizeWithoutCookie := numElements * typeSizeMultiplier
584 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000585 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000586 // size := sizeWithoutCookie + cookieSize
587 // and check whether it overflows.
588
Craig Topper8a13c412014-05-21 05:09:00 +0000589 llvm::Value *hasOverflow = nullptr;
John McCall036f2f62011-05-15 07:14:44 +0000590
591 // If numElementsWidth > sizeWidth, then one way or another, we're
592 // going to have to do a comparison for (2), and this happens to
593 // take care of (1), too.
594 if (numElementsWidth > sizeWidth) {
595 llvm::APInt threshold(numElementsWidth, 1);
596 threshold <<= sizeWidth;
597
598 llvm::Value *thresholdV
599 = llvm::ConstantInt::get(numElementsType, threshold);
600
601 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
602 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
603
604 // Otherwise, if we're signed, we want to sext up to size_t.
605 } else if (isSigned) {
606 if (numElementsWidth < sizeWidth)
607 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
608
609 // If there's a non-1 type size multiplier, then we can do the
610 // signedness check at the same time as we do the multiply
611 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000612 // unsigned overflow. Otherwise, we have to do it here. But at least
613 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000614 if (typeSizeMultiplier == 1)
615 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000616 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000617
618 // Otherwise, zext up to size_t if necessary.
619 } else if (numElementsWidth < sizeWidth) {
620 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
621 }
622
623 assert(numElements->getType() == CGF.SizeTy);
624
Sebastian Redlf862eb62012-02-22 17:37:52 +0000625 if (minElements) {
626 // Don't allow allocation of fewer elements than we have initializers.
627 if (!hasOverflow) {
628 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
629 llvm::ConstantInt::get(CGF.SizeTy, minElements));
630 } else if (numElementsWidth > sizeWidth) {
631 // The other existing overflow subsumes this check.
632 // We do an unsigned comparison, since any signed value < -1 is
633 // taken care of either above or below.
634 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
635 CGF.Builder.CreateICmpULT(numElements,
636 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
637 }
638 }
639
John McCall036f2f62011-05-15 07:14:44 +0000640 size = numElements;
641
642 // Multiply by the type size if necessary. This multiplier
643 // includes all the factors for nested arrays.
644 //
645 // This step also causes numElements to be scaled up by the
646 // nested-array factor if necessary. Overflow on this computation
647 // can be ignored because the result shouldn't be used if
648 // allocation fails.
649 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000650 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000651 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000652
653 llvm::Value *tsmV =
654 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
655 llvm::Value *result =
656 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
657
658 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
659 if (hasOverflow)
660 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
661 else
662 hasOverflow = overflowed;
663
664 size = CGF.Builder.CreateExtractValue(result, 0);
665
666 // Also scale up numElements by the array size multiplier.
667 if (arraySizeMultiplier != 1) {
668 // If the base element type size is 1, then we can re-use the
669 // multiply we just did.
670 if (typeSize.isOne()) {
671 assert(arraySizeMultiplier == typeSizeMultiplier);
672 numElements = size;
673
674 // Otherwise we need a separate multiply.
675 } else {
676 llvm::Value *asmV =
677 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
678 numElements = CGF.Builder.CreateMul(numElements, asmV);
679 }
680 }
681 } else {
682 // numElements doesn't need to be scaled.
683 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000684 }
685
John McCall036f2f62011-05-15 07:14:44 +0000686 // Add in the cookie size if necessary.
687 if (cookieSize != 0) {
688 sizeWithoutCookie = size;
689
John McCall036f2f62011-05-15 07:14:44 +0000690 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000691 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000692
693 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
694 llvm::Value *result =
695 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
696
697 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
698 if (hasOverflow)
699 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
700 else
701 hasOverflow = overflowed;
702
703 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000704 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000705
John McCall036f2f62011-05-15 07:14:44 +0000706 // If we had any possibility of dynamic overflow, make a select to
707 // overwrite 'size' with an all-ones value, which should cause
708 // operator new to throw.
709 if (hasOverflow)
710 size = CGF.Builder.CreateSelect(hasOverflow,
711 llvm::Constant::getAllOnesValue(CGF.SizeTy),
712 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000713 }
John McCall8ed55a52010-09-02 09:58:18 +0000714
John McCall036f2f62011-05-15 07:14:44 +0000715 if (cookieSize == 0)
716 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000717 else
John McCall036f2f62011-05-15 07:14:44 +0000718 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000719
John McCall036f2f62011-05-15 07:14:44 +0000720 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000721}
722
Sebastian Redlf862eb62012-02-22 17:37:52 +0000723static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
724 QualType AllocType, llvm::Value *NewPtr) {
Richard Smith1c96bc52013-12-11 01:40:16 +0000725 // FIXME: Refactor with EmitExprAsInit.
Eli Friedman38cd36d2011-12-03 02:13:40 +0000726 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
John McCall47fb9502013-03-07 21:37:08 +0000727 switch (CGF.getEvaluationKind(AllocType)) {
728 case TEK_Scalar:
Craig Topper8a13c412014-05-21 05:09:00 +0000729 CGF.EmitScalarInit(Init, nullptr, CGF.MakeAddrLValue(NewPtr, AllocType,
730 Alignment),
John McCall1553b192011-06-16 04:16:24 +0000731 false);
John McCall47fb9502013-03-07 21:37:08 +0000732 return;
733 case TEK_Complex:
734 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
735 Alignment),
736 /*isInit*/ true);
737 return;
738 case TEK_Aggregate: {
John McCall7a626f62010-09-15 10:14:12 +0000739 AggValueSlot Slot
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000740 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000741 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000742 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000743 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000744 CGF.EmitAggExpr(Init, Slot);
John McCall47fb9502013-03-07 21:37:08 +0000745 return;
John McCall7a626f62010-09-15 10:14:12 +0000746 }
John McCall47fb9502013-03-07 21:37:08 +0000747 }
748 llvm_unreachable("bad evaluation kind");
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000749}
750
751void
Richard Smith06a67e22014-06-03 06:58:52 +0000752CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
753 QualType ElementType,
754 llvm::Value *BeginPtr,
755 llvm::Value *NumElements,
756 llvm::Value *AllocSizeWithoutCookie) {
757 // If we have a type with trivial initialization and no initializer,
758 // there's nothing to do.
Sebastian Redl6047f072012-02-16 12:22:20 +0000759 if (!E->hasInitializer())
Richard Smith06a67e22014-06-03 06:58:52 +0000760 return;
John McCall99210dc2011-09-15 06:49:18 +0000761
Richard Smith06a67e22014-06-03 06:58:52 +0000762 llvm::Value *CurPtr = BeginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000763
Richard Smith06a67e22014-06-03 06:58:52 +0000764 unsigned InitListElements = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000765
766 const Expr *Init = E->getInitializer();
Richard Smith06a67e22014-06-03 06:58:52 +0000767 llvm::AllocaInst *EndOfInit = nullptr;
768 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
769 EHScopeStack::stable_iterator Cleanup;
770 llvm::Instruction *CleanupDominator = nullptr;
Richard Smith1c96bc52013-12-11 01:40:16 +0000771
Sebastian Redlf862eb62012-02-22 17:37:52 +0000772 // If the initializer is an initializer list, first do the explicit elements.
773 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +0000774 InitListElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +0000775
Richard Smith1c96bc52013-12-11 01:40:16 +0000776 // If this is a multi-dimensional array new, we will initialize multiple
777 // elements with each init list element.
778 QualType AllocType = E->getAllocatedType();
779 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
780 AllocType->getAsArrayTypeUnsafe())) {
Richard Smith06a67e22014-06-03 06:58:52 +0000781 unsigned AS = CurPtr->getType()->getPointerAddressSpace();
Richard Smith1c96bc52013-12-11 01:40:16 +0000782 llvm::Type *AllocPtrTy = ConvertTypeForMem(AllocType)->getPointerTo(AS);
Richard Smith06a67e22014-06-03 06:58:52 +0000783 CurPtr = Builder.CreateBitCast(CurPtr, AllocPtrTy);
784 InitListElements *= getContext().getConstantArrayElementCount(CAT);
Richard Smith1c96bc52013-12-11 01:40:16 +0000785 }
786
Richard Smith06a67e22014-06-03 06:58:52 +0000787 // Enter a partial-destruction Cleanup if necessary.
788 if (needsEHCleanup(DtorKind)) {
789 // In principle we could tell the Cleanup where we are more
Chad Rosierf62290a2012-02-24 00:13:55 +0000790 // directly, but the control flow can get so varied here that it
791 // would actually be quite complex. Therefore we go through an
792 // alloca.
Richard Smith06a67e22014-06-03 06:58:52 +0000793 EndOfInit = CreateTempAlloca(BeginPtr->getType(), "array.init.end");
794 CleanupDominator = Builder.CreateStore(BeginPtr, EndOfInit);
795 pushIrregularPartialArrayCleanup(BeginPtr, EndOfInit, ElementType,
796 getDestroyer(DtorKind));
797 Cleanup = EHStack.stable_begin();
Chad Rosierf62290a2012-02-24 00:13:55 +0000798 }
799
Sebastian Redlf862eb62012-02-22 17:37:52 +0000800 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +0000801 // Tell the cleanup that it needs to destroy up to this
802 // element. TODO: some of these stores can be trivially
803 // observed to be unnecessary.
Richard Smith06a67e22014-06-03 06:58:52 +0000804 if (EndOfInit)
805 Builder.CreateStore(Builder.CreateBitCast(CurPtr, BeginPtr->getType()),
806 EndOfInit);
807 // FIXME: If the last initializer is an incomplete initializer list for
808 // an array, and we have an array filler, we can fold together the two
809 // initialization loops.
Richard Smith1c96bc52013-12-11 01:40:16 +0000810 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
Richard Smith06a67e22014-06-03 06:58:52 +0000811 ILE->getInit(i)->getType(), CurPtr);
812 CurPtr = Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.exp.next");
Sebastian Redlf862eb62012-02-22 17:37:52 +0000813 }
814
815 // The remaining elements are filled with the array filler expression.
816 Init = ILE->getArrayFiller();
Richard Smith1c96bc52013-12-11 01:40:16 +0000817
Richard Smith06a67e22014-06-03 06:58:52 +0000818 // Extract the initializer for the individual array elements by pulling
819 // out the array filler from all the nested initializer lists. This avoids
820 // generating a nested loop for the initialization.
821 while (Init && Init->getType()->isConstantArrayType()) {
822 auto *SubILE = dyn_cast<InitListExpr>(Init);
823 if (!SubILE)
824 break;
825 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
826 Init = SubILE->getArrayFiller();
827 }
828
829 // Switch back to initializing one base element at a time.
830 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr->getType());
Sebastian Redlf862eb62012-02-22 17:37:52 +0000831 }
832
Richard Smith06a67e22014-06-03 06:58:52 +0000833 // Attempt to perform zero-initialization using memset.
834 auto TryMemsetInitialization = [&]() -> bool {
835 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
836 // we can initialize with a memset to -1.
837 if (!CGM.getTypes().isZeroInitializable(ElementType))
838 return false;
Chandler Carruthe6c980c2014-05-03 09:16:57 +0000839
Richard Smith06a67e22014-06-03 06:58:52 +0000840 // Optimization: since zero initialization will just set the memory
841 // to all zeroes, generate a single memset to do it in one shot.
842
843 // Subtract out the size of any elements we've already initialized.
844 auto *RemainingSize = AllocSizeWithoutCookie;
845 if (InitListElements) {
846 // We know this can't overflow; we check this when doing the allocation.
847 auto *InitializedSize = llvm::ConstantInt::get(
848 RemainingSize->getType(),
849 getContext().getTypeSizeInChars(ElementType).getQuantity() *
850 InitListElements);
851 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
852 }
853
854 // Create the memset.
855 CharUnits Alignment = getContext().getTypeAlignInChars(ElementType);
856 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize,
857 Alignment.getQuantity(), false);
858 return true;
859 };
860
861 // If this is a constructor call, try to optimize it out, and failing that
862 // emit a single loop to initialize all remaining elements.
863 if (const CXXConstructExpr *CCE = dyn_cast_or_null<CXXConstructExpr>(Init)){
864 CXXConstructorDecl *Ctor = CCE->getConstructor();
865 if (Ctor->isTrivial()) {
866 // If new expression did not specify value-initialization, then there
867 // is no initialization.
868 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
869 return;
870
871 if (TryMemsetInitialization())
872 return;
873 }
874
875 // Store the new Cleanup position for irregular Cleanups.
876 //
877 // FIXME: Share this cleanup with the constructor call emission rather than
878 // having it create a cleanup of its own.
879 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
880
881 // Emit a constructor call loop to initialize the remaining elements.
882 if (InitListElements)
883 NumElements = Builder.CreateSub(
884 NumElements,
885 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
886 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr,
887 CCE->arg_begin(), CCE->arg_end(),
888 CCE->requiresZeroInitialization());
Chandler Carruthe6c980c2014-05-03 09:16:57 +0000889 return;
890 }
891
Richard Smith06a67e22014-06-03 06:58:52 +0000892 // If this is value-initialization, we can usually use memset.
893 ImplicitValueInitExpr IVIE(ElementType);
894 if (Init && isa<ImplicitValueInitExpr>(Init)) {
895 if (TryMemsetInitialization())
896 return;
897
898 // Switch to an ImplicitValueInitExpr for the element type. This handles
899 // only one case: multidimensional array new of pointers to members. In
900 // all other cases, we already have an initializer for the array element.
901 Init = &IVIE;
902 }
903
904 // At this point we should have found an initializer for the individual
905 // elements of the array.
906 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
907 "got wrong type of element to initialize");
908
909 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
910
911 // If all elements have already been initialized, skip the whole loop.
912 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
913 // If there was a Cleanup, deactivate it.
914 if (CleanupDominator)
915 DeactivateCleanupBlock(Cleanup, CleanupDominator);
916 return;
917 }
918
919 // Create the loop blocks.
920 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
921 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
922 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
923
924 // Find the end of the array, hoisted out of the loop.
925 llvm::Value *EndPtr =
926 Builder.CreateInBoundsGEP(BeginPtr, NumElements, "array.end");
John McCall99210dc2011-09-15 06:49:18 +0000927
Sebastian Redlf862eb62012-02-22 17:37:52 +0000928 // If the number of elements isn't constant, we have to now check if there is
929 // anything left to initialize.
Richard Smith06a67e22014-06-03 06:58:52 +0000930 if (!ConstNum) {
931 llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr, EndPtr,
John McCall99210dc2011-09-15 06:49:18 +0000932 "array.isempty");
Richard Smith06a67e22014-06-03 06:58:52 +0000933 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
John McCall99210dc2011-09-15 06:49:18 +0000934 }
935
936 // Enter the loop.
Richard Smith06a67e22014-06-03 06:58:52 +0000937 EmitBlock(LoopBB);
John McCall99210dc2011-09-15 06:49:18 +0000938
939 // Set up the current-element phi.
Richard Smith06a67e22014-06-03 06:58:52 +0000940 llvm::PHINode *CurPtrPhi =
941 Builder.CreatePHI(CurPtr->getType(), 2, "array.cur");
942 CurPtrPhi->addIncoming(CurPtr, EntryBB);
943 CurPtr = CurPtrPhi;
John McCall99210dc2011-09-15 06:49:18 +0000944
Richard Smith06a67e22014-06-03 06:58:52 +0000945 // Store the new Cleanup position for irregular Cleanups.
946 if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
Chad Rosierf62290a2012-02-24 00:13:55 +0000947
Richard Smith06a67e22014-06-03 06:58:52 +0000948 // Enter a partial-destruction Cleanup if necessary.
949 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
950 pushRegularPartialArrayCleanup(BeginPtr, CurPtr, ElementType,
951 getDestroyer(DtorKind));
952 Cleanup = EHStack.stable_begin();
953 CleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +0000954 }
955
956 // Emit the initializer into this element.
Richard Smith06a67e22014-06-03 06:58:52 +0000957 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
John McCall99210dc2011-09-15 06:49:18 +0000958
Richard Smith06a67e22014-06-03 06:58:52 +0000959 // Leave the Cleanup if we entered one.
960 if (CleanupDominator) {
961 DeactivateCleanupBlock(Cleanup, CleanupDominator);
962 CleanupDominator->eraseFromParent();
John McCallf4beacd2011-11-10 10:43:54 +0000963 }
John McCall99210dc2011-09-15 06:49:18 +0000964
Faisal Vali57ae0562013-12-14 00:40:05 +0000965 // Advance to the next element by adjusting the pointer type as necessary.
Richard Smith06a67e22014-06-03 06:58:52 +0000966 llvm::Value *NextPtr =
967 Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.next");
968
John McCall99210dc2011-09-15 06:49:18 +0000969 // Check whether we've gotten to the end of the array and, if so,
970 // exit the loop.
Richard Smith06a67e22014-06-03 06:58:52 +0000971 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
972 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
973 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
John McCall99210dc2011-09-15 06:49:18 +0000974
Richard Smith06a67e22014-06-03 06:58:52 +0000975 EmitBlock(ContBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000976}
977
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000978static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
John McCall99210dc2011-09-15 06:49:18 +0000979 QualType ElementType,
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000980 llvm::Value *NewPtr,
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000981 llvm::Value *NumElements,
982 llvm::Value *AllocSizeWithoutCookie) {
Richard Smith06a67e22014-06-03 06:58:52 +0000983 if (E->isArray())
984 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements,
985 AllocSizeWithoutCookie);
986 else if (const Expr *Init = E->getInitializer())
987 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000988}
989
Richard Smith8d0dc312013-07-21 23:12:18 +0000990/// Emit a call to an operator new or operator delete function, as implicitly
991/// created by new-expressions and delete-expressions.
992static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
993 const FunctionDecl *Callee,
994 const FunctionProtoType *CalleeType,
995 const CallArgList &Args) {
996 llvm::Instruction *CallOrInvoke;
Richard Smith1235a8d2013-07-29 20:14:16 +0000997 llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
Richard Smith8d0dc312013-07-21 23:12:18 +0000998 RValue RV =
999 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(Args, CalleeType),
Richard Smith1235a8d2013-07-29 20:14:16 +00001000 CalleeAddr, ReturnValueSlot(), Args,
Richard Smith8d0dc312013-07-21 23:12:18 +00001001 Callee, &CallOrInvoke);
1002
1003 /// C++1y [expr.new]p10:
1004 /// [In a new-expression,] an implementation is allowed to omit a call
1005 /// to a replaceable global allocation function.
1006 ///
1007 /// We model such elidable calls with the 'builtin' attribute.
Rafael Espindola6956d582013-10-22 14:23:09 +00001008 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
Richard Smith1235a8d2013-07-29 20:14:16 +00001009 if (Callee->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola6956d582013-10-22 14:23:09 +00001010 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smith8d0dc312013-07-21 23:12:18 +00001011 // FIXME: Add addAttribute to CallSite.
1012 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1013 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1014 llvm::Attribute::Builtin);
1015 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1016 II->addAttribute(llvm::AttributeSet::FunctionIndex,
1017 llvm::Attribute::Builtin);
1018 else
1019 llvm_unreachable("unexpected kind of call instruction");
1020 }
1021
1022 return RV;
1023}
1024
John McCall824c2f52010-09-14 07:57:04 +00001025namespace {
1026 /// A cleanup to call the given 'operator delete' function upon
1027 /// abnormal exit from a new expression.
1028 class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1029 size_t NumPlacementArgs;
1030 const FunctionDecl *OperatorDelete;
1031 llvm::Value *Ptr;
1032 llvm::Value *AllocSize;
1033
1034 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1035
1036 public:
1037 static size_t getExtraSize(size_t NumPlacementArgs) {
1038 return NumPlacementArgs * sizeof(RValue);
1039 }
1040
1041 CallDeleteDuringNew(size_t NumPlacementArgs,
1042 const FunctionDecl *OperatorDelete,
1043 llvm::Value *Ptr,
1044 llvm::Value *AllocSize)
1045 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1046 Ptr(Ptr), AllocSize(AllocSize) {}
1047
1048 void setPlacementArg(unsigned I, RValue Arg) {
1049 assert(I < NumPlacementArgs && "index out of range");
1050 getPlacementArgs()[I] = Arg;
1051 }
1052
Craig Topper4f12f102014-03-12 06:41:41 +00001053 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall824c2f52010-09-14 07:57:04 +00001054 const FunctionProtoType *FPT
1055 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001056 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1057 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall824c2f52010-09-14 07:57:04 +00001058
1059 CallArgList DeleteArgs;
1060
1061 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001062 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001063 DeleteArgs.add(RValue::get(Ptr), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001064
1065 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001066 if (FPT->getNumParams() == NumPlacementArgs + 2)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001067 DeleteArgs.add(RValue::get(AllocSize), *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001068
1069 // Pass the rest of the arguments, which must match exactly.
1070 for (unsigned I = 0; I != NumPlacementArgs; ++I)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001071 DeleteArgs.add(getPlacementArgs()[I], *AI++);
John McCall824c2f52010-09-14 07:57:04 +00001072
1073 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001074 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall824c2f52010-09-14 07:57:04 +00001075 }
1076 };
John McCall7f9c92a2010-09-17 00:50:28 +00001077
1078 /// A cleanup to call the given 'operator delete' function upon
1079 /// abnormal exit from a new expression when the new expression is
1080 /// conditional.
1081 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
1082 size_t NumPlacementArgs;
1083 const FunctionDecl *OperatorDelete;
John McCallcb5f77f2011-01-28 10:53:53 +00001084 DominatingValue<RValue>::saved_type Ptr;
1085 DominatingValue<RValue>::saved_type AllocSize;
John McCall7f9c92a2010-09-17 00:50:28 +00001086
John McCallcb5f77f2011-01-28 10:53:53 +00001087 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1088 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
John McCall7f9c92a2010-09-17 00:50:28 +00001089 }
1090
1091 public:
1092 static size_t getExtraSize(size_t NumPlacementArgs) {
John McCallcb5f77f2011-01-28 10:53:53 +00001093 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
John McCall7f9c92a2010-09-17 00:50:28 +00001094 }
1095
1096 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1097 const FunctionDecl *OperatorDelete,
John McCallcb5f77f2011-01-28 10:53:53 +00001098 DominatingValue<RValue>::saved_type Ptr,
1099 DominatingValue<RValue>::saved_type AllocSize)
John McCall7f9c92a2010-09-17 00:50:28 +00001100 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1101 Ptr(Ptr), AllocSize(AllocSize) {}
1102
John McCallcb5f77f2011-01-28 10:53:53 +00001103 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
John McCall7f9c92a2010-09-17 00:50:28 +00001104 assert(I < NumPlacementArgs && "index out of range");
1105 getPlacementArgs()[I] = Arg;
1106 }
1107
Craig Topper4f12f102014-03-12 06:41:41 +00001108 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall7f9c92a2010-09-17 00:50:28 +00001109 const FunctionProtoType *FPT
1110 = OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001111 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1112 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
John McCall7f9c92a2010-09-17 00:50:28 +00001113
1114 CallArgList DeleteArgs;
1115
1116 // The first argument is always a void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00001117 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
Eli Friedman43dca6a2011-05-02 17:57:46 +00001118 DeleteArgs.add(Ptr.restore(CGF), *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001119
1120 // A member 'operator delete' can take an extra 'size_t' argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001121 if (FPT->getNumParams() == NumPlacementArgs + 2) {
John McCallcb5f77f2011-01-28 10:53:53 +00001122 RValue RV = AllocSize.restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001123 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001124 }
1125
1126 // Pass the rest of the arguments, which must match exactly.
1127 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
John McCallcb5f77f2011-01-28 10:53:53 +00001128 RValue RV = getPlacementArgs()[I].restore(CGF);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001129 DeleteArgs.add(RV, *AI++);
John McCall7f9c92a2010-09-17 00:50:28 +00001130 }
1131
1132 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001133 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7f9c92a2010-09-17 00:50:28 +00001134 }
1135 };
1136}
1137
1138/// Enter a cleanup to call 'operator delete' if the initializer in a
1139/// new-expression throws.
1140static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1141 const CXXNewExpr *E,
1142 llvm::Value *NewPtr,
1143 llvm::Value *AllocSize,
1144 const CallArgList &NewArgs) {
1145 // If we're not inside a conditional branch, then the cleanup will
1146 // dominate and we can do the easier (and more efficient) thing.
1147 if (!CGF.isInConditionalBranch()) {
1148 CallDeleteDuringNew *Cleanup = CGF.EHStack
1149 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1150 E->getNumPlacementArgs(),
1151 E->getOperatorDelete(),
1152 NewPtr, AllocSize);
1153 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001154 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
John McCall7f9c92a2010-09-17 00:50:28 +00001155
1156 return;
1157 }
1158
1159 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001160 DominatingValue<RValue>::saved_type SavedNewPtr =
1161 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1162 DominatingValue<RValue>::saved_type SavedAllocSize =
1163 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001164
1165 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
John McCallf4beacd2011-11-10 10:43:54 +00001166 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
John McCall7f9c92a2010-09-17 00:50:28 +00001167 E->getNumPlacementArgs(),
1168 E->getOperatorDelete(),
1169 SavedNewPtr,
1170 SavedAllocSize);
1171 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
John McCallcb5f77f2011-01-28 10:53:53 +00001172 Cleanup->setPlacementArg(I,
Eli Friedmanf4258eb2011-05-02 18:05:27 +00001173 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
John McCall7f9c92a2010-09-17 00:50:28 +00001174
John McCallf4beacd2011-11-10 10:43:54 +00001175 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001176}
1177
Anders Carlssoncc52f652009-09-22 22:53:17 +00001178llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001179 // The element type being allocated.
1180 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001181
John McCall75f94982011-03-07 03:12:35 +00001182 // 1. Build a call to the allocation function.
1183 FunctionDecl *allocator = E->getOperatorNew();
1184 const FunctionProtoType *allocatorType =
1185 allocator->getType()->castAs<FunctionProtoType>();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001186
John McCall75f94982011-03-07 03:12:35 +00001187 CallArgList allocatorArgs;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001188
1189 // The allocation size is the first argument.
John McCall75f94982011-03-07 03:12:35 +00001190 QualType sizeType = getContext().getSizeType();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001191
Sebastian Redlf862eb62012-02-22 17:37:52 +00001192 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1193 unsigned minElements = 0;
1194 if (E->isArray() && E->hasInitializer()) {
1195 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1196 minElements = ILE->getNumInits();
1197 }
1198
Craig Topper8a13c412014-05-21 05:09:00 +00001199 llvm::Value *numElements = nullptr;
1200 llvm::Value *allocSizeWithoutCookie = nullptr;
John McCall75f94982011-03-07 03:12:35 +00001201 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001202 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1203 allocSizeWithoutCookie);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001204
Eli Friedman43dca6a2011-05-02 17:57:46 +00001205 allocatorArgs.add(RValue::get(allocSize), sizeType);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001206
Anders Carlssoncc52f652009-09-22 22:53:17 +00001207 // We start at 1 here because the first argument (the allocation size)
1208 // has already been emitted.
Reid Kleckner739756c2013-12-04 19:23:12 +00001209 EmitCallArgs(allocatorArgs, allocatorType->isVariadic(),
Alp Toker9cacbab2014-01-20 20:26:09 +00001210 allocatorType->param_type_begin() + 1,
1211 allocatorType->param_type_end(), E->placement_arg_begin(),
Reid Kleckner739756c2013-12-04 19:23:12 +00001212 E->placement_arg_end());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001213
John McCall7ec4b432011-05-16 01:05:12 +00001214 // Emit the allocation call. If the allocator is a global placement
1215 // operator, just "inline" it directly.
1216 RValue RV;
1217 if (allocator->isReservedGlobalPlacementOperator()) {
1218 assert(allocatorArgs.size() == 2);
1219 RV = allocatorArgs[1].RV;
1220 // TODO: kill any unnecessary computations done for the size
1221 // argument.
1222 } else {
Richard Smith8d0dc312013-07-21 23:12:18 +00001223 RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
John McCall7ec4b432011-05-16 01:05:12 +00001224 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001225
John McCall75f94982011-03-07 03:12:35 +00001226 // Emit a null check on the allocation result if the allocation
1227 // function is allowed to return null (because it has a non-throwing
1228 // exception spec; for this part, we inline
1229 // CXXNewExpr::shouldNullCheckAllocation()) and we have an
1230 // interesting initializer.
Sebastian Redl31ad7542011-03-13 17:09:40 +00001231 bool nullCheck = allocatorType->isNothrow(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001232 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001233
Craig Topper8a13c412014-05-21 05:09:00 +00001234 llvm::BasicBlock *nullCheckBB = nullptr;
1235 llvm::BasicBlock *contBB = nullptr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001236
John McCall75f94982011-03-07 03:12:35 +00001237 llvm::Value *allocation = RV.getScalarVal();
Micah Villmowea2fea22012-10-25 15:39:14 +00001238 unsigned AS = allocation->getType()->getPointerAddressSpace();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001239
John McCallf7dcf322011-03-07 01:52:56 +00001240 // The null-check means that the initializer is conditionally
1241 // evaluated.
1242 ConditionalEvaluation conditional(*this);
1243
John McCall75f94982011-03-07 03:12:35 +00001244 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001245 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001246
1247 nullCheckBB = Builder.GetInsertBlock();
1248 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1249 contBB = createBasicBlock("new.cont");
1250
1251 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
1252 Builder.CreateCondBr(isNull, contBB, notNullBB);
1253 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001254 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001255
John McCall824c2f52010-09-14 07:57:04 +00001256 // If there's an operator delete, enter a cleanup to call it if an
1257 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001258 EHScopeStack::stable_iterator operatorDeleteCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001259 llvm::Instruction *cleanupDominator = nullptr;
John McCall7ec4b432011-05-16 01:05:12 +00001260 if (E->getOperatorDelete() &&
1261 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
John McCall75f94982011-03-07 03:12:35 +00001262 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1263 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001264 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001265 }
1266
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001267 assert((allocSize == allocSizeWithoutCookie) ==
1268 CalculateCookiePadding(*this, E).isZero());
1269 if (allocSize != allocSizeWithoutCookie) {
1270 assert(E->isArray());
1271 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1272 numElements,
1273 E, allocType);
1274 }
1275
Chris Lattner2192fe52011-07-18 04:24:23 +00001276 llvm::Type *elementPtrTy
John McCall75f94982011-03-07 03:12:35 +00001277 = ConvertTypeForMem(allocType)->getPointerTo(AS);
1278 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
John McCall824c2f52010-09-14 07:57:04 +00001279
John McCall99210dc2011-09-15 06:49:18 +00001280 EmitNewInitializer(*this, E, allocType, result, numElements,
1281 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001282 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001283 // NewPtr is a pointer to the base element type. If we're
1284 // allocating an array of arrays, we'll need to cast back to the
1285 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001286 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall75f94982011-03-07 03:12:35 +00001287 if (result->getType() != resultType)
1288 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001289 }
John McCall824c2f52010-09-14 07:57:04 +00001290
1291 // Deactivate the 'operator delete' cleanup if we finished
1292 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001293 if (operatorDeleteCleanup.isValid()) {
1294 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1295 cleanupDominator->eraseFromParent();
1296 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001297
John McCall75f94982011-03-07 03:12:35 +00001298 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001299 conditional.end(*this);
1300
John McCall75f94982011-03-07 03:12:35 +00001301 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1302 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001303
Jay Foad20c0f022011-03-30 11:28:58 +00001304 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
John McCall75f94982011-03-07 03:12:35 +00001305 PHI->addIncoming(result, notNullBB);
1306 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
1307 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001308
John McCall75f94982011-03-07 03:12:35 +00001309 result = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001310 }
John McCall8ed55a52010-09-02 09:58:18 +00001311
John McCall75f94982011-03-07 03:12:35 +00001312 return result;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001313}
1314
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001315void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1316 llvm::Value *Ptr,
1317 QualType DeleteTy) {
John McCall8ed55a52010-09-02 09:58:18 +00001318 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1319
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001320 const FunctionProtoType *DeleteFTy =
1321 DeleteFD->getType()->getAs<FunctionProtoType>();
1322
1323 CallArgList DeleteArgs;
1324
Anders Carlsson21122cf2009-12-13 20:04:38 +00001325 // Check if we need to pass the size to the delete operator.
Craig Topper8a13c412014-05-21 05:09:00 +00001326 llvm::Value *Size = nullptr;
Anders Carlsson21122cf2009-12-13 20:04:38 +00001327 QualType SizeTy;
Alp Toker9cacbab2014-01-20 20:26:09 +00001328 if (DeleteFTy->getNumParams() == 2) {
1329 SizeTy = DeleteFTy->getParamType(1);
Ken Dyck7df3cbe2010-01-26 19:59:28 +00001330 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1331 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1332 DeleteTypeSize.getQuantity());
Anders Carlsson21122cf2009-12-13 20:04:38 +00001333 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001334
1335 QualType ArgTy = DeleteFTy->getParamType(0);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001336 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001337 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001338
Anders Carlsson21122cf2009-12-13 20:04:38 +00001339 if (Size)
Eli Friedman43dca6a2011-05-02 17:57:46 +00001340 DeleteArgs.add(RValue::get(Size), SizeTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001341
1342 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001343 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001344}
1345
John McCall8ed55a52010-09-02 09:58:18 +00001346namespace {
1347 /// Calls the given 'operator delete' on a single object.
1348 struct CallObjectDelete : EHScopeStack::Cleanup {
1349 llvm::Value *Ptr;
1350 const FunctionDecl *OperatorDelete;
1351 QualType ElementType;
1352
1353 CallObjectDelete(llvm::Value *Ptr,
1354 const FunctionDecl *OperatorDelete,
1355 QualType ElementType)
1356 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1357
Craig Topper4f12f102014-03-12 06:41:41 +00001358 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001359 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1360 }
1361 };
1362}
1363
1364/// Emit the code for deleting a single object.
1365static void EmitObjectDelete(CodeGenFunction &CGF,
1366 const FunctionDecl *OperatorDelete,
1367 llvm::Value *Ptr,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001368 QualType ElementType,
1369 bool UseGlobalDelete) {
John McCall8ed55a52010-09-02 09:58:18 +00001370 // Find the destructor for the type, if applicable. If the
1371 // destructor is virtual, we'll just emit the vcall and return.
Craig Topper8a13c412014-05-21 05:09:00 +00001372 const CXXDestructorDecl *Dtor = nullptr;
John McCall8ed55a52010-09-02 09:58:18 +00001373 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1374 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001375 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001376 Dtor = RD->getDestructor();
1377
1378 if (Dtor->isVirtual()) {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001379 if (UseGlobalDelete) {
1380 // If we're supposed to call the global delete, make sure we do so
1381 // even if the destructor throws.
John McCall82fb8922012-09-25 10:10:39 +00001382
1383 // Derive the complete-object pointer, which is what we need
1384 // to pass to the deallocation function.
1385 llvm::Value *completePtr =
1386 CGF.CGM.getCXXABI().adjustToCompleteObject(CGF, Ptr, ElementType);
1387
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001388 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
John McCall82fb8922012-09-25 10:10:39 +00001389 completePtr, OperatorDelete,
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001390 ElementType);
1391 }
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001392
Richard Smithe30752c2012-10-09 19:52:38 +00001393 // FIXME: Provide a source location here.
Timur Iskhodzhanovd6197112013-02-15 14:45:22 +00001394 CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1395 CGF.CGM.getCXXABI().EmitVirtualDestructorCall(CGF, Dtor, DtorType,
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001396 SourceLocation(), Ptr);
John McCall8ed55a52010-09-02 09:58:18 +00001397
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001398 if (UseGlobalDelete) {
1399 CGF.PopCleanupBlock();
1400 }
1401
John McCall8ed55a52010-09-02 09:58:18 +00001402 return;
1403 }
1404 }
1405 }
1406
1407 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001408 // This doesn't have to a conditional cleanup because we're going
1409 // to pop it off in a second.
John McCall8ed55a52010-09-02 09:58:18 +00001410 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1411 Ptr, OperatorDelete, ElementType);
1412
1413 if (Dtor)
1414 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001415 /*ForVirtualBase=*/false,
1416 /*Delegating=*/false,
1417 Ptr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001418 else if (CGF.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001419 ElementType->isObjCLifetimeType()) {
1420 switch (ElementType.getObjCLifetime()) {
1421 case Qualifiers::OCL_None:
1422 case Qualifiers::OCL_ExplicitNone:
1423 case Qualifiers::OCL_Autoreleasing:
1424 break;
John McCall8ed55a52010-09-02 09:58:18 +00001425
John McCall31168b02011-06-15 23:02:42 +00001426 case Qualifiers::OCL_Strong: {
1427 // Load the pointer value.
1428 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
1429 ElementType.isVolatileQualified());
1430
John McCallcdda29c2013-03-13 03:10:54 +00001431 CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001432 break;
1433 }
1434
1435 case Qualifiers::OCL_Weak:
1436 CGF.EmitARCDestroyWeak(Ptr);
1437 break;
1438 }
1439 }
1440
John McCall8ed55a52010-09-02 09:58:18 +00001441 CGF.PopCleanupBlock();
1442}
1443
1444namespace {
1445 /// Calls the given 'operator delete' on an array of objects.
1446 struct CallArrayDelete : EHScopeStack::Cleanup {
1447 llvm::Value *Ptr;
1448 const FunctionDecl *OperatorDelete;
1449 llvm::Value *NumElements;
1450 QualType ElementType;
1451 CharUnits CookieSize;
1452
1453 CallArrayDelete(llvm::Value *Ptr,
1454 const FunctionDecl *OperatorDelete,
1455 llvm::Value *NumElements,
1456 QualType ElementType,
1457 CharUnits CookieSize)
1458 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1459 ElementType(ElementType), CookieSize(CookieSize) {}
1460
Craig Topper4f12f102014-03-12 06:41:41 +00001461 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001462 const FunctionProtoType *DeleteFTy =
1463 OperatorDelete->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00001464 assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
John McCall8ed55a52010-09-02 09:58:18 +00001465
1466 CallArgList Args;
1467
1468 // Pass the pointer as the first argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001469 QualType VoidPtrTy = DeleteFTy->getParamType(0);
John McCall8ed55a52010-09-02 09:58:18 +00001470 llvm::Value *DeletePtr
1471 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001472 Args.add(RValue::get(DeletePtr), VoidPtrTy);
John McCall8ed55a52010-09-02 09:58:18 +00001473
1474 // Pass the original requested size as the second argument.
Alp Toker9cacbab2014-01-20 20:26:09 +00001475 if (DeleteFTy->getNumParams() == 2) {
1476 QualType size_t = DeleteFTy->getParamType(1);
Chris Lattner2192fe52011-07-18 04:24:23 +00001477 llvm::IntegerType *SizeTy
John McCall8ed55a52010-09-02 09:58:18 +00001478 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1479
1480 CharUnits ElementTypeSize =
1481 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1482
1483 // The size of an element, multiplied by the number of elements.
1484 llvm::Value *Size
1485 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1486 Size = CGF.Builder.CreateMul(Size, NumElements);
1487
1488 // Plus the size of the cookie if applicable.
1489 if (!CookieSize.isZero()) {
1490 llvm::Value *CookieSizeV
1491 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1492 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1493 }
1494
Eli Friedman43dca6a2011-05-02 17:57:46 +00001495 Args.add(RValue::get(Size), size_t);
John McCall8ed55a52010-09-02 09:58:18 +00001496 }
1497
1498 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001499 EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
John McCall8ed55a52010-09-02 09:58:18 +00001500 }
1501 };
1502}
1503
1504/// Emit the code for deleting an array of objects.
1505static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001506 const CXXDeleteExpr *E,
John McCallca2c56f2011-07-13 01:41:37 +00001507 llvm::Value *deletedPtr,
1508 QualType elementType) {
Craig Topper8a13c412014-05-21 05:09:00 +00001509 llvm::Value *numElements = nullptr;
1510 llvm::Value *allocatedPtr = nullptr;
John McCallca2c56f2011-07-13 01:41:37 +00001511 CharUnits cookieSize;
1512 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1513 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001514
John McCallca2c56f2011-07-13 01:41:37 +00001515 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001516
1517 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001518 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001519 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001520 allocatedPtr, operatorDelete,
1521 numElements, elementType,
1522 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001523
John McCallca2c56f2011-07-13 01:41:37 +00001524 // Destroy the elements.
1525 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1526 assert(numElements && "no element count for a type with a destructor!");
1527
John McCallca2c56f2011-07-13 01:41:37 +00001528 llvm::Value *arrayEnd =
1529 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001530
1531 // Note that it is legal to allocate a zero-length array, and we
1532 // can never fold the check away because the length should always
1533 // come from a cookie.
John McCallca2c56f2011-07-13 01:41:37 +00001534 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1535 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001536 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001537 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001538 }
1539
John McCallca2c56f2011-07-13 01:41:37 +00001540 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001541 CGF.PopCleanupBlock();
1542}
1543
Anders Carlssoncc52f652009-09-22 22:53:17 +00001544void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001545 const Expr *Arg = E->getArgument();
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001546 llvm::Value *Ptr = EmitScalarExpr(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001547
1548 // Null check the pointer.
1549 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1550 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1551
Anders Carlsson98981b12011-04-11 00:30:07 +00001552 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001553
1554 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1555 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001556
John McCall8ed55a52010-09-02 09:58:18 +00001557 // We might be deleting a pointer to array. If so, GEP down to the
1558 // first non-array element.
1559 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1560 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1561 if (DeleteTy->isConstantArrayType()) {
1562 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001563 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001564
1565 GEP.push_back(Zero); // point at the outermost array
1566
1567 // For each layer of array type we're pointing at:
1568 while (const ConstantArrayType *Arr
1569 = getContext().getAsConstantArrayType(DeleteTy)) {
1570 // 1. Unpeel the array type.
1571 DeleteTy = Arr->getElementType();
1572
1573 // 2. GEP to the first element of the array.
1574 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001575 }
John McCall8ed55a52010-09-02 09:58:18 +00001576
Jay Foad040dd822011-07-22 08:16:57 +00001577 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001578 }
1579
Douglas Gregor04f36212010-09-02 17:38:50 +00001580 assert(ConvertTypeForMem(DeleteTy) ==
1581 cast<llvm::PointerType>(Ptr->getType())->getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001582
1583 if (E->isArrayForm()) {
John McCall284c48f2011-01-27 09:37:56 +00001584 EmitArrayDelete(*this, E, Ptr, DeleteTy);
John McCall8ed55a52010-09-02 09:58:18 +00001585 } else {
Douglas Gregor1c2e20d2011-07-13 00:54:47 +00001586 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
1587 E->isGlobalDelete());
John McCall8ed55a52010-09-02 09:58:18 +00001588 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001589
Anders Carlssoncc52f652009-09-22 22:53:17 +00001590 EmitBlock(DeleteEnd);
1591}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001592
Anders Carlsson0c633502011-04-11 14:13:40 +00001593static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) {
1594 // void __cxa_bad_typeid();
Chris Lattnerece04092012-02-07 00:39:47 +00001595 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson0c633502011-04-11 14:13:40 +00001596
1597 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid");
1598}
1599
1600static void EmitBadTypeidCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001601 llvm::Value *Fn = getBadTypeidFn(CGF);
John McCall882987f2013-02-28 19:01:20 +00001602 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlsson0c633502011-04-11 14:13:40 +00001603 CGF.Builder.CreateUnreachable();
1604}
1605
Anders Carlsson940f02d2011-04-18 00:57:03 +00001606static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF,
1607 const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001608 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001609 // Get the vtable pointer.
1610 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1611
1612 // C++ [expr.typeid]p2:
1613 // If the glvalue expression is obtained by applying the unary * operator to
1614 // a pointer and the pointer is a null pointer value, the typeid expression
1615 // throws the std::bad_typeid exception.
1616 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
1617 if (UO->getOpcode() == UO_Deref) {
1618 llvm::BasicBlock *BadTypeidBlock =
1619 CGF.createBasicBlock("typeid.bad_typeid");
1620 llvm::BasicBlock *EndBlock =
1621 CGF.createBasicBlock("typeid.end");
1622
1623 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1624 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1625
1626 CGF.EmitBlock(BadTypeidBlock);
1627 EmitBadTypeidCall(CGF);
1628 CGF.EmitBlock(EndBlock);
1629 }
1630 }
1631
1632 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr,
1633 StdTypeInfoPtrTy->getPointerTo());
1634
1635 // Load the type info.
1636 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL);
1637 return CGF.Builder.CreateLoad(Value);
1638}
1639
John McCalle4df6c82011-01-28 08:37:24 +00001640llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001641 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001642 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001643
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001644 if (E->isTypeOperand()) {
David Majnemer143c55e2013-09-27 07:04:31 +00001645 llvm::Constant *TypeInfo =
1646 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson940f02d2011-04-18 00:57:03 +00001647 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001648 }
Anders Carlsson0c633502011-04-11 14:13:40 +00001649
Anders Carlsson940f02d2011-04-18 00:57:03 +00001650 // C++ [expr.typeid]p2:
1651 // When typeid is applied to a glvalue expression whose type is a
1652 // polymorphic class type, the result refers to a std::type_info object
1653 // representing the type of the most derived object (that is, the dynamic
1654 // type) to which the glvalue refers.
Richard Smithef8bf432012-08-13 20:08:14 +00001655 if (E->isPotentiallyEvaluated())
1656 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1657 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001658
1659 QualType OperandTy = E->getExprOperand()->getType();
1660 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1661 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00001662}
Mike Stump65511702009-11-16 06:50:58 +00001663
Anders Carlsson882d7902011-04-11 00:46:40 +00001664static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) {
1665 // void *__dynamic_cast(const void *sub,
1666 // const abi::__class_type_info *src,
1667 // const abi::__class_type_info *dst,
1668 // std::ptrdiff_t src2dst_offset);
1669
Chris Lattnerece04092012-02-07 00:39:47 +00001670 llvm::Type *Int8PtrTy = CGF.Int8PtrTy;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001671 llvm::Type *PtrDiffTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001672 CGF.ConvertType(CGF.getContext().getPointerDiffType());
1673
Chris Lattnera5f58b02011-07-09 17:41:47 +00001674 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy };
Benjamin Kramerb5206332013-02-03 17:44:25 +00001675
1676 llvm::FunctionType *FTy = llvm::FunctionType::get(Int8PtrTy, Args, false);
1677
1678 // Mark the function as nounwind readonly.
1679 llvm::Attribute::AttrKind FuncAttrs[] = { llvm::Attribute::NoUnwind,
1680 llvm::Attribute::ReadOnly };
1681 llvm::AttributeSet Attrs = llvm::AttributeSet::get(
1682 CGF.getLLVMContext(), llvm::AttributeSet::FunctionIndex, FuncAttrs);
1683
1684 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast", Attrs);
Anders Carlsson882d7902011-04-11 00:46:40 +00001685}
1686
1687static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) {
1688 // void __cxa_bad_cast();
Chris Lattnerece04092012-02-07 00:39:47 +00001689 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false);
Anders Carlsson882d7902011-04-11 00:46:40 +00001690 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast");
1691}
1692
Anders Carlssonc1c99712011-04-11 01:45:29 +00001693static void EmitBadCastCall(CodeGenFunction &CGF) {
Anders Carlssonbbe277c2011-04-13 02:35:36 +00001694 llvm::Value *Fn = getBadCastFn(CGF);
John McCall882987f2013-02-28 19:01:20 +00001695 CGF.EmitRuntimeCallOrInvoke(Fn).setDoesNotReturn();
Anders Carlssonc1c99712011-04-11 01:45:29 +00001696 CGF.Builder.CreateUnreachable();
1697}
1698
Benjamin Kramerd9c84552013-02-03 19:59:25 +00001699/// \brief Compute the src2dst_offset hint as described in the
1700/// Itanium C++ ABI [2.9.7]
1701static CharUnits computeOffsetHint(ASTContext &Context,
1702 const CXXRecordDecl *Src,
1703 const CXXRecordDecl *Dst) {
1704 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1705 /*DetectVirtual=*/false);
1706
1707 // If Dst is not derived from Src we can skip the whole computation below and
1708 // return that Src is not a public base of Dst. Record all inheritance paths.
1709 if (!Dst->isDerivedFrom(Src, Paths))
1710 return CharUnits::fromQuantity(-2ULL);
1711
1712 unsigned NumPublicPaths = 0;
1713 CharUnits Offset;
1714
1715 // Now walk all possible inheritance paths.
1716 for (CXXBasePaths::paths_iterator I = Paths.begin(), E = Paths.end();
1717 I != E; ++I) {
1718 if (I->Access != AS_public) // Ignore non-public inheritance.
1719 continue;
1720
1721 ++NumPublicPaths;
1722
1723 for (CXXBasePath::iterator J = I->begin(), JE = I->end(); J != JE; ++J) {
1724 // If the path contains a virtual base class we can't give any hint.
1725 // -1: no hint.
1726 if (J->Base->isVirtual())
1727 return CharUnits::fromQuantity(-1ULL);
1728
1729 if (NumPublicPaths > 1) // Won't use offsets, skip computation.
1730 continue;
1731
1732 // Accumulate the base class offsets.
1733 const ASTRecordLayout &L = Context.getASTRecordLayout(J->Class);
1734 Offset += L.getBaseClassOffset(J->Base->getType()->getAsCXXRecordDecl());
1735 }
1736 }
1737
1738 // -2: Src is not a public base of Dst.
1739 if (NumPublicPaths == 0)
1740 return CharUnits::fromQuantity(-2ULL);
1741
1742 // -3: Src is a multiple public base type but never a virtual base type.
1743 if (NumPublicPaths > 1)
1744 return CharUnits::fromQuantity(-3ULL);
1745
1746 // Otherwise, the Src type is a unique public nonvirtual base type of Dst.
1747 // Return the offset of Src from the origin of Dst.
1748 return Offset;
1749}
1750
Anders Carlsson882d7902011-04-11 00:46:40 +00001751static llvm::Value *
1752EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value,
1753 QualType SrcTy, QualType DestTy,
1754 llvm::BasicBlock *CastEnd) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001755 llvm::Type *PtrDiffLTy =
Anders Carlsson882d7902011-04-11 00:46:40 +00001756 CGF.ConvertType(CGF.getContext().getPointerDiffType());
Chris Lattner2192fe52011-07-18 04:24:23 +00001757 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlsson882d7902011-04-11 00:46:40 +00001758
1759 if (const PointerType *PTy = DestTy->getAs<PointerType>()) {
1760 if (PTy->getPointeeType()->isVoidType()) {
1761 // C++ [expr.dynamic.cast]p7:
1762 // If T is "pointer to cv void," then the result is a pointer to the
1763 // most derived object pointed to by v.
1764
1765 // Get the vtable pointer.
1766 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo());
1767
1768 // Get the offset-to-top from the vtable.
1769 llvm::Value *OffsetToTop =
1770 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL);
1771 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top");
1772
1773 // Finally, add the offset to the pointer.
1774 Value = CGF.EmitCastToVoidPtr(Value);
1775 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop);
1776
1777 return CGF.Builder.CreateBitCast(Value, DestLTy);
1778 }
1779 }
1780
1781 QualType SrcRecordTy;
1782 QualType DestRecordTy;
1783
1784 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) {
1785 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1786 DestRecordTy = DestPTy->getPointeeType();
1787 } else {
1788 SrcRecordTy = SrcTy;
1789 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1790 }
1791
1792 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1793 assert(DestRecordTy->isRecordType() && "dest type must be a record type!");
1794
1795 llvm::Value *SrcRTTI =
1796 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
1797 llvm::Value *DestRTTI =
1798 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
1799
Benjamin Kramerd9c84552013-02-03 19:59:25 +00001800 // Compute the offset hint.
1801 const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
1802 const CXXRecordDecl *DestDecl = DestRecordTy->getAsCXXRecordDecl();
1803 llvm::Value *OffsetHint =
1804 llvm::ConstantInt::get(PtrDiffLTy,
1805 computeOffsetHint(CGF.getContext(), SrcDecl,
1806 DestDecl).getQuantity());
Anders Carlsson882d7902011-04-11 00:46:40 +00001807
1808 // Emit the call to __dynamic_cast.
1809 Value = CGF.EmitCastToVoidPtr(Value);
John McCall882987f2013-02-28 19:01:20 +00001810
1811 llvm::Value *args[] = { Value, SrcRTTI, DestRTTI, OffsetHint };
1812 Value = CGF.EmitNounwindRuntimeCall(getDynamicCastFn(CGF), args);
Anders Carlsson882d7902011-04-11 00:46:40 +00001813 Value = CGF.Builder.CreateBitCast(Value, DestLTy);
1814
1815 /// C++ [expr.dynamic.cast]p9:
1816 /// A failed cast to reference type throws std::bad_cast
1817 if (DestTy->isReferenceType()) {
1818 llvm::BasicBlock *BadCastBlock =
1819 CGF.createBasicBlock("dynamic_cast.bad_cast");
1820
1821 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value);
1822 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd);
1823
1824 CGF.EmitBlock(BadCastBlock);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001825 EmitBadCastCall(CGF);
Anders Carlsson882d7902011-04-11 00:46:40 +00001826 }
1827
1828 return Value;
1829}
1830
Anders Carlssonc1c99712011-04-11 01:45:29 +00001831static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1832 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001833 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00001834 if (DestTy->isPointerType())
1835 return llvm::Constant::getNullValue(DestLTy);
1836
1837 /// C++ [expr.dynamic.cast]p9:
1838 /// A failed cast to reference type throws std::bad_cast
1839 EmitBadCastCall(CGF);
1840
1841 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1842 return llvm::UndefValue::get(DestLTy);
1843}
1844
Anders Carlsson882d7902011-04-11 00:46:40 +00001845llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
Mike Stump65511702009-11-16 06:50:58 +00001846 const CXXDynamicCastExpr *DCE) {
Anders Carlsson3f4336c2009-12-17 07:09:17 +00001847 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00001848
Anders Carlssonc1c99712011-04-11 01:45:29 +00001849 if (DCE->isAlwaysNull())
1850 return EmitDynamicCastToNull(*this, DestTy);
1851
1852 QualType SrcTy = DCE->getSubExpr()->getType();
1853
Anders Carlsson882d7902011-04-11 00:46:40 +00001854 // C++ [expr.dynamic.cast]p4:
1855 // If the value of v is a null pointer value in the pointer case, the result
1856 // is the null pointer value of type T.
1857 bool ShouldNullCheckSrcValue = SrcTy->isPointerType();
Craig Topper8a13c412014-05-21 05:09:00 +00001858
1859 llvm::BasicBlock *CastNull = nullptr;
1860 llvm::BasicBlock *CastNotNull = nullptr;
Anders Carlsson882d7902011-04-11 00:46:40 +00001861 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00001862
Anders Carlsson882d7902011-04-11 00:46:40 +00001863 if (ShouldNullCheckSrcValue) {
1864 CastNull = createBasicBlock("dynamic_cast.null");
1865 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1866
1867 llvm::Value *IsNull = Builder.CreateIsNull(Value);
1868 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1869 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00001870 }
1871
Anders Carlsson882d7902011-04-11 00:46:40 +00001872 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd);
1873
1874 if (ShouldNullCheckSrcValue) {
1875 EmitBranch(CastEnd);
1876
1877 EmitBlock(CastNull);
1878 EmitBranch(CastEnd);
1879 }
1880
1881 EmitBlock(CastEnd);
1882
1883 if (ShouldNullCheckSrcValue) {
1884 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1885 PHI->addIncoming(Value, CastNotNull);
1886 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1887
1888 Value = PHI;
1889 }
1890
1891 return Value;
Mike Stump65511702009-11-16 06:50:58 +00001892}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001893
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001894void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00001895 RunCleanupsScope Scope(*this);
Eli Friedman7f1ff602012-04-16 03:54:45 +00001896 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
1897 Slot.getAlignment());
Eli Friedman8631f3e82012-02-09 03:47:20 +00001898
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001899 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1900 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1901 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00001902 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001903 // Emit initialization
Eli Friedman7f1ff602012-04-16 03:54:45 +00001904
David Blaikie40ed2972012-06-06 20:45:41 +00001905 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Eli Friedman5f1a04f2012-02-14 02:31:03 +00001906 ArrayRef<VarDecl *> ArrayIndexes;
1907 if (CurField->getType()->isArrayType())
1908 ArrayIndexes = E->getCaptureInitIndexVars(i);
David Blaikie40ed2972012-06-06 20:45:41 +00001909 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001910 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00001911}