blob: 88a5f35d2dce0678f4dbc5ca70dd19357730c837 [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"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000020#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000021#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000022#include "llvm/IR/Intrinsics.h"
Anders Carlssonbbe277c2011-04-13 02:35:36 +000023
Anders Carlssoncc52f652009-09-22 22:53:17 +000024using namespace clang;
25using namespace CodeGen;
26
Alexey Samsonovefa956c2016-03-10 00:20:33 +000027static RequiredArgs
28commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
29 llvm::Value *This, llvm::Value *ImplicitParam,
30 QualType ImplicitParamTy, const CallExpr *CE,
Richard Smith762672a2016-09-28 19:09:10 +000031 CallArgList &Args, CallArgList *RtlArgs) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000032 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
33 isa<CXXOperatorCallExpr>(CE));
Anders Carlsson27da15b2010-01-01 20:29:01 +000034 assert(MD->isInstance() &&
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000035 "Trying to emit a member or operator call expr on a static method!");
Reid Kleckner034e7272016-09-07 15:15:51 +000036 ASTContext &C = CGF.getContext();
Anders Carlsson27da15b2010-01-01 20:29:01 +000037
Richard Smith69d0d262012-08-24 00:54:33 +000038 // C++11 [class.mfct.non-static]p2:
39 // If a non-static member function of a class X is called for an object that
40 // is not of type X, or of a type derived from X, the behavior is undefined.
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000041 SourceLocation CallLoc;
42 if (CE)
43 CallLoc = CE->getExprLoc();
Reid Kleckner034e7272016-09-07 15:15:51 +000044 CGF.EmitTypeCheck(isa<CXXConstructorDecl>(MD)
45 ? CodeGenFunction::TCK_ConstructorCall
46 : CodeGenFunction::TCK_MemberCall,
47 CallLoc, This, C.getRecordType(MD->getParent()));
Anders Carlsson27da15b2010-01-01 20:29:01 +000048
49 // Push the this ptr.
Reid Kleckner034e7272016-09-07 15:15:51 +000050 const CXXRecordDecl *RD =
51 CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
52 Args.add(RValue::get(This),
53 RD ? C.getPointerType(C.getTypeDeclType(RD)) : C.VoidPtrTy);
Anders Carlsson27da15b2010-01-01 20:29:01 +000054
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +000055 // If there is an implicit parameter (e.g. VTT), emit it.
56 if (ImplicitParam) {
57 Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
Anders Carlssone36a6b32010-01-02 01:01:18 +000058 }
John McCalla729c622012-02-17 03:33:10 +000059
60 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
George Burgess IV419996c2016-06-16 23:06:04 +000061 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size(), MD);
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000062
John McCalla729c622012-02-17 03:33:10 +000063 // And the rest of the call args.
Richard Smith762672a2016-09-28 19:09:10 +000064 if (RtlArgs) {
65 // Special case: if the caller emitted the arguments right-to-left already
66 // (prior to emitting the *this argument), we're done. This happens for
67 // assignment operators.
68 Args.addFrom(*RtlArgs);
69 } else if (CE) {
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000070 // Special case: skip first argument of CXXOperatorCall (it is "this").
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000071 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
David Blaikief05779e2015-07-21 18:37:18 +000072 CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
David Majnemer0c0b6d92014-10-31 20:09:12 +000073 CE->getDirectCallee());
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000074 } else {
Alexey Samsonov8e1162c2014-09-08 17:22:45 +000075 assert(
76 FPT->getNumParams() == 0 &&
77 "No CallExpr specified for function with non-zero number of arguments");
Alexey Samsonova5bf76b2014-08-25 20:17:35 +000078 }
David Majnemer0c0b6d92014-10-31 20:09:12 +000079 return required;
80}
Anders Carlsson27da15b2010-01-01 20:29:01 +000081
David Majnemer0c0b6d92014-10-31 20:09:12 +000082RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
John McCallb92ab1a2016-10-26 23:46:34 +000083 const CXXMethodDecl *MD, const CGCallee &Callee,
84 ReturnValueSlot ReturnValue,
David Majnemer0c0b6d92014-10-31 20:09:12 +000085 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
Richard Smith762672a2016-09-28 19:09:10 +000086 const CallExpr *CE, CallArgList *RtlArgs) {
David Majnemer0c0b6d92014-10-31 20:09:12 +000087 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
88 CallArgList Args;
89 RequiredArgs required = commonEmitCXXMemberOrOperatorCall(
Richard Smith762672a2016-09-28 19:09:10 +000090 *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
John McCallb92ab1a2016-10-26 23:46:34 +000091 auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required);
92 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +000093}
94
Alexey Samsonovae81bbb2016-03-10 00:20:37 +000095RValue CodeGenFunction::EmitCXXDestructorCall(
John McCallb92ab1a2016-10-26 23:46:34 +000096 const CXXDestructorDecl *DD, const CGCallee &Callee, llvm::Value *This,
Alexey Samsonovae81bbb2016-03-10 00:20:37 +000097 llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE,
98 StructorType Type) {
David Majnemer0c0b6d92014-10-31 20:09:12 +000099 CallArgList Args;
Alexey Samsonovae81bbb2016-03-10 00:20:37 +0000100 commonEmitCXXMemberOrOperatorCall(*this, DD, This, ImplicitParam,
Richard Smith762672a2016-09-28 19:09:10 +0000101 ImplicitParamTy, CE, Args, nullptr);
Alexey Samsonovae81bbb2016-03-10 00:20:37 +0000102 return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(DD, Type),
John McCallb92ab1a2016-10-26 23:46:34 +0000103 Callee, ReturnValueSlot(), Args);
104}
105
106RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
107 const CXXPseudoDestructorExpr *E) {
108 QualType DestroyedType = E->getDestroyedType();
109 if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
110 // Automatic Reference Counting:
111 // If the pseudo-expression names a retainable object with weak or
112 // strong lifetime, the object shall be released.
113 Expr *BaseExpr = E->getBase();
114 Address BaseValue = Address::invalid();
115 Qualifiers BaseQuals;
116
117 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
118 if (E->isArrow()) {
119 BaseValue = EmitPointerWithAlignment(BaseExpr);
120 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
121 BaseQuals = PTy->getPointeeType().getQualifiers();
122 } else {
123 LValue BaseLV = EmitLValue(BaseExpr);
124 BaseValue = BaseLV.getAddress();
125 QualType BaseTy = BaseExpr->getType();
126 BaseQuals = BaseTy.getQualifiers();
127 }
128
129 switch (DestroyedType.getObjCLifetime()) {
130 case Qualifiers::OCL_None:
131 case Qualifiers::OCL_ExplicitNone:
132 case Qualifiers::OCL_Autoreleasing:
133 break;
134
135 case Qualifiers::OCL_Strong:
136 EmitARCRelease(Builder.CreateLoad(BaseValue,
137 DestroyedType.isVolatileQualified()),
138 ARCPreciseLifetime);
139 break;
140
141 case Qualifiers::OCL_Weak:
142 EmitARCDestroyWeak(BaseValue);
143 break;
144 }
145 } else {
146 // C++ [expr.pseudo]p1:
147 // The result shall only be used as the operand for the function call
148 // operator (), and the result of such a call has type void. The only
149 // effect is the evaluation of the postfix-expression before the dot or
150 // arrow.
151 EmitIgnoredExpr(E->getBase());
152 }
153
154 return RValue::get(nullptr);
David Majnemer0c0b6d92014-10-31 20:09:12 +0000155}
156
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000157static CXXRecordDecl *getCXXRecord(const Expr *E) {
158 QualType T = E->getType();
159 if (const PointerType *PTy = T->getAs<PointerType>())
160 T = PTy->getPointeeType();
161 const RecordType *Ty = T->castAs<RecordType>();
162 return cast<CXXRecordDecl>(Ty->getDecl());
163}
164
Francois Pichet64225792011-01-18 05:04:39 +0000165// Note: This function also emit constructor calls to support a MSVC
166// extensions allowing explicit constructor function call.
Anders Carlsson27da15b2010-01-01 20:29:01 +0000167RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
168 ReturnValueSlot ReturnValue) {
John McCall2d2e8702011-04-11 07:02:50 +0000169 const Expr *callee = CE->getCallee()->IgnoreParens();
170
171 if (isa<BinaryOperator>(callee))
Anders Carlsson27da15b2010-01-01 20:29:01 +0000172 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
John McCall2d2e8702011-04-11 07:02:50 +0000173
174 const MemberExpr *ME = cast<MemberExpr>(callee);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000175 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
176
177 if (MD->isStatic()) {
178 // The method is static, emit it as we would a regular call.
John McCallb92ab1a2016-10-26 23:46:34 +0000179 CGCallee callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD), MD);
180 return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
Alexey Samsonov70b9c012014-08-21 20:26:47 +0000181 ReturnValue);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000182 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000183
Nico Weberaad4af62014-12-03 01:21:41 +0000184 bool HasQualifier = ME->hasQualifier();
185 NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
186 bool IsArrow = ME->isArrow();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000187 const Expr *Base = ME->getBase();
Nico Weberaad4af62014-12-03 01:21:41 +0000188
189 return EmitCXXMemberOrOperatorMemberCallExpr(
190 CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
191}
192
193RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
194 const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
195 bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
196 const Expr *Base) {
197 assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
198
199 // Compute the object pointer.
200 bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000201
Craig Topper8a13c412014-05-21 05:09:00 +0000202 const CXXMethodDecl *DevirtualizedMethod = nullptr;
Benjamin Kramer7463ed72013-08-25 22:46:27 +0000203 if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000204 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
205 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
206 assert(DevirtualizedMethod);
207 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
208 const Expr *Inner = Base->ignoreParenBaseCasts();
Alexey Bataev5bd68792014-09-29 10:32:21 +0000209 if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
210 MD->getReturnType().getCanonicalType())
211 // If the return types are not the same, this might be a case where more
212 // code needs to run to compensate for it. For example, the derived
213 // method might return a type that inherits form from the return
214 // type of MD and has a prefix.
215 // For now we just avoid devirtualizing these covariant cases.
216 DevirtualizedMethod = nullptr;
217 else if (getCXXRecord(Inner) == DevirtualizedClass)
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000218 // If the class of the Inner expression is where the dynamic method
219 // is defined, build the this pointer from it.
220 Base = Inner;
221 else if (getCXXRecord(Base) != DevirtualizedClass) {
222 // If the method is defined in a class that is not the best dynamic
223 // one or the one of the full expression, we would have to build
224 // a derived-to-base cast to compute the correct this pointer, but
225 // we don't have support for that yet, so do a virtual call.
Craig Topper8a13c412014-05-21 05:09:00 +0000226 DevirtualizedMethod = nullptr;
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000227 }
228 }
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000229
Richard Smith762672a2016-09-28 19:09:10 +0000230 // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
231 // operator before the LHS.
232 CallArgList RtlArgStorage;
233 CallArgList *RtlArgs = nullptr;
234 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
235 if (OCE->isAssignmentOp()) {
236 RtlArgs = &RtlArgStorage;
237 EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
238 drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
Richard Smitha560ccf2016-09-29 21:30:12 +0000239 /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
Richard Smith762672a2016-09-28 19:09:10 +0000240 }
241 }
242
John McCall7f416cc2015-09-08 08:05:57 +0000243 Address This = Address::invalid();
Nico Weberaad4af62014-12-03 01:21:41 +0000244 if (IsArrow)
John McCall7f416cc2015-09-08 08:05:57 +0000245 This = EmitPointerWithAlignment(Base);
John McCalle26a8722010-12-04 08:14:53 +0000246 else
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000247 This = EmitLValue(Base).getAddress();
Rafael Espindolaecbe2e92012-06-28 01:56:38 +0000248
Anders Carlsson27da15b2010-01-01 20:29:01 +0000249
Richard Smith419bd092015-04-29 19:26:57 +0000250 if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
Craig Topper8a13c412014-05-21 05:09:00 +0000251 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
Francois Pichet64225792011-01-18 05:04:39 +0000252 if (isa<CXXConstructorDecl>(MD) &&
253 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
Craig Topper8a13c412014-05-21 05:09:00 +0000254 return RValue::get(nullptr);
John McCall0d635f52010-09-03 01:26:39 +0000255
Nico Weberaad4af62014-12-03 01:21:41 +0000256 if (!MD->getParent()->mayInsertExtraPadding()) {
257 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
258 // We don't like to generate the trivial copy/move assignment operator
259 // when it isn't necessary; just produce the proper effect here.
Richard Smith762672a2016-09-28 19:09:10 +0000260 LValue RHS = isa<CXXOperatorCallExpr>(CE)
261 ? MakeNaturalAlignAddrLValue(
262 (*RtlArgs)[0].RV.getScalarVal(),
263 (*(CE->arg_begin() + 1))->getType())
264 : EmitLValue(*CE->arg_begin());
265 EmitAggregateAssign(This, RHS.getAddress(), CE->getType());
John McCall7f416cc2015-09-08 08:05:57 +0000266 return RValue::get(This.getPointer());
Nico Weberaad4af62014-12-03 01:21:41 +0000267 }
Alexey Samsonov525bf652014-08-25 21:58:56 +0000268
Nico Weberaad4af62014-12-03 01:21:41 +0000269 if (isa<CXXConstructorDecl>(MD) &&
270 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
271 // Trivial move and copy ctor are the same.
272 assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
John McCall7f416cc2015-09-08 08:05:57 +0000273 Address RHS = EmitLValue(*CE->arg_begin()).getAddress();
Benjamin Kramerf48ee442015-07-18 14:35:53 +0000274 EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType());
John McCall7f416cc2015-09-08 08:05:57 +0000275 return RValue::get(This.getPointer());
Nico Weberaad4af62014-12-03 01:21:41 +0000276 }
277 llvm_unreachable("unknown trivial member function");
Francois Pichet64225792011-01-18 05:04:39 +0000278 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000279 }
280
John McCall0d635f52010-09-03 01:26:39 +0000281 // Compute the function type we're calling.
Nico Weber3abfe952014-12-02 20:41:18 +0000282 const CXXMethodDecl *CalleeDecl =
283 DevirtualizedMethod ? DevirtualizedMethod : MD;
Craig Topper8a13c412014-05-21 05:09:00 +0000284 const CGFunctionInfo *FInfo = nullptr;
Nico Weber3abfe952014-12-02 20:41:18 +0000285 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000286 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
287 Dtor, StructorType::Complete);
Nico Weber3abfe952014-12-02 20:41:18 +0000288 else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000289 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
290 Ctor, StructorType::Complete);
Francois Pichet64225792011-01-18 05:04:39 +0000291 else
Eli Friedmanade60972012-10-25 00:12:49 +0000292 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
John McCall0d635f52010-09-03 01:26:39 +0000293
Reid Klecknere7de47e2013-07-22 13:51:44 +0000294 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
John McCall0d635f52010-09-03 01:26:39 +0000295
Vedant Kumar018f2662016-10-19 20:21:16 +0000296 // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
297 // 'CalleeDecl' instead.
298
Anders Carlsson27da15b2010-01-01 20:29:01 +0000299 // C++ [class.virtual]p12:
300 // Explicit qualification with the scope operator (5.1) suppresses the
301 // virtual call mechanism.
302 //
303 // We also don't emit a virtual call if the base expression has a record type
304 // because then we know what the type is.
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000305 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
John McCallb92ab1a2016-10-26 23:46:34 +0000306
John McCall0d635f52010-09-03 01:26:39 +0000307 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000308 assert(CE->arg_begin() == CE->arg_end() &&
309 "Destructor shouldn't have explicit parameters");
310 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
John McCall0d635f52010-09-03 01:26:39 +0000311 if (UseVirtualCall) {
Nico Weberaad4af62014-12-03 01:21:41 +0000312 CGM.getCXXABI().EmitVirtualDestructorCall(
313 *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
Anders Carlsson27da15b2010-01-01 20:29:01 +0000314 } else {
John McCallb92ab1a2016-10-26 23:46:34 +0000315 CGCallee Callee;
Nico Weberaad4af62014-12-03 01:21:41 +0000316 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
317 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000318 else if (!DevirtualizedMethod)
John McCallb92ab1a2016-10-26 23:46:34 +0000319 Callee = CGCallee::forDirect(
320 CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty),
321 Dtor);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000322 else {
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000323 const CXXDestructorDecl *DDtor =
324 cast<CXXDestructorDecl>(DevirtualizedMethod);
John McCallb92ab1a2016-10-26 23:46:34 +0000325 Callee = CGCallee::forDirect(
326 CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty),
327 DDtor);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000328 }
Vedant Kumar018f2662016-10-19 20:21:16 +0000329 EmitCXXMemberOrOperatorCall(
330 CalleeDecl, Callee, ReturnValue, This.getPointer(),
331 /*ImplicitParam=*/nullptr, QualType(), CE, nullptr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000332 }
Craig Topper8a13c412014-05-21 05:09:00 +0000333 return RValue::get(nullptr);
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000334 }
335
John McCallb92ab1a2016-10-26 23:46:34 +0000336 CGCallee Callee;
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000337 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
John McCallb92ab1a2016-10-26 23:46:34 +0000338 Callee = CGCallee::forDirect(
339 CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty),
340 Ctor);
John McCall0d635f52010-09-03 01:26:39 +0000341 } else if (UseVirtualCall) {
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000342 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty,
343 CE->getLocStart());
Anders Carlsson27da15b2010-01-01 20:29:01 +0000344 } else {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +0000345 if (SanOpts.has(SanitizerKind::CFINVCall) &&
346 MD->getParent()->isDynamicClass()) {
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000347 llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy, MD->getParent());
Peter Collingbournefb532b92016-02-24 20:46:36 +0000348 EmitVTablePtrCheckForCall(MD->getParent(), VTable, CFITCK_NVCall,
349 CE->getLocStart());
Peter Collingbourne1a7488a2015-04-02 00:23:30 +0000350 }
351
Nico Weberaad4af62014-12-03 01:21:41 +0000352 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
353 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
Rafael Espindola3b33c4e2012-06-28 14:28:57 +0000354 else if (!DevirtualizedMethod)
John McCallb92ab1a2016-10-26 23:46:34 +0000355 Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), MD);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000356 else {
John McCallb92ab1a2016-10-26 23:46:34 +0000357 Callee = CGCallee::forDirect(
358 CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
359 DevirtualizedMethod);
Rafael Espindola49e860b2012-06-26 17:45:31 +0000360 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000361 }
362
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000363 if (MD->isVirtual()) {
364 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
Reid Kleckner4b60f302016-05-03 18:44:29 +0000365 *this, CalleeDecl, This, UseVirtualCall);
Timur Iskhodzhanovf1749422014-03-14 17:43:37 +0000366 }
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000367
Vedant Kumar018f2662016-10-19 20:21:16 +0000368 return EmitCXXMemberOrOperatorCall(
369 CalleeDecl, Callee, ReturnValue, This.getPointer(),
370 /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000371}
372
373RValue
374CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
375 ReturnValueSlot ReturnValue) {
376 const BinaryOperator *BO =
377 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
378 const Expr *BaseExpr = BO->getLHS();
379 const Expr *MemFnExpr = BO->getRHS();
380
381 const MemberPointerType *MPT =
John McCall0009fcc2011-04-26 20:42:42 +0000382 MemFnExpr->getType()->castAs<MemberPointerType>();
John McCall475999d2010-08-22 00:05:51 +0000383
Anders Carlsson27da15b2010-01-01 20:29:01 +0000384 const FunctionProtoType *FPT =
John McCall0009fcc2011-04-26 20:42:42 +0000385 MPT->getPointeeType()->castAs<FunctionProtoType>();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000386 const CXXRecordDecl *RD =
387 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
388
Anders Carlsson27da15b2010-01-01 20:29:01 +0000389 // Emit the 'this' pointer.
John McCall7f416cc2015-09-08 08:05:57 +0000390 Address This = Address::invalid();
John McCalle3027922010-08-25 11:45:40 +0000391 if (BO->getOpcode() == BO_PtrMemI)
John McCall7f416cc2015-09-08 08:05:57 +0000392 This = EmitPointerWithAlignment(BaseExpr);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000393 else
394 This = EmitLValue(BaseExpr).getAddress();
Anders Carlsson27da15b2010-01-01 20:29:01 +0000395
John McCall7f416cc2015-09-08 08:05:57 +0000396 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
Richard Smithe30752c2012-10-09 19:52:38 +0000397 QualType(MPT->getClass(), 0));
Richard Smith69d0d262012-08-24 00:54:33 +0000398
Richard Smithbde62d72016-09-26 23:56:57 +0000399 // Get the member function pointer.
400 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
401
John McCall475999d2010-08-22 00:05:51 +0000402 // Ask the ABI to load the callee. Note that This is modified.
John McCall7f416cc2015-09-08 08:05:57 +0000403 llvm::Value *ThisPtrForCall = nullptr;
John McCallb92ab1a2016-10-26 23:46:34 +0000404 CGCallee Callee =
John McCall7f416cc2015-09-08 08:05:57 +0000405 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
406 ThisPtrForCall, MemFnPtr, MPT);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000407
Anders Carlsson27da15b2010-01-01 20:29:01 +0000408 CallArgList Args;
409
410 QualType ThisType =
411 getContext().getPointerType(getContext().getTagDeclType(RD));
412
413 // Push the this ptr.
John McCall7f416cc2015-09-08 08:05:57 +0000414 Args.add(RValue::get(ThisPtrForCall), ThisType);
John McCall8dda7b22012-07-07 06:41:13 +0000415
George Burgess IV419996c2016-06-16 23:06:04 +0000416 RequiredArgs required =
417 RequiredArgs::forPrototypePlus(FPT, 1, /*FD=*/nullptr);
418
Anders Carlsson27da15b2010-01-01 20:29:01 +0000419 // And the rest of the call args
George Burgess IV419996c2016-06-16 23:06:04 +0000420 EmitCallArgs(Args, FPT, E->arguments());
Nick Lewycky5fa40c32013-10-01 21:51:38 +0000421 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
422 Callee, ReturnValue, Args);
Anders Carlsson27da15b2010-01-01 20:29:01 +0000423}
424
425RValue
426CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
427 const CXXMethodDecl *MD,
428 ReturnValueSlot ReturnValue) {
429 assert(MD->isInstance() &&
430 "Trying to emit a member call expr on a static method!");
Nico Weberaad4af62014-12-03 01:21:41 +0000431 return EmitCXXMemberOrOperatorMemberCallExpr(
432 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
433 /*IsArrow=*/false, E->getArg(0));
Anders Carlsson27da15b2010-01-01 20:29:01 +0000434}
435
Peter Collingbournefe883422011-10-06 18:29:37 +0000436RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
437 ReturnValueSlot ReturnValue) {
438 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
439}
440
Eli Friedmanfde961d2011-10-14 02:27:24 +0000441static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +0000442 Address DestPtr,
Eli Friedmanfde961d2011-10-14 02:27:24 +0000443 const CXXRecordDecl *Base) {
444 if (Base->isEmpty())
445 return;
446
John McCall7f416cc2015-09-08 08:05:57 +0000447 DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
Eli Friedmanfde961d2011-10-14 02:27:24 +0000448
449 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
David Majnemer8671c6e2015-11-02 09:01:44 +0000450 CharUnits NVSize = Layout.getNonVirtualSize();
451
452 // We cannot simply zero-initialize the entire base sub-object if vbptrs are
453 // present, they are initialized by the most derived class before calling the
454 // constructor.
455 SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
456 Stores.emplace_back(CharUnits::Zero(), NVSize);
457
458 // Each store is split by the existence of a vbptr.
459 CharUnits VBPtrWidth = CGF.getPointerSize();
460 std::vector<CharUnits> VBPtrOffsets =
461 CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
462 for (CharUnits VBPtrOffset : VBPtrOffsets) {
David Majnemer7f980d82016-05-12 03:51:52 +0000463 // Stop before we hit any virtual base pointers located in virtual bases.
464 if (VBPtrOffset >= NVSize)
465 break;
David Majnemer8671c6e2015-11-02 09:01:44 +0000466 std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
467 CharUnits LastStoreOffset = LastStore.first;
468 CharUnits LastStoreSize = LastStore.second;
469
470 CharUnits SplitBeforeOffset = LastStoreOffset;
471 CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
472 assert(!SplitBeforeSize.isNegative() && "negative store size!");
473 if (!SplitBeforeSize.isZero())
474 Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
475
476 CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
477 CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
478 assert(!SplitAfterSize.isNegative() && "negative store size!");
479 if (!SplitAfterSize.isZero())
480 Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
481 }
Eli Friedmanfde961d2011-10-14 02:27:24 +0000482
483 // If the type contains a pointer to data member we can't memset it to zero.
484 // Instead, create a null constant and copy it to the destination.
485 // TODO: there are other patterns besides zero that we can usefully memset,
486 // like -1, which happens to be the pattern used by member-pointers.
487 // TODO: isZeroInitializable can be over-conservative in the case where a
488 // virtual base contains a member pointer.
David Majnemer8671c6e2015-11-02 09:01:44 +0000489 llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
490 if (!NullConstantForBase->isNullValue()) {
491 llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
492 CGF.CGM.getModule(), NullConstantForBase->getType(),
493 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
494 NullConstantForBase, Twine());
John McCall7f416cc2015-09-08 08:05:57 +0000495
496 CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
497 DestPtr.getAlignment());
Eli Friedmanfde961d2011-10-14 02:27:24 +0000498 NullVariable->setAlignment(Align.getQuantity());
John McCall7f416cc2015-09-08 08:05:57 +0000499
500 Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
Eli Friedmanfde961d2011-10-14 02:27:24 +0000501
502 // Get and call the appropriate llvm.memcpy overload.
David Majnemer8671c6e2015-11-02 09:01:44 +0000503 for (std::pair<CharUnits, CharUnits> Store : Stores) {
504 CharUnits StoreOffset = Store.first;
505 CharUnits StoreSize = Store.second;
506 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
507 CGF.Builder.CreateMemCpy(
508 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
509 CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
510 StoreSizeVal);
511 }
512
Eli Friedmanfde961d2011-10-14 02:27:24 +0000513 // Otherwise, just memset the whole thing to zero. This is legal
514 // because in LLVM, all default initializers (other than the ones we just
515 // handled above) are guaranteed to have a bit pattern of all zeros.
David Majnemer8671c6e2015-11-02 09:01:44 +0000516 } else {
517 for (std::pair<CharUnits, CharUnits> Store : Stores) {
518 CharUnits StoreOffset = Store.first;
519 CharUnits StoreSize = Store.second;
520 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
521 CGF.Builder.CreateMemSet(
522 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
523 CGF.Builder.getInt8(0), StoreSizeVal);
524 }
525 }
Eli Friedmanfde961d2011-10-14 02:27:24 +0000526}
527
Anders Carlsson27da15b2010-01-01 20:29:01 +0000528void
John McCall7a626f62010-09-15 10:14:12 +0000529CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
530 AggValueSlot Dest) {
531 assert(!Dest.isIgnored() && "Must have a destination!");
Anders Carlsson27da15b2010-01-01 20:29:01 +0000532 const CXXConstructorDecl *CD = E->getConstructor();
Douglas Gregor630c76e2010-08-22 16:15:35 +0000533
534 // If we require zero initialization before (or instead of) calling the
535 // constructor, as can be the case with a non-user-provided default
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000536 // constructor, emit the zero initialization now, unless destination is
537 // already zeroed.
Eli Friedmanfde961d2011-10-14 02:27:24 +0000538 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
539 switch (E->getConstructionKind()) {
540 case CXXConstructExpr::CK_Delegating:
Eli Friedmanfde961d2011-10-14 02:27:24 +0000541 case CXXConstructExpr::CK_Complete:
John McCall7f416cc2015-09-08 08:05:57 +0000542 EmitNullInitialization(Dest.getAddress(), E->getType());
Eli Friedmanfde961d2011-10-14 02:27:24 +0000543 break;
544 case CXXConstructExpr::CK_VirtualBase:
545 case CXXConstructExpr::CK_NonVirtualBase:
John McCall7f416cc2015-09-08 08:05:57 +0000546 EmitNullBaseClassInitialization(*this, Dest.getAddress(),
547 CD->getParent());
Eli Friedmanfde961d2011-10-14 02:27:24 +0000548 break;
549 }
550 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000551
552 // If this is a call to a trivial default constructor, do nothing.
553 if (CD->isTrivial() && CD->isDefaultConstructor())
554 return;
555
John McCall8ea46b62010-09-18 00:58:34 +0000556 // Elide the constructor if we're constructing from a temporary.
557 // The temporary check is required because Sema sets this on NRVO
558 // returns.
Richard Smith9c6890a2012-11-01 22:30:59 +0000559 if (getLangOpts().ElideConstructors && E->isElidable()) {
John McCall8ea46b62010-09-18 00:58:34 +0000560 assert(getContext().hasSameUnqualifiedType(E->getType(),
561 E->getArg(0)->getType()));
John McCall7a626f62010-09-15 10:14:12 +0000562 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
563 EmitAggExpr(E->getArg(0), Dest);
Douglas Gregor222cf0e2010-05-15 00:13:29 +0000564 return;
565 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000566 }
Douglas Gregor630c76e2010-08-22 16:15:35 +0000567
Alexey Bataeve7545b32016-04-29 09:39:50 +0000568 if (const ArrayType *arrayType
569 = getContext().getAsArrayType(E->getType())) {
John McCall7f416cc2015-09-08 08:05:57 +0000570 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E);
John McCallf677a8e2011-07-13 06:10:41 +0000571 } else {
Cameron Esfahanibceca202011-05-06 21:28:42 +0000572 CXXCtorType Type = Ctor_Complete;
Alexis Hunt271c3682011-05-03 20:19:28 +0000573 bool ForVirtualBase = false;
Douglas Gregor61535002013-01-31 05:50:40 +0000574 bool Delegating = false;
575
Alexis Hunt271c3682011-05-03 20:19:28 +0000576 switch (E->getConstructionKind()) {
577 case CXXConstructExpr::CK_Delegating:
Alexis Hunt61bc1732011-05-01 07:04:31 +0000578 // We should be emitting a constructor; GlobalDecl will assert this
579 Type = CurGD.getCtorType();
Douglas Gregor61535002013-01-31 05:50:40 +0000580 Delegating = true;
Alexis Hunt271c3682011-05-03 20:19:28 +0000581 break;
Alexis Hunt61bc1732011-05-01 07:04:31 +0000582
Alexis Hunt271c3682011-05-03 20:19:28 +0000583 case CXXConstructExpr::CK_Complete:
584 Type = Ctor_Complete;
585 break;
586
587 case CXXConstructExpr::CK_VirtualBase:
588 ForVirtualBase = true;
589 // fall-through
590
591 case CXXConstructExpr::CK_NonVirtualBase:
592 Type = Ctor_Base;
593 }
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000594
Anders Carlsson27da15b2010-01-01 20:29:01 +0000595 // Call the constructor.
John McCall7f416cc2015-09-08 08:05:57 +0000596 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
597 Dest.getAddress(), E);
Anders Carlssone11f9ce2010-05-02 23:20:53 +0000598 }
Anders Carlsson27da15b2010-01-01 20:29:01 +0000599}
600
John McCall7f416cc2015-09-08 08:05:57 +0000601void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
602 const Expr *Exp) {
John McCall5d413782010-12-06 08:20:24 +0000603 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000604 Exp = E->getSubExpr();
605 assert(isa<CXXConstructExpr>(Exp) &&
606 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
607 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
608 const CXXConstructorDecl *CD = E->getConstructor();
609 RunCleanupsScope Scope(*this);
610
611 // If we require zero initialization before (or instead of) calling the
612 // constructor, as can be the case with a non-user-provided default
613 // constructor, emit the zero initialization now.
614 // FIXME. Do I still need this for a copy ctor synthesis?
615 if (E->requiresZeroInitialization())
616 EmitNullInitialization(Dest, E->getType());
617
Chandler Carruth99da11c2010-11-15 13:54:43 +0000618 assert(!getContext().getAsConstantArrayType(E->getType())
619 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
Alexey Samsonov525bf652014-08-25 21:58:56 +0000620 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +0000621}
622
John McCall8ed55a52010-09-02 09:58:18 +0000623static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
624 const CXXNewExpr *E) {
Anders Carlsson21122cf2009-12-13 20:04:38 +0000625 if (!E->isArray())
Ken Dyck3eb55cf2010-01-26 19:44:24 +0000626 return CharUnits::Zero();
Anders Carlsson21122cf2009-12-13 20:04:38 +0000627
John McCall7ec4b432011-05-16 01:05:12 +0000628 // No cookie is required if the operator new[] being used is the
629 // reserved placement operator new[].
630 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
John McCallaa4149a2010-08-23 01:17:59 +0000631 return CharUnits::Zero();
632
John McCall284c48f2011-01-27 09:37:56 +0000633 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000634}
635
John McCall036f2f62011-05-15 07:14:44 +0000636static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
637 const CXXNewExpr *e,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000638 unsigned minElements,
John McCall036f2f62011-05-15 07:14:44 +0000639 llvm::Value *&numElements,
640 llvm::Value *&sizeWithoutCookie) {
641 QualType type = e->getAllocatedType();
John McCall8ed55a52010-09-02 09:58:18 +0000642
John McCall036f2f62011-05-15 07:14:44 +0000643 if (!e->isArray()) {
644 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
645 sizeWithoutCookie
646 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
647 return sizeWithoutCookie;
Douglas Gregor05fc5be2010-07-21 01:10:17 +0000648 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000649
John McCall036f2f62011-05-15 07:14:44 +0000650 // The width of size_t.
651 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
652
John McCall8ed55a52010-09-02 09:58:18 +0000653 // Figure out the cookie size.
John McCall036f2f62011-05-15 07:14:44 +0000654 llvm::APInt cookieSize(sizeWidth,
655 CalculateCookiePadding(CGF, e).getQuantity());
John McCall8ed55a52010-09-02 09:58:18 +0000656
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000657 // Emit the array size expression.
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000658 // We multiply the size of all dimensions for NumElements.
659 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
John McCall036f2f62011-05-15 07:14:44 +0000660 numElements = CGF.EmitScalarExpr(e->getArraySize());
661 assert(isa<llvm::IntegerType>(numElements->getType()));
John McCall8ed55a52010-09-02 09:58:18 +0000662
John McCall036f2f62011-05-15 07:14:44 +0000663 // The number of elements can be have an arbitrary integer type;
664 // essentially, we need to multiply it by a constant factor, add a
665 // cookie size, and verify that the result is representable as a
666 // size_t. That's just a gloss, though, and it's wrong in one
667 // important way: if the count is negative, it's an error even if
668 // the cookie size would bring the total size >= 0.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000669 bool isSigned
670 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner2192fe52011-07-18 04:24:23 +0000671 llvm::IntegerType *numElementsType
John McCall036f2f62011-05-15 07:14:44 +0000672 = cast<llvm::IntegerType>(numElements->getType());
673 unsigned numElementsWidth = numElementsType->getBitWidth();
674
675 // Compute the constant factor.
676 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000677 while (const ConstantArrayType *CAT
John McCall036f2f62011-05-15 07:14:44 +0000678 = CGF.getContext().getAsConstantArrayType(type)) {
679 type = CAT->getElementType();
680 arraySizeMultiplier *= CAT->getSize();
Argyrios Kyrtzidis7648fb42010-08-26 15:23:38 +0000681 }
682
John McCall036f2f62011-05-15 07:14:44 +0000683 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
684 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
685 typeSizeMultiplier *= arraySizeMultiplier;
686
687 // This will be a size_t.
688 llvm::Value *size;
Chris Lattnerf2f38702010-07-20 21:07:09 +0000689
Chris Lattner32ac5832010-07-20 21:55:52 +0000690 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
691 // Don't bloat the -O0 code.
John McCall036f2f62011-05-15 07:14:44 +0000692 if (llvm::ConstantInt *numElementsC =
693 dyn_cast<llvm::ConstantInt>(numElements)) {
694 const llvm::APInt &count = numElementsC->getValue();
John McCall8ed55a52010-09-02 09:58:18 +0000695
John McCall036f2f62011-05-15 07:14:44 +0000696 bool hasAnyOverflow = false;
John McCall8ed55a52010-09-02 09:58:18 +0000697
John McCall036f2f62011-05-15 07:14:44 +0000698 // If 'count' was a negative number, it's an overflow.
699 if (isSigned && count.isNegative())
700 hasAnyOverflow = true;
John McCall8ed55a52010-09-02 09:58:18 +0000701
John McCall036f2f62011-05-15 07:14:44 +0000702 // We want to do all this arithmetic in size_t. If numElements is
703 // wider than that, check whether it's already too big, and if so,
704 // overflow.
705 else if (numElementsWidth > sizeWidth &&
706 numElementsWidth - sizeWidth > count.countLeadingZeros())
707 hasAnyOverflow = true;
708
709 // Okay, compute a count at the right width.
710 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
711
Sebastian Redlf862eb62012-02-22 17:37:52 +0000712 // If there is a brace-initializer, we cannot allocate fewer elements than
713 // there are initializers. If we do, that's treated like an overflow.
714 if (adjustedCount.ult(minElements))
715 hasAnyOverflow = true;
716
John McCall036f2f62011-05-15 07:14:44 +0000717 // Scale numElements by that. This might overflow, but we don't
718 // care because it only overflows if allocationSize does, too, and
719 // if that overflows then we shouldn't use this.
720 numElements = llvm::ConstantInt::get(CGF.SizeTy,
721 adjustedCount * arraySizeMultiplier);
722
723 // Compute the size before cookie, and track whether it overflowed.
724 bool overflow;
725 llvm::APInt allocationSize
726 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
727 hasAnyOverflow |= overflow;
728
729 // Add in the cookie, and check whether it's overflowed.
730 if (cookieSize != 0) {
731 // Save the current size without a cookie. This shouldn't be
732 // used if there was overflow.
733 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
734
735 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
736 hasAnyOverflow |= overflow;
737 }
738
739 // On overflow, produce a -1 so operator new will fail.
Aaron Ballman455f42c2014-08-28 17:24:14 +0000740 if (hasAnyOverflow) {
741 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
742 } else {
John McCall036f2f62011-05-15 07:14:44 +0000743 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
Aaron Ballman455f42c2014-08-28 17:24:14 +0000744 }
John McCall036f2f62011-05-15 07:14:44 +0000745
746 // Otherwise, we might need to use the overflow intrinsics.
747 } else {
Sebastian Redlf862eb62012-02-22 17:37:52 +0000748 // There are up to five conditions we need to test for:
John McCall036f2f62011-05-15 07:14:44 +0000749 // 1) if isSigned, we need to check whether numElements is negative;
750 // 2) if numElementsWidth > sizeWidth, we need to check whether
751 // numElements is larger than something representable in size_t;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000752 // 3) if minElements > 0, we need to check whether numElements is smaller
753 // than that.
754 // 4) we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000755 // sizeWithoutCookie := numElements * typeSizeMultiplier
756 // and check whether it overflows; and
Sebastian Redlf862eb62012-02-22 17:37:52 +0000757 // 5) if we need a cookie, we need to compute
John McCall036f2f62011-05-15 07:14:44 +0000758 // size := sizeWithoutCookie + cookieSize
759 // and check whether it overflows.
760
Craig Topper8a13c412014-05-21 05:09:00 +0000761 llvm::Value *hasOverflow = nullptr;
John McCall036f2f62011-05-15 07:14:44 +0000762
763 // If numElementsWidth > sizeWidth, then one way or another, we're
764 // going to have to do a comparison for (2), and this happens to
765 // take care of (1), too.
766 if (numElementsWidth > sizeWidth) {
767 llvm::APInt threshold(numElementsWidth, 1);
768 threshold <<= sizeWidth;
769
770 llvm::Value *thresholdV
771 = llvm::ConstantInt::get(numElementsType, threshold);
772
773 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
774 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
775
776 // Otherwise, if we're signed, we want to sext up to size_t.
777 } else if (isSigned) {
778 if (numElementsWidth < sizeWidth)
779 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
780
781 // If there's a non-1 type size multiplier, then we can do the
782 // signedness check at the same time as we do the multiply
783 // because a negative number times anything will cause an
Sebastian Redlf862eb62012-02-22 17:37:52 +0000784 // unsigned overflow. Otherwise, we have to do it here. But at least
785 // in this case, we can subsume the >= minElements check.
John McCall036f2f62011-05-15 07:14:44 +0000786 if (typeSizeMultiplier == 1)
787 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
Sebastian Redlf862eb62012-02-22 17:37:52 +0000788 llvm::ConstantInt::get(CGF.SizeTy, minElements));
John McCall036f2f62011-05-15 07:14:44 +0000789
790 // Otherwise, zext up to size_t if necessary.
791 } else if (numElementsWidth < sizeWidth) {
792 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
793 }
794
795 assert(numElements->getType() == CGF.SizeTy);
796
Sebastian Redlf862eb62012-02-22 17:37:52 +0000797 if (minElements) {
798 // Don't allow allocation of fewer elements than we have initializers.
799 if (!hasOverflow) {
800 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
801 llvm::ConstantInt::get(CGF.SizeTy, minElements));
802 } else if (numElementsWidth > sizeWidth) {
803 // The other existing overflow subsumes this check.
804 // We do an unsigned comparison, since any signed value < -1 is
805 // taken care of either above or below.
806 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
807 CGF.Builder.CreateICmpULT(numElements,
808 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
809 }
810 }
811
John McCall036f2f62011-05-15 07:14:44 +0000812 size = numElements;
813
814 // Multiply by the type size if necessary. This multiplier
815 // includes all the factors for nested arrays.
816 //
817 // This step also causes numElements to be scaled up by the
818 // nested-array factor if necessary. Overflow on this computation
819 // can be ignored because the result shouldn't be used if
820 // allocation fails.
821 if (typeSizeMultiplier != 1) {
John McCall036f2f62011-05-15 07:14:44 +0000822 llvm::Value *umul_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000823 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000824
825 llvm::Value *tsmV =
826 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
827 llvm::Value *result =
David Blaikie43f9bb72015-05-18 22:14:03 +0000828 CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
John McCall036f2f62011-05-15 07:14:44 +0000829
830 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
831 if (hasOverflow)
832 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
833 else
834 hasOverflow = overflowed;
835
836 size = CGF.Builder.CreateExtractValue(result, 0);
837
838 // Also scale up numElements by the array size multiplier.
839 if (arraySizeMultiplier != 1) {
840 // If the base element type size is 1, then we can re-use the
841 // multiply we just did.
842 if (typeSize.isOne()) {
843 assert(arraySizeMultiplier == typeSizeMultiplier);
844 numElements = size;
845
846 // Otherwise we need a separate multiply.
847 } else {
848 llvm::Value *asmV =
849 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
850 numElements = CGF.Builder.CreateMul(numElements, asmV);
851 }
852 }
853 } else {
854 // numElements doesn't need to be scaled.
855 assert(arraySizeMultiplier == 1);
Chris Lattner32ac5832010-07-20 21:55:52 +0000856 }
857
John McCall036f2f62011-05-15 07:14:44 +0000858 // Add in the cookie size if necessary.
859 if (cookieSize != 0) {
860 sizeWithoutCookie = size;
861
John McCall036f2f62011-05-15 07:14:44 +0000862 llvm::Value *uadd_with_overflow
Benjamin Kramer8d375ce2011-07-14 17:45:50 +0000863 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
John McCall036f2f62011-05-15 07:14:44 +0000864
865 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
866 llvm::Value *result =
David Blaikie43f9bb72015-05-18 22:14:03 +0000867 CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
John McCall036f2f62011-05-15 07:14:44 +0000868
869 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
870 if (hasOverflow)
871 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
872 else
873 hasOverflow = overflowed;
874
875 size = CGF.Builder.CreateExtractValue(result, 0);
John McCall8ed55a52010-09-02 09:58:18 +0000876 }
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000877
John McCall036f2f62011-05-15 07:14:44 +0000878 // If we had any possibility of dynamic overflow, make a select to
879 // overwrite 'size' with an all-ones value, which should cause
880 // operator new to throw.
881 if (hasOverflow)
Aaron Ballman455f42c2014-08-28 17:24:14 +0000882 size = CGF.Builder.CreateSelect(hasOverflow,
883 llvm::Constant::getAllOnesValue(CGF.SizeTy),
884 size);
Chris Lattner32ac5832010-07-20 21:55:52 +0000885 }
John McCall8ed55a52010-09-02 09:58:18 +0000886
John McCall036f2f62011-05-15 07:14:44 +0000887 if (cookieSize == 0)
888 sizeWithoutCookie = size;
John McCall8ed55a52010-09-02 09:58:18 +0000889 else
John McCall036f2f62011-05-15 07:14:44 +0000890 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
John McCall8ed55a52010-09-02 09:58:18 +0000891
John McCall036f2f62011-05-15 07:14:44 +0000892 return size;
Anders Carlssonb4bd0662009-09-23 16:07:23 +0000893}
894
Sebastian Redlf862eb62012-02-22 17:37:52 +0000895static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
John McCall7f416cc2015-09-08 08:05:57 +0000896 QualType AllocType, Address NewPtr) {
Richard Smith1c96bc52013-12-11 01:40:16 +0000897 // FIXME: Refactor with EmitExprAsInit.
John McCall47fb9502013-03-07 21:37:08 +0000898 switch (CGF.getEvaluationKind(AllocType)) {
899 case TEK_Scalar:
David Blaikiea2c11242014-12-10 19:04:09 +0000900 CGF.EmitScalarInit(Init, nullptr,
John McCall7f416cc2015-09-08 08:05:57 +0000901 CGF.MakeAddrLValue(NewPtr, AllocType), false);
John McCall47fb9502013-03-07 21:37:08 +0000902 return;
903 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000904 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
John McCall47fb9502013-03-07 21:37:08 +0000905 /*isInit*/ true);
906 return;
907 case TEK_Aggregate: {
John McCall7a626f62010-09-15 10:14:12 +0000908 AggValueSlot Slot
John McCall7f416cc2015-09-08 08:05:57 +0000909 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000910 AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000911 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000912 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000913 CGF.EmitAggExpr(Init, Slot);
John McCall47fb9502013-03-07 21:37:08 +0000914 return;
John McCall7a626f62010-09-15 10:14:12 +0000915 }
John McCall47fb9502013-03-07 21:37:08 +0000916 }
917 llvm_unreachable("bad evaluation kind");
Fariborz Jahaniand5202e02010-06-25 18:26:07 +0000918}
919
David Blaikiefb901c7a2015-04-04 15:12:29 +0000920void CodeGenFunction::EmitNewArrayInitializer(
921 const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
John McCall7f416cc2015-09-08 08:05:57 +0000922 Address BeginPtr, llvm::Value *NumElements,
David Blaikiefb901c7a2015-04-04 15:12:29 +0000923 llvm::Value *AllocSizeWithoutCookie) {
Richard Smith06a67e22014-06-03 06:58:52 +0000924 // If we have a type with trivial initialization and no initializer,
925 // there's nothing to do.
Sebastian Redl6047f072012-02-16 12:22:20 +0000926 if (!E->hasInitializer())
Richard Smith06a67e22014-06-03 06:58:52 +0000927 return;
John McCall99210dc2011-09-15 06:49:18 +0000928
John McCall7f416cc2015-09-08 08:05:57 +0000929 Address CurPtr = BeginPtr;
John McCall99210dc2011-09-15 06:49:18 +0000930
Richard Smith06a67e22014-06-03 06:58:52 +0000931 unsigned InitListElements = 0;
Sebastian Redlf862eb62012-02-22 17:37:52 +0000932
933 const Expr *Init = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +0000934 Address EndOfInit = Address::invalid();
Richard Smith06a67e22014-06-03 06:58:52 +0000935 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
936 EHScopeStack::stable_iterator Cleanup;
937 llvm::Instruction *CleanupDominator = nullptr;
Richard Smith1c96bc52013-12-11 01:40:16 +0000938
John McCall7f416cc2015-09-08 08:05:57 +0000939 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
940 CharUnits ElementAlign =
941 BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
942
Richard Smith0511d232016-10-05 22:41:02 +0000943 // Attempt to perform zero-initialization using memset.
944 auto TryMemsetInitialization = [&]() -> bool {
945 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
946 // we can initialize with a memset to -1.
947 if (!CGM.getTypes().isZeroInitializable(ElementType))
948 return false;
949
950 // Optimization: since zero initialization will just set the memory
951 // to all zeroes, generate a single memset to do it in one shot.
952
953 // Subtract out the size of any elements we've already initialized.
954 auto *RemainingSize = AllocSizeWithoutCookie;
955 if (InitListElements) {
956 // We know this can't overflow; we check this when doing the allocation.
957 auto *InitializedSize = llvm::ConstantInt::get(
958 RemainingSize->getType(),
959 getContext().getTypeSizeInChars(ElementType).getQuantity() *
960 InitListElements);
961 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
962 }
963
964 // Create the memset.
965 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
966 return true;
967 };
968
Sebastian Redlf862eb62012-02-22 17:37:52 +0000969 // If the initializer is an initializer list, first do the explicit elements.
970 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
Richard Smith0511d232016-10-05 22:41:02 +0000971 // Initializing from a (braced) string literal is a special case; the init
972 // list element does not initialize a (single) array element.
973 if (ILE->isStringLiteralInit()) {
974 // Initialize the initial portion of length equal to that of the string
975 // literal. The allocation must be for at least this much; we emitted a
976 // check for that earlier.
977 AggValueSlot Slot =
978 AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
979 AggValueSlot::IsDestructed,
980 AggValueSlot::DoesNotNeedGCBarriers,
981 AggValueSlot::IsNotAliased);
982 EmitAggExpr(ILE->getInit(0), Slot);
983
984 // Move past these elements.
985 InitListElements =
986 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
987 ->getSize().getZExtValue();
988 CurPtr =
989 Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
990 Builder.getSize(InitListElements),
991 "string.init.end"),
992 CurPtr.getAlignment().alignmentAtOffset(InitListElements *
993 ElementSize));
994
995 // Zero out the rest, if any remain.
996 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
997 if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
998 bool OK = TryMemsetInitialization();
999 (void)OK;
1000 assert(OK && "couldn't memset character type?");
1001 }
1002 return;
1003 }
1004
Richard Smith06a67e22014-06-03 06:58:52 +00001005 InitListElements = ILE->getNumInits();
Chad Rosierf62290a2012-02-24 00:13:55 +00001006
Richard Smith1c96bc52013-12-11 01:40:16 +00001007 // If this is a multi-dimensional array new, we will initialize multiple
1008 // elements with each init list element.
1009 QualType AllocType = E->getAllocatedType();
1010 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
1011 AllocType->getAsArrayTypeUnsafe())) {
David Blaikiefb901c7a2015-04-04 15:12:29 +00001012 ElementTy = ConvertTypeForMem(AllocType);
John McCall7f416cc2015-09-08 08:05:57 +00001013 CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
Richard Smith06a67e22014-06-03 06:58:52 +00001014 InitListElements *= getContext().getConstantArrayElementCount(CAT);
Richard Smith1c96bc52013-12-11 01:40:16 +00001015 }
1016
Richard Smith06a67e22014-06-03 06:58:52 +00001017 // Enter a partial-destruction Cleanup if necessary.
1018 if (needsEHCleanup(DtorKind)) {
1019 // In principle we could tell the Cleanup where we are more
Chad Rosierf62290a2012-02-24 00:13:55 +00001020 // directly, but the control flow can get so varied here that it
1021 // would actually be quite complex. Therefore we go through an
1022 // alloca.
John McCall7f416cc2015-09-08 08:05:57 +00001023 EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
1024 "array.init.end");
1025 CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
1026 pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
1027 ElementType, ElementAlign,
Richard Smith06a67e22014-06-03 06:58:52 +00001028 getDestroyer(DtorKind));
1029 Cleanup = EHStack.stable_begin();
Chad Rosierf62290a2012-02-24 00:13:55 +00001030 }
1031
John McCall7f416cc2015-09-08 08:05:57 +00001032 CharUnits StartAlign = CurPtr.getAlignment();
Sebastian Redlf862eb62012-02-22 17:37:52 +00001033 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
Chad Rosierf62290a2012-02-24 00:13:55 +00001034 // Tell the cleanup that it needs to destroy up to this
1035 // element. TODO: some of these stores can be trivially
1036 // observed to be unnecessary.
John McCall7f416cc2015-09-08 08:05:57 +00001037 if (EndOfInit.isValid()) {
1038 auto FinishedPtr =
1039 Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
1040 Builder.CreateStore(FinishedPtr, EndOfInit);
1041 }
Richard Smith06a67e22014-06-03 06:58:52 +00001042 // FIXME: If the last initializer is an incomplete initializer list for
1043 // an array, and we have an array filler, we can fold together the two
1044 // initialization loops.
Richard Smith1c96bc52013-12-11 01:40:16 +00001045 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
Richard Smith06a67e22014-06-03 06:58:52 +00001046 ILE->getInit(i)->getType(), CurPtr);
John McCall7f416cc2015-09-08 08:05:57 +00001047 CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1048 Builder.getSize(1),
1049 "array.exp.next"),
1050 StartAlign.alignmentAtOffset((i + 1) * ElementSize));
Sebastian Redlf862eb62012-02-22 17:37:52 +00001051 }
1052
1053 // The remaining elements are filled with the array filler expression.
1054 Init = ILE->getArrayFiller();
Richard Smith1c96bc52013-12-11 01:40:16 +00001055
Richard Smith06a67e22014-06-03 06:58:52 +00001056 // Extract the initializer for the individual array elements by pulling
1057 // out the array filler from all the nested initializer lists. This avoids
1058 // generating a nested loop for the initialization.
1059 while (Init && Init->getType()->isConstantArrayType()) {
1060 auto *SubILE = dyn_cast<InitListExpr>(Init);
1061 if (!SubILE)
1062 break;
1063 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
1064 Init = SubILE->getArrayFiller();
1065 }
1066
1067 // Switch back to initializing one base element at a time.
John McCall7f416cc2015-09-08 08:05:57 +00001068 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
Sebastian Redlf862eb62012-02-22 17:37:52 +00001069 }
1070
Richard Smith454a7cd2014-06-03 08:26:00 +00001071 // If all elements have already been initialized, skip any further
1072 // initialization.
1073 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1074 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1075 // If there was a Cleanup, deactivate it.
1076 if (CleanupDominator)
1077 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1078 return;
1079 }
1080
1081 assert(Init && "have trailing elements to initialize but no initializer");
1082
Richard Smith06a67e22014-06-03 06:58:52 +00001083 // If this is a constructor call, try to optimize it out, and failing that
1084 // emit a single loop to initialize all remaining elements.
Richard Smith454a7cd2014-06-03 08:26:00 +00001085 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +00001086 CXXConstructorDecl *Ctor = CCE->getConstructor();
1087 if (Ctor->isTrivial()) {
1088 // If new expression did not specify value-initialization, then there
1089 // is no initialization.
1090 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
1091 return;
1092
1093 if (TryMemsetInitialization())
1094 return;
1095 }
1096
1097 // Store the new Cleanup position for irregular Cleanups.
1098 //
1099 // FIXME: Share this cleanup with the constructor call emission rather than
1100 // having it create a cleanup of its own.
John McCall7f416cc2015-09-08 08:05:57 +00001101 if (EndOfInit.isValid())
1102 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
Richard Smith06a67e22014-06-03 06:58:52 +00001103
1104 // Emit a constructor call loop to initialize the remaining elements.
1105 if (InitListElements)
1106 NumElements = Builder.CreateSub(
1107 NumElements,
1108 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001109 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
Richard Smith06a67e22014-06-03 06:58:52 +00001110 CCE->requiresZeroInitialization());
Chandler Carruthe6c980c2014-05-03 09:16:57 +00001111 return;
1112 }
1113
Richard Smith06a67e22014-06-03 06:58:52 +00001114 // If this is value-initialization, we can usually use memset.
1115 ImplicitValueInitExpr IVIE(ElementType);
Richard Smith454a7cd2014-06-03 08:26:00 +00001116 if (isa<ImplicitValueInitExpr>(Init)) {
Richard Smith06a67e22014-06-03 06:58:52 +00001117 if (TryMemsetInitialization())
1118 return;
1119
1120 // Switch to an ImplicitValueInitExpr for the element type. This handles
1121 // only one case: multidimensional array new of pointers to members. In
1122 // all other cases, we already have an initializer for the array element.
1123 Init = &IVIE;
1124 }
1125
1126 // At this point we should have found an initializer for the individual
1127 // elements of the array.
1128 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
1129 "got wrong type of element to initialize");
1130
Richard Smith454a7cd2014-06-03 08:26:00 +00001131 // If we have an empty initializer list, we can usually use memset.
1132 if (auto *ILE = dyn_cast<InitListExpr>(Init))
1133 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1134 return;
Richard Smith06a67e22014-06-03 06:58:52 +00001135
Yunzhong Gaocb779302015-06-10 00:27:52 +00001136 // If we have a struct whose every field is value-initialized, we can
1137 // usually use memset.
1138 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1139 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1140 if (RType->getDecl()->isStruct()) {
Richard Smith872307e2016-03-08 22:17:41 +00001141 unsigned NumElements = 0;
1142 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1143 NumElements = CXXRD->getNumBases();
Yunzhong Gaocb779302015-06-10 00:27:52 +00001144 for (auto *Field : RType->getDecl()->fields())
1145 if (!Field->isUnnamedBitfield())
Richard Smith872307e2016-03-08 22:17:41 +00001146 ++NumElements;
1147 // FIXME: Recurse into nested InitListExprs.
1148 if (ILE->getNumInits() == NumElements)
Yunzhong Gaocb779302015-06-10 00:27:52 +00001149 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1150 if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
Richard Smith872307e2016-03-08 22:17:41 +00001151 --NumElements;
1152 if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
Yunzhong Gaocb779302015-06-10 00:27:52 +00001153 return;
1154 }
1155 }
1156 }
1157
Richard Smith06a67e22014-06-03 06:58:52 +00001158 // Create the loop blocks.
1159 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1160 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
1161 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
1162
1163 // Find the end of the array, hoisted out of the loop.
1164 llvm::Value *EndPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001165 Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
John McCall99210dc2011-09-15 06:49:18 +00001166
Sebastian Redlf862eb62012-02-22 17:37:52 +00001167 // If the number of elements isn't constant, we have to now check if there is
1168 // anything left to initialize.
Richard Smith06a67e22014-06-03 06:58:52 +00001169 if (!ConstNum) {
John McCall7f416cc2015-09-08 08:05:57 +00001170 llvm::Value *IsEmpty =
1171 Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
Richard Smith06a67e22014-06-03 06:58:52 +00001172 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
John McCall99210dc2011-09-15 06:49:18 +00001173 }
1174
1175 // Enter the loop.
Richard Smith06a67e22014-06-03 06:58:52 +00001176 EmitBlock(LoopBB);
John McCall99210dc2011-09-15 06:49:18 +00001177
1178 // Set up the current-element phi.
Richard Smith06a67e22014-06-03 06:58:52 +00001179 llvm::PHINode *CurPtrPhi =
John McCall7f416cc2015-09-08 08:05:57 +00001180 Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1181 CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
1182
1183 CurPtr = Address(CurPtrPhi, ElementAlign);
John McCall99210dc2011-09-15 06:49:18 +00001184
Richard Smith06a67e22014-06-03 06:58:52 +00001185 // Store the new Cleanup position for irregular Cleanups.
John McCall7f416cc2015-09-08 08:05:57 +00001186 if (EndOfInit.isValid())
1187 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
Chad Rosierf62290a2012-02-24 00:13:55 +00001188
Richard Smith06a67e22014-06-03 06:58:52 +00001189 // Enter a partial-destruction Cleanup if necessary.
1190 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
John McCall7f416cc2015-09-08 08:05:57 +00001191 pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
1192 ElementType, ElementAlign,
Richard Smith06a67e22014-06-03 06:58:52 +00001193 getDestroyer(DtorKind));
1194 Cleanup = EHStack.stable_begin();
1195 CleanupDominator = Builder.CreateUnreachable();
John McCall99210dc2011-09-15 06:49:18 +00001196 }
1197
1198 // Emit the initializer into this element.
Richard Smith06a67e22014-06-03 06:58:52 +00001199 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
John McCall99210dc2011-09-15 06:49:18 +00001200
Richard Smith06a67e22014-06-03 06:58:52 +00001201 // Leave the Cleanup if we entered one.
1202 if (CleanupDominator) {
1203 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1204 CleanupDominator->eraseFromParent();
John McCallf4beacd2011-11-10 10:43:54 +00001205 }
John McCall99210dc2011-09-15 06:49:18 +00001206
Faisal Vali57ae0562013-12-14 00:40:05 +00001207 // Advance to the next element by adjusting the pointer type as necessary.
Richard Smith06a67e22014-06-03 06:58:52 +00001208 llvm::Value *NextPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001209 Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
1210 "array.next");
Richard Smith06a67e22014-06-03 06:58:52 +00001211
John McCall99210dc2011-09-15 06:49:18 +00001212 // Check whether we've gotten to the end of the array and, if so,
1213 // exit the loop.
Richard Smith06a67e22014-06-03 06:58:52 +00001214 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1215 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1216 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
John McCall99210dc2011-09-15 06:49:18 +00001217
Richard Smith06a67e22014-06-03 06:58:52 +00001218 EmitBlock(ContBB);
Fariborz Jahaniand5202e02010-06-25 18:26:07 +00001219}
1220
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001221static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
David Blaikiefb901c7a2015-04-04 15:12:29 +00001222 QualType ElementType, llvm::Type *ElementTy,
John McCall7f416cc2015-09-08 08:05:57 +00001223 Address NewPtr, llvm::Value *NumElements,
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001224 llvm::Value *AllocSizeWithoutCookie) {
David Blaikie9b479662015-01-25 01:19:10 +00001225 ApplyDebugLocation DL(CGF, E);
Richard Smith06a67e22014-06-03 06:58:52 +00001226 if (E->isArray())
David Blaikiefb901c7a2015-04-04 15:12:29 +00001227 CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
Richard Smith06a67e22014-06-03 06:58:52 +00001228 AllocSizeWithoutCookie);
1229 else if (const Expr *Init = E->getInitializer())
David Blaikie66e41972015-01-14 07:38:27 +00001230 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
Anders Carlssonb4bd0662009-09-23 16:07:23 +00001231}
1232
Richard Smith8d0dc312013-07-21 23:12:18 +00001233/// Emit a call to an operator new or operator delete function, as implicitly
1234/// created by new-expressions and delete-expressions.
1235static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
John McCallb92ab1a2016-10-26 23:46:34 +00001236 const FunctionDecl *CalleeDecl,
Richard Smith8d0dc312013-07-21 23:12:18 +00001237 const FunctionProtoType *CalleeType,
1238 const CallArgList &Args) {
1239 llvm::Instruction *CallOrInvoke;
John McCallb92ab1a2016-10-26 23:46:34 +00001240 llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
1241 CGCallee Callee = CGCallee::forDirect(CalleePtr, CalleeDecl);
Richard Smith8d0dc312013-07-21 23:12:18 +00001242 RValue RV =
Peter Collingbournef7706832014-12-12 23:41:25 +00001243 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1244 Args, CalleeType, /*chainCall=*/false),
John McCallb92ab1a2016-10-26 23:46:34 +00001245 Callee, ReturnValueSlot(), Args, &CallOrInvoke);
Richard Smith8d0dc312013-07-21 23:12:18 +00001246
1247 /// C++1y [expr.new]p10:
1248 /// [In a new-expression,] an implementation is allowed to omit a call
1249 /// to a replaceable global allocation function.
1250 ///
1251 /// We model such elidable calls with the 'builtin' attribute.
John McCallb92ab1a2016-10-26 23:46:34 +00001252 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1253 if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
Rafael Espindola6956d582013-10-22 14:23:09 +00001254 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
Richard Smith8d0dc312013-07-21 23:12:18 +00001255 // FIXME: Add addAttribute to CallSite.
1256 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1257 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1258 llvm::Attribute::Builtin);
1259 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1260 II->addAttribute(llvm::AttributeSet::FunctionIndex,
1261 llvm::Attribute::Builtin);
1262 else
1263 llvm_unreachable("unexpected kind of call instruction");
1264 }
1265
1266 return RV;
1267}
1268
Richard Smith760520b2014-06-03 23:27:44 +00001269RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1270 const Expr *Arg,
1271 bool IsDelete) {
1272 CallArgList Args;
1273 const Stmt *ArgS = Arg;
David Blaikief05779e2015-07-21 18:37:18 +00001274 EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS));
Richard Smith760520b2014-06-03 23:27:44 +00001275 // Find the allocation or deallocation function that we're calling.
1276 ASTContext &Ctx = getContext();
1277 DeclarationName Name = Ctx.DeclarationNames
1278 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1279 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
Richard Smith599bed72014-06-05 00:43:02 +00001280 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1281 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1282 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
Richard Smith760520b2014-06-03 23:27:44 +00001283 llvm_unreachable("predeclared global operator new/delete is missing");
1284}
1285
Richard Smithb2f0f052016-10-10 18:54:32 +00001286static std::pair<bool, bool>
1287shouldPassSizeAndAlignToUsualDelete(const FunctionProtoType *FPT) {
1288 auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
Richard Smith189e52f2016-10-10 06:42:31 +00001289
Richard Smithb2f0f052016-10-10 18:54:32 +00001290 // The first argument is always a void*.
1291 ++AI;
1292
1293 // Figure out what other parameters we should be implicitly passing.
1294 bool PassSize = false;
1295 bool PassAlignment = false;
1296
1297 if (AI != AE && (*AI)->isIntegerType()) {
1298 PassSize = true;
1299 ++AI;
1300 }
1301
1302 if (AI != AE && (*AI)->isAlignValT()) {
1303 PassAlignment = true;
1304 ++AI;
1305 }
1306
1307 assert(AI == AE && "unexpected usual deallocation function parameter");
1308 return {PassSize, PassAlignment};
1309}
1310
1311namespace {
1312 /// A cleanup to call the given 'operator delete' function upon abnormal
1313 /// exit from a new expression. Templated on a traits type that deals with
1314 /// ensuring that the arguments dominate the cleanup if necessary.
1315 template<typename Traits>
1316 class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1317 /// Type used to hold llvm::Value*s.
1318 typedef typename Traits::ValueTy ValueTy;
1319 /// Type used to hold RValues.
1320 typedef typename Traits::RValueTy RValueTy;
1321 struct PlacementArg {
1322 RValueTy ArgValue;
1323 QualType ArgType;
1324 };
1325
1326 unsigned NumPlacementArgs : 31;
1327 unsigned PassAlignmentToPlacementDelete : 1;
1328 const FunctionDecl *OperatorDelete;
1329 ValueTy Ptr;
1330 ValueTy AllocSize;
1331 CharUnits AllocAlign;
1332
1333 PlacementArg *getPlacementArgs() {
1334 return reinterpret_cast<PlacementArg *>(this + 1);
1335 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00001336
1337 public:
1338 static size_t getExtraSize(size_t NumPlacementArgs) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001339 return NumPlacementArgs * sizeof(PlacementArg);
Daniel Jaspere9abe642016-10-10 14:13:55 +00001340 }
1341
1342 CallDeleteDuringNew(size_t NumPlacementArgs,
Richard Smithb2f0f052016-10-10 18:54:32 +00001343 const FunctionDecl *OperatorDelete, ValueTy Ptr,
1344 ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1345 CharUnits AllocAlign)
1346 : NumPlacementArgs(NumPlacementArgs),
1347 PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1348 OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1349 AllocAlign(AllocAlign) {}
Daniel Jaspere9abe642016-10-10 14:13:55 +00001350
Richard Smithb2f0f052016-10-10 18:54:32 +00001351 void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
Daniel Jaspere9abe642016-10-10 14:13:55 +00001352 assert(I < NumPlacementArgs && "index out of range");
Richard Smithb2f0f052016-10-10 18:54:32 +00001353 getPlacementArgs()[I] = {Arg, Type};
Daniel Jaspere9abe642016-10-10 14:13:55 +00001354 }
1355
1356 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smithb2f0f052016-10-10 18:54:32 +00001357 const FunctionProtoType *FPT =
1358 OperatorDelete->getType()->getAs<FunctionProtoType>();
Daniel Jaspere9abe642016-10-10 14:13:55 +00001359 CallArgList DeleteArgs;
1360
1361 // The first argument is always a void*.
Richard Smithb2f0f052016-10-10 18:54:32 +00001362 DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
Daniel Jaspere9abe642016-10-10 14:13:55 +00001363
Richard Smithb2f0f052016-10-10 18:54:32 +00001364 // Figure out what other parameters we should be implicitly passing.
1365 bool PassSize = false;
1366 bool PassAlignment = false;
1367 if (NumPlacementArgs) {
1368 // A placement deallocation function is implicitly passed an alignment
1369 // if the placement allocation function was, but is never passed a size.
1370 PassAlignment = PassAlignmentToPlacementDelete;
1371 } else {
1372 // For a non-placement new-expression, 'operator delete' can take a
1373 // size and/or an alignment if it has the right parameters.
1374 std::tie(PassSize, PassAlignment) =
1375 shouldPassSizeAndAlignToUsualDelete(FPT);
John McCall7f9c92a2010-09-17 00:50:28 +00001376 }
1377
Richard Smithb2f0f052016-10-10 18:54:32 +00001378 // The second argument can be a std::size_t (for non-placement delete).
1379 if (PassSize)
1380 DeleteArgs.add(Traits::get(CGF, AllocSize),
1381 CGF.getContext().getSizeType());
1382
1383 // The next (second or third) argument can be a std::align_val_t, which
1384 // is an enum whose underlying type is std::size_t.
1385 // FIXME: Use the right type as the parameter type. Note that in a call
1386 // to operator delete(size_t, ...), we may not have it available.
1387 if (PassAlignment)
1388 DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1389 CGF.SizeTy, AllocAlign.getQuantity())),
1390 CGF.getContext().getSizeType());
1391
John McCall7f9c92a2010-09-17 00:50:28 +00001392 // Pass the rest of the arguments, which must match exactly.
1393 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001394 auto Arg = getPlacementArgs()[I];
1395 DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
John McCall7f9c92a2010-09-17 00:50:28 +00001396 }
1397
1398 // Call 'operator delete'.
Richard Smith8d0dc312013-07-21 23:12:18 +00001399 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
John McCall7f9c92a2010-09-17 00:50:28 +00001400 }
1401 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001402}
John McCall7f9c92a2010-09-17 00:50:28 +00001403
1404/// Enter a cleanup to call 'operator delete' if the initializer in a
1405/// new-expression throws.
1406static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1407 const CXXNewExpr *E,
John McCall7f416cc2015-09-08 08:05:57 +00001408 Address NewPtr,
John McCall7f9c92a2010-09-17 00:50:28 +00001409 llvm::Value *AllocSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00001410 CharUnits AllocAlign,
John McCall7f9c92a2010-09-17 00:50:28 +00001411 const CallArgList &NewArgs) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001412 unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1413
John McCall7f9c92a2010-09-17 00:50:28 +00001414 // If we're not inside a conditional branch, then the cleanup will
1415 // dominate and we can do the easier (and more efficient) thing.
1416 if (!CGF.isInConditionalBranch()) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001417 struct DirectCleanupTraits {
1418 typedef llvm::Value *ValueTy;
1419 typedef RValue RValueTy;
1420 static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1421 static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1422 };
1423
1424 typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1425
1426 DirectCleanup *Cleanup = CGF.EHStack
1427 .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
1428 E->getNumPlacementArgs(),
1429 E->getOperatorDelete(),
1430 NewPtr.getPointer(),
1431 AllocSize,
1432 E->passAlignment(),
1433 AllocAlign);
1434 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1435 auto &Arg = NewArgs[I + NumNonPlacementArgs];
1436 Cleanup->setPlacementArg(I, Arg.RV, Arg.Ty);
1437 }
John McCall7f9c92a2010-09-17 00:50:28 +00001438
1439 return;
1440 }
1441
1442 // Otherwise, we need to save all this stuff.
John McCallcb5f77f2011-01-28 10:53:53 +00001443 DominatingValue<RValue>::saved_type SavedNewPtr =
John McCall7f416cc2015-09-08 08:05:57 +00001444 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
John McCallcb5f77f2011-01-28 10:53:53 +00001445 DominatingValue<RValue>::saved_type SavedAllocSize =
1446 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
John McCall7f9c92a2010-09-17 00:50:28 +00001447
Richard Smithb2f0f052016-10-10 18:54:32 +00001448 struct ConditionalCleanupTraits {
1449 typedef DominatingValue<RValue>::saved_type ValueTy;
1450 typedef DominatingValue<RValue>::saved_type RValueTy;
1451 static RValue get(CodeGenFunction &CGF, ValueTy V) {
1452 return V.restore(CGF);
1453 }
1454 };
1455 typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1456
1457 ConditionalCleanup *Cleanup = CGF.EHStack
1458 .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
1459 E->getNumPlacementArgs(),
1460 E->getOperatorDelete(),
1461 SavedNewPtr,
1462 SavedAllocSize,
1463 E->passAlignment(),
1464 AllocAlign);
1465 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1466 auto &Arg = NewArgs[I + NumNonPlacementArgs];
1467 Cleanup->setPlacementArg(I, DominatingValue<RValue>::save(CGF, Arg.RV),
1468 Arg.Ty);
1469 }
John McCall7f9c92a2010-09-17 00:50:28 +00001470
John McCallf4beacd2011-11-10 10:43:54 +00001471 CGF.initFullExprCleanup();
John McCall824c2f52010-09-14 07:57:04 +00001472}
1473
Anders Carlssoncc52f652009-09-22 22:53:17 +00001474llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
John McCall75f94982011-03-07 03:12:35 +00001475 // The element type being allocated.
1476 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
John McCall8ed55a52010-09-02 09:58:18 +00001477
John McCall75f94982011-03-07 03:12:35 +00001478 // 1. Build a call to the allocation function.
1479 FunctionDecl *allocator = E->getOperatorNew();
Anders Carlssoncc52f652009-09-22 22:53:17 +00001480
Sebastian Redlf862eb62012-02-22 17:37:52 +00001481 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1482 unsigned minElements = 0;
1483 if (E->isArray() && E->hasInitializer()) {
Richard Smith0511d232016-10-05 22:41:02 +00001484 const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
1485 if (ILE && ILE->isStringLiteralInit())
1486 minElements =
1487 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1488 ->getSize().getZExtValue();
1489 else if (ILE)
Sebastian Redlf862eb62012-02-22 17:37:52 +00001490 minElements = ILE->getNumInits();
1491 }
1492
Craig Topper8a13c412014-05-21 05:09:00 +00001493 llvm::Value *numElements = nullptr;
1494 llvm::Value *allocSizeWithoutCookie = nullptr;
John McCall75f94982011-03-07 03:12:35 +00001495 llvm::Value *allocSize =
Sebastian Redlf862eb62012-02-22 17:37:52 +00001496 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1497 allocSizeWithoutCookie);
Richard Smithb2f0f052016-10-10 18:54:32 +00001498 CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
Alexey Samsonovcbe875a2014-08-28 00:22:11 +00001499
John McCall7ec4b432011-05-16 01:05:12 +00001500 // Emit the allocation call. If the allocator is a global placement
1501 // operator, just "inline" it directly.
John McCall7f416cc2015-09-08 08:05:57 +00001502 Address allocation = Address::invalid();
1503 CallArgList allocatorArgs;
John McCall7ec4b432011-05-16 01:05:12 +00001504 if (allocator->isReservedGlobalPlacementOperator()) {
John McCall53dcf942015-09-29 23:55:17 +00001505 assert(E->getNumPlacementArgs() == 1);
1506 const Expr *arg = *E->placement_arguments().begin();
1507
John McCall7f416cc2015-09-08 08:05:57 +00001508 AlignmentSource alignSource;
John McCall53dcf942015-09-29 23:55:17 +00001509 allocation = EmitPointerWithAlignment(arg, &alignSource);
John McCall7f416cc2015-09-08 08:05:57 +00001510
1511 // The pointer expression will, in many cases, be an opaque void*.
1512 // In these cases, discard the computed alignment and use the
1513 // formal alignment of the allocated type.
Richard Smithb2f0f052016-10-10 18:54:32 +00001514 if (alignSource != AlignmentSource::Decl)
1515 allocation = Address(allocation.getPointer(), allocAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001516
John McCall53dcf942015-09-29 23:55:17 +00001517 // Set up allocatorArgs for the call to operator delete if it's not
1518 // the reserved global operator.
1519 if (E->getOperatorDelete() &&
1520 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1521 allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1522 allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
1523 }
1524
John McCall7ec4b432011-05-16 01:05:12 +00001525 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001526 const FunctionProtoType *allocatorType =
1527 allocator->getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00001528 unsigned ParamsToSkip = 0;
John McCall7f416cc2015-09-08 08:05:57 +00001529
1530 // The allocation size is the first argument.
1531 QualType sizeType = getContext().getSizeType();
1532 allocatorArgs.add(RValue::get(allocSize), sizeType);
Richard Smithb2f0f052016-10-10 18:54:32 +00001533 ++ParamsToSkip;
John McCall7f416cc2015-09-08 08:05:57 +00001534
Richard Smithb2f0f052016-10-10 18:54:32 +00001535 if (allocSize != allocSizeWithoutCookie) {
1536 CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1537 allocAlign = std::max(allocAlign, cookieAlign);
1538 }
1539
1540 // The allocation alignment may be passed as the second argument.
1541 if (E->passAlignment()) {
1542 QualType AlignValT = sizeType;
1543 if (allocatorType->getNumParams() > 1) {
1544 AlignValT = allocatorType->getParamType(1);
1545 assert(getContext().hasSameUnqualifiedType(
1546 AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
1547 sizeType) &&
1548 "wrong type for alignment parameter");
1549 ++ParamsToSkip;
1550 } else {
1551 // Corner case, passing alignment to 'operator new(size_t, ...)'.
1552 assert(allocator->isVariadic() && "can't pass alignment to allocator");
1553 }
1554 allocatorArgs.add(
1555 RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1556 AlignValT);
1557 }
1558
1559 // FIXME: Why do we not pass a CalleeDecl here?
John McCall7f416cc2015-09-08 08:05:57 +00001560 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
Richard Smithb2f0f052016-10-10 18:54:32 +00001561 /*CalleeDecl*/nullptr, /*ParamsToSkip*/ParamsToSkip);
John McCall7f416cc2015-09-08 08:05:57 +00001562
1563 RValue RV =
1564 EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1565
Richard Smithb2f0f052016-10-10 18:54:32 +00001566 // If this was a call to a global replaceable allocation function that does
1567 // not take an alignment argument, the allocator is known to produce
1568 // storage that's suitably aligned for any object that fits, up to a known
1569 // threshold. Otherwise assume it's suitably aligned for the allocated type.
1570 CharUnits allocationAlign = allocAlign;
1571 if (!E->passAlignment() &&
1572 allocator->isReplaceableGlobalAllocationFunction()) {
1573 unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1574 Target.getNewAlign(), getContext().getTypeSize(allocType)));
1575 allocationAlign = std::max(
1576 allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
John McCall7f416cc2015-09-08 08:05:57 +00001577 }
1578
1579 allocation = Address(RV.getScalarVal(), allocationAlign);
John McCall7ec4b432011-05-16 01:05:12 +00001580 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001581
John McCall75f94982011-03-07 03:12:35 +00001582 // Emit a null check on the allocation result if the allocation
1583 // function is allowed to return null (because it has a non-throwing
Richard Smith902a0232015-02-14 01:52:20 +00001584 // exception spec or is the reserved placement new) and we have an
John McCall75f94982011-03-07 03:12:35 +00001585 // interesting initializer.
Richard Smith902a0232015-02-14 01:52:20 +00001586 bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
Sebastian Redl6047f072012-02-16 12:22:20 +00001587 (!allocType.isPODType(getContext()) || E->hasInitializer());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001588
Craig Topper8a13c412014-05-21 05:09:00 +00001589 llvm::BasicBlock *nullCheckBB = nullptr;
1590 llvm::BasicBlock *contBB = nullptr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001591
John McCallf7dcf322011-03-07 01:52:56 +00001592 // The null-check means that the initializer is conditionally
1593 // evaluated.
1594 ConditionalEvaluation conditional(*this);
1595
John McCall75f94982011-03-07 03:12:35 +00001596 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001597 conditional.begin(*this);
John McCall75f94982011-03-07 03:12:35 +00001598
1599 nullCheckBB = Builder.GetInsertBlock();
1600 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1601 contBB = createBasicBlock("new.cont");
1602
John McCall7f416cc2015-09-08 08:05:57 +00001603 llvm::Value *isNull =
1604 Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
John McCall75f94982011-03-07 03:12:35 +00001605 Builder.CreateCondBr(isNull, contBB, notNullBB);
1606 EmitBlock(notNullBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001607 }
Anders Carlssonf7716812009-09-23 18:59:48 +00001608
John McCall824c2f52010-09-14 07:57:04 +00001609 // If there's an operator delete, enter a cleanup to call it if an
1610 // exception is thrown.
John McCall75f94982011-03-07 03:12:35 +00001611 EHScopeStack::stable_iterator operatorDeleteCleanup;
Craig Topper8a13c412014-05-21 05:09:00 +00001612 llvm::Instruction *cleanupDominator = nullptr;
John McCall7ec4b432011-05-16 01:05:12 +00001613 if (E->getOperatorDelete() &&
1614 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001615 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1616 allocatorArgs);
John McCall75f94982011-03-07 03:12:35 +00001617 operatorDeleteCleanup = EHStack.stable_begin();
John McCallf4beacd2011-11-10 10:43:54 +00001618 cleanupDominator = Builder.CreateUnreachable();
John McCall824c2f52010-09-14 07:57:04 +00001619 }
1620
Eli Friedmancf9b1f62011-09-06 18:53:03 +00001621 assert((allocSize == allocSizeWithoutCookie) ==
1622 CalculateCookiePadding(*this, E).isZero());
1623 if (allocSize != allocSizeWithoutCookie) {
1624 assert(E->isArray());
1625 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1626 numElements,
1627 E, allocType);
1628 }
1629
David Blaikiefb901c7a2015-04-04 15:12:29 +00001630 llvm::Type *elementTy = ConvertTypeForMem(allocType);
John McCall7f416cc2015-09-08 08:05:57 +00001631 Address result = Builder.CreateElementBitCast(allocation, elementTy);
John McCall824c2f52010-09-14 07:57:04 +00001632
Piotr Padlewski338c9d02015-09-15 21:46:47 +00001633 // Passing pointer through invariant.group.barrier to avoid propagation of
1634 // vptrs information which may be included in previous type.
1635 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1636 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1637 allocator->isReservedGlobalPlacementOperator())
1638 result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()),
1639 result.getAlignment());
1640
David Blaikiefb901c7a2015-04-04 15:12:29 +00001641 EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
John McCall99210dc2011-09-15 06:49:18 +00001642 allocSizeWithoutCookie);
John McCall8ed55a52010-09-02 09:58:18 +00001643 if (E->isArray()) {
John McCall8ed55a52010-09-02 09:58:18 +00001644 // NewPtr is a pointer to the base element type. If we're
1645 // allocating an array of arrays, we'll need to cast back to the
1646 // array pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001647 llvm::Type *resultType = ConvertTypeForMem(E->getType());
John McCall7f416cc2015-09-08 08:05:57 +00001648 if (result.getType() != resultType)
John McCall75f94982011-03-07 03:12:35 +00001649 result = Builder.CreateBitCast(result, resultType);
Fariborz Jahanian47b46292010-03-24 16:57:01 +00001650 }
John McCall824c2f52010-09-14 07:57:04 +00001651
1652 // Deactivate the 'operator delete' cleanup if we finished
1653 // initialization.
John McCallf4beacd2011-11-10 10:43:54 +00001654 if (operatorDeleteCleanup.isValid()) {
1655 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1656 cleanupDominator->eraseFromParent();
1657 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001658
John McCall7f416cc2015-09-08 08:05:57 +00001659 llvm::Value *resultPtr = result.getPointer();
John McCall75f94982011-03-07 03:12:35 +00001660 if (nullCheck) {
John McCallf7dcf322011-03-07 01:52:56 +00001661 conditional.end(*this);
1662
John McCall75f94982011-03-07 03:12:35 +00001663 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1664 EmitBlock(contBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001665
John McCall7f416cc2015-09-08 08:05:57 +00001666 llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
1667 PHI->addIncoming(resultPtr, notNullBB);
1668 PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
John McCall75f94982011-03-07 03:12:35 +00001669 nullCheckBB);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001670
John McCall7f416cc2015-09-08 08:05:57 +00001671 resultPtr = PHI;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001672 }
John McCall8ed55a52010-09-02 09:58:18 +00001673
John McCall7f416cc2015-09-08 08:05:57 +00001674 return resultPtr;
Anders Carlssoncc52f652009-09-22 22:53:17 +00001675}
1676
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001677void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
Richard Smithb2f0f052016-10-10 18:54:32 +00001678 llvm::Value *Ptr, QualType DeleteTy,
1679 llvm::Value *NumElements,
1680 CharUnits CookieSize) {
1681 assert((!NumElements && CookieSize.isZero()) ||
1682 DeleteFD->getOverloadedOperator() == OO_Array_Delete);
John McCall8ed55a52010-09-02 09:58:18 +00001683
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001684 const FunctionProtoType *DeleteFTy =
1685 DeleteFD->getType()->getAs<FunctionProtoType>();
1686
1687 CallArgList DeleteArgs;
1688
Richard Smithb2f0f052016-10-10 18:54:32 +00001689 std::pair<bool, bool> PassSizeAndAlign =
1690 shouldPassSizeAndAlignToUsualDelete(DeleteFTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00001691
Richard Smithb2f0f052016-10-10 18:54:32 +00001692 auto ParamTypeIt = DeleteFTy->param_type_begin();
1693
1694 // Pass the pointer itself.
1695 QualType ArgTy = *ParamTypeIt++;
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001696 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
Eli Friedman43dca6a2011-05-02 17:57:46 +00001697 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001698
Richard Smithb2f0f052016-10-10 18:54:32 +00001699 // Pass the size if the delete function has a size_t parameter.
1700 if (PassSizeAndAlign.first) {
1701 QualType SizeType = *ParamTypeIt++;
1702 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1703 llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1704 DeleteTypeSize.getQuantity());
1705
1706 // For array new, multiply by the number of elements.
1707 if (NumElements)
1708 Size = Builder.CreateMul(Size, NumElements);
1709
1710 // If there is a cookie, add the cookie size.
1711 if (!CookieSize.isZero())
1712 Size = Builder.CreateAdd(
1713 Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1714
1715 DeleteArgs.add(RValue::get(Size), SizeType);
1716 }
1717
1718 // Pass the alignment if the delete function has an align_val_t parameter.
1719 if (PassSizeAndAlign.second) {
1720 QualType AlignValType = *ParamTypeIt++;
1721 CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits(
1722 getContext().getTypeAlignIfKnown(DeleteTy));
1723 llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1724 DeleteTypeAlign.getQuantity());
1725 DeleteArgs.add(RValue::get(Align), AlignValType);
1726 }
1727
1728 assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1729 "unknown parameter to usual delete function");
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001730
1731 // Emit the call to delete.
Richard Smith8d0dc312013-07-21 23:12:18 +00001732 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
Eli Friedmanfe81e3f2009-11-18 00:50:08 +00001733}
1734
John McCall8ed55a52010-09-02 09:58:18 +00001735namespace {
1736 /// Calls the given 'operator delete' on a single object.
David Blaikie7e70d682015-08-18 22:40:54 +00001737 struct CallObjectDelete final : EHScopeStack::Cleanup {
John McCall8ed55a52010-09-02 09:58:18 +00001738 llvm::Value *Ptr;
1739 const FunctionDecl *OperatorDelete;
1740 QualType ElementType;
1741
1742 CallObjectDelete(llvm::Value *Ptr,
1743 const FunctionDecl *OperatorDelete,
1744 QualType ElementType)
1745 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1746
Craig Topper4f12f102014-03-12 06:41:41 +00001747 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall8ed55a52010-09-02 09:58:18 +00001748 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1749 }
1750 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001751}
John McCall8ed55a52010-09-02 09:58:18 +00001752
David Majnemer0c0b6d92014-10-31 20:09:12 +00001753void
1754CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1755 llvm::Value *CompletePtr,
1756 QualType ElementType) {
1757 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1758 OperatorDelete, ElementType);
1759}
1760
John McCall8ed55a52010-09-02 09:58:18 +00001761/// Emit the code for deleting a single object.
1762static void EmitObjectDelete(CodeGenFunction &CGF,
David Majnemer08681372014-11-01 07:37:17 +00001763 const CXXDeleteExpr *DE,
John McCall7f416cc2015-09-08 08:05:57 +00001764 Address Ptr,
David Majnemer08681372014-11-01 07:37:17 +00001765 QualType ElementType) {
John McCall8ed55a52010-09-02 09:58:18 +00001766 // Find the destructor for the type, if applicable. If the
1767 // destructor is virtual, we'll just emit the vcall and return.
Craig Topper8a13c412014-05-21 05:09:00 +00001768 const CXXDestructorDecl *Dtor = nullptr;
John McCall8ed55a52010-09-02 09:58:18 +00001769 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1770 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Eli Friedmanb23533d2011-08-02 18:05:30 +00001771 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
John McCall8ed55a52010-09-02 09:58:18 +00001772 Dtor = RD->getDestructor();
1773
1774 if (Dtor->isVirtual()) {
David Majnemer08681372014-11-01 07:37:17 +00001775 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1776 Dtor);
John McCall8ed55a52010-09-02 09:58:18 +00001777 return;
1778 }
1779 }
1780 }
1781
1782 // Make sure that we call delete even if the dtor throws.
John McCalle4df6c82011-01-28 08:37:24 +00001783 // This doesn't have to a conditional cleanup because we're going
1784 // to pop it off in a second.
David Majnemer08681372014-11-01 07:37:17 +00001785 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001786 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
John McCall7f416cc2015-09-08 08:05:57 +00001787 Ptr.getPointer(),
1788 OperatorDelete, ElementType);
John McCall8ed55a52010-09-02 09:58:18 +00001789
1790 if (Dtor)
1791 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001792 /*ForVirtualBase=*/false,
1793 /*Delegating=*/false,
1794 Ptr);
John McCall460ce582015-10-22 18:38:17 +00001795 else if (auto Lifetime = ElementType.getObjCLifetime()) {
1796 switch (Lifetime) {
John McCall31168b02011-06-15 23:02:42 +00001797 case Qualifiers::OCL_None:
1798 case Qualifiers::OCL_ExplicitNone:
1799 case Qualifiers::OCL_Autoreleasing:
1800 break;
John McCall8ed55a52010-09-02 09:58:18 +00001801
John McCall7f416cc2015-09-08 08:05:57 +00001802 case Qualifiers::OCL_Strong:
1803 CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001804 break;
John McCall31168b02011-06-15 23:02:42 +00001805
1806 case Qualifiers::OCL_Weak:
1807 CGF.EmitARCDestroyWeak(Ptr);
1808 break;
1809 }
1810 }
1811
John McCall8ed55a52010-09-02 09:58:18 +00001812 CGF.PopCleanupBlock();
1813}
1814
1815namespace {
1816 /// Calls the given 'operator delete' on an array of objects.
David Blaikie7e70d682015-08-18 22:40:54 +00001817 struct CallArrayDelete final : EHScopeStack::Cleanup {
John McCall8ed55a52010-09-02 09:58:18 +00001818 llvm::Value *Ptr;
1819 const FunctionDecl *OperatorDelete;
1820 llvm::Value *NumElements;
1821 QualType ElementType;
1822 CharUnits CookieSize;
1823
1824 CallArrayDelete(llvm::Value *Ptr,
1825 const FunctionDecl *OperatorDelete,
1826 llvm::Value *NumElements,
1827 QualType ElementType,
1828 CharUnits CookieSize)
1829 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1830 ElementType(ElementType), CookieSize(CookieSize) {}
1831
Craig Topper4f12f102014-03-12 06:41:41 +00001832 void Emit(CodeGenFunction &CGF, Flags flags) override {
Richard Smithb2f0f052016-10-10 18:54:32 +00001833 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
1834 CookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001835 }
1836 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001837}
John McCall8ed55a52010-09-02 09:58:18 +00001838
1839/// Emit the code for deleting an array of objects.
1840static void EmitArrayDelete(CodeGenFunction &CGF,
John McCall284c48f2011-01-27 09:37:56 +00001841 const CXXDeleteExpr *E,
John McCall7f416cc2015-09-08 08:05:57 +00001842 Address deletedPtr,
John McCallca2c56f2011-07-13 01:41:37 +00001843 QualType elementType) {
Craig Topper8a13c412014-05-21 05:09:00 +00001844 llvm::Value *numElements = nullptr;
1845 llvm::Value *allocatedPtr = nullptr;
John McCallca2c56f2011-07-13 01:41:37 +00001846 CharUnits cookieSize;
1847 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1848 numElements, allocatedPtr, cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001849
John McCallca2c56f2011-07-13 01:41:37 +00001850 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
John McCall8ed55a52010-09-02 09:58:18 +00001851
1852 // Make sure that we call delete even if one of the dtors throws.
John McCallca2c56f2011-07-13 01:41:37 +00001853 const FunctionDecl *operatorDelete = E->getOperatorDelete();
John McCall8ed55a52010-09-02 09:58:18 +00001854 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
John McCallca2c56f2011-07-13 01:41:37 +00001855 allocatedPtr, operatorDelete,
1856 numElements, elementType,
1857 cookieSize);
John McCall8ed55a52010-09-02 09:58:18 +00001858
John McCallca2c56f2011-07-13 01:41:37 +00001859 // Destroy the elements.
1860 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1861 assert(numElements && "no element count for a type with a destructor!");
1862
John McCall7f416cc2015-09-08 08:05:57 +00001863 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1864 CharUnits elementAlign =
1865 deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
1866
1867 llvm::Value *arrayBegin = deletedPtr.getPointer();
John McCallca2c56f2011-07-13 01:41:37 +00001868 llvm::Value *arrayEnd =
John McCall7f416cc2015-09-08 08:05:57 +00001869 CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
John McCall97eab0a2011-07-13 08:09:46 +00001870
1871 // Note that it is legal to allocate a zero-length array, and we
1872 // can never fold the check away because the length should always
1873 // come from a cookie.
John McCall7f416cc2015-09-08 08:05:57 +00001874 CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
John McCallca2c56f2011-07-13 01:41:37 +00001875 CGF.getDestroyer(dtorKind),
John McCall97eab0a2011-07-13 08:09:46 +00001876 /*checkZeroLength*/ true,
John McCallca2c56f2011-07-13 01:41:37 +00001877 CGF.needsEHCleanup(dtorKind));
John McCall8ed55a52010-09-02 09:58:18 +00001878 }
1879
John McCallca2c56f2011-07-13 01:41:37 +00001880 // Pop the cleanup block.
John McCall8ed55a52010-09-02 09:58:18 +00001881 CGF.PopCleanupBlock();
1882}
1883
Anders Carlssoncc52f652009-09-22 22:53:17 +00001884void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001885 const Expr *Arg = E->getArgument();
John McCall7f416cc2015-09-08 08:05:57 +00001886 Address Ptr = EmitPointerWithAlignment(Arg);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001887
1888 // Null check the pointer.
1889 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1890 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1891
John McCall7f416cc2015-09-08 08:05:57 +00001892 llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
Anders Carlssoncc52f652009-09-22 22:53:17 +00001893
1894 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1895 EmitBlock(DeleteNotNull);
Anders Carlssone828c362009-11-13 04:45:41 +00001896
John McCall8ed55a52010-09-02 09:58:18 +00001897 // We might be deleting a pointer to array. If so, GEP down to the
1898 // first non-array element.
1899 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1900 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1901 if (DeleteTy->isConstantArrayType()) {
1902 llvm::Value *Zero = Builder.getInt32(0);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001903 SmallVector<llvm::Value*,8> GEP;
John McCall8ed55a52010-09-02 09:58:18 +00001904
1905 GEP.push_back(Zero); // point at the outermost array
1906
1907 // For each layer of array type we're pointing at:
1908 while (const ConstantArrayType *Arr
1909 = getContext().getAsConstantArrayType(DeleteTy)) {
1910 // 1. Unpeel the array type.
1911 DeleteTy = Arr->getElementType();
1912
1913 // 2. GEP to the first element of the array.
1914 GEP.push_back(Zero);
Anders Carlssoncc52f652009-09-22 22:53:17 +00001915 }
John McCall8ed55a52010-09-02 09:58:18 +00001916
John McCall7f416cc2015-09-08 08:05:57 +00001917 Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
1918 Ptr.getAlignment());
Anders Carlssoncc52f652009-09-22 22:53:17 +00001919 }
1920
John McCall7f416cc2015-09-08 08:05:57 +00001921 assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
John McCall8ed55a52010-09-02 09:58:18 +00001922
Reid Kleckner7270ef52015-03-19 17:03:58 +00001923 if (E->isArrayForm()) {
1924 EmitArrayDelete(*this, E, Ptr, DeleteTy);
1925 } else {
1926 EmitObjectDelete(*this, E, Ptr, DeleteTy);
1927 }
Anders Carlssoncc52f652009-09-22 22:53:17 +00001928
Anders Carlssoncc52f652009-09-22 22:53:17 +00001929 EmitBlock(DeleteEnd);
1930}
Mike Stumpc9b231c2009-11-15 08:09:41 +00001931
David Majnemer1c3d95e2014-07-19 00:17:06 +00001932static bool isGLValueFromPointerDeref(const Expr *E) {
1933 E = E->IgnoreParens();
1934
1935 if (const auto *CE = dyn_cast<CastExpr>(E)) {
1936 if (!CE->getSubExpr()->isGLValue())
1937 return false;
1938 return isGLValueFromPointerDeref(CE->getSubExpr());
1939 }
1940
1941 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
1942 return isGLValueFromPointerDeref(OVE->getSourceExpr());
1943
1944 if (const auto *BO = dyn_cast<BinaryOperator>(E))
1945 if (BO->getOpcode() == BO_Comma)
1946 return isGLValueFromPointerDeref(BO->getRHS());
1947
1948 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
1949 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
1950 isGLValueFromPointerDeref(ACO->getFalseExpr());
1951
1952 // C++11 [expr.sub]p1:
1953 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
1954 if (isa<ArraySubscriptExpr>(E))
1955 return true;
1956
1957 if (const auto *UO = dyn_cast<UnaryOperator>(E))
1958 if (UO->getOpcode() == UO_Deref)
1959 return true;
1960
1961 return false;
1962}
1963
Warren Hunt747e3012014-06-18 21:15:55 +00001964static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
Chris Lattner2192fe52011-07-18 04:24:23 +00001965 llvm::Type *StdTypeInfoPtrTy) {
Anders Carlsson940f02d2011-04-18 00:57:03 +00001966 // Get the vtable pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001967 Address ThisPtr = CGF.EmitLValue(E).getAddress();
Anders Carlsson940f02d2011-04-18 00:57:03 +00001968
1969 // C++ [expr.typeid]p2:
1970 // If the glvalue expression is obtained by applying the unary * operator to
1971 // a pointer and the pointer is a null pointer value, the typeid expression
1972 // throws the std::bad_typeid exception.
David Majnemer1c3d95e2014-07-19 00:17:06 +00001973 //
1974 // However, this paragraph's intent is not clear. We choose a very generous
1975 // interpretation which implores us to consider comma operators, conditional
1976 // operators, parentheses and other such constructs.
David Majnemer1162d252014-06-22 19:05:33 +00001977 QualType SrcRecordTy = E->getType();
David Majnemer1c3d95e2014-07-19 00:17:06 +00001978 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
1979 isGLValueFromPointerDeref(E), SrcRecordTy)) {
David Majnemer1162d252014-06-22 19:05:33 +00001980 llvm::BasicBlock *BadTypeidBlock =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001981 CGF.createBasicBlock("typeid.bad_typeid");
David Majnemer1162d252014-06-22 19:05:33 +00001982 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
Anders Carlsson940f02d2011-04-18 00:57:03 +00001983
John McCall7f416cc2015-09-08 08:05:57 +00001984 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
David Majnemer1162d252014-06-22 19:05:33 +00001985 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001986
David Majnemer1162d252014-06-22 19:05:33 +00001987 CGF.EmitBlock(BadTypeidBlock);
1988 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1989 CGF.EmitBlock(EndBlock);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001990 }
1991
David Majnemer1162d252014-06-22 19:05:33 +00001992 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
1993 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00001994}
1995
John McCalle4df6c82011-01-28 08:37:24 +00001996llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001997 llvm::Type *StdTypeInfoPtrTy =
Anders Carlsson940f02d2011-04-18 00:57:03 +00001998 ConvertType(E->getType())->getPointerTo();
Anders Carlssonfd7dfeb2009-12-11 02:46:30 +00001999
Anders Carlsson3f4336c2009-12-17 07:09:17 +00002000 if (E->isTypeOperand()) {
David Majnemer143c55e2013-09-27 07:04:31 +00002001 llvm::Constant *TypeInfo =
2002 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
Anders Carlsson940f02d2011-04-18 00:57:03 +00002003 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00002004 }
Anders Carlsson0c633502011-04-11 14:13:40 +00002005
Anders Carlsson940f02d2011-04-18 00:57:03 +00002006 // C++ [expr.typeid]p2:
2007 // When typeid is applied to a glvalue expression whose type is a
2008 // polymorphic class type, the result refers to a std::type_info object
2009 // representing the type of the most derived object (that is, the dynamic
2010 // type) to which the glvalue refers.
Richard Smithef8bf432012-08-13 20:08:14 +00002011 if (E->isPotentiallyEvaluated())
2012 return EmitTypeidFromVTable(*this, E->getExprOperand(),
2013 StdTypeInfoPtrTy);
Anders Carlsson940f02d2011-04-18 00:57:03 +00002014
2015 QualType OperandTy = E->getExprOperand()->getType();
2016 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
2017 StdTypeInfoPtrTy);
Mike Stumpc9b231c2009-11-15 08:09:41 +00002018}
Mike Stump65511702009-11-16 06:50:58 +00002019
Anders Carlssonc1c99712011-04-11 01:45:29 +00002020static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
2021 QualType DestTy) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002022 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
Anders Carlssonc1c99712011-04-11 01:45:29 +00002023 if (DestTy->isPointerType())
2024 return llvm::Constant::getNullValue(DestLTy);
2025
2026 /// C++ [expr.dynamic.cast]p9:
2027 /// A failed cast to reference type throws std::bad_cast
David Majnemer1162d252014-06-22 19:05:33 +00002028 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
2029 return nullptr;
Anders Carlssonc1c99712011-04-11 01:45:29 +00002030
2031 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
2032 return llvm::UndefValue::get(DestLTy);
2033}
2034
John McCall7f416cc2015-09-08 08:05:57 +00002035llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
Mike Stump65511702009-11-16 06:50:58 +00002036 const CXXDynamicCastExpr *DCE) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00002037 CGM.EmitExplicitCastExprType(DCE, this);
Anders Carlsson3f4336c2009-12-17 07:09:17 +00002038 QualType DestTy = DCE->getTypeAsWritten();
Anders Carlsson882d7902011-04-11 00:46:40 +00002039
Anders Carlssonc1c99712011-04-11 01:45:29 +00002040 if (DCE->isAlwaysNull())
David Majnemer1162d252014-06-22 19:05:33 +00002041 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
2042 return T;
Anders Carlssonc1c99712011-04-11 01:45:29 +00002043
2044 QualType SrcTy = DCE->getSubExpr()->getType();
2045
David Majnemer1162d252014-06-22 19:05:33 +00002046 // C++ [expr.dynamic.cast]p7:
2047 // If T is "pointer to cv void," then the result is a pointer to the most
2048 // derived object pointed to by v.
2049 const PointerType *DestPTy = DestTy->getAs<PointerType>();
2050
2051 bool isDynamicCastToVoid;
2052 QualType SrcRecordTy;
2053 QualType DestRecordTy;
2054 if (DestPTy) {
2055 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
2056 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
2057 DestRecordTy = DestPTy->getPointeeType();
2058 } else {
2059 isDynamicCastToVoid = false;
2060 SrcRecordTy = SrcTy;
2061 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
2062 }
2063
2064 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
2065
Anders Carlsson882d7902011-04-11 00:46:40 +00002066 // C++ [expr.dynamic.cast]p4:
2067 // If the value of v is a null pointer value in the pointer case, the result
2068 // is the null pointer value of type T.
David Majnemer1162d252014-06-22 19:05:33 +00002069 bool ShouldNullCheckSrcValue =
2070 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
2071 SrcRecordTy);
Craig Topper8a13c412014-05-21 05:09:00 +00002072
2073 llvm::BasicBlock *CastNull = nullptr;
2074 llvm::BasicBlock *CastNotNull = nullptr;
Anders Carlsson882d7902011-04-11 00:46:40 +00002075 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
Mike Stump65511702009-11-16 06:50:58 +00002076
Anders Carlsson882d7902011-04-11 00:46:40 +00002077 if (ShouldNullCheckSrcValue) {
2078 CastNull = createBasicBlock("dynamic_cast.null");
2079 CastNotNull = createBasicBlock("dynamic_cast.notnull");
2080
John McCall7f416cc2015-09-08 08:05:57 +00002081 llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
Anders Carlsson882d7902011-04-11 00:46:40 +00002082 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2083 EmitBlock(CastNotNull);
Mike Stump65511702009-11-16 06:50:58 +00002084 }
2085
John McCall7f416cc2015-09-08 08:05:57 +00002086 llvm::Value *Value;
David Majnemer1162d252014-06-22 19:05:33 +00002087 if (isDynamicCastToVoid) {
John McCall7f416cc2015-09-08 08:05:57 +00002088 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00002089 DestTy);
2090 } else {
2091 assert(DestRecordTy->isRecordType() &&
2092 "destination type must be a record type!");
John McCall7f416cc2015-09-08 08:05:57 +00002093 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
David Majnemer1162d252014-06-22 19:05:33 +00002094 DestTy, DestRecordTy, CastEnd);
David Majnemer67528ea2015-11-23 03:01:14 +00002095 CastNotNull = Builder.GetInsertBlock();
David Majnemer1162d252014-06-22 19:05:33 +00002096 }
Anders Carlsson882d7902011-04-11 00:46:40 +00002097
2098 if (ShouldNullCheckSrcValue) {
2099 EmitBranch(CastEnd);
2100
2101 EmitBlock(CastNull);
2102 EmitBranch(CastEnd);
2103 }
2104
2105 EmitBlock(CastEnd);
2106
2107 if (ShouldNullCheckSrcValue) {
2108 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2109 PHI->addIncoming(Value, CastNotNull);
2110 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
2111
2112 Value = PHI;
2113 }
2114
2115 return Value;
Mike Stump65511702009-11-16 06:50:58 +00002116}
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002117
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002118void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
Eli Friedman8631f3e82012-02-09 03:47:20 +00002119 RunCleanupsScope Scope(*this);
John McCall7f416cc2015-09-08 08:05:57 +00002120 LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType());
Eli Friedman8631f3e82012-02-09 03:47:20 +00002121
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002122 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
James Y Knight53c76162015-07-17 18:21:37 +00002123 for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
2124 e = E->capture_init_end();
Eric Christopherd47e0862012-02-29 03:25:18 +00002125 i != e; ++i, ++CurField) {
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002126 // Emit initialization
David Blaikie40ed2972012-06-06 20:45:41 +00002127 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
Alexey Bataev39c81e22014-08-28 04:28:19 +00002128 if (CurField->hasCapturedVLAType()) {
2129 auto VAT = CurField->getCapturedVLAType();
2130 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2131 } else {
2132 ArrayRef<VarDecl *> ArrayIndexes;
2133 if (CurField->getType()->isArrayType())
2134 ArrayIndexes = E->getCaptureInitIndexVars(i);
2135 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
2136 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002137 }
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002138}