159486a2dSAnders Carlsson //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
259486a2dSAnders Carlsson //
359486a2dSAnders Carlsson //                     The LLVM Compiler Infrastructure
459486a2dSAnders Carlsson //
559486a2dSAnders Carlsson // This file is distributed under the University of Illinois Open Source
659486a2dSAnders Carlsson // License. See LICENSE.TXT for details.
759486a2dSAnders Carlsson //
859486a2dSAnders Carlsson //===----------------------------------------------------------------------===//
959486a2dSAnders Carlsson //
1059486a2dSAnders Carlsson // This contains code dealing with code generation of C++ expressions
1159486a2dSAnders Carlsson //
1259486a2dSAnders Carlsson //===----------------------------------------------------------------------===//
1359486a2dSAnders Carlsson 
1459486a2dSAnders Carlsson #include "CodeGenFunction.h"
15fe883422SPeter Collingbourne #include "CGCUDARuntime.h"
165d865c32SJohn McCall #include "CGCXXABI.h"
1791bbb554SDevang Patel #include "CGDebugInfo.h"
183a02247dSChandler Carruth #include "CGObjCRuntime.h"
19a8e7df36SMark Lacey #include "clang/CodeGen/CGFunctionInfo.h"
203a02247dSChandler Carruth #include "clang/Frontend/CodeGenOptions.h"
21c80ceea9SChandler Carruth #include "llvm/IR/CallSite.h"
22ffd5551bSChandler Carruth #include "llvm/IR/Intrinsics.h"
23bbe277c4SAnders Carlsson 
2459486a2dSAnders Carlsson using namespace clang;
2559486a2dSAnders Carlsson using namespace CodeGen;
2659486a2dSAnders Carlsson 
27*a5bf76bdSAlexey Samsonov RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
28*a5bf76bdSAlexey Samsonov     const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
29*a5bf76bdSAlexey Samsonov     llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
30*a5bf76bdSAlexey Samsonov     const CallExpr *CE) {
31*a5bf76bdSAlexey Samsonov   assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
32*a5bf76bdSAlexey Samsonov          isa<CXXOperatorCallExpr>(CE));
3327da15baSAnders Carlsson   assert(MD->isInstance() &&
34*a5bf76bdSAlexey Samsonov          "Trying to emit a member or operator call expr on a static method!");
3527da15baSAnders Carlsson 
3669d0d262SRichard Smith   // C++11 [class.mfct.non-static]p2:
3769d0d262SRichard Smith   //   If a non-static member function of a class X is called for an object that
3869d0d262SRichard Smith   //   is not of type X, or of a type derived from X, the behavior is undefined.
39*a5bf76bdSAlexey Samsonov   SourceLocation CallLoc;
40*a5bf76bdSAlexey Samsonov   if (CE)
41*a5bf76bdSAlexey Samsonov     CallLoc = CE->getExprLoc();
424d3110afSRichard Smith   EmitTypeCheck(isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall
434d3110afSRichard Smith                                             : TCK_MemberCall,
444d3110afSRichard Smith                 CallLoc, This, getContext().getRecordType(MD->getParent()));
4569d0d262SRichard Smith 
4627da15baSAnders Carlsson   CallArgList Args;
4727da15baSAnders Carlsson 
4827da15baSAnders Carlsson   // Push the this ptr.
4943dca6a8SEli Friedman   Args.add(RValue::get(This), MD->getThisType(getContext()));
5027da15baSAnders Carlsson 
51ee6bc533STimur Iskhodzhanov   // If there is an implicit parameter (e.g. VTT), emit it.
52ee6bc533STimur Iskhodzhanov   if (ImplicitParam) {
53ee6bc533STimur Iskhodzhanov     Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
54e36a6b3eSAnders Carlsson   }
55e36a6b3eSAnders Carlsson 
56a729c62bSJohn McCall   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
57a729c62bSJohn McCall   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
58a729c62bSJohn McCall 
59a729c62bSJohn McCall   // And the rest of the call args.
60*a5bf76bdSAlexey Samsonov   CallExpr::const_arg_iterator ArgBeg, ArgEnd;
61*a5bf76bdSAlexey Samsonov   if (CE == nullptr) {
62*a5bf76bdSAlexey Samsonov     ArgBeg = ArgEnd = nullptr;
63*a5bf76bdSAlexey Samsonov   } else if (auto OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
64*a5bf76bdSAlexey Samsonov     // Special case: skip first argument of CXXOperatorCall (it is "this").
65*a5bf76bdSAlexey Samsonov     ArgBeg = OCE->arg_begin() + 1;
66*a5bf76bdSAlexey Samsonov     ArgEnd = OCE->arg_end();
67*a5bf76bdSAlexey Samsonov   } else {
68*a5bf76bdSAlexey Samsonov     ArgBeg = CE->arg_begin();
69*a5bf76bdSAlexey Samsonov     ArgEnd = CE->arg_end();
70*a5bf76bdSAlexey Samsonov   }
7127da15baSAnders Carlsson   EmitCallArgs(Args, FPT, ArgBeg, ArgEnd);
7227da15baSAnders Carlsson 
738dda7b27SJohn McCall   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
74c50c27ccSRafael Espindola                   Callee, ReturnValue, Args, MD);
7527da15baSAnders Carlsson }
7627da15baSAnders Carlsson 
773b33c4ecSRafael Espindola static CXXRecordDecl *getCXXRecord(const Expr *E) {
783b33c4ecSRafael Espindola   QualType T = E->getType();
793b33c4ecSRafael Espindola   if (const PointerType *PTy = T->getAs<PointerType>())
803b33c4ecSRafael Espindola     T = PTy->getPointeeType();
813b33c4ecSRafael Espindola   const RecordType *Ty = T->castAs<RecordType>();
823b33c4ecSRafael Espindola   return cast<CXXRecordDecl>(Ty->getDecl());
833b33c4ecSRafael Espindola }
843b33c4ecSRafael Espindola 
8564225794SFrancois Pichet // Note: This function also emit constructor calls to support a MSVC
8664225794SFrancois Pichet // extensions allowing explicit constructor function call.
8727da15baSAnders Carlsson RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
8827da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
892d2e8707SJohn McCall   const Expr *callee = CE->getCallee()->IgnoreParens();
902d2e8707SJohn McCall 
912d2e8707SJohn McCall   if (isa<BinaryOperator>(callee))
9227da15baSAnders Carlsson     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
9327da15baSAnders Carlsson 
942d2e8707SJohn McCall   const MemberExpr *ME = cast<MemberExpr>(callee);
9527da15baSAnders Carlsson   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
9627da15baSAnders Carlsson 
9727da15baSAnders Carlsson   if (MD->isStatic()) {
9827da15baSAnders Carlsson     // The method is static, emit it as we would a regular call.
9927da15baSAnders Carlsson     llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
10070b9c01bSAlexey Samsonov     return EmitCall(getContext().getPointerType(MD->getType()), Callee, CE,
10170b9c01bSAlexey Samsonov                     ReturnValue);
10227da15baSAnders Carlsson   }
10327da15baSAnders Carlsson 
1040d635f53SJohn McCall   // Compute the object pointer.
105ecbe2e97SRafael Espindola   const Expr *Base = ME->getBase();
106ecbe2e97SRafael Espindola   bool CanUseVirtualCall = MD->isVirtual() && !ME->hasQualifier();
107ecbe2e97SRafael Espindola 
1088a13c418SCraig Topper   const CXXMethodDecl *DevirtualizedMethod = nullptr;
1097463ed7cSBenjamin Kramer   if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
1103b33c4ecSRafael Espindola     const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
1113b33c4ecSRafael Espindola     DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
1123b33c4ecSRafael Espindola     assert(DevirtualizedMethod);
1133b33c4ecSRafael Espindola     const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
1143b33c4ecSRafael Espindola     const Expr *Inner = Base->ignoreParenBaseCasts();
1153b33c4ecSRafael Espindola     if (getCXXRecord(Inner) == DevirtualizedClass)
1163b33c4ecSRafael Espindola       // If the class of the Inner expression is where the dynamic method
1173b33c4ecSRafael Espindola       // is defined, build the this pointer from it.
1183b33c4ecSRafael Espindola       Base = Inner;
1193b33c4ecSRafael Espindola     else if (getCXXRecord(Base) != DevirtualizedClass) {
1203b33c4ecSRafael Espindola       // If the method is defined in a class that is not the best dynamic
1213b33c4ecSRafael Espindola       // one or the one of the full expression, we would have to build
1223b33c4ecSRafael Espindola       // a derived-to-base cast to compute the correct this pointer, but
1233b33c4ecSRafael Espindola       // we don't have support for that yet, so do a virtual call.
1248a13c418SCraig Topper       DevirtualizedMethod = nullptr;
1253b33c4ecSRafael Espindola     }
126b27564afSRafael Espindola     // If the return types are not the same, this might be a case where more
127b27564afSRafael Espindola     // code needs to run to compensate for it. For example, the derived
128b27564afSRafael Espindola     // method might return a type that inherits form from the return
129b27564afSRafael Espindola     // type of MD and has a prefix.
130b27564afSRafael Espindola     // For now we just avoid devirtualizing these covariant cases.
131b27564afSRafael Espindola     if (DevirtualizedMethod &&
132314cc81bSAlp Toker         DevirtualizedMethod->getReturnType().getCanonicalType() !=
133314cc81bSAlp Toker             MD->getReturnType().getCanonicalType())
1348a13c418SCraig Topper       DevirtualizedMethod = nullptr;
1353b33c4ecSRafael Espindola   }
136ecbe2e97SRafael Espindola 
13727da15baSAnders Carlsson   llvm::Value *This;
13827da15baSAnders Carlsson   if (ME->isArrow())
1393b33c4ecSRafael Espindola     This = EmitScalarExpr(Base);
140f93ac894SFariborz Jahanian   else
1413b33c4ecSRafael Espindola     This = EmitLValue(Base).getAddress();
142ecbe2e97SRafael Espindola 
14327da15baSAnders Carlsson 
1440d635f53SJohn McCall   if (MD->isTrivial()) {
1458a13c418SCraig Topper     if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
14664225794SFrancois Pichet     if (isa<CXXConstructorDecl>(MD) &&
14764225794SFrancois Pichet         cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
1488a13c418SCraig Topper       return RValue::get(nullptr);
1490d635f53SJohn McCall 
15022653bacSSebastian Redl     if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
15122653bacSSebastian Redl       // We don't like to generate the trivial copy/move assignment operator
15222653bacSSebastian Redl       // when it isn't necessary; just produce the proper effect here.
15327da15baSAnders Carlsson       llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
1541ca66919SBenjamin Kramer       EmitAggregateAssign(This, RHS, CE->getType());
15527da15baSAnders Carlsson       return RValue::get(This);
15627da15baSAnders Carlsson     }
15727da15baSAnders Carlsson 
15864225794SFrancois Pichet     if (isa<CXXConstructorDecl>(MD) &&
15922653bacSSebastian Redl         cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
16022653bacSSebastian Redl       // Trivial move and copy ctor are the same.
16164225794SFrancois Pichet       llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
16264225794SFrancois Pichet       EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS,
16364225794SFrancois Pichet                                      CE->arg_begin(), CE->arg_end());
16464225794SFrancois Pichet       return RValue::get(This);
16564225794SFrancois Pichet     }
16664225794SFrancois Pichet     llvm_unreachable("unknown trivial member function");
16764225794SFrancois Pichet   }
16864225794SFrancois Pichet 
1690d635f53SJohn McCall   // Compute the function type we're calling.
170ade60977SEli Friedman   const CXXMethodDecl *CalleeDecl = DevirtualizedMethod ? DevirtualizedMethod : MD;
1718a13c418SCraig Topper   const CGFunctionInfo *FInfo = nullptr;
172ade60977SEli Friedman   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
173ade60977SEli Friedman     FInfo = &CGM.getTypes().arrangeCXXDestructor(Dtor,
17464225794SFrancois Pichet                                                  Dtor_Complete);
175ade60977SEli Friedman   else if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
176ade60977SEli Friedman     FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor,
17764225794SFrancois Pichet                                                              Ctor_Complete);
17864225794SFrancois Pichet   else
179ade60977SEli Friedman     FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
1800d635f53SJohn McCall 
181e7de47efSReid Kleckner   llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
1820d635f53SJohn McCall 
18327da15baSAnders Carlsson   // C++ [class.virtual]p12:
18427da15baSAnders Carlsson   //   Explicit qualification with the scope operator (5.1) suppresses the
18527da15baSAnders Carlsson   //   virtual call mechanism.
18627da15baSAnders Carlsson   //
18727da15baSAnders Carlsson   // We also don't emit a virtual call if the base expression has a record type
18827da15baSAnders Carlsson   // because then we know what the type is.
1893b33c4ecSRafael Espindola   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
19019cee187SStephen Lin   llvm::Value *Callee;
1919dc6eef7SStephen Lin 
1920d635f53SJohn McCall   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
19319cee187SStephen Lin     assert(CE->arg_begin() == CE->arg_end() &&
1949dc6eef7SStephen Lin            "Destructor shouldn't have explicit parameters");
1959dc6eef7SStephen Lin     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
1969dc6eef7SStephen Lin     if (UseVirtualCall) {
1979dc6eef7SStephen Lin       CGM.getCXXABI().EmitVirtualDestructorCall(*this, Dtor, Dtor_Complete,
198*a5bf76bdSAlexey Samsonov                                                 This, CE);
19927da15baSAnders Carlsson     } else {
2009c6890a7SRichard Smith       if (getLangOpts().AppleKext &&
201265c325eSFariborz Jahanian           MD->isVirtual() &&
202265c325eSFariborz Jahanian           ME->hasQualifier())
2037f6f81baSFariborz Jahanian         Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
2043b33c4ecSRafael Espindola       else if (!DevirtualizedMethod)
205e7de47efSReid Kleckner         Callee = CGM.GetAddrOfCXXDestructor(Dtor, Dtor_Complete, FInfo, Ty);
20649e860b2SRafael Espindola       else {
2073b33c4ecSRafael Espindola         const CXXDestructorDecl *DDtor =
2083b33c4ecSRafael Espindola           cast<CXXDestructorDecl>(DevirtualizedMethod);
20949e860b2SRafael Espindola         Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
21049e860b2SRafael Espindola       }
211*a5bf76bdSAlexey Samsonov       EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
212*a5bf76bdSAlexey Samsonov                                   /*ImplicitParam=*/nullptr, QualType(), CE);
21327da15baSAnders Carlsson     }
2148a13c418SCraig Topper     return RValue::get(nullptr);
2159dc6eef7SStephen Lin   }
2169dc6eef7SStephen Lin 
2179dc6eef7SStephen Lin   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
21864225794SFrancois Pichet     Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
2190d635f53SJohn McCall   } else if (UseVirtualCall) {
22088fd439aSTimur Iskhodzhanov     Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
22127da15baSAnders Carlsson   } else {
2229c6890a7SRichard Smith     if (getLangOpts().AppleKext &&
2239f9438b3SFariborz Jahanian         MD->isVirtual() &&
224252a47f6SFariborz Jahanian         ME->hasQualifier())
2257f6f81baSFariborz Jahanian       Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty);
2263b33c4ecSRafael Espindola     else if (!DevirtualizedMethod)
227727a771aSRafael Espindola       Callee = CGM.GetAddrOfFunction(MD, Ty);
22849e860b2SRafael Espindola     else {
2293b33c4ecSRafael Espindola       Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
23049e860b2SRafael Espindola     }
23127da15baSAnders Carlsson   }
23227da15baSAnders Carlsson 
233f1749427STimur Iskhodzhanov   if (MD->isVirtual()) {
234f1749427STimur Iskhodzhanov     This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
235f1749427STimur Iskhodzhanov         *this, MD, This, UseVirtualCall);
236f1749427STimur Iskhodzhanov   }
23788fd439aSTimur Iskhodzhanov 
238*a5bf76bdSAlexey Samsonov   return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
239*a5bf76bdSAlexey Samsonov                                      /*ImplicitParam=*/nullptr, QualType(), CE);
24027da15baSAnders Carlsson }
24127da15baSAnders Carlsson 
24227da15baSAnders Carlsson RValue
24327da15baSAnders Carlsson CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
24427da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
24527da15baSAnders Carlsson   const BinaryOperator *BO =
24627da15baSAnders Carlsson       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
24727da15baSAnders Carlsson   const Expr *BaseExpr = BO->getLHS();
24827da15baSAnders Carlsson   const Expr *MemFnExpr = BO->getRHS();
24927da15baSAnders Carlsson 
25027da15baSAnders Carlsson   const MemberPointerType *MPT =
2510009fcc3SJohn McCall     MemFnExpr->getType()->castAs<MemberPointerType>();
252475999dcSJohn McCall 
25327da15baSAnders Carlsson   const FunctionProtoType *FPT =
2540009fcc3SJohn McCall     MPT->getPointeeType()->castAs<FunctionProtoType>();
25527da15baSAnders Carlsson   const CXXRecordDecl *RD =
25627da15baSAnders Carlsson     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
25727da15baSAnders Carlsson 
25827da15baSAnders Carlsson   // Get the member function pointer.
259a1dee530SJohn McCall   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
26027da15baSAnders Carlsson 
26127da15baSAnders Carlsson   // Emit the 'this' pointer.
26227da15baSAnders Carlsson   llvm::Value *This;
26327da15baSAnders Carlsson 
264e302792bSJohn McCall   if (BO->getOpcode() == BO_PtrMemI)
26527da15baSAnders Carlsson     This = EmitScalarExpr(BaseExpr);
26627da15baSAnders Carlsson   else
26727da15baSAnders Carlsson     This = EmitLValue(BaseExpr).getAddress();
26827da15baSAnders Carlsson 
269e30752c9SRichard Smith   EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
270e30752c9SRichard Smith                 QualType(MPT->getClass(), 0));
27169d0d262SRichard Smith 
272475999dcSJohn McCall   // Ask the ABI to load the callee.  Note that This is modified.
273475999dcSJohn McCall   llvm::Value *Callee =
2742b0d66dfSDavid Majnemer     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, MemFnPtr, MPT);
27527da15baSAnders Carlsson 
27627da15baSAnders Carlsson   CallArgList Args;
27727da15baSAnders Carlsson 
27827da15baSAnders Carlsson   QualType ThisType =
27927da15baSAnders Carlsson     getContext().getPointerType(getContext().getTagDeclType(RD));
28027da15baSAnders Carlsson 
28127da15baSAnders Carlsson   // Push the this ptr.
28243dca6a8SEli Friedman   Args.add(RValue::get(This), ThisType);
28327da15baSAnders Carlsson 
2848dda7b27SJohn McCall   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
2858dda7b27SJohn McCall 
28627da15baSAnders Carlsson   // And the rest of the call args
28727da15baSAnders Carlsson   EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end());
2885fa40c3bSNick Lewycky   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
2895fa40c3bSNick Lewycky                   Callee, ReturnValue, Args);
29027da15baSAnders Carlsson }
29127da15baSAnders Carlsson 
29227da15baSAnders Carlsson RValue
29327da15baSAnders Carlsson CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
29427da15baSAnders Carlsson                                                const CXXMethodDecl *MD,
29527da15baSAnders Carlsson                                                ReturnValueSlot ReturnValue) {
29627da15baSAnders Carlsson   assert(MD->isInstance() &&
29727da15baSAnders Carlsson          "Trying to emit a member call expr on a static method!");
298e26a872bSJohn McCall   LValue LV = EmitLValue(E->getArg(0));
299e26a872bSJohn McCall   llvm::Value *This = LV.getAddress();
300e26a872bSJohn McCall 
301146b8e9aSDouglas Gregor   if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
302146b8e9aSDouglas Gregor       MD->isTrivial()) {
30327da15baSAnders Carlsson     llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress();
30427da15baSAnders Carlsson     QualType Ty = E->getType();
3051ca66919SBenjamin Kramer     EmitAggregateAssign(This, Src, Ty);
30627da15baSAnders Carlsson     return RValue::get(This);
30727da15baSAnders Carlsson   }
30827da15baSAnders Carlsson 
309c36783e8SAnders Carlsson   llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This);
310*a5bf76bdSAlexey Samsonov   return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
311*a5bf76bdSAlexey Samsonov                                      /*ImplicitParam=*/nullptr, QualType(), E);
31227da15baSAnders Carlsson }
31327da15baSAnders Carlsson 
314fe883422SPeter Collingbourne RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
315fe883422SPeter Collingbourne                                                ReturnValueSlot ReturnValue) {
316fe883422SPeter Collingbourne   return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
317fe883422SPeter Collingbourne }
318fe883422SPeter Collingbourne 
319fde961dbSEli Friedman static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
320fde961dbSEli Friedman                                             llvm::Value *DestPtr,
321fde961dbSEli Friedman                                             const CXXRecordDecl *Base) {
322fde961dbSEli Friedman   if (Base->isEmpty())
323fde961dbSEli Friedman     return;
324fde961dbSEli Friedman 
325fde961dbSEli Friedman   DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
326fde961dbSEli Friedman 
327fde961dbSEli Friedman   const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
328fde961dbSEli Friedman   CharUnits Size = Layout.getNonVirtualSize();
329d640d7d9SWarren Hunt   CharUnits Align = Layout.getNonVirtualAlignment();
330fde961dbSEli Friedman 
331fde961dbSEli Friedman   llvm::Value *SizeVal = CGF.CGM.getSize(Size);
332fde961dbSEli Friedman 
333fde961dbSEli Friedman   // If the type contains a pointer to data member we can't memset it to zero.
334fde961dbSEli Friedman   // Instead, create a null constant and copy it to the destination.
335fde961dbSEli Friedman   // TODO: there are other patterns besides zero that we can usefully memset,
336fde961dbSEli Friedman   // like -1, which happens to be the pattern used by member-pointers.
337fde961dbSEli Friedman   // TODO: isZeroInitializable can be over-conservative in the case where a
338fde961dbSEli Friedman   // virtual base contains a member pointer.
339fde961dbSEli Friedman   if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
340fde961dbSEli Friedman     llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
341fde961dbSEli Friedman 
342fde961dbSEli Friedman     llvm::GlobalVariable *NullVariable =
343fde961dbSEli Friedman       new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
344fde961dbSEli Friedman                                /*isConstant=*/true,
345fde961dbSEli Friedman                                llvm::GlobalVariable::PrivateLinkage,
346fde961dbSEli Friedman                                NullConstant, Twine());
347fde961dbSEli Friedman     NullVariable->setAlignment(Align.getQuantity());
348fde961dbSEli Friedman     llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
349fde961dbSEli Friedman 
350fde961dbSEli Friedman     // Get and call the appropriate llvm.memcpy overload.
351fde961dbSEli Friedman     CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
352fde961dbSEli Friedman     return;
353fde961dbSEli Friedman   }
354fde961dbSEli Friedman 
355fde961dbSEli Friedman   // Otherwise, just memset the whole thing to zero.  This is legal
356fde961dbSEli Friedman   // because in LLVM, all default initializers (other than the ones we just
357fde961dbSEli Friedman   // handled above) are guaranteed to have a bit pattern of all zeros.
358fde961dbSEli Friedman   CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
359fde961dbSEli Friedman                            Align.getQuantity());
360fde961dbSEli Friedman }
361fde961dbSEli Friedman 
36227da15baSAnders Carlsson void
3637a626f63SJohn McCall CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
3647a626f63SJohn McCall                                       AggValueSlot Dest) {
3657a626f63SJohn McCall   assert(!Dest.isIgnored() && "Must have a destination!");
36627da15baSAnders Carlsson   const CXXConstructorDecl *CD = E->getConstructor();
367630c76efSDouglas Gregor 
368630c76efSDouglas Gregor   // If we require zero initialization before (or instead of) calling the
369630c76efSDouglas Gregor   // constructor, as can be the case with a non-user-provided default
37003535265SArgyrios Kyrtzidis   // constructor, emit the zero initialization now, unless destination is
37103535265SArgyrios Kyrtzidis   // already zeroed.
372fde961dbSEli Friedman   if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
373fde961dbSEli Friedman     switch (E->getConstructionKind()) {
374fde961dbSEli Friedman     case CXXConstructExpr::CK_Delegating:
375fde961dbSEli Friedman     case CXXConstructExpr::CK_Complete:
3767a626f63SJohn McCall       EmitNullInitialization(Dest.getAddr(), E->getType());
377fde961dbSEli Friedman       break;
378fde961dbSEli Friedman     case CXXConstructExpr::CK_VirtualBase:
379fde961dbSEli Friedman     case CXXConstructExpr::CK_NonVirtualBase:
380fde961dbSEli Friedman       EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
381fde961dbSEli Friedman       break;
382fde961dbSEli Friedman     }
383fde961dbSEli Friedman   }
384630c76efSDouglas Gregor 
385630c76efSDouglas Gregor   // If this is a call to a trivial default constructor, do nothing.
386630c76efSDouglas Gregor   if (CD->isTrivial() && CD->isDefaultConstructor())
38727da15baSAnders Carlsson     return;
388630c76efSDouglas Gregor 
3898ea46b66SJohn McCall   // Elide the constructor if we're constructing from a temporary.
3908ea46b66SJohn McCall   // The temporary check is required because Sema sets this on NRVO
3918ea46b66SJohn McCall   // returns.
3929c6890a7SRichard Smith   if (getLangOpts().ElideConstructors && E->isElidable()) {
3938ea46b66SJohn McCall     assert(getContext().hasSameUnqualifiedType(E->getType(),
3948ea46b66SJohn McCall                                                E->getArg(0)->getType()));
3957a626f63SJohn McCall     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
3967a626f63SJohn McCall       EmitAggExpr(E->getArg(0), Dest);
39727da15baSAnders Carlsson       return;
39827da15baSAnders Carlsson     }
399222cf0efSDouglas Gregor   }
400630c76efSDouglas Gregor 
401f677a8e9SJohn McCall   if (const ConstantArrayType *arrayType
402f677a8e9SJohn McCall         = getContext().getAsConstantArrayType(E->getType())) {
40370b9c01bSAlexey Samsonov     EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(), E);
404f677a8e9SJohn McCall   } else {
405bceca20aSCameron Esfahani     CXXCtorType Type = Ctor_Complete;
406271c3681SAlexis Hunt     bool ForVirtualBase = false;
40761535005SDouglas Gregor     bool Delegating = false;
408271c3681SAlexis Hunt 
409271c3681SAlexis Hunt     switch (E->getConstructionKind()) {
410271c3681SAlexis Hunt      case CXXConstructExpr::CK_Delegating:
41161bc1737SAlexis Hunt       // We should be emitting a constructor; GlobalDecl will assert this
41261bc1737SAlexis Hunt       Type = CurGD.getCtorType();
41361535005SDouglas Gregor       Delegating = true;
414271c3681SAlexis Hunt       break;
41561bc1737SAlexis Hunt 
416271c3681SAlexis Hunt      case CXXConstructExpr::CK_Complete:
417271c3681SAlexis Hunt       Type = Ctor_Complete;
418271c3681SAlexis Hunt       break;
419271c3681SAlexis Hunt 
420271c3681SAlexis Hunt      case CXXConstructExpr::CK_VirtualBase:
421271c3681SAlexis Hunt       ForVirtualBase = true;
422271c3681SAlexis Hunt       // fall-through
423271c3681SAlexis Hunt 
424271c3681SAlexis Hunt      case CXXConstructExpr::CK_NonVirtualBase:
425271c3681SAlexis Hunt       Type = Ctor_Base;
426271c3681SAlexis Hunt     }
427e11f9ce9SAnders Carlsson 
42827da15baSAnders Carlsson     // Call the constructor.
42961535005SDouglas Gregor     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
43070b9c01bSAlexey Samsonov                            E);
43127da15baSAnders Carlsson   }
432e11f9ce9SAnders Carlsson }
43327da15baSAnders Carlsson 
434e988bdacSFariborz Jahanian void
435e988bdacSFariborz Jahanian CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
436e988bdacSFariborz Jahanian                                             llvm::Value *Src,
43750198098SFariborz Jahanian                                             const Expr *Exp) {
4385d413781SJohn McCall   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
439e988bdacSFariborz Jahanian     Exp = E->getSubExpr();
440e988bdacSFariborz Jahanian   assert(isa<CXXConstructExpr>(Exp) &&
441e988bdacSFariborz Jahanian          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
442e988bdacSFariborz Jahanian   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
443e988bdacSFariborz Jahanian   const CXXConstructorDecl *CD = E->getConstructor();
444e988bdacSFariborz Jahanian   RunCleanupsScope Scope(*this);
445e988bdacSFariborz Jahanian 
446e988bdacSFariborz Jahanian   // If we require zero initialization before (or instead of) calling the
447e988bdacSFariborz Jahanian   // constructor, as can be the case with a non-user-provided default
448e988bdacSFariborz Jahanian   // constructor, emit the zero initialization now.
449e988bdacSFariborz Jahanian   // FIXME. Do I still need this for a copy ctor synthesis?
450e988bdacSFariborz Jahanian   if (E->requiresZeroInitialization())
451e988bdacSFariborz Jahanian     EmitNullInitialization(Dest, E->getType());
452e988bdacSFariborz Jahanian 
45399da11cfSChandler Carruth   assert(!getContext().getAsConstantArrayType(E->getType())
45499da11cfSChandler Carruth          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
4555fa40c3bSNick Lewycky   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E->arg_begin(), E->arg_end());
456e988bdacSFariborz Jahanian }
457e988bdacSFariborz Jahanian 
4588ed55a54SJohn McCall static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
4598ed55a54SJohn McCall                                         const CXXNewExpr *E) {
46021122cf6SAnders Carlsson   if (!E->isArray())
4613eb55cfeSKen Dyck     return CharUnits::Zero();
46221122cf6SAnders Carlsson 
4637ec4b434SJohn McCall   // No cookie is required if the operator new[] being used is the
4647ec4b434SJohn McCall   // reserved placement operator new[].
4657ec4b434SJohn McCall   if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
4663eb55cfeSKen Dyck     return CharUnits::Zero();
467399f499fSAnders Carlsson 
468284c48ffSJohn McCall   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
46959486a2dSAnders Carlsson }
47059486a2dSAnders Carlsson 
471036f2f6bSJohn McCall static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
472036f2f6bSJohn McCall                                         const CXXNewExpr *e,
473f862eb6aSSebastian Redl                                         unsigned minElements,
474036f2f6bSJohn McCall                                         llvm::Value *&numElements,
475036f2f6bSJohn McCall                                         llvm::Value *&sizeWithoutCookie) {
476036f2f6bSJohn McCall   QualType type = e->getAllocatedType();
47759486a2dSAnders Carlsson 
478036f2f6bSJohn McCall   if (!e->isArray()) {
479036f2f6bSJohn McCall     CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
480036f2f6bSJohn McCall     sizeWithoutCookie
481036f2f6bSJohn McCall       = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
482036f2f6bSJohn McCall     return sizeWithoutCookie;
48305fc5be3SDouglas Gregor   }
48459486a2dSAnders Carlsson 
485036f2f6bSJohn McCall   // The width of size_t.
486036f2f6bSJohn McCall   unsigned sizeWidth = CGF.SizeTy->getBitWidth();
487036f2f6bSJohn McCall 
4888ed55a54SJohn McCall   // Figure out the cookie size.
489036f2f6bSJohn McCall   llvm::APInt cookieSize(sizeWidth,
490036f2f6bSJohn McCall                          CalculateCookiePadding(CGF, e).getQuantity());
4918ed55a54SJohn McCall 
49259486a2dSAnders Carlsson   // Emit the array size expression.
4937648fb46SArgyrios Kyrtzidis   // We multiply the size of all dimensions for NumElements.
4947648fb46SArgyrios Kyrtzidis   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
495036f2f6bSJohn McCall   numElements = CGF.EmitScalarExpr(e->getArraySize());
496036f2f6bSJohn McCall   assert(isa<llvm::IntegerType>(numElements->getType()));
4978ed55a54SJohn McCall 
498036f2f6bSJohn McCall   // The number of elements can be have an arbitrary integer type;
499036f2f6bSJohn McCall   // essentially, we need to multiply it by a constant factor, add a
500036f2f6bSJohn McCall   // cookie size, and verify that the result is representable as a
501036f2f6bSJohn McCall   // size_t.  That's just a gloss, though, and it's wrong in one
502036f2f6bSJohn McCall   // important way: if the count is negative, it's an error even if
503036f2f6bSJohn McCall   // the cookie size would bring the total size >= 0.
5046ab2fa8fSDouglas Gregor   bool isSigned
5056ab2fa8fSDouglas Gregor     = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
5062192fe50SChris Lattner   llvm::IntegerType *numElementsType
507036f2f6bSJohn McCall     = cast<llvm::IntegerType>(numElements->getType());
508036f2f6bSJohn McCall   unsigned numElementsWidth = numElementsType->getBitWidth();
509036f2f6bSJohn McCall 
510036f2f6bSJohn McCall   // Compute the constant factor.
511036f2f6bSJohn McCall   llvm::APInt arraySizeMultiplier(sizeWidth, 1);
5127648fb46SArgyrios Kyrtzidis   while (const ConstantArrayType *CAT
513036f2f6bSJohn McCall              = CGF.getContext().getAsConstantArrayType(type)) {
514036f2f6bSJohn McCall     type = CAT->getElementType();
515036f2f6bSJohn McCall     arraySizeMultiplier *= CAT->getSize();
5167648fb46SArgyrios Kyrtzidis   }
51759486a2dSAnders Carlsson 
518036f2f6bSJohn McCall   CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
519036f2f6bSJohn McCall   llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
520036f2f6bSJohn McCall   typeSizeMultiplier *= arraySizeMultiplier;
521036f2f6bSJohn McCall 
522036f2f6bSJohn McCall   // This will be a size_t.
523036f2f6bSJohn McCall   llvm::Value *size;
52432ac583dSChris Lattner 
52532ac583dSChris Lattner   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
52632ac583dSChris Lattner   // Don't bloat the -O0 code.
527036f2f6bSJohn McCall   if (llvm::ConstantInt *numElementsC =
528036f2f6bSJohn McCall         dyn_cast<llvm::ConstantInt>(numElements)) {
529036f2f6bSJohn McCall     const llvm::APInt &count = numElementsC->getValue();
53032ac583dSChris Lattner 
531036f2f6bSJohn McCall     bool hasAnyOverflow = false;
53232ac583dSChris Lattner 
533036f2f6bSJohn McCall     // If 'count' was a negative number, it's an overflow.
534036f2f6bSJohn McCall     if (isSigned && count.isNegative())
535036f2f6bSJohn McCall       hasAnyOverflow = true;
5368ed55a54SJohn McCall 
537036f2f6bSJohn McCall     // We want to do all this arithmetic in size_t.  If numElements is
538036f2f6bSJohn McCall     // wider than that, check whether it's already too big, and if so,
539036f2f6bSJohn McCall     // overflow.
540036f2f6bSJohn McCall     else if (numElementsWidth > sizeWidth &&
541036f2f6bSJohn McCall              numElementsWidth - sizeWidth > count.countLeadingZeros())
542036f2f6bSJohn McCall       hasAnyOverflow = true;
543036f2f6bSJohn McCall 
544036f2f6bSJohn McCall     // Okay, compute a count at the right width.
545036f2f6bSJohn McCall     llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
546036f2f6bSJohn McCall 
547f862eb6aSSebastian Redl     // If there is a brace-initializer, we cannot allocate fewer elements than
548f862eb6aSSebastian Redl     // there are initializers. If we do, that's treated like an overflow.
549f862eb6aSSebastian Redl     if (adjustedCount.ult(minElements))
550f862eb6aSSebastian Redl       hasAnyOverflow = true;
551f862eb6aSSebastian Redl 
552036f2f6bSJohn McCall     // Scale numElements by that.  This might overflow, but we don't
553036f2f6bSJohn McCall     // care because it only overflows if allocationSize does, too, and
554036f2f6bSJohn McCall     // if that overflows then we shouldn't use this.
555036f2f6bSJohn McCall     numElements = llvm::ConstantInt::get(CGF.SizeTy,
556036f2f6bSJohn McCall                                          adjustedCount * arraySizeMultiplier);
557036f2f6bSJohn McCall 
558036f2f6bSJohn McCall     // Compute the size before cookie, and track whether it overflowed.
559036f2f6bSJohn McCall     bool overflow;
560036f2f6bSJohn McCall     llvm::APInt allocationSize
561036f2f6bSJohn McCall       = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
562036f2f6bSJohn McCall     hasAnyOverflow |= overflow;
563036f2f6bSJohn McCall 
564036f2f6bSJohn McCall     // Add in the cookie, and check whether it's overflowed.
565036f2f6bSJohn McCall     if (cookieSize != 0) {
566036f2f6bSJohn McCall       // Save the current size without a cookie.  This shouldn't be
567036f2f6bSJohn McCall       // used if there was overflow.
568036f2f6bSJohn McCall       sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
569036f2f6bSJohn McCall 
570036f2f6bSJohn McCall       allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
571036f2f6bSJohn McCall       hasAnyOverflow |= overflow;
5728ed55a54SJohn McCall     }
5738ed55a54SJohn McCall 
574036f2f6bSJohn McCall     // On overflow, produce a -1 so operator new will fail.
575036f2f6bSJohn McCall     if (hasAnyOverflow) {
576036f2f6bSJohn McCall       size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
57732ac583dSChris Lattner     } else {
578036f2f6bSJohn McCall       size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
57932ac583dSChris Lattner     }
58032ac583dSChris Lattner 
581036f2f6bSJohn McCall   // Otherwise, we might need to use the overflow intrinsics.
5828ed55a54SJohn McCall   } else {
583f862eb6aSSebastian Redl     // There are up to five conditions we need to test for:
584036f2f6bSJohn McCall     // 1) if isSigned, we need to check whether numElements is negative;
585036f2f6bSJohn McCall     // 2) if numElementsWidth > sizeWidth, we need to check whether
586036f2f6bSJohn McCall     //   numElements is larger than something representable in size_t;
587f862eb6aSSebastian Redl     // 3) if minElements > 0, we need to check whether numElements is smaller
588f862eb6aSSebastian Redl     //    than that.
589f862eb6aSSebastian Redl     // 4) we need to compute
590036f2f6bSJohn McCall     //      sizeWithoutCookie := numElements * typeSizeMultiplier
591036f2f6bSJohn McCall     //    and check whether it overflows; and
592f862eb6aSSebastian Redl     // 5) if we need a cookie, we need to compute
593036f2f6bSJohn McCall     //      size := sizeWithoutCookie + cookieSize
594036f2f6bSJohn McCall     //    and check whether it overflows.
5958ed55a54SJohn McCall 
5968a13c418SCraig Topper     llvm::Value *hasOverflow = nullptr;
5978ed55a54SJohn McCall 
598036f2f6bSJohn McCall     // If numElementsWidth > sizeWidth, then one way or another, we're
599036f2f6bSJohn McCall     // going to have to do a comparison for (2), and this happens to
600036f2f6bSJohn McCall     // take care of (1), too.
601036f2f6bSJohn McCall     if (numElementsWidth > sizeWidth) {
602036f2f6bSJohn McCall       llvm::APInt threshold(numElementsWidth, 1);
603036f2f6bSJohn McCall       threshold <<= sizeWidth;
6048ed55a54SJohn McCall 
605036f2f6bSJohn McCall       llvm::Value *thresholdV
606036f2f6bSJohn McCall         = llvm::ConstantInt::get(numElementsType, threshold);
607036f2f6bSJohn McCall 
608036f2f6bSJohn McCall       hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
609036f2f6bSJohn McCall       numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
610036f2f6bSJohn McCall 
611036f2f6bSJohn McCall     // Otherwise, if we're signed, we want to sext up to size_t.
612036f2f6bSJohn McCall     } else if (isSigned) {
613036f2f6bSJohn McCall       if (numElementsWidth < sizeWidth)
614036f2f6bSJohn McCall         numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
615036f2f6bSJohn McCall 
616036f2f6bSJohn McCall       // If there's a non-1 type size multiplier, then we can do the
617036f2f6bSJohn McCall       // signedness check at the same time as we do the multiply
618036f2f6bSJohn McCall       // because a negative number times anything will cause an
619f862eb6aSSebastian Redl       // unsigned overflow.  Otherwise, we have to do it here. But at least
620f862eb6aSSebastian Redl       // in this case, we can subsume the >= minElements check.
621036f2f6bSJohn McCall       if (typeSizeMultiplier == 1)
622036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
623f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
624036f2f6bSJohn McCall 
625036f2f6bSJohn McCall     // Otherwise, zext up to size_t if necessary.
626036f2f6bSJohn McCall     } else if (numElementsWidth < sizeWidth) {
627036f2f6bSJohn McCall       numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
628036f2f6bSJohn McCall     }
629036f2f6bSJohn McCall 
630036f2f6bSJohn McCall     assert(numElements->getType() == CGF.SizeTy);
631036f2f6bSJohn McCall 
632f862eb6aSSebastian Redl     if (minElements) {
633f862eb6aSSebastian Redl       // Don't allow allocation of fewer elements than we have initializers.
634f862eb6aSSebastian Redl       if (!hasOverflow) {
635f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateICmpULT(numElements,
636f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
637f862eb6aSSebastian Redl       } else if (numElementsWidth > sizeWidth) {
638f862eb6aSSebastian Redl         // The other existing overflow subsumes this check.
639f862eb6aSSebastian Redl         // We do an unsigned comparison, since any signed value < -1 is
640f862eb6aSSebastian Redl         // taken care of either above or below.
641f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateOr(hasOverflow,
642f862eb6aSSebastian Redl                           CGF.Builder.CreateICmpULT(numElements,
643f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements)));
644f862eb6aSSebastian Redl       }
645f862eb6aSSebastian Redl     }
646f862eb6aSSebastian Redl 
647036f2f6bSJohn McCall     size = numElements;
648036f2f6bSJohn McCall 
649036f2f6bSJohn McCall     // Multiply by the type size if necessary.  This multiplier
650036f2f6bSJohn McCall     // includes all the factors for nested arrays.
6518ed55a54SJohn McCall     //
652036f2f6bSJohn McCall     // This step also causes numElements to be scaled up by the
653036f2f6bSJohn McCall     // nested-array factor if necessary.  Overflow on this computation
654036f2f6bSJohn McCall     // can be ignored because the result shouldn't be used if
655036f2f6bSJohn McCall     // allocation fails.
656036f2f6bSJohn McCall     if (typeSizeMultiplier != 1) {
657036f2f6bSJohn McCall       llvm::Value *umul_with_overflow
6588d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
6598ed55a54SJohn McCall 
660036f2f6bSJohn McCall       llvm::Value *tsmV =
661036f2f6bSJohn McCall         llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
662036f2f6bSJohn McCall       llvm::Value *result =
663036f2f6bSJohn McCall         CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
6648ed55a54SJohn McCall 
665036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
666036f2f6bSJohn McCall       if (hasOverflow)
667036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
6688ed55a54SJohn McCall       else
669036f2f6bSJohn McCall         hasOverflow = overflowed;
67059486a2dSAnders Carlsson 
671036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
672036f2f6bSJohn McCall 
673036f2f6bSJohn McCall       // Also scale up numElements by the array size multiplier.
674036f2f6bSJohn McCall       if (arraySizeMultiplier != 1) {
675036f2f6bSJohn McCall         // If the base element type size is 1, then we can re-use the
676036f2f6bSJohn McCall         // multiply we just did.
677036f2f6bSJohn McCall         if (typeSize.isOne()) {
678036f2f6bSJohn McCall           assert(arraySizeMultiplier == typeSizeMultiplier);
679036f2f6bSJohn McCall           numElements = size;
680036f2f6bSJohn McCall 
681036f2f6bSJohn McCall         // Otherwise we need a separate multiply.
682036f2f6bSJohn McCall         } else {
683036f2f6bSJohn McCall           llvm::Value *asmV =
684036f2f6bSJohn McCall             llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
685036f2f6bSJohn McCall           numElements = CGF.Builder.CreateMul(numElements, asmV);
686036f2f6bSJohn McCall         }
687036f2f6bSJohn McCall       }
688036f2f6bSJohn McCall     } else {
689036f2f6bSJohn McCall       // numElements doesn't need to be scaled.
690036f2f6bSJohn McCall       assert(arraySizeMultiplier == 1);
691036f2f6bSJohn McCall     }
692036f2f6bSJohn McCall 
693036f2f6bSJohn McCall     // Add in the cookie size if necessary.
694036f2f6bSJohn McCall     if (cookieSize != 0) {
695036f2f6bSJohn McCall       sizeWithoutCookie = size;
696036f2f6bSJohn McCall 
697036f2f6bSJohn McCall       llvm::Value *uadd_with_overflow
6988d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
699036f2f6bSJohn McCall 
700036f2f6bSJohn McCall       llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
701036f2f6bSJohn McCall       llvm::Value *result =
702036f2f6bSJohn McCall         CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
703036f2f6bSJohn McCall 
704036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
705036f2f6bSJohn McCall       if (hasOverflow)
706036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
707036f2f6bSJohn McCall       else
708036f2f6bSJohn McCall         hasOverflow = overflowed;
709036f2f6bSJohn McCall 
710036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
711036f2f6bSJohn McCall     }
712036f2f6bSJohn McCall 
713036f2f6bSJohn McCall     // If we had any possibility of dynamic overflow, make a select to
714036f2f6bSJohn McCall     // overwrite 'size' with an all-ones value, which should cause
715036f2f6bSJohn McCall     // operator new to throw.
716036f2f6bSJohn McCall     if (hasOverflow)
717036f2f6bSJohn McCall       size = CGF.Builder.CreateSelect(hasOverflow,
718036f2f6bSJohn McCall                                  llvm::Constant::getAllOnesValue(CGF.SizeTy),
719036f2f6bSJohn McCall                                       size);
720036f2f6bSJohn McCall   }
721036f2f6bSJohn McCall 
722036f2f6bSJohn McCall   if (cookieSize == 0)
723036f2f6bSJohn McCall     sizeWithoutCookie = size;
724036f2f6bSJohn McCall   else
725036f2f6bSJohn McCall     assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
726036f2f6bSJohn McCall 
727036f2f6bSJohn McCall   return size;
72859486a2dSAnders Carlsson }
72959486a2dSAnders Carlsson 
730f862eb6aSSebastian Redl static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
731f862eb6aSSebastian Redl                                     QualType AllocType, llvm::Value *NewPtr) {
7321c96bc5dSRichard Smith   // FIXME: Refactor with EmitExprAsInit.
73338cd36dbSEli Friedman   CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
73447fb9508SJohn McCall   switch (CGF.getEvaluationKind(AllocType)) {
73547fb9508SJohn McCall   case TEK_Scalar:
7368a13c418SCraig Topper     CGF.EmitScalarInit(Init, nullptr, CGF.MakeAddrLValue(NewPtr, AllocType,
737a0544d6fSEli Friedman                                                          Alignment),
7381553b190SJohn McCall                        false);
73947fb9508SJohn McCall     return;
74047fb9508SJohn McCall   case TEK_Complex:
74147fb9508SJohn McCall     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
74247fb9508SJohn McCall                                                            Alignment),
74347fb9508SJohn McCall                                   /*isInit*/ true);
74447fb9508SJohn McCall     return;
74547fb9508SJohn McCall   case TEK_Aggregate: {
7467a626f63SJohn McCall     AggValueSlot Slot
747c1d85b93SEli Friedman       = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
7488d6fc958SJohn McCall                               AggValueSlot::IsDestructed,
74946759f4fSJohn McCall                               AggValueSlot::DoesNotNeedGCBarriers,
750615ed1a3SChad Rosier                               AggValueSlot::IsNotAliased);
7517a626f63SJohn McCall     CGF.EmitAggExpr(Init, Slot);
75247fb9508SJohn McCall     return;
7537a626f63SJohn McCall   }
754d5202e09SFariborz Jahanian   }
75547fb9508SJohn McCall   llvm_unreachable("bad evaluation kind");
75647fb9508SJohn McCall }
757d5202e09SFariborz Jahanian 
758d5202e09SFariborz Jahanian void
759d5202e09SFariborz Jahanian CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
76006a67e2cSRichard Smith                                          QualType ElementType,
76106a67e2cSRichard Smith                                          llvm::Value *BeginPtr,
76206a67e2cSRichard Smith                                          llvm::Value *NumElements,
76306a67e2cSRichard Smith                                          llvm::Value *AllocSizeWithoutCookie) {
76406a67e2cSRichard Smith   // If we have a type with trivial initialization and no initializer,
76506a67e2cSRichard Smith   // there's nothing to do.
7666047f07eSSebastian Redl   if (!E->hasInitializer())
76706a67e2cSRichard Smith     return;
768b66b08efSFariborz Jahanian 
76906a67e2cSRichard Smith   llvm::Value *CurPtr = BeginPtr;
770d5202e09SFariborz Jahanian 
77106a67e2cSRichard Smith   unsigned InitListElements = 0;
772f862eb6aSSebastian Redl 
773f862eb6aSSebastian Redl   const Expr *Init = E->getInitializer();
77406a67e2cSRichard Smith   llvm::AllocaInst *EndOfInit = nullptr;
77506a67e2cSRichard Smith   QualType::DestructionKind DtorKind = ElementType.isDestructedType();
77606a67e2cSRichard Smith   EHScopeStack::stable_iterator Cleanup;
77706a67e2cSRichard Smith   llvm::Instruction *CleanupDominator = nullptr;
7781c96bc5dSRichard Smith 
779f862eb6aSSebastian Redl   // If the initializer is an initializer list, first do the explicit elements.
780f862eb6aSSebastian Redl   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
78106a67e2cSRichard Smith     InitListElements = ILE->getNumInits();
782f62290a1SChad Rosier 
7831c96bc5dSRichard Smith     // If this is a multi-dimensional array new, we will initialize multiple
7841c96bc5dSRichard Smith     // elements with each init list element.
7851c96bc5dSRichard Smith     QualType AllocType = E->getAllocatedType();
7861c96bc5dSRichard Smith     if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
7871c96bc5dSRichard Smith             AllocType->getAsArrayTypeUnsafe())) {
78806a67e2cSRichard Smith       unsigned AS = CurPtr->getType()->getPointerAddressSpace();
7891c96bc5dSRichard Smith       llvm::Type *AllocPtrTy = ConvertTypeForMem(AllocType)->getPointerTo(AS);
79006a67e2cSRichard Smith       CurPtr = Builder.CreateBitCast(CurPtr, AllocPtrTy);
79106a67e2cSRichard Smith       InitListElements *= getContext().getConstantArrayElementCount(CAT);
7921c96bc5dSRichard Smith     }
7931c96bc5dSRichard Smith 
79406a67e2cSRichard Smith     // Enter a partial-destruction Cleanup if necessary.
79506a67e2cSRichard Smith     if (needsEHCleanup(DtorKind)) {
79606a67e2cSRichard Smith       // In principle we could tell the Cleanup where we are more
797f62290a1SChad Rosier       // directly, but the control flow can get so varied here that it
798f62290a1SChad Rosier       // would actually be quite complex.  Therefore we go through an
799f62290a1SChad Rosier       // alloca.
80006a67e2cSRichard Smith       EndOfInit = CreateTempAlloca(BeginPtr->getType(), "array.init.end");
80106a67e2cSRichard Smith       CleanupDominator = Builder.CreateStore(BeginPtr, EndOfInit);
80206a67e2cSRichard Smith       pushIrregularPartialArrayCleanup(BeginPtr, EndOfInit, ElementType,
80306a67e2cSRichard Smith                                        getDestroyer(DtorKind));
80406a67e2cSRichard Smith       Cleanup = EHStack.stable_begin();
805f62290a1SChad Rosier     }
806f62290a1SChad Rosier 
807f862eb6aSSebastian Redl     for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
808f62290a1SChad Rosier       // Tell the cleanup that it needs to destroy up to this
809f62290a1SChad Rosier       // element.  TODO: some of these stores can be trivially
810f62290a1SChad Rosier       // observed to be unnecessary.
81106a67e2cSRichard Smith       if (EndOfInit)
81206a67e2cSRichard Smith         Builder.CreateStore(Builder.CreateBitCast(CurPtr, BeginPtr->getType()),
81306a67e2cSRichard Smith                             EndOfInit);
81406a67e2cSRichard Smith       // FIXME: If the last initializer is an incomplete initializer list for
81506a67e2cSRichard Smith       // an array, and we have an array filler, we can fold together the two
81606a67e2cSRichard Smith       // initialization loops.
8171c96bc5dSRichard Smith       StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
81806a67e2cSRichard Smith                               ILE->getInit(i)->getType(), CurPtr);
81906a67e2cSRichard Smith       CurPtr = Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.exp.next");
820f862eb6aSSebastian Redl     }
821f862eb6aSSebastian Redl 
822f862eb6aSSebastian Redl     // The remaining elements are filled with the array filler expression.
823f862eb6aSSebastian Redl     Init = ILE->getArrayFiller();
8241c96bc5dSRichard Smith 
82506a67e2cSRichard Smith     // Extract the initializer for the individual array elements by pulling
82606a67e2cSRichard Smith     // out the array filler from all the nested initializer lists. This avoids
82706a67e2cSRichard Smith     // generating a nested loop for the initialization.
82806a67e2cSRichard Smith     while (Init && Init->getType()->isConstantArrayType()) {
82906a67e2cSRichard Smith       auto *SubILE = dyn_cast<InitListExpr>(Init);
83006a67e2cSRichard Smith       if (!SubILE)
83106a67e2cSRichard Smith         break;
83206a67e2cSRichard Smith       assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
83306a67e2cSRichard Smith       Init = SubILE->getArrayFiller();
834f862eb6aSSebastian Redl     }
835f862eb6aSSebastian Redl 
83606a67e2cSRichard Smith     // Switch back to initializing one base element at a time.
83706a67e2cSRichard Smith     CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr->getType());
838f62290a1SChad Rosier   }
839e6c980c4SChandler Carruth 
84006a67e2cSRichard Smith   // Attempt to perform zero-initialization using memset.
84106a67e2cSRichard Smith   auto TryMemsetInitialization = [&]() -> bool {
84206a67e2cSRichard Smith     // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
84306a67e2cSRichard Smith     // we can initialize with a memset to -1.
84406a67e2cSRichard Smith     if (!CGM.getTypes().isZeroInitializable(ElementType))
84506a67e2cSRichard Smith       return false;
846e6c980c4SChandler Carruth 
84706a67e2cSRichard Smith     // Optimization: since zero initialization will just set the memory
84806a67e2cSRichard Smith     // to all zeroes, generate a single memset to do it in one shot.
84906a67e2cSRichard Smith 
85006a67e2cSRichard Smith     // Subtract out the size of any elements we've already initialized.
85106a67e2cSRichard Smith     auto *RemainingSize = AllocSizeWithoutCookie;
85206a67e2cSRichard Smith     if (InitListElements) {
85306a67e2cSRichard Smith       // We know this can't overflow; we check this when doing the allocation.
85406a67e2cSRichard Smith       auto *InitializedSize = llvm::ConstantInt::get(
85506a67e2cSRichard Smith           RemainingSize->getType(),
85606a67e2cSRichard Smith           getContext().getTypeSizeInChars(ElementType).getQuantity() *
85706a67e2cSRichard Smith               InitListElements);
85806a67e2cSRichard Smith       RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
85999210dc9SJohn McCall     }
860d5202e09SFariborz Jahanian 
86106a67e2cSRichard Smith     // Create the memset.
86206a67e2cSRichard Smith     CharUnits Alignment = getContext().getTypeAlignInChars(ElementType);
86306a67e2cSRichard Smith     Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize,
864705ba07eSKen Dyck                          Alignment.getQuantity(), false);
86506a67e2cSRichard Smith     return true;
86606a67e2cSRichard Smith   };
86705fc5be3SDouglas Gregor 
868454a7cdfSRichard Smith   // If all elements have already been initialized, skip any further
869454a7cdfSRichard Smith   // initialization.
870454a7cdfSRichard Smith   llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
871454a7cdfSRichard Smith   if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
872454a7cdfSRichard Smith     // If there was a Cleanup, deactivate it.
873454a7cdfSRichard Smith     if (CleanupDominator)
874454a7cdfSRichard Smith       DeactivateCleanupBlock(Cleanup, CleanupDominator);
875454a7cdfSRichard Smith     return;
876454a7cdfSRichard Smith   }
877454a7cdfSRichard Smith 
878454a7cdfSRichard Smith   assert(Init && "have trailing elements to initialize but no initializer");
879454a7cdfSRichard Smith 
88006a67e2cSRichard Smith   // If this is a constructor call, try to optimize it out, and failing that
88106a67e2cSRichard Smith   // emit a single loop to initialize all remaining elements.
882454a7cdfSRichard Smith   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
8836047f07eSSebastian Redl     CXXConstructorDecl *Ctor = CCE->getConstructor();
884d153103cSDouglas Gregor     if (Ctor->isTrivial()) {
88505fc5be3SDouglas Gregor       // If new expression did not specify value-initialization, then there
88605fc5be3SDouglas Gregor       // is no initialization.
8876047f07eSSebastian Redl       if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
88805fc5be3SDouglas Gregor         return;
88905fc5be3SDouglas Gregor 
89006a67e2cSRichard Smith       if (TryMemsetInitialization())
8913a202f60SAnders Carlsson         return;
8923a202f60SAnders Carlsson     }
89305fc5be3SDouglas Gregor 
89406a67e2cSRichard Smith     // Store the new Cleanup position for irregular Cleanups.
89506a67e2cSRichard Smith     //
89606a67e2cSRichard Smith     // FIXME: Share this cleanup with the constructor call emission rather than
89706a67e2cSRichard Smith     // having it create a cleanup of its own.
89806a67e2cSRichard Smith     if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
89906a67e2cSRichard Smith 
90006a67e2cSRichard Smith     // Emit a constructor call loop to initialize the remaining elements.
90106a67e2cSRichard Smith     if (InitListElements)
90206a67e2cSRichard Smith       NumElements = Builder.CreateSub(
90306a67e2cSRichard Smith           NumElements,
90406a67e2cSRichard Smith           llvm::ConstantInt::get(NumElements->getType(), InitListElements));
90570b9c01bSAlexey Samsonov     EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
90648ddcf2cSEli Friedman                                CCE->requiresZeroInitialization());
90705fc5be3SDouglas Gregor     return;
9086047f07eSSebastian Redl   }
90906a67e2cSRichard Smith 
91006a67e2cSRichard Smith   // If this is value-initialization, we can usually use memset.
91106a67e2cSRichard Smith   ImplicitValueInitExpr IVIE(ElementType);
912454a7cdfSRichard Smith   if (isa<ImplicitValueInitExpr>(Init)) {
91306a67e2cSRichard Smith     if (TryMemsetInitialization())
91406a67e2cSRichard Smith       return;
91506a67e2cSRichard Smith 
91606a67e2cSRichard Smith     // Switch to an ImplicitValueInitExpr for the element type. This handles
91706a67e2cSRichard Smith     // only one case: multidimensional array new of pointers to members. In
91806a67e2cSRichard Smith     // all other cases, we already have an initializer for the array element.
91906a67e2cSRichard Smith     Init = &IVIE;
92006a67e2cSRichard Smith   }
92106a67e2cSRichard Smith 
92206a67e2cSRichard Smith   // At this point we should have found an initializer for the individual
92306a67e2cSRichard Smith   // elements of the array.
92406a67e2cSRichard Smith   assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
92506a67e2cSRichard Smith          "got wrong type of element to initialize");
92606a67e2cSRichard Smith 
927454a7cdfSRichard Smith   // If we have an empty initializer list, we can usually use memset.
928454a7cdfSRichard Smith   if (auto *ILE = dyn_cast<InitListExpr>(Init))
929454a7cdfSRichard Smith     if (ILE->getNumInits() == 0 && TryMemsetInitialization())
930d5202e09SFariborz Jahanian       return;
93159486a2dSAnders Carlsson 
93206a67e2cSRichard Smith   // Create the loop blocks.
93306a67e2cSRichard Smith   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
93406a67e2cSRichard Smith   llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
93506a67e2cSRichard Smith   llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
93659486a2dSAnders Carlsson 
93706a67e2cSRichard Smith   // Find the end of the array, hoisted out of the loop.
93806a67e2cSRichard Smith   llvm::Value *EndPtr =
93906a67e2cSRichard Smith     Builder.CreateInBoundsGEP(BeginPtr, NumElements, "array.end");
94006a67e2cSRichard Smith 
94106a67e2cSRichard Smith   // If the number of elements isn't constant, we have to now check if there is
94206a67e2cSRichard Smith   // anything left to initialize.
94306a67e2cSRichard Smith   if (!ConstNum) {
94406a67e2cSRichard Smith     llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr, EndPtr,
94506a67e2cSRichard Smith                                                 "array.isempty");
94606a67e2cSRichard Smith     Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
94706a67e2cSRichard Smith   }
94806a67e2cSRichard Smith 
94906a67e2cSRichard Smith   // Enter the loop.
95006a67e2cSRichard Smith   EmitBlock(LoopBB);
95106a67e2cSRichard Smith 
95206a67e2cSRichard Smith   // Set up the current-element phi.
95306a67e2cSRichard Smith   llvm::PHINode *CurPtrPhi =
95406a67e2cSRichard Smith     Builder.CreatePHI(CurPtr->getType(), 2, "array.cur");
95506a67e2cSRichard Smith   CurPtrPhi->addIncoming(CurPtr, EntryBB);
95606a67e2cSRichard Smith   CurPtr = CurPtrPhi;
95706a67e2cSRichard Smith 
95806a67e2cSRichard Smith   // Store the new Cleanup position for irregular Cleanups.
95906a67e2cSRichard Smith   if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
96006a67e2cSRichard Smith 
96106a67e2cSRichard Smith   // Enter a partial-destruction Cleanup if necessary.
96206a67e2cSRichard Smith   if (!CleanupDominator && needsEHCleanup(DtorKind)) {
96306a67e2cSRichard Smith     pushRegularPartialArrayCleanup(BeginPtr, CurPtr, ElementType,
96406a67e2cSRichard Smith                                    getDestroyer(DtorKind));
96506a67e2cSRichard Smith     Cleanup = EHStack.stable_begin();
96606a67e2cSRichard Smith     CleanupDominator = Builder.CreateUnreachable();
96706a67e2cSRichard Smith   }
96806a67e2cSRichard Smith 
96906a67e2cSRichard Smith   // Emit the initializer into this element.
97006a67e2cSRichard Smith   StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
97106a67e2cSRichard Smith 
97206a67e2cSRichard Smith   // Leave the Cleanup if we entered one.
97306a67e2cSRichard Smith   if (CleanupDominator) {
97406a67e2cSRichard Smith     DeactivateCleanupBlock(Cleanup, CleanupDominator);
97506a67e2cSRichard Smith     CleanupDominator->eraseFromParent();
97606a67e2cSRichard Smith   }
97706a67e2cSRichard Smith 
97806a67e2cSRichard Smith   // Advance to the next element by adjusting the pointer type as necessary.
97906a67e2cSRichard Smith   llvm::Value *NextPtr =
98006a67e2cSRichard Smith       Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.next");
98106a67e2cSRichard Smith 
98206a67e2cSRichard Smith   // Check whether we've gotten to the end of the array and, if so,
98306a67e2cSRichard Smith   // exit the loop.
98406a67e2cSRichard Smith   llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
98506a67e2cSRichard Smith   Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
98606a67e2cSRichard Smith   CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
98706a67e2cSRichard Smith 
98806a67e2cSRichard Smith   EmitBlock(ContBB);
98906a67e2cSRichard Smith }
99006a67e2cSRichard Smith 
99106a67e2cSRichard Smith static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
99206a67e2cSRichard Smith                                QualType ElementType,
99306a67e2cSRichard Smith                                llvm::Value *NewPtr,
99406a67e2cSRichard Smith                                llvm::Value *NumElements,
99506a67e2cSRichard Smith                                llvm::Value *AllocSizeWithoutCookie) {
99606a67e2cSRichard Smith   if (E->isArray())
99706a67e2cSRichard Smith     CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements,
99806a67e2cSRichard Smith                                 AllocSizeWithoutCookie);
99906a67e2cSRichard Smith   else if (const Expr *Init = E->getInitializer())
1000f862eb6aSSebastian Redl     StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
100159486a2dSAnders Carlsson }
100259486a2dSAnders Carlsson 
10038d0dc31dSRichard Smith /// Emit a call to an operator new or operator delete function, as implicitly
10048d0dc31dSRichard Smith /// created by new-expressions and delete-expressions.
10058d0dc31dSRichard Smith static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
10068d0dc31dSRichard Smith                                 const FunctionDecl *Callee,
10078d0dc31dSRichard Smith                                 const FunctionProtoType *CalleeType,
10088d0dc31dSRichard Smith                                 const CallArgList &Args) {
10098d0dc31dSRichard Smith   llvm::Instruction *CallOrInvoke;
10101235a8daSRichard Smith   llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
10118d0dc31dSRichard Smith   RValue RV =
10128d0dc31dSRichard Smith       CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(Args, CalleeType),
10131235a8daSRichard Smith                    CalleeAddr, ReturnValueSlot(), Args,
10148d0dc31dSRichard Smith                    Callee, &CallOrInvoke);
10158d0dc31dSRichard Smith 
10168d0dc31dSRichard Smith   /// C++1y [expr.new]p10:
10178d0dc31dSRichard Smith   ///   [In a new-expression,] an implementation is allowed to omit a call
10188d0dc31dSRichard Smith   ///   to a replaceable global allocation function.
10198d0dc31dSRichard Smith   ///
10208d0dc31dSRichard Smith   /// We model such elidable calls with the 'builtin' attribute.
10216956d587SRafael Espindola   llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
10221235a8daSRichard Smith   if (Callee->isReplaceableGlobalAllocationFunction() &&
10236956d587SRafael Espindola       Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
10248d0dc31dSRichard Smith     // FIXME: Add addAttribute to CallSite.
10258d0dc31dSRichard Smith     if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
10268d0dc31dSRichard Smith       CI->addAttribute(llvm::AttributeSet::FunctionIndex,
10278d0dc31dSRichard Smith                        llvm::Attribute::Builtin);
10288d0dc31dSRichard Smith     else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
10298d0dc31dSRichard Smith       II->addAttribute(llvm::AttributeSet::FunctionIndex,
10308d0dc31dSRichard Smith                        llvm::Attribute::Builtin);
10318d0dc31dSRichard Smith     else
10328d0dc31dSRichard Smith       llvm_unreachable("unexpected kind of call instruction");
10338d0dc31dSRichard Smith   }
10348d0dc31dSRichard Smith 
10358d0dc31dSRichard Smith   return RV;
10368d0dc31dSRichard Smith }
10378d0dc31dSRichard Smith 
1038760520bcSRichard Smith RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1039760520bcSRichard Smith                                                  const Expr *Arg,
1040760520bcSRichard Smith                                                  bool IsDelete) {
1041760520bcSRichard Smith   CallArgList Args;
1042760520bcSRichard Smith   const Stmt *ArgS = Arg;
1043760520bcSRichard Smith   EmitCallArgs(Args, *Type->param_type_begin(),
1044760520bcSRichard Smith                ConstExprIterator(&ArgS), ConstExprIterator(&ArgS + 1));
1045760520bcSRichard Smith   // Find the allocation or deallocation function that we're calling.
1046760520bcSRichard Smith   ASTContext &Ctx = getContext();
1047760520bcSRichard Smith   DeclarationName Name = Ctx.DeclarationNames
1048760520bcSRichard Smith       .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1049760520bcSRichard Smith   for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1050599bed75SRichard Smith     if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1051599bed75SRichard Smith       if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1052760520bcSRichard Smith         return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1053760520bcSRichard Smith   llvm_unreachable("predeclared global operator new/delete is missing");
1054760520bcSRichard Smith }
1055760520bcSRichard Smith 
1056824c2f53SJohn McCall namespace {
1057824c2f53SJohn McCall   /// A cleanup to call the given 'operator delete' function upon
1058824c2f53SJohn McCall   /// abnormal exit from a new expression.
1059824c2f53SJohn McCall   class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1060824c2f53SJohn McCall     size_t NumPlacementArgs;
1061824c2f53SJohn McCall     const FunctionDecl *OperatorDelete;
1062824c2f53SJohn McCall     llvm::Value *Ptr;
1063824c2f53SJohn McCall     llvm::Value *AllocSize;
1064824c2f53SJohn McCall 
1065824c2f53SJohn McCall     RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1066824c2f53SJohn McCall 
1067824c2f53SJohn McCall   public:
1068824c2f53SJohn McCall     static size_t getExtraSize(size_t NumPlacementArgs) {
1069824c2f53SJohn McCall       return NumPlacementArgs * sizeof(RValue);
1070824c2f53SJohn McCall     }
1071824c2f53SJohn McCall 
1072824c2f53SJohn McCall     CallDeleteDuringNew(size_t NumPlacementArgs,
1073824c2f53SJohn McCall                         const FunctionDecl *OperatorDelete,
1074824c2f53SJohn McCall                         llvm::Value *Ptr,
1075824c2f53SJohn McCall                         llvm::Value *AllocSize)
1076824c2f53SJohn McCall       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1077824c2f53SJohn McCall         Ptr(Ptr), AllocSize(AllocSize) {}
1078824c2f53SJohn McCall 
1079824c2f53SJohn McCall     void setPlacementArg(unsigned I, RValue Arg) {
1080824c2f53SJohn McCall       assert(I < NumPlacementArgs && "index out of range");
1081824c2f53SJohn McCall       getPlacementArgs()[I] = Arg;
1082824c2f53SJohn McCall     }
1083824c2f53SJohn McCall 
10844f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
1085824c2f53SJohn McCall       const FunctionProtoType *FPT
1086824c2f53SJohn McCall         = OperatorDelete->getType()->getAs<FunctionProtoType>();
10879cacbabdSAlp Toker       assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
10889cacbabdSAlp Toker              (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
1089824c2f53SJohn McCall 
1090824c2f53SJohn McCall       CallArgList DeleteArgs;
1091824c2f53SJohn McCall 
1092824c2f53SJohn McCall       // The first argument is always a void*.
10939cacbabdSAlp Toker       FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
109443dca6a8SEli Friedman       DeleteArgs.add(RValue::get(Ptr), *AI++);
1095824c2f53SJohn McCall 
1096824c2f53SJohn McCall       // A member 'operator delete' can take an extra 'size_t' argument.
10979cacbabdSAlp Toker       if (FPT->getNumParams() == NumPlacementArgs + 2)
109843dca6a8SEli Friedman         DeleteArgs.add(RValue::get(AllocSize), *AI++);
1099824c2f53SJohn McCall 
1100824c2f53SJohn McCall       // Pass the rest of the arguments, which must match exactly.
1101824c2f53SJohn McCall       for (unsigned I = 0; I != NumPlacementArgs; ++I)
110243dca6a8SEli Friedman         DeleteArgs.add(getPlacementArgs()[I], *AI++);
1103824c2f53SJohn McCall 
1104824c2f53SJohn McCall       // Call 'operator delete'.
11058d0dc31dSRichard Smith       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1106824c2f53SJohn McCall     }
1107824c2f53SJohn McCall   };
11087f9c92a9SJohn McCall 
11097f9c92a9SJohn McCall   /// A cleanup to call the given 'operator delete' function upon
11107f9c92a9SJohn McCall   /// abnormal exit from a new expression when the new expression is
11117f9c92a9SJohn McCall   /// conditional.
11127f9c92a9SJohn McCall   class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
11137f9c92a9SJohn McCall     size_t NumPlacementArgs;
11147f9c92a9SJohn McCall     const FunctionDecl *OperatorDelete;
1115cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type Ptr;
1116cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type AllocSize;
11177f9c92a9SJohn McCall 
1118cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type *getPlacementArgs() {
1119cb5f77f0SJohn McCall       return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
11207f9c92a9SJohn McCall     }
11217f9c92a9SJohn McCall 
11227f9c92a9SJohn McCall   public:
11237f9c92a9SJohn McCall     static size_t getExtraSize(size_t NumPlacementArgs) {
1124cb5f77f0SJohn McCall       return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
11257f9c92a9SJohn McCall     }
11267f9c92a9SJohn McCall 
11277f9c92a9SJohn McCall     CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
11287f9c92a9SJohn McCall                                    const FunctionDecl *OperatorDelete,
1129cb5f77f0SJohn McCall                                    DominatingValue<RValue>::saved_type Ptr,
1130cb5f77f0SJohn McCall                               DominatingValue<RValue>::saved_type AllocSize)
11317f9c92a9SJohn McCall       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
11327f9c92a9SJohn McCall         Ptr(Ptr), AllocSize(AllocSize) {}
11337f9c92a9SJohn McCall 
1134cb5f77f0SJohn McCall     void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
11357f9c92a9SJohn McCall       assert(I < NumPlacementArgs && "index out of range");
11367f9c92a9SJohn McCall       getPlacementArgs()[I] = Arg;
11377f9c92a9SJohn McCall     }
11387f9c92a9SJohn McCall 
11394f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
11407f9c92a9SJohn McCall       const FunctionProtoType *FPT
11417f9c92a9SJohn McCall         = OperatorDelete->getType()->getAs<FunctionProtoType>();
11429cacbabdSAlp Toker       assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
11439cacbabdSAlp Toker              (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
11447f9c92a9SJohn McCall 
11457f9c92a9SJohn McCall       CallArgList DeleteArgs;
11467f9c92a9SJohn McCall 
11477f9c92a9SJohn McCall       // The first argument is always a void*.
11489cacbabdSAlp Toker       FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
114943dca6a8SEli Friedman       DeleteArgs.add(Ptr.restore(CGF), *AI++);
11507f9c92a9SJohn McCall 
11517f9c92a9SJohn McCall       // A member 'operator delete' can take an extra 'size_t' argument.
11529cacbabdSAlp Toker       if (FPT->getNumParams() == NumPlacementArgs + 2) {
1153cb5f77f0SJohn McCall         RValue RV = AllocSize.restore(CGF);
115443dca6a8SEli Friedman         DeleteArgs.add(RV, *AI++);
11557f9c92a9SJohn McCall       }
11567f9c92a9SJohn McCall 
11577f9c92a9SJohn McCall       // Pass the rest of the arguments, which must match exactly.
11587f9c92a9SJohn McCall       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1159cb5f77f0SJohn McCall         RValue RV = getPlacementArgs()[I].restore(CGF);
116043dca6a8SEli Friedman         DeleteArgs.add(RV, *AI++);
11617f9c92a9SJohn McCall       }
11627f9c92a9SJohn McCall 
11637f9c92a9SJohn McCall       // Call 'operator delete'.
11648d0dc31dSRichard Smith       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
11657f9c92a9SJohn McCall     }
11667f9c92a9SJohn McCall   };
11677f9c92a9SJohn McCall }
11687f9c92a9SJohn McCall 
11697f9c92a9SJohn McCall /// Enter a cleanup to call 'operator delete' if the initializer in a
11707f9c92a9SJohn McCall /// new-expression throws.
11717f9c92a9SJohn McCall static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
11727f9c92a9SJohn McCall                                   const CXXNewExpr *E,
11737f9c92a9SJohn McCall                                   llvm::Value *NewPtr,
11747f9c92a9SJohn McCall                                   llvm::Value *AllocSize,
11757f9c92a9SJohn McCall                                   const CallArgList &NewArgs) {
11767f9c92a9SJohn McCall   // If we're not inside a conditional branch, then the cleanup will
11777f9c92a9SJohn McCall   // dominate and we can do the easier (and more efficient) thing.
11787f9c92a9SJohn McCall   if (!CGF.isInConditionalBranch()) {
11797f9c92a9SJohn McCall     CallDeleteDuringNew *Cleanup = CGF.EHStack
11807f9c92a9SJohn McCall       .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
11817f9c92a9SJohn McCall                                                  E->getNumPlacementArgs(),
11827f9c92a9SJohn McCall                                                  E->getOperatorDelete(),
11837f9c92a9SJohn McCall                                                  NewPtr, AllocSize);
11847f9c92a9SJohn McCall     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1185f4258eb4SEli Friedman       Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
11867f9c92a9SJohn McCall 
11877f9c92a9SJohn McCall     return;
11887f9c92a9SJohn McCall   }
11897f9c92a9SJohn McCall 
11907f9c92a9SJohn McCall   // Otherwise, we need to save all this stuff.
1191cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedNewPtr =
1192cb5f77f0SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1193cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedAllocSize =
1194cb5f77f0SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
11957f9c92a9SJohn McCall 
11967f9c92a9SJohn McCall   CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
1197f4beacd0SJohn McCall     .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
11987f9c92a9SJohn McCall                                                  E->getNumPlacementArgs(),
11997f9c92a9SJohn McCall                                                  E->getOperatorDelete(),
12007f9c92a9SJohn McCall                                                  SavedNewPtr,
12017f9c92a9SJohn McCall                                                  SavedAllocSize);
12027f9c92a9SJohn McCall   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1203cb5f77f0SJohn McCall     Cleanup->setPlacementArg(I,
1204f4258eb4SEli Friedman                      DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
12057f9c92a9SJohn McCall 
1206f4beacd0SJohn McCall   CGF.initFullExprCleanup();
1207824c2f53SJohn McCall }
1208824c2f53SJohn McCall 
120959486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
121075f9498aSJohn McCall   // The element type being allocated.
121175f9498aSJohn McCall   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
12128ed55a54SJohn McCall 
121375f9498aSJohn McCall   // 1. Build a call to the allocation function.
121475f9498aSJohn McCall   FunctionDecl *allocator = E->getOperatorNew();
121575f9498aSJohn McCall   const FunctionProtoType *allocatorType =
121675f9498aSJohn McCall     allocator->getType()->castAs<FunctionProtoType>();
121759486a2dSAnders Carlsson 
121875f9498aSJohn McCall   CallArgList allocatorArgs;
121959486a2dSAnders Carlsson 
122059486a2dSAnders Carlsson   // The allocation size is the first argument.
122175f9498aSJohn McCall   QualType sizeType = getContext().getSizeType();
122259486a2dSAnders Carlsson 
1223f862eb6aSSebastian Redl   // If there is a brace-initializer, cannot allocate fewer elements than inits.
1224f862eb6aSSebastian Redl   unsigned minElements = 0;
1225f862eb6aSSebastian Redl   if (E->isArray() && E->hasInitializer()) {
1226f862eb6aSSebastian Redl     if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1227f862eb6aSSebastian Redl       minElements = ILE->getNumInits();
1228f862eb6aSSebastian Redl   }
1229f862eb6aSSebastian Redl 
12308a13c418SCraig Topper   llvm::Value *numElements = nullptr;
12318a13c418SCraig Topper   llvm::Value *allocSizeWithoutCookie = nullptr;
123275f9498aSJohn McCall   llvm::Value *allocSize =
1233f862eb6aSSebastian Redl     EmitCXXNewAllocSize(*this, E, minElements, numElements,
1234f862eb6aSSebastian Redl                         allocSizeWithoutCookie);
123559486a2dSAnders Carlsson 
123643dca6a8SEli Friedman   allocatorArgs.add(RValue::get(allocSize), sizeType);
123759486a2dSAnders Carlsson 
123859486a2dSAnders Carlsson   // We start at 1 here because the first argument (the allocation size)
123959486a2dSAnders Carlsson   // has already been emitted.
1240739756c0SReid Kleckner   EmitCallArgs(allocatorArgs, allocatorType->isVariadic(),
12419cacbabdSAlp Toker                allocatorType->param_type_begin() + 1,
12429cacbabdSAlp Toker                allocatorType->param_type_end(), E->placement_arg_begin(),
1243739756c0SReid Kleckner                E->placement_arg_end());
124459486a2dSAnders Carlsson 
12457ec4b434SJohn McCall   // Emit the allocation call.  If the allocator is a global placement
12467ec4b434SJohn McCall   // operator, just "inline" it directly.
12477ec4b434SJohn McCall   RValue RV;
12487ec4b434SJohn McCall   if (allocator->isReservedGlobalPlacementOperator()) {
12497ec4b434SJohn McCall     assert(allocatorArgs.size() == 2);
12507ec4b434SJohn McCall     RV = allocatorArgs[1].RV;
12517ec4b434SJohn McCall     // TODO: kill any unnecessary computations done for the size
12527ec4b434SJohn McCall     // argument.
12537ec4b434SJohn McCall   } else {
12548d0dc31dSRichard Smith     RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
12557ec4b434SJohn McCall   }
125659486a2dSAnders Carlsson 
125775f9498aSJohn McCall   // Emit a null check on the allocation result if the allocation
125875f9498aSJohn McCall   // function is allowed to return null (because it has a non-throwing
125975f9498aSJohn McCall   // exception spec; for this part, we inline
126075f9498aSJohn McCall   // CXXNewExpr::shouldNullCheckAllocation()) and we have an
126175f9498aSJohn McCall   // interesting initializer.
126231ad754cSSebastian Redl   bool nullCheck = allocatorType->isNothrow(getContext()) &&
12636047f07eSSebastian Redl     (!allocType.isPODType(getContext()) || E->hasInitializer());
126459486a2dSAnders Carlsson 
12658a13c418SCraig Topper   llvm::BasicBlock *nullCheckBB = nullptr;
12668a13c418SCraig Topper   llvm::BasicBlock *contBB = nullptr;
126759486a2dSAnders Carlsson 
126875f9498aSJohn McCall   llvm::Value *allocation = RV.getScalarVal();
1269ea2fea2aSMicah Villmow   unsigned AS = allocation->getType()->getPointerAddressSpace();
127059486a2dSAnders Carlsson 
1271f7dcf320SJohn McCall   // The null-check means that the initializer is conditionally
1272f7dcf320SJohn McCall   // evaluated.
1273f7dcf320SJohn McCall   ConditionalEvaluation conditional(*this);
1274f7dcf320SJohn McCall 
127575f9498aSJohn McCall   if (nullCheck) {
1276f7dcf320SJohn McCall     conditional.begin(*this);
127775f9498aSJohn McCall 
127875f9498aSJohn McCall     nullCheckBB = Builder.GetInsertBlock();
127975f9498aSJohn McCall     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
128075f9498aSJohn McCall     contBB = createBasicBlock("new.cont");
128175f9498aSJohn McCall 
128275f9498aSJohn McCall     llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
128375f9498aSJohn McCall     Builder.CreateCondBr(isNull, contBB, notNullBB);
128475f9498aSJohn McCall     EmitBlock(notNullBB);
128559486a2dSAnders Carlsson   }
128659486a2dSAnders Carlsson 
1287824c2f53SJohn McCall   // If there's an operator delete, enter a cleanup to call it if an
1288824c2f53SJohn McCall   // exception is thrown.
128975f9498aSJohn McCall   EHScopeStack::stable_iterator operatorDeleteCleanup;
12908a13c418SCraig Topper   llvm::Instruction *cleanupDominator = nullptr;
12917ec4b434SJohn McCall   if (E->getOperatorDelete() &&
12927ec4b434SJohn McCall       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
129375f9498aSJohn McCall     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
129475f9498aSJohn McCall     operatorDeleteCleanup = EHStack.stable_begin();
1295f4beacd0SJohn McCall     cleanupDominator = Builder.CreateUnreachable();
1296824c2f53SJohn McCall   }
1297824c2f53SJohn McCall 
1298cf9b1f65SEli Friedman   assert((allocSize == allocSizeWithoutCookie) ==
1299cf9b1f65SEli Friedman          CalculateCookiePadding(*this, E).isZero());
1300cf9b1f65SEli Friedman   if (allocSize != allocSizeWithoutCookie) {
1301cf9b1f65SEli Friedman     assert(E->isArray());
1302cf9b1f65SEli Friedman     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1303cf9b1f65SEli Friedman                                                        numElements,
1304cf9b1f65SEli Friedman                                                        E, allocType);
1305cf9b1f65SEli Friedman   }
1306cf9b1f65SEli Friedman 
13072192fe50SChris Lattner   llvm::Type *elementPtrTy
130875f9498aSJohn McCall     = ConvertTypeForMem(allocType)->getPointerTo(AS);
130975f9498aSJohn McCall   llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
1310824c2f53SJohn McCall 
131199210dc9SJohn McCall   EmitNewInitializer(*this, E, allocType, result, numElements,
131299210dc9SJohn McCall                      allocSizeWithoutCookie);
13138ed55a54SJohn McCall   if (E->isArray()) {
13148ed55a54SJohn McCall     // NewPtr is a pointer to the base element type.  If we're
13158ed55a54SJohn McCall     // allocating an array of arrays, we'll need to cast back to the
13168ed55a54SJohn McCall     // array pointer type.
13172192fe50SChris Lattner     llvm::Type *resultType = ConvertTypeForMem(E->getType());
131875f9498aSJohn McCall     if (result->getType() != resultType)
131975f9498aSJohn McCall       result = Builder.CreateBitCast(result, resultType);
132047b4629bSFariborz Jahanian   }
132159486a2dSAnders Carlsson 
1322824c2f53SJohn McCall   // Deactivate the 'operator delete' cleanup if we finished
1323824c2f53SJohn McCall   // initialization.
1324f4beacd0SJohn McCall   if (operatorDeleteCleanup.isValid()) {
1325f4beacd0SJohn McCall     DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1326f4beacd0SJohn McCall     cleanupDominator->eraseFromParent();
1327f4beacd0SJohn McCall   }
1328824c2f53SJohn McCall 
132975f9498aSJohn McCall   if (nullCheck) {
1330f7dcf320SJohn McCall     conditional.end(*this);
1331f7dcf320SJohn McCall 
133275f9498aSJohn McCall     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
133375f9498aSJohn McCall     EmitBlock(contBB);
133459486a2dSAnders Carlsson 
133520c0f02cSJay Foad     llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
133675f9498aSJohn McCall     PHI->addIncoming(result, notNullBB);
133775f9498aSJohn McCall     PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
133875f9498aSJohn McCall                      nullCheckBB);
133959486a2dSAnders Carlsson 
134075f9498aSJohn McCall     result = PHI;
134159486a2dSAnders Carlsson   }
134259486a2dSAnders Carlsson 
134375f9498aSJohn McCall   return result;
134459486a2dSAnders Carlsson }
134559486a2dSAnders Carlsson 
134659486a2dSAnders Carlsson void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
134759486a2dSAnders Carlsson                                      llvm::Value *Ptr,
134859486a2dSAnders Carlsson                                      QualType DeleteTy) {
13498ed55a54SJohn McCall   assert(DeleteFD->getOverloadedOperator() == OO_Delete);
13508ed55a54SJohn McCall 
135159486a2dSAnders Carlsson   const FunctionProtoType *DeleteFTy =
135259486a2dSAnders Carlsson     DeleteFD->getType()->getAs<FunctionProtoType>();
135359486a2dSAnders Carlsson 
135459486a2dSAnders Carlsson   CallArgList DeleteArgs;
135559486a2dSAnders Carlsson 
135621122cf6SAnders Carlsson   // Check if we need to pass the size to the delete operator.
13578a13c418SCraig Topper   llvm::Value *Size = nullptr;
135821122cf6SAnders Carlsson   QualType SizeTy;
13599cacbabdSAlp Toker   if (DeleteFTy->getNumParams() == 2) {
13609cacbabdSAlp Toker     SizeTy = DeleteFTy->getParamType(1);
13617df3cbebSKen Dyck     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
13627df3cbebSKen Dyck     Size = llvm::ConstantInt::get(ConvertType(SizeTy),
13637df3cbebSKen Dyck                                   DeleteTypeSize.getQuantity());
136421122cf6SAnders Carlsson   }
136521122cf6SAnders Carlsson 
13669cacbabdSAlp Toker   QualType ArgTy = DeleteFTy->getParamType(0);
136759486a2dSAnders Carlsson   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
136843dca6a8SEli Friedman   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
136959486a2dSAnders Carlsson 
137021122cf6SAnders Carlsson   if (Size)
137143dca6a8SEli Friedman     DeleteArgs.add(RValue::get(Size), SizeTy);
137259486a2dSAnders Carlsson 
137359486a2dSAnders Carlsson   // Emit the call to delete.
13748d0dc31dSRichard Smith   EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
137559486a2dSAnders Carlsson }
137659486a2dSAnders Carlsson 
13778ed55a54SJohn McCall namespace {
13788ed55a54SJohn McCall   /// Calls the given 'operator delete' on a single object.
13798ed55a54SJohn McCall   struct CallObjectDelete : EHScopeStack::Cleanup {
13808ed55a54SJohn McCall     llvm::Value *Ptr;
13818ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
13828ed55a54SJohn McCall     QualType ElementType;
13838ed55a54SJohn McCall 
13848ed55a54SJohn McCall     CallObjectDelete(llvm::Value *Ptr,
13858ed55a54SJohn McCall                      const FunctionDecl *OperatorDelete,
13868ed55a54SJohn McCall                      QualType ElementType)
13878ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
13888ed55a54SJohn McCall 
13894f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
13908ed55a54SJohn McCall       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
13918ed55a54SJohn McCall     }
13928ed55a54SJohn McCall   };
13938ed55a54SJohn McCall }
13948ed55a54SJohn McCall 
13958ed55a54SJohn McCall /// Emit the code for deleting a single object.
13968ed55a54SJohn McCall static void EmitObjectDelete(CodeGenFunction &CGF,
13978ed55a54SJohn McCall                              const FunctionDecl *OperatorDelete,
13988ed55a54SJohn McCall                              llvm::Value *Ptr,
13991c2e20d7SDouglas Gregor                              QualType ElementType,
14001c2e20d7SDouglas Gregor                              bool UseGlobalDelete) {
14018ed55a54SJohn McCall   // Find the destructor for the type, if applicable.  If the
14028ed55a54SJohn McCall   // destructor is virtual, we'll just emit the vcall and return.
14038a13c418SCraig Topper   const CXXDestructorDecl *Dtor = nullptr;
14048ed55a54SJohn McCall   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
14058ed55a54SJohn McCall     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1406b23533dbSEli Friedman     if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
14078ed55a54SJohn McCall       Dtor = RD->getDestructor();
14088ed55a54SJohn McCall 
14098ed55a54SJohn McCall       if (Dtor->isVirtual()) {
14101c2e20d7SDouglas Gregor         if (UseGlobalDelete) {
14111c2e20d7SDouglas Gregor           // If we're supposed to call the global delete, make sure we do so
14121c2e20d7SDouglas Gregor           // even if the destructor throws.
141382fb8920SJohn McCall 
141482fb8920SJohn McCall           // Derive the complete-object pointer, which is what we need
141582fb8920SJohn McCall           // to pass to the deallocation function.
141682fb8920SJohn McCall           llvm::Value *completePtr =
141782fb8920SJohn McCall             CGF.CGM.getCXXABI().adjustToCompleteObject(CGF, Ptr, ElementType);
141882fb8920SJohn McCall 
14191c2e20d7SDouglas Gregor           CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
142082fb8920SJohn McCall                                                     completePtr, OperatorDelete,
14211c2e20d7SDouglas Gregor                                                     ElementType);
14221c2e20d7SDouglas Gregor         }
14231c2e20d7SDouglas Gregor 
1424*a5bf76bdSAlexey Samsonov         // FIXME: Provide a source location here even though there's no
1425*a5bf76bdSAlexey Samsonov         // CXXMemberCallExpr for dtor call.
1426d619711cSTimur Iskhodzhanov         CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
1427*a5bf76bdSAlexey Samsonov         CGF.CGM.getCXXABI().EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr,
1428*a5bf76bdSAlexey Samsonov                                                       nullptr);
14298ed55a54SJohn McCall 
14301c2e20d7SDouglas Gregor         if (UseGlobalDelete) {
14311c2e20d7SDouglas Gregor           CGF.PopCleanupBlock();
14321c2e20d7SDouglas Gregor         }
14331c2e20d7SDouglas Gregor 
14348ed55a54SJohn McCall         return;
14358ed55a54SJohn McCall       }
14368ed55a54SJohn McCall     }
14378ed55a54SJohn McCall   }
14388ed55a54SJohn McCall 
14398ed55a54SJohn McCall   // Make sure that we call delete even if the dtor throws.
1440e4df6c8dSJohn McCall   // This doesn't have to a conditional cleanup because we're going
1441e4df6c8dSJohn McCall   // to pop it off in a second.
14428ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
14438ed55a54SJohn McCall                                             Ptr, OperatorDelete, ElementType);
14448ed55a54SJohn McCall 
14458ed55a54SJohn McCall   if (Dtor)
14468ed55a54SJohn McCall     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
144761535005SDouglas Gregor                               /*ForVirtualBase=*/false,
144861535005SDouglas Gregor                               /*Delegating=*/false,
144961535005SDouglas Gregor                               Ptr);
1450bbafb8a7SDavid Blaikie   else if (CGF.getLangOpts().ObjCAutoRefCount &&
145131168b07SJohn McCall            ElementType->isObjCLifetimeType()) {
145231168b07SJohn McCall     switch (ElementType.getObjCLifetime()) {
145331168b07SJohn McCall     case Qualifiers::OCL_None:
145431168b07SJohn McCall     case Qualifiers::OCL_ExplicitNone:
145531168b07SJohn McCall     case Qualifiers::OCL_Autoreleasing:
145631168b07SJohn McCall       break;
145731168b07SJohn McCall 
145831168b07SJohn McCall     case Qualifiers::OCL_Strong: {
145931168b07SJohn McCall       // Load the pointer value.
146031168b07SJohn McCall       llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
146131168b07SJohn McCall                                              ElementType.isVolatileQualified());
146231168b07SJohn McCall 
1463cdda29c9SJohn McCall       CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
146431168b07SJohn McCall       break;
146531168b07SJohn McCall     }
146631168b07SJohn McCall 
146731168b07SJohn McCall     case Qualifiers::OCL_Weak:
146831168b07SJohn McCall       CGF.EmitARCDestroyWeak(Ptr);
146931168b07SJohn McCall       break;
147031168b07SJohn McCall     }
147131168b07SJohn McCall   }
14728ed55a54SJohn McCall 
14738ed55a54SJohn McCall   CGF.PopCleanupBlock();
14748ed55a54SJohn McCall }
14758ed55a54SJohn McCall 
14768ed55a54SJohn McCall namespace {
14778ed55a54SJohn McCall   /// Calls the given 'operator delete' on an array of objects.
14788ed55a54SJohn McCall   struct CallArrayDelete : EHScopeStack::Cleanup {
14798ed55a54SJohn McCall     llvm::Value *Ptr;
14808ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
14818ed55a54SJohn McCall     llvm::Value *NumElements;
14828ed55a54SJohn McCall     QualType ElementType;
14838ed55a54SJohn McCall     CharUnits CookieSize;
14848ed55a54SJohn McCall 
14858ed55a54SJohn McCall     CallArrayDelete(llvm::Value *Ptr,
14868ed55a54SJohn McCall                     const FunctionDecl *OperatorDelete,
14878ed55a54SJohn McCall                     llvm::Value *NumElements,
14888ed55a54SJohn McCall                     QualType ElementType,
14898ed55a54SJohn McCall                     CharUnits CookieSize)
14908ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
14918ed55a54SJohn McCall         ElementType(ElementType), CookieSize(CookieSize) {}
14928ed55a54SJohn McCall 
14934f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
14948ed55a54SJohn McCall       const FunctionProtoType *DeleteFTy =
14958ed55a54SJohn McCall         OperatorDelete->getType()->getAs<FunctionProtoType>();
14969cacbabdSAlp Toker       assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
14978ed55a54SJohn McCall 
14988ed55a54SJohn McCall       CallArgList Args;
14998ed55a54SJohn McCall 
15008ed55a54SJohn McCall       // Pass the pointer as the first argument.
15019cacbabdSAlp Toker       QualType VoidPtrTy = DeleteFTy->getParamType(0);
15028ed55a54SJohn McCall       llvm::Value *DeletePtr
15038ed55a54SJohn McCall         = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
150443dca6a8SEli Friedman       Args.add(RValue::get(DeletePtr), VoidPtrTy);
15058ed55a54SJohn McCall 
15068ed55a54SJohn McCall       // Pass the original requested size as the second argument.
15079cacbabdSAlp Toker       if (DeleteFTy->getNumParams() == 2) {
15089cacbabdSAlp Toker         QualType size_t = DeleteFTy->getParamType(1);
15092192fe50SChris Lattner         llvm::IntegerType *SizeTy
15108ed55a54SJohn McCall           = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
15118ed55a54SJohn McCall 
15128ed55a54SJohn McCall         CharUnits ElementTypeSize =
15138ed55a54SJohn McCall           CGF.CGM.getContext().getTypeSizeInChars(ElementType);
15148ed55a54SJohn McCall 
15158ed55a54SJohn McCall         // The size of an element, multiplied by the number of elements.
15168ed55a54SJohn McCall         llvm::Value *Size
15178ed55a54SJohn McCall           = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
15188ed55a54SJohn McCall         Size = CGF.Builder.CreateMul(Size, NumElements);
15198ed55a54SJohn McCall 
15208ed55a54SJohn McCall         // Plus the size of the cookie if applicable.
15218ed55a54SJohn McCall         if (!CookieSize.isZero()) {
15228ed55a54SJohn McCall           llvm::Value *CookieSizeV
15238ed55a54SJohn McCall             = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
15248ed55a54SJohn McCall           Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
15258ed55a54SJohn McCall         }
15268ed55a54SJohn McCall 
152743dca6a8SEli Friedman         Args.add(RValue::get(Size), size_t);
15288ed55a54SJohn McCall       }
15298ed55a54SJohn McCall 
15308ed55a54SJohn McCall       // Emit the call to delete.
15318d0dc31dSRichard Smith       EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
15328ed55a54SJohn McCall     }
15338ed55a54SJohn McCall   };
15348ed55a54SJohn McCall }
15358ed55a54SJohn McCall 
15368ed55a54SJohn McCall /// Emit the code for deleting an array of objects.
15378ed55a54SJohn McCall static void EmitArrayDelete(CodeGenFunction &CGF,
1538284c48ffSJohn McCall                             const CXXDeleteExpr *E,
1539ca2c56f2SJohn McCall                             llvm::Value *deletedPtr,
1540ca2c56f2SJohn McCall                             QualType elementType) {
15418a13c418SCraig Topper   llvm::Value *numElements = nullptr;
15428a13c418SCraig Topper   llvm::Value *allocatedPtr = nullptr;
1543ca2c56f2SJohn McCall   CharUnits cookieSize;
1544ca2c56f2SJohn McCall   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1545ca2c56f2SJohn McCall                                       numElements, allocatedPtr, cookieSize);
15468ed55a54SJohn McCall 
1547ca2c56f2SJohn McCall   assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
15488ed55a54SJohn McCall 
15498ed55a54SJohn McCall   // Make sure that we call delete even if one of the dtors throws.
1550ca2c56f2SJohn McCall   const FunctionDecl *operatorDelete = E->getOperatorDelete();
15518ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1552ca2c56f2SJohn McCall                                            allocatedPtr, operatorDelete,
1553ca2c56f2SJohn McCall                                            numElements, elementType,
1554ca2c56f2SJohn McCall                                            cookieSize);
15558ed55a54SJohn McCall 
1556ca2c56f2SJohn McCall   // Destroy the elements.
1557ca2c56f2SJohn McCall   if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1558ca2c56f2SJohn McCall     assert(numElements && "no element count for a type with a destructor!");
155931168b07SJohn McCall 
1560ca2c56f2SJohn McCall     llvm::Value *arrayEnd =
1561ca2c56f2SJohn McCall       CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
156297eab0a2SJohn McCall 
156397eab0a2SJohn McCall     // Note that it is legal to allocate a zero-length array, and we
156497eab0a2SJohn McCall     // can never fold the check away because the length should always
156597eab0a2SJohn McCall     // come from a cookie.
1566ca2c56f2SJohn McCall     CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1567ca2c56f2SJohn McCall                          CGF.getDestroyer(dtorKind),
156897eab0a2SJohn McCall                          /*checkZeroLength*/ true,
1569ca2c56f2SJohn McCall                          CGF.needsEHCleanup(dtorKind));
15708ed55a54SJohn McCall   }
15718ed55a54SJohn McCall 
1572ca2c56f2SJohn McCall   // Pop the cleanup block.
15738ed55a54SJohn McCall   CGF.PopCleanupBlock();
15748ed55a54SJohn McCall }
15758ed55a54SJohn McCall 
157659486a2dSAnders Carlsson void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
157759486a2dSAnders Carlsson   const Expr *Arg = E->getArgument();
157859486a2dSAnders Carlsson   llvm::Value *Ptr = EmitScalarExpr(Arg);
157959486a2dSAnders Carlsson 
158059486a2dSAnders Carlsson   // Null check the pointer.
158159486a2dSAnders Carlsson   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
158259486a2dSAnders Carlsson   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
158359486a2dSAnders Carlsson 
158498981b10SAnders Carlsson   llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
158559486a2dSAnders Carlsson 
158659486a2dSAnders Carlsson   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
158759486a2dSAnders Carlsson   EmitBlock(DeleteNotNull);
158859486a2dSAnders Carlsson 
15898ed55a54SJohn McCall   // We might be deleting a pointer to array.  If so, GEP down to the
15908ed55a54SJohn McCall   // first non-array element.
15918ed55a54SJohn McCall   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
15928ed55a54SJohn McCall   QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
15938ed55a54SJohn McCall   if (DeleteTy->isConstantArrayType()) {
15948ed55a54SJohn McCall     llvm::Value *Zero = Builder.getInt32(0);
15950e62c1ccSChris Lattner     SmallVector<llvm::Value*,8> GEP;
159659486a2dSAnders Carlsson 
15978ed55a54SJohn McCall     GEP.push_back(Zero); // point at the outermost array
15988ed55a54SJohn McCall 
15998ed55a54SJohn McCall     // For each layer of array type we're pointing at:
16008ed55a54SJohn McCall     while (const ConstantArrayType *Arr
16018ed55a54SJohn McCall              = getContext().getAsConstantArrayType(DeleteTy)) {
16028ed55a54SJohn McCall       // 1. Unpeel the array type.
16038ed55a54SJohn McCall       DeleteTy = Arr->getElementType();
16048ed55a54SJohn McCall 
16058ed55a54SJohn McCall       // 2. GEP to the first element of the array.
16068ed55a54SJohn McCall       GEP.push_back(Zero);
16078ed55a54SJohn McCall     }
16088ed55a54SJohn McCall 
1609040dd82fSJay Foad     Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
16108ed55a54SJohn McCall   }
16118ed55a54SJohn McCall 
161204f36218SDouglas Gregor   assert(ConvertTypeForMem(DeleteTy) ==
161304f36218SDouglas Gregor          cast<llvm::PointerType>(Ptr->getType())->getElementType());
16148ed55a54SJohn McCall 
161559486a2dSAnders Carlsson   if (E->isArrayForm()) {
1616284c48ffSJohn McCall     EmitArrayDelete(*this, E, Ptr, DeleteTy);
16178ed55a54SJohn McCall   } else {
16181c2e20d7SDouglas Gregor     EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy,
16191c2e20d7SDouglas Gregor                      E->isGlobalDelete());
162059486a2dSAnders Carlsson   }
162159486a2dSAnders Carlsson 
162259486a2dSAnders Carlsson   EmitBlock(DeleteEnd);
162359486a2dSAnders Carlsson }
162459486a2dSAnders Carlsson 
16251c3d95ebSDavid Majnemer static bool isGLValueFromPointerDeref(const Expr *E) {
16261c3d95ebSDavid Majnemer   E = E->IgnoreParens();
16271c3d95ebSDavid Majnemer 
16281c3d95ebSDavid Majnemer   if (const auto *CE = dyn_cast<CastExpr>(E)) {
16291c3d95ebSDavid Majnemer     if (!CE->getSubExpr()->isGLValue())
16301c3d95ebSDavid Majnemer       return false;
16311c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(CE->getSubExpr());
16321c3d95ebSDavid Majnemer   }
16331c3d95ebSDavid Majnemer 
16341c3d95ebSDavid Majnemer   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
16351c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(OVE->getSourceExpr());
16361c3d95ebSDavid Majnemer 
16371c3d95ebSDavid Majnemer   if (const auto *BO = dyn_cast<BinaryOperator>(E))
16381c3d95ebSDavid Majnemer     if (BO->getOpcode() == BO_Comma)
16391c3d95ebSDavid Majnemer       return isGLValueFromPointerDeref(BO->getRHS());
16401c3d95ebSDavid Majnemer 
16411c3d95ebSDavid Majnemer   if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
16421c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
16431c3d95ebSDavid Majnemer            isGLValueFromPointerDeref(ACO->getFalseExpr());
16441c3d95ebSDavid Majnemer 
16451c3d95ebSDavid Majnemer   // C++11 [expr.sub]p1:
16461c3d95ebSDavid Majnemer   //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
16471c3d95ebSDavid Majnemer   if (isa<ArraySubscriptExpr>(E))
16481c3d95ebSDavid Majnemer     return true;
16491c3d95ebSDavid Majnemer 
16501c3d95ebSDavid Majnemer   if (const auto *UO = dyn_cast<UnaryOperator>(E))
16511c3d95ebSDavid Majnemer     if (UO->getOpcode() == UO_Deref)
16521c3d95ebSDavid Majnemer       return true;
16531c3d95ebSDavid Majnemer 
16541c3d95ebSDavid Majnemer   return false;
16551c3d95ebSDavid Majnemer }
16561c3d95ebSDavid Majnemer 
1657747e301eSWarren Hunt static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
16582192fe50SChris Lattner                                          llvm::Type *StdTypeInfoPtrTy) {
1659940f02d2SAnders Carlsson   // Get the vtable pointer.
1660940f02d2SAnders Carlsson   llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1661940f02d2SAnders Carlsson 
1662940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
1663940f02d2SAnders Carlsson   //   If the glvalue expression is obtained by applying the unary * operator to
1664940f02d2SAnders Carlsson   //   a pointer and the pointer is a null pointer value, the typeid expression
1665940f02d2SAnders Carlsson   //   throws the std::bad_typeid exception.
16661c3d95ebSDavid Majnemer   //
16671c3d95ebSDavid Majnemer   // However, this paragraph's intent is not clear.  We choose a very generous
16681c3d95ebSDavid Majnemer   // interpretation which implores us to consider comma operators, conditional
16691c3d95ebSDavid Majnemer   // operators, parentheses and other such constructs.
16701162d25cSDavid Majnemer   QualType SrcRecordTy = E->getType();
16711c3d95ebSDavid Majnemer   if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
16721c3d95ebSDavid Majnemer           isGLValueFromPointerDeref(E), SrcRecordTy)) {
1673940f02d2SAnders Carlsson     llvm::BasicBlock *BadTypeidBlock =
1674940f02d2SAnders Carlsson         CGF.createBasicBlock("typeid.bad_typeid");
16751162d25cSDavid Majnemer     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
1676940f02d2SAnders Carlsson 
1677940f02d2SAnders Carlsson     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1678940f02d2SAnders Carlsson     CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1679940f02d2SAnders Carlsson 
1680940f02d2SAnders Carlsson     CGF.EmitBlock(BadTypeidBlock);
16811162d25cSDavid Majnemer     CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1682940f02d2SAnders Carlsson     CGF.EmitBlock(EndBlock);
1683940f02d2SAnders Carlsson   }
1684940f02d2SAnders Carlsson 
16851162d25cSDavid Majnemer   return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
16861162d25cSDavid Majnemer                                         StdTypeInfoPtrTy);
1687940f02d2SAnders Carlsson }
1688940f02d2SAnders Carlsson 
168959486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
16902192fe50SChris Lattner   llvm::Type *StdTypeInfoPtrTy =
1691940f02d2SAnders Carlsson     ConvertType(E->getType())->getPointerTo();
1692fd7dfeb7SAnders Carlsson 
16933f4336cbSAnders Carlsson   if (E->isTypeOperand()) {
16943f4336cbSAnders Carlsson     llvm::Constant *TypeInfo =
1695143c55eaSDavid Majnemer         CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
1696940f02d2SAnders Carlsson     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
16973f4336cbSAnders Carlsson   }
1698fd7dfeb7SAnders Carlsson 
1699940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
1700940f02d2SAnders Carlsson   //   When typeid is applied to a glvalue expression whose type is a
1701940f02d2SAnders Carlsson   //   polymorphic class type, the result refers to a std::type_info object
1702940f02d2SAnders Carlsson   //   representing the type of the most derived object (that is, the dynamic
1703940f02d2SAnders Carlsson   //   type) to which the glvalue refers.
1704ef8bf436SRichard Smith   if (E->isPotentiallyEvaluated())
1705940f02d2SAnders Carlsson     return EmitTypeidFromVTable(*this, E->getExprOperand(),
1706940f02d2SAnders Carlsson                                 StdTypeInfoPtrTy);
1707940f02d2SAnders Carlsson 
1708940f02d2SAnders Carlsson   QualType OperandTy = E->getExprOperand()->getType();
1709940f02d2SAnders Carlsson   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1710940f02d2SAnders Carlsson                                StdTypeInfoPtrTy);
171159486a2dSAnders Carlsson }
171259486a2dSAnders Carlsson 
1713c1c9971cSAnders Carlsson static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1714c1c9971cSAnders Carlsson                                           QualType DestTy) {
17152192fe50SChris Lattner   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1716c1c9971cSAnders Carlsson   if (DestTy->isPointerType())
1717c1c9971cSAnders Carlsson     return llvm::Constant::getNullValue(DestLTy);
1718c1c9971cSAnders Carlsson 
1719c1c9971cSAnders Carlsson   /// C++ [expr.dynamic.cast]p9:
1720c1c9971cSAnders Carlsson   ///   A failed cast to reference type throws std::bad_cast
17211162d25cSDavid Majnemer   if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
17221162d25cSDavid Majnemer     return nullptr;
1723c1c9971cSAnders Carlsson 
1724c1c9971cSAnders Carlsson   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1725c1c9971cSAnders Carlsson   return llvm::UndefValue::get(DestLTy);
1726c1c9971cSAnders Carlsson }
1727c1c9971cSAnders Carlsson 
1728882d790fSAnders Carlsson llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
172959486a2dSAnders Carlsson                                               const CXXDynamicCastExpr *DCE) {
17303f4336cbSAnders Carlsson   QualType DestTy = DCE->getTypeAsWritten();
17313f4336cbSAnders Carlsson 
1732c1c9971cSAnders Carlsson   if (DCE->isAlwaysNull())
17331162d25cSDavid Majnemer     if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
17341162d25cSDavid Majnemer       return T;
1735c1c9971cSAnders Carlsson 
1736c1c9971cSAnders Carlsson   QualType SrcTy = DCE->getSubExpr()->getType();
1737c1c9971cSAnders Carlsson 
17381162d25cSDavid Majnemer   // C++ [expr.dynamic.cast]p7:
17391162d25cSDavid Majnemer   //   If T is "pointer to cv void," then the result is a pointer to the most
17401162d25cSDavid Majnemer   //   derived object pointed to by v.
17411162d25cSDavid Majnemer   const PointerType *DestPTy = DestTy->getAs<PointerType>();
17421162d25cSDavid Majnemer 
17431162d25cSDavid Majnemer   bool isDynamicCastToVoid;
17441162d25cSDavid Majnemer   QualType SrcRecordTy;
17451162d25cSDavid Majnemer   QualType DestRecordTy;
17461162d25cSDavid Majnemer   if (DestPTy) {
17471162d25cSDavid Majnemer     isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
17481162d25cSDavid Majnemer     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
17491162d25cSDavid Majnemer     DestRecordTy = DestPTy->getPointeeType();
17501162d25cSDavid Majnemer   } else {
17511162d25cSDavid Majnemer     isDynamicCastToVoid = false;
17521162d25cSDavid Majnemer     SrcRecordTy = SrcTy;
17531162d25cSDavid Majnemer     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
17541162d25cSDavid Majnemer   }
17551162d25cSDavid Majnemer 
17561162d25cSDavid Majnemer   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
17571162d25cSDavid Majnemer 
1758882d790fSAnders Carlsson   // C++ [expr.dynamic.cast]p4:
1759882d790fSAnders Carlsson   //   If the value of v is a null pointer value in the pointer case, the result
1760882d790fSAnders Carlsson   //   is the null pointer value of type T.
17611162d25cSDavid Majnemer   bool ShouldNullCheckSrcValue =
17621162d25cSDavid Majnemer       CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
17631162d25cSDavid Majnemer                                                          SrcRecordTy);
176459486a2dSAnders Carlsson 
17658a13c418SCraig Topper   llvm::BasicBlock *CastNull = nullptr;
17668a13c418SCraig Topper   llvm::BasicBlock *CastNotNull = nullptr;
1767882d790fSAnders Carlsson   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
1768fa8b4955SDouglas Gregor 
1769882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1770882d790fSAnders Carlsson     CastNull = createBasicBlock("dynamic_cast.null");
1771882d790fSAnders Carlsson     CastNotNull = createBasicBlock("dynamic_cast.notnull");
1772882d790fSAnders Carlsson 
1773882d790fSAnders Carlsson     llvm::Value *IsNull = Builder.CreateIsNull(Value);
1774882d790fSAnders Carlsson     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1775882d790fSAnders Carlsson     EmitBlock(CastNotNull);
177659486a2dSAnders Carlsson   }
177759486a2dSAnders Carlsson 
17781162d25cSDavid Majnemer   if (isDynamicCastToVoid) {
17791162d25cSDavid Majnemer     Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, Value, SrcRecordTy,
17801162d25cSDavid Majnemer                                                   DestTy);
17811162d25cSDavid Majnemer   } else {
17821162d25cSDavid Majnemer     assert(DestRecordTy->isRecordType() &&
17831162d25cSDavid Majnemer            "destination type must be a record type!");
17841162d25cSDavid Majnemer     Value = CGM.getCXXABI().EmitDynamicCastCall(*this, Value, SrcRecordTy,
17851162d25cSDavid Majnemer                                                 DestTy, DestRecordTy, CastEnd);
17861162d25cSDavid Majnemer   }
17873f4336cbSAnders Carlsson 
1788882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1789882d790fSAnders Carlsson     EmitBranch(CastEnd);
179059486a2dSAnders Carlsson 
1791882d790fSAnders Carlsson     EmitBlock(CastNull);
1792882d790fSAnders Carlsson     EmitBranch(CastEnd);
179359486a2dSAnders Carlsson   }
179459486a2dSAnders Carlsson 
1795882d790fSAnders Carlsson   EmitBlock(CastEnd);
179659486a2dSAnders Carlsson 
1797882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1798882d790fSAnders Carlsson     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1799882d790fSAnders Carlsson     PHI->addIncoming(Value, CastNotNull);
1800882d790fSAnders Carlsson     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
180159486a2dSAnders Carlsson 
1802882d790fSAnders Carlsson     Value = PHI;
180359486a2dSAnders Carlsson   }
180459486a2dSAnders Carlsson 
1805882d790fSAnders Carlsson   return Value;
180659486a2dSAnders Carlsson }
1807c370a7eeSEli Friedman 
1808c370a7eeSEli Friedman void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
18098631f3e8SEli Friedman   RunCleanupsScope Scope(*this);
18107f1ff600SEli Friedman   LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(),
18117f1ff600SEli Friedman                                  Slot.getAlignment());
18128631f3e8SEli Friedman 
1813c370a7eeSEli Friedman   CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1814c370a7eeSEli Friedman   for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1815c370a7eeSEli Friedman                                          e = E->capture_init_end();
1816c370a7eeSEli Friedman        i != e; ++i, ++CurField) {
1817c370a7eeSEli Friedman     // Emit initialization
18187f1ff600SEli Friedman 
181940ed2973SDavid Blaikie     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
18205f1a04ffSEli Friedman     ArrayRef<VarDecl *> ArrayIndexes;
18215f1a04ffSEli Friedman     if (CurField->getType()->isArrayType())
18225f1a04ffSEli Friedman       ArrayIndexes = E->getCaptureInitIndexVars(i);
182340ed2973SDavid Blaikie     EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
1824c370a7eeSEli Friedman   }
1825c370a7eeSEli Friedman }
1826