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 
270c0b6d9aSDavid Majnemer static RequiredArgs commonEmitCXXMemberOrOperatorCall(
280c0b6d9aSDavid Majnemer     CodeGenFunction &CGF, const CXXMethodDecl *MD, llvm::Value *Callee,
290c0b6d9aSDavid Majnemer     ReturnValueSlot ReturnValue, llvm::Value *This, llvm::Value *ImplicitParam,
300c0b6d9aSDavid Majnemer     QualType ImplicitParamTy, const CallExpr *CE, CallArgList &Args) {
31a5bf76bdSAlexey Samsonov   assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
32a5bf76bdSAlexey Samsonov          isa<CXXOperatorCallExpr>(CE));
3327da15baSAnders Carlsson   assert(MD->isInstance() &&
34a5bf76bdSAlexey 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.
39a5bf76bdSAlexey Samsonov   SourceLocation CallLoc;
40a5bf76bdSAlexey Samsonov   if (CE)
41a5bf76bdSAlexey Samsonov     CallLoc = CE->getExprLoc();
420c0b6d9aSDavid Majnemer   CGF.EmitTypeCheck(
430c0b6d9aSDavid Majnemer       isa<CXXConstructorDecl>(MD) ? CodeGenFunction::TCK_ConstructorCall
440c0b6d9aSDavid Majnemer                                   : CodeGenFunction::TCK_MemberCall,
450c0b6d9aSDavid Majnemer       CallLoc, This, CGF.getContext().getRecordType(MD->getParent()));
4627da15baSAnders Carlsson 
4727da15baSAnders Carlsson   // Push the this ptr.
480c0b6d9aSDavid Majnemer   Args.add(RValue::get(This), MD->getThisType(CGF.getContext()));
4927da15baSAnders Carlsson 
50ee6bc533STimur Iskhodzhanov   // If there is an implicit parameter (e.g. VTT), emit it.
51ee6bc533STimur Iskhodzhanov   if (ImplicitParam) {
52ee6bc533STimur Iskhodzhanov     Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
53e36a6b3eSAnders Carlsson   }
54e36a6b3eSAnders Carlsson 
55a729c62bSJohn McCall   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
56a729c62bSJohn McCall   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
57a729c62bSJohn McCall 
58a729c62bSJohn McCall   // And the rest of the call args.
598e1162c7SAlexey Samsonov   if (CE) {
60a5bf76bdSAlexey Samsonov     // Special case: skip first argument of CXXOperatorCall (it is "this").
618e1162c7SAlexey Samsonov     unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
62f05779e2SDavid Blaikie     CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
638e1162c7SAlexey Samsonov                      CE->getDirectCallee());
64a5bf76bdSAlexey Samsonov   } else {
658e1162c7SAlexey Samsonov     assert(
668e1162c7SAlexey Samsonov         FPT->getNumParams() == 0 &&
678e1162c7SAlexey Samsonov         "No CallExpr specified for function with non-zero number of arguments");
68a5bf76bdSAlexey Samsonov   }
690c0b6d9aSDavid Majnemer   return required;
700c0b6d9aSDavid Majnemer }
7127da15baSAnders Carlsson 
720c0b6d9aSDavid Majnemer RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
730c0b6d9aSDavid Majnemer     const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
740c0b6d9aSDavid Majnemer     llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
750c0b6d9aSDavid Majnemer     const CallExpr *CE) {
760c0b6d9aSDavid Majnemer   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
770c0b6d9aSDavid Majnemer   CallArgList Args;
780c0b6d9aSDavid Majnemer   RequiredArgs required = commonEmitCXXMemberOrOperatorCall(
790c0b6d9aSDavid Majnemer       *this, MD, Callee, ReturnValue, This, ImplicitParam, ImplicitParamTy, CE,
800c0b6d9aSDavid Majnemer       Args);
818dda7b27SJohn McCall   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
82c50c27ccSRafael Espindola                   Callee, ReturnValue, Args, MD);
8327da15baSAnders Carlsson }
8427da15baSAnders Carlsson 
850c0b6d9aSDavid Majnemer RValue CodeGenFunction::EmitCXXStructorCall(
860c0b6d9aSDavid Majnemer     const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
870c0b6d9aSDavid Majnemer     llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
880c0b6d9aSDavid Majnemer     const CallExpr *CE, StructorType Type) {
890c0b6d9aSDavid Majnemer   CallArgList Args;
900c0b6d9aSDavid Majnemer   commonEmitCXXMemberOrOperatorCall(*this, MD, Callee, ReturnValue, This,
910c0b6d9aSDavid Majnemer                                     ImplicitParam, ImplicitParamTy, CE, Args);
920c0b6d9aSDavid Majnemer   return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(MD, Type),
930c0b6d9aSDavid Majnemer                   Callee, ReturnValue, Args, MD);
940c0b6d9aSDavid Majnemer }
950c0b6d9aSDavid Majnemer 
963b33c4ecSRafael Espindola static CXXRecordDecl *getCXXRecord(const Expr *E) {
973b33c4ecSRafael Espindola   QualType T = E->getType();
983b33c4ecSRafael Espindola   if (const PointerType *PTy = T->getAs<PointerType>())
993b33c4ecSRafael Espindola     T = PTy->getPointeeType();
1003b33c4ecSRafael Espindola   const RecordType *Ty = T->castAs<RecordType>();
1013b33c4ecSRafael Espindola   return cast<CXXRecordDecl>(Ty->getDecl());
1023b33c4ecSRafael Espindola }
1033b33c4ecSRafael Espindola 
10464225794SFrancois Pichet // Note: This function also emit constructor calls to support a MSVC
10564225794SFrancois Pichet // extensions allowing explicit constructor function call.
10627da15baSAnders Carlsson RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
10727da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
1082d2e8707SJohn McCall   const Expr *callee = CE->getCallee()->IgnoreParens();
1092d2e8707SJohn McCall 
1102d2e8707SJohn McCall   if (isa<BinaryOperator>(callee))
11127da15baSAnders Carlsson     return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
11227da15baSAnders Carlsson 
1132d2e8707SJohn McCall   const MemberExpr *ME = cast<MemberExpr>(callee);
11427da15baSAnders Carlsson   const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
11527da15baSAnders Carlsson 
11627da15baSAnders Carlsson   if (MD->isStatic()) {
11727da15baSAnders Carlsson     // The method is static, emit it as we would a regular call.
11827da15baSAnders Carlsson     llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
11970b9c01bSAlexey Samsonov     return EmitCall(getContext().getPointerType(MD->getType()), Callee, CE,
12070b9c01bSAlexey Samsonov                     ReturnValue);
12127da15baSAnders Carlsson   }
12227da15baSAnders Carlsson 
123aad4af6dSNico Weber   bool HasQualifier = ME->hasQualifier();
124aad4af6dSNico Weber   NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
125aad4af6dSNico Weber   bool IsArrow = ME->isArrow();
126ecbe2e97SRafael Espindola   const Expr *Base = ME->getBase();
127aad4af6dSNico Weber 
128aad4af6dSNico Weber   return EmitCXXMemberOrOperatorMemberCallExpr(
129aad4af6dSNico Weber       CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
130aad4af6dSNico Weber }
131aad4af6dSNico Weber 
132aad4af6dSNico Weber RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
133aad4af6dSNico Weber     const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
134aad4af6dSNico Weber     bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
135aad4af6dSNico Weber     const Expr *Base) {
136aad4af6dSNico Weber   assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
137aad4af6dSNico Weber 
138aad4af6dSNico Weber   // Compute the object pointer.
139aad4af6dSNico Weber   bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
140ecbe2e97SRafael Espindola 
1418a13c418SCraig Topper   const CXXMethodDecl *DevirtualizedMethod = nullptr;
1427463ed7cSBenjamin Kramer   if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
1433b33c4ecSRafael Espindola     const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
1443b33c4ecSRafael Espindola     DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
1453b33c4ecSRafael Espindola     assert(DevirtualizedMethod);
1463b33c4ecSRafael Espindola     const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
1473b33c4ecSRafael Espindola     const Expr *Inner = Base->ignoreParenBaseCasts();
1485bd68794SAlexey Bataev     if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
1495bd68794SAlexey Bataev         MD->getReturnType().getCanonicalType())
1505bd68794SAlexey Bataev       // If the return types are not the same, this might be a case where more
1515bd68794SAlexey Bataev       // code needs to run to compensate for it. For example, the derived
1525bd68794SAlexey Bataev       // method might return a type that inherits form from the return
1535bd68794SAlexey Bataev       // type of MD and has a prefix.
1545bd68794SAlexey Bataev       // For now we just avoid devirtualizing these covariant cases.
1555bd68794SAlexey Bataev       DevirtualizedMethod = nullptr;
1565bd68794SAlexey Bataev     else if (getCXXRecord(Inner) == DevirtualizedClass)
1573b33c4ecSRafael Espindola       // If the class of the Inner expression is where the dynamic method
1583b33c4ecSRafael Espindola       // is defined, build the this pointer from it.
1593b33c4ecSRafael Espindola       Base = Inner;
1603b33c4ecSRafael Espindola     else if (getCXXRecord(Base) != DevirtualizedClass) {
1613b33c4ecSRafael Espindola       // If the method is defined in a class that is not the best dynamic
1623b33c4ecSRafael Espindola       // one or the one of the full expression, we would have to build
1633b33c4ecSRafael Espindola       // a derived-to-base cast to compute the correct this pointer, but
1643b33c4ecSRafael Espindola       // we don't have support for that yet, so do a virtual call.
1658a13c418SCraig Topper       DevirtualizedMethod = nullptr;
1663b33c4ecSRafael Espindola     }
1673b33c4ecSRafael Espindola   }
168ecbe2e97SRafael Espindola 
1697f416cc4SJohn McCall   Address This = Address::invalid();
170aad4af6dSNico Weber   if (IsArrow)
1717f416cc4SJohn McCall     This = EmitPointerWithAlignment(Base);
172f93ac894SFariborz Jahanian   else
1733b33c4ecSRafael Espindola     This = EmitLValue(Base).getAddress();
174ecbe2e97SRafael Espindola 
17527da15baSAnders Carlsson 
176419bd094SRichard Smith   if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
1778a13c418SCraig Topper     if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
17864225794SFrancois Pichet     if (isa<CXXConstructorDecl>(MD) &&
17964225794SFrancois Pichet         cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
1808a13c418SCraig Topper       return RValue::get(nullptr);
1810d635f53SJohn McCall 
182aad4af6dSNico Weber     if (!MD->getParent()->mayInsertExtraPadding()) {
18322653bacSSebastian Redl       if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
18422653bacSSebastian Redl         // We don't like to generate the trivial copy/move assignment operator
18522653bacSSebastian Redl         // when it isn't necessary; just produce the proper effect here.
186aad4af6dSNico Weber         // Special case: skip first argument of CXXOperatorCall (it is "this").
187aad4af6dSNico Weber         unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
1887f416cc4SJohn McCall         Address RHS = EmitLValue(*(CE->arg_begin() + ArgsToSkip)).getAddress();
1891ca66919SBenjamin Kramer         EmitAggregateAssign(This, RHS, CE->getType());
1907f416cc4SJohn McCall         return RValue::get(This.getPointer());
19127da15baSAnders Carlsson       }
19227da15baSAnders Carlsson 
19364225794SFrancois Pichet       if (isa<CXXConstructorDecl>(MD) &&
19422653bacSSebastian Redl           cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
19522653bacSSebastian Redl         // Trivial move and copy ctor are the same.
196525bf650SAlexey Samsonov         assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
1977f416cc4SJohn McCall         Address RHS = EmitLValue(*CE->arg_begin()).getAddress();
198f48ee448SBenjamin Kramer         EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType());
1997f416cc4SJohn McCall         return RValue::get(This.getPointer());
20064225794SFrancois Pichet       }
20164225794SFrancois Pichet       llvm_unreachable("unknown trivial member function");
20264225794SFrancois Pichet     }
203aad4af6dSNico Weber   }
20464225794SFrancois Pichet 
2050d635f53SJohn McCall   // Compute the function type we're calling.
2063abfe958SNico Weber   const CXXMethodDecl *CalleeDecl =
2073abfe958SNico Weber       DevirtualizedMethod ? DevirtualizedMethod : MD;
2088a13c418SCraig Topper   const CGFunctionInfo *FInfo = nullptr;
2093abfe958SNico Weber   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
2108d2a19b4SRafael Espindola     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
2118d2a19b4SRafael Espindola         Dtor, StructorType::Complete);
2123abfe958SNico Weber   else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
2138d2a19b4SRafael Espindola     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
2148d2a19b4SRafael Espindola         Ctor, StructorType::Complete);
21564225794SFrancois Pichet   else
216ade60977SEli Friedman     FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
2170d635f53SJohn McCall 
218e7de47efSReid Kleckner   llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
2190d635f53SJohn McCall 
22027da15baSAnders Carlsson   // C++ [class.virtual]p12:
22127da15baSAnders Carlsson   //   Explicit qualification with the scope operator (5.1) suppresses the
22227da15baSAnders Carlsson   //   virtual call mechanism.
22327da15baSAnders Carlsson   //
22427da15baSAnders Carlsson   // We also don't emit a virtual call if the base expression has a record type
22527da15baSAnders Carlsson   // because then we know what the type is.
2263b33c4ecSRafael Espindola   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
22719cee187SStephen Lin   llvm::Value *Callee;
2289dc6eef7SStephen Lin 
2290d635f53SJohn McCall   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
23019cee187SStephen Lin     assert(CE->arg_begin() == CE->arg_end() &&
2319dc6eef7SStephen Lin            "Destructor shouldn't have explicit parameters");
2329dc6eef7SStephen Lin     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
2339dc6eef7SStephen Lin     if (UseVirtualCall) {
234aad4af6dSNico Weber       CGM.getCXXABI().EmitVirtualDestructorCall(
235aad4af6dSNico Weber           *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
23627da15baSAnders Carlsson     } else {
237aad4af6dSNico Weber       if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
238aad4af6dSNico Weber         Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
2393b33c4ecSRafael Espindola       else if (!DevirtualizedMethod)
2401ac0ec86SRafael Espindola         Callee =
2411ac0ec86SRafael Espindola             CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty);
24249e860b2SRafael Espindola       else {
2433b33c4ecSRafael Espindola         const CXXDestructorDecl *DDtor =
2443b33c4ecSRafael Espindola           cast<CXXDestructorDecl>(DevirtualizedMethod);
24549e860b2SRafael Espindola         Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
24649e860b2SRafael Espindola       }
2477f416cc4SJohn McCall       EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This.getPointer(),
248a5bf76bdSAlexey Samsonov                                   /*ImplicitParam=*/nullptr, QualType(), CE);
24927da15baSAnders Carlsson     }
2508a13c418SCraig Topper     return RValue::get(nullptr);
2519dc6eef7SStephen Lin   }
2529dc6eef7SStephen Lin 
2539dc6eef7SStephen Lin   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
25464225794SFrancois Pichet     Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
2550d635f53SJohn McCall   } else if (UseVirtualCall) {
2566708c4a1SPeter Collingbourne     Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty,
2576708c4a1SPeter Collingbourne                                                        CE->getLocStart());
25827da15baSAnders Carlsson   } else {
2591a7488afSPeter Collingbourne     if (SanOpts.has(SanitizerKind::CFINVCall) &&
2601a7488afSPeter Collingbourne         MD->getParent()->isDynamicClass()) {
2614b1ac72cSPiotr Padlewski       llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy, MD->getParent());
2626708c4a1SPeter Collingbourne       EmitVTablePtrCheckForCall(MD, VTable, CFITCK_NVCall, CE->getLocStart());
2631a7488afSPeter Collingbourne     }
2641a7488afSPeter Collingbourne 
265aad4af6dSNico Weber     if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
266aad4af6dSNico Weber       Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
2673b33c4ecSRafael Espindola     else if (!DevirtualizedMethod)
268727a771aSRafael Espindola       Callee = CGM.GetAddrOfFunction(MD, Ty);
26949e860b2SRafael Espindola     else {
2703b33c4ecSRafael Espindola       Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
27149e860b2SRafael Espindola     }
27227da15baSAnders Carlsson   }
27327da15baSAnders Carlsson 
274f1749427STimur Iskhodzhanov   if (MD->isVirtual()) {
275f1749427STimur Iskhodzhanov     This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
276f1749427STimur Iskhodzhanov         *this, MD, This, UseVirtualCall);
277f1749427STimur Iskhodzhanov   }
27888fd439aSTimur Iskhodzhanov 
2797f416cc4SJohn McCall   return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This.getPointer(),
280a5bf76bdSAlexey Samsonov                                      /*ImplicitParam=*/nullptr, QualType(), CE);
28127da15baSAnders Carlsson }
28227da15baSAnders Carlsson 
28327da15baSAnders Carlsson RValue
28427da15baSAnders Carlsson CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
28527da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
28627da15baSAnders Carlsson   const BinaryOperator *BO =
28727da15baSAnders Carlsson       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
28827da15baSAnders Carlsson   const Expr *BaseExpr = BO->getLHS();
28927da15baSAnders Carlsson   const Expr *MemFnExpr = BO->getRHS();
29027da15baSAnders Carlsson 
29127da15baSAnders Carlsson   const MemberPointerType *MPT =
2920009fcc3SJohn McCall     MemFnExpr->getType()->castAs<MemberPointerType>();
293475999dcSJohn McCall 
29427da15baSAnders Carlsson   const FunctionProtoType *FPT =
2950009fcc3SJohn McCall     MPT->getPointeeType()->castAs<FunctionProtoType>();
29627da15baSAnders Carlsson   const CXXRecordDecl *RD =
29727da15baSAnders Carlsson     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
29827da15baSAnders Carlsson 
29927da15baSAnders Carlsson   // Get the member function pointer.
300a1dee530SJohn McCall   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
30127da15baSAnders Carlsson 
30227da15baSAnders Carlsson   // Emit the 'this' pointer.
3037f416cc4SJohn McCall   Address This = Address::invalid();
304e302792bSJohn McCall   if (BO->getOpcode() == BO_PtrMemI)
3057f416cc4SJohn McCall     This = EmitPointerWithAlignment(BaseExpr);
30627da15baSAnders Carlsson   else
30727da15baSAnders Carlsson     This = EmitLValue(BaseExpr).getAddress();
30827da15baSAnders Carlsson 
3097f416cc4SJohn McCall   EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
310e30752c9SRichard Smith                 QualType(MPT->getClass(), 0));
31169d0d262SRichard Smith 
312475999dcSJohn McCall   // Ask the ABI to load the callee.  Note that This is modified.
3137f416cc4SJohn McCall   llvm::Value *ThisPtrForCall = nullptr;
314475999dcSJohn McCall   llvm::Value *Callee =
3157f416cc4SJohn McCall     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
3167f416cc4SJohn McCall                                              ThisPtrForCall, MemFnPtr, MPT);
31727da15baSAnders Carlsson 
31827da15baSAnders Carlsson   CallArgList Args;
31927da15baSAnders Carlsson 
32027da15baSAnders Carlsson   QualType ThisType =
32127da15baSAnders Carlsson     getContext().getPointerType(getContext().getTagDeclType(RD));
32227da15baSAnders Carlsson 
32327da15baSAnders Carlsson   // Push the this ptr.
3247f416cc4SJohn McCall   Args.add(RValue::get(ThisPtrForCall), ThisType);
32527da15baSAnders Carlsson 
3268dda7b27SJohn McCall   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
3278dda7b27SJohn McCall 
32827da15baSAnders Carlsson   // And the rest of the call args
329f05779e2SDavid Blaikie   EmitCallArgs(Args, FPT, E->arguments(), E->getDirectCallee());
3305fa40c3bSNick Lewycky   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
3315fa40c3bSNick Lewycky                   Callee, ReturnValue, Args);
33227da15baSAnders Carlsson }
33327da15baSAnders Carlsson 
33427da15baSAnders Carlsson RValue
33527da15baSAnders Carlsson CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
33627da15baSAnders Carlsson                                                const CXXMethodDecl *MD,
33727da15baSAnders Carlsson                                                ReturnValueSlot ReturnValue) {
33827da15baSAnders Carlsson   assert(MD->isInstance() &&
33927da15baSAnders Carlsson          "Trying to emit a member call expr on a static method!");
340aad4af6dSNico Weber   return EmitCXXMemberOrOperatorMemberCallExpr(
341aad4af6dSNico Weber       E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
342aad4af6dSNico Weber       /*IsArrow=*/false, E->getArg(0));
34327da15baSAnders Carlsson }
34427da15baSAnders Carlsson 
345fe883422SPeter Collingbourne RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
346fe883422SPeter Collingbourne                                                ReturnValueSlot ReturnValue) {
347fe883422SPeter Collingbourne   return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
348fe883422SPeter Collingbourne }
349fe883422SPeter Collingbourne 
350fde961dbSEli Friedman static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
3517f416cc4SJohn McCall                                             Address DestPtr,
352fde961dbSEli Friedman                                             const CXXRecordDecl *Base) {
353fde961dbSEli Friedman   if (Base->isEmpty())
354fde961dbSEli Friedman     return;
355fde961dbSEli Friedman 
3567f416cc4SJohn McCall   DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
357fde961dbSEli Friedman 
358fde961dbSEli Friedman   const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
3597f416cc4SJohn McCall   llvm::Value *SizeVal = CGF.CGM.getSize(Layout.getNonVirtualSize());
360fde961dbSEli Friedman 
361fde961dbSEli Friedman   // If the type contains a pointer to data member we can't memset it to zero.
362fde961dbSEli Friedman   // Instead, create a null constant and copy it to the destination.
363fde961dbSEli Friedman   // TODO: there are other patterns besides zero that we can usefully memset,
364fde961dbSEli Friedman   // like -1, which happens to be the pattern used by member-pointers.
365fde961dbSEli Friedman   // TODO: isZeroInitializable can be over-conservative in the case where a
366fde961dbSEli Friedman   // virtual base contains a member pointer.
367fde961dbSEli Friedman   if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
368fde961dbSEli Friedman     llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
369fde961dbSEli Friedman 
370fde961dbSEli Friedman     llvm::GlobalVariable *NullVariable =
371fde961dbSEli Friedman       new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
372fde961dbSEli Friedman                                /*isConstant=*/true,
373fde961dbSEli Friedman                                llvm::GlobalVariable::PrivateLinkage,
374fde961dbSEli Friedman                                NullConstant, Twine());
3757f416cc4SJohn McCall 
3767f416cc4SJohn McCall     CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
3777f416cc4SJohn McCall                                DestPtr.getAlignment());
378fde961dbSEli Friedman     NullVariable->setAlignment(Align.getQuantity());
3797f416cc4SJohn McCall 
3807f416cc4SJohn McCall     Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
381fde961dbSEli Friedman 
382fde961dbSEli Friedman     // Get and call the appropriate llvm.memcpy overload.
3837f416cc4SJohn McCall     CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal);
384fde961dbSEli Friedman     return;
385fde961dbSEli Friedman   }
386fde961dbSEli Friedman 
387fde961dbSEli Friedman   // Otherwise, just memset the whole thing to zero.  This is legal
388fde961dbSEli Friedman   // because in LLVM, all default initializers (other than the ones we just
389fde961dbSEli Friedman   // handled above) are guaranteed to have a bit pattern of all zeros.
3907f416cc4SJohn McCall   CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal);
391fde961dbSEli Friedman }
392fde961dbSEli Friedman 
39327da15baSAnders Carlsson void
3947a626f63SJohn McCall CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
3957a626f63SJohn McCall                                       AggValueSlot Dest) {
3967a626f63SJohn McCall   assert(!Dest.isIgnored() && "Must have a destination!");
39727da15baSAnders Carlsson   const CXXConstructorDecl *CD = E->getConstructor();
398630c76efSDouglas Gregor 
399630c76efSDouglas Gregor   // If we require zero initialization before (or instead of) calling the
400630c76efSDouglas Gregor   // constructor, as can be the case with a non-user-provided default
40103535265SArgyrios Kyrtzidis   // constructor, emit the zero initialization now, unless destination is
40203535265SArgyrios Kyrtzidis   // already zeroed.
403fde961dbSEli Friedman   if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
404fde961dbSEli Friedman     switch (E->getConstructionKind()) {
405fde961dbSEli Friedman     case CXXConstructExpr::CK_Delegating:
406fde961dbSEli Friedman     case CXXConstructExpr::CK_Complete:
4077f416cc4SJohn McCall       EmitNullInitialization(Dest.getAddress(), E->getType());
408fde961dbSEli Friedman       break;
409fde961dbSEli Friedman     case CXXConstructExpr::CK_VirtualBase:
410fde961dbSEli Friedman     case CXXConstructExpr::CK_NonVirtualBase:
4117f416cc4SJohn McCall       EmitNullBaseClassInitialization(*this, Dest.getAddress(),
4127f416cc4SJohn McCall                                       CD->getParent());
413fde961dbSEli Friedman       break;
414fde961dbSEli Friedman     }
415fde961dbSEli Friedman   }
416630c76efSDouglas Gregor 
417630c76efSDouglas Gregor   // If this is a call to a trivial default constructor, do nothing.
418630c76efSDouglas Gregor   if (CD->isTrivial() && CD->isDefaultConstructor())
41927da15baSAnders Carlsson     return;
420630c76efSDouglas Gregor 
4218ea46b66SJohn McCall   // Elide the constructor if we're constructing from a temporary.
4228ea46b66SJohn McCall   // The temporary check is required because Sema sets this on NRVO
4238ea46b66SJohn McCall   // returns.
4249c6890a7SRichard Smith   if (getLangOpts().ElideConstructors && E->isElidable()) {
4258ea46b66SJohn McCall     assert(getContext().hasSameUnqualifiedType(E->getType(),
4268ea46b66SJohn McCall                                                E->getArg(0)->getType()));
4277a626f63SJohn McCall     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
4287a626f63SJohn McCall       EmitAggExpr(E->getArg(0), Dest);
42927da15baSAnders Carlsson       return;
43027da15baSAnders Carlsson     }
431222cf0efSDouglas Gregor   }
432630c76efSDouglas Gregor 
433f677a8e9SJohn McCall   if (const ConstantArrayType *arrayType
434f677a8e9SJohn McCall         = getContext().getAsConstantArrayType(E->getType())) {
4357f416cc4SJohn McCall     EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E);
436f677a8e9SJohn McCall   } else {
437bceca20aSCameron Esfahani     CXXCtorType Type = Ctor_Complete;
438271c3681SAlexis Hunt     bool ForVirtualBase = false;
43961535005SDouglas Gregor     bool Delegating = false;
440271c3681SAlexis Hunt 
441271c3681SAlexis Hunt     switch (E->getConstructionKind()) {
442271c3681SAlexis Hunt      case CXXConstructExpr::CK_Delegating:
44361bc1737SAlexis Hunt       // We should be emitting a constructor; GlobalDecl will assert this
44461bc1737SAlexis Hunt       Type = CurGD.getCtorType();
44561535005SDouglas Gregor       Delegating = true;
446271c3681SAlexis Hunt       break;
44761bc1737SAlexis Hunt 
448271c3681SAlexis Hunt      case CXXConstructExpr::CK_Complete:
449271c3681SAlexis Hunt       Type = Ctor_Complete;
450271c3681SAlexis Hunt       break;
451271c3681SAlexis Hunt 
452271c3681SAlexis Hunt      case CXXConstructExpr::CK_VirtualBase:
453271c3681SAlexis Hunt       ForVirtualBase = true;
454271c3681SAlexis Hunt       // fall-through
455271c3681SAlexis Hunt 
456271c3681SAlexis Hunt      case CXXConstructExpr::CK_NonVirtualBase:
457271c3681SAlexis Hunt       Type = Ctor_Base;
458271c3681SAlexis Hunt     }
459e11f9ce9SAnders Carlsson 
46027da15baSAnders Carlsson     // Call the constructor.
4617f416cc4SJohn McCall     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
4627f416cc4SJohn McCall                            Dest.getAddress(), E);
46327da15baSAnders Carlsson   }
464e11f9ce9SAnders Carlsson }
46527da15baSAnders Carlsson 
4667f416cc4SJohn McCall void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
46750198098SFariborz Jahanian                                                  const Expr *Exp) {
4685d413781SJohn McCall   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
469e988bdacSFariborz Jahanian     Exp = E->getSubExpr();
470e988bdacSFariborz Jahanian   assert(isa<CXXConstructExpr>(Exp) &&
471e988bdacSFariborz Jahanian          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
472e988bdacSFariborz Jahanian   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
473e988bdacSFariborz Jahanian   const CXXConstructorDecl *CD = E->getConstructor();
474e988bdacSFariborz Jahanian   RunCleanupsScope Scope(*this);
475e988bdacSFariborz Jahanian 
476e988bdacSFariborz Jahanian   // If we require zero initialization before (or instead of) calling the
477e988bdacSFariborz Jahanian   // constructor, as can be the case with a non-user-provided default
478e988bdacSFariborz Jahanian   // constructor, emit the zero initialization now.
479e988bdacSFariborz Jahanian   // FIXME. Do I still need this for a copy ctor synthesis?
480e988bdacSFariborz Jahanian   if (E->requiresZeroInitialization())
481e988bdacSFariborz Jahanian     EmitNullInitialization(Dest, E->getType());
482e988bdacSFariborz Jahanian 
48399da11cfSChandler Carruth   assert(!getContext().getAsConstantArrayType(E->getType())
48499da11cfSChandler Carruth          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
485525bf650SAlexey Samsonov   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
486e988bdacSFariborz Jahanian }
487e988bdacSFariborz Jahanian 
4888ed55a54SJohn McCall static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
4898ed55a54SJohn McCall                                         const CXXNewExpr *E) {
49021122cf6SAnders Carlsson   if (!E->isArray())
4913eb55cfeSKen Dyck     return CharUnits::Zero();
49221122cf6SAnders Carlsson 
4937ec4b434SJohn McCall   // No cookie is required if the operator new[] being used is the
4947ec4b434SJohn McCall   // reserved placement operator new[].
4957ec4b434SJohn McCall   if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
4963eb55cfeSKen Dyck     return CharUnits::Zero();
497399f499fSAnders Carlsson 
498284c48ffSJohn McCall   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
49959486a2dSAnders Carlsson }
50059486a2dSAnders Carlsson 
501036f2f6bSJohn McCall static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
502036f2f6bSJohn McCall                                         const CXXNewExpr *e,
503f862eb6aSSebastian Redl                                         unsigned minElements,
504036f2f6bSJohn McCall                                         llvm::Value *&numElements,
505036f2f6bSJohn McCall                                         llvm::Value *&sizeWithoutCookie) {
506036f2f6bSJohn McCall   QualType type = e->getAllocatedType();
50759486a2dSAnders Carlsson 
508036f2f6bSJohn McCall   if (!e->isArray()) {
509036f2f6bSJohn McCall     CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
510036f2f6bSJohn McCall     sizeWithoutCookie
511036f2f6bSJohn McCall       = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
512036f2f6bSJohn McCall     return sizeWithoutCookie;
51305fc5be3SDouglas Gregor   }
51459486a2dSAnders Carlsson 
515036f2f6bSJohn McCall   // The width of size_t.
516036f2f6bSJohn McCall   unsigned sizeWidth = CGF.SizeTy->getBitWidth();
517036f2f6bSJohn McCall 
5188ed55a54SJohn McCall   // Figure out the cookie size.
519036f2f6bSJohn McCall   llvm::APInt cookieSize(sizeWidth,
520036f2f6bSJohn McCall                          CalculateCookiePadding(CGF, e).getQuantity());
5218ed55a54SJohn McCall 
52259486a2dSAnders Carlsson   // Emit the array size expression.
5237648fb46SArgyrios Kyrtzidis   // We multiply the size of all dimensions for NumElements.
5247648fb46SArgyrios Kyrtzidis   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
525036f2f6bSJohn McCall   numElements = CGF.EmitScalarExpr(e->getArraySize());
526036f2f6bSJohn McCall   assert(isa<llvm::IntegerType>(numElements->getType()));
5278ed55a54SJohn McCall 
528036f2f6bSJohn McCall   // The number of elements can be have an arbitrary integer type;
529036f2f6bSJohn McCall   // essentially, we need to multiply it by a constant factor, add a
530036f2f6bSJohn McCall   // cookie size, and verify that the result is representable as a
531036f2f6bSJohn McCall   // size_t.  That's just a gloss, though, and it's wrong in one
532036f2f6bSJohn McCall   // important way: if the count is negative, it's an error even if
533036f2f6bSJohn McCall   // the cookie size would bring the total size >= 0.
5346ab2fa8fSDouglas Gregor   bool isSigned
5356ab2fa8fSDouglas Gregor     = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
5362192fe50SChris Lattner   llvm::IntegerType *numElementsType
537036f2f6bSJohn McCall     = cast<llvm::IntegerType>(numElements->getType());
538036f2f6bSJohn McCall   unsigned numElementsWidth = numElementsType->getBitWidth();
539036f2f6bSJohn McCall 
540036f2f6bSJohn McCall   // Compute the constant factor.
541036f2f6bSJohn McCall   llvm::APInt arraySizeMultiplier(sizeWidth, 1);
5427648fb46SArgyrios Kyrtzidis   while (const ConstantArrayType *CAT
543036f2f6bSJohn McCall              = CGF.getContext().getAsConstantArrayType(type)) {
544036f2f6bSJohn McCall     type = CAT->getElementType();
545036f2f6bSJohn McCall     arraySizeMultiplier *= CAT->getSize();
5467648fb46SArgyrios Kyrtzidis   }
54759486a2dSAnders Carlsson 
548036f2f6bSJohn McCall   CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
549036f2f6bSJohn McCall   llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
550036f2f6bSJohn McCall   typeSizeMultiplier *= arraySizeMultiplier;
551036f2f6bSJohn McCall 
552036f2f6bSJohn McCall   // This will be a size_t.
553036f2f6bSJohn McCall   llvm::Value *size;
55432ac583dSChris Lattner 
55532ac583dSChris Lattner   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
55632ac583dSChris Lattner   // Don't bloat the -O0 code.
557036f2f6bSJohn McCall   if (llvm::ConstantInt *numElementsC =
558036f2f6bSJohn McCall         dyn_cast<llvm::ConstantInt>(numElements)) {
559036f2f6bSJohn McCall     const llvm::APInt &count = numElementsC->getValue();
56032ac583dSChris Lattner 
561036f2f6bSJohn McCall     bool hasAnyOverflow = false;
56232ac583dSChris Lattner 
563036f2f6bSJohn McCall     // If 'count' was a negative number, it's an overflow.
564036f2f6bSJohn McCall     if (isSigned && count.isNegative())
565036f2f6bSJohn McCall       hasAnyOverflow = true;
5668ed55a54SJohn McCall 
567036f2f6bSJohn McCall     // We want to do all this arithmetic in size_t.  If numElements is
568036f2f6bSJohn McCall     // wider than that, check whether it's already too big, and if so,
569036f2f6bSJohn McCall     // overflow.
570036f2f6bSJohn McCall     else if (numElementsWidth > sizeWidth &&
571036f2f6bSJohn McCall              numElementsWidth - sizeWidth > count.countLeadingZeros())
572036f2f6bSJohn McCall       hasAnyOverflow = true;
573036f2f6bSJohn McCall 
574036f2f6bSJohn McCall     // Okay, compute a count at the right width.
575036f2f6bSJohn McCall     llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
576036f2f6bSJohn McCall 
577f862eb6aSSebastian Redl     // If there is a brace-initializer, we cannot allocate fewer elements than
578f862eb6aSSebastian Redl     // there are initializers. If we do, that's treated like an overflow.
579f862eb6aSSebastian Redl     if (adjustedCount.ult(minElements))
580f862eb6aSSebastian Redl       hasAnyOverflow = true;
581f862eb6aSSebastian Redl 
582036f2f6bSJohn McCall     // Scale numElements by that.  This might overflow, but we don't
583036f2f6bSJohn McCall     // care because it only overflows if allocationSize does, too, and
584036f2f6bSJohn McCall     // if that overflows then we shouldn't use this.
585036f2f6bSJohn McCall     numElements = llvm::ConstantInt::get(CGF.SizeTy,
586036f2f6bSJohn McCall                                          adjustedCount * arraySizeMultiplier);
587036f2f6bSJohn McCall 
588036f2f6bSJohn McCall     // Compute the size before cookie, and track whether it overflowed.
589036f2f6bSJohn McCall     bool overflow;
590036f2f6bSJohn McCall     llvm::APInt allocationSize
591036f2f6bSJohn McCall       = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
592036f2f6bSJohn McCall     hasAnyOverflow |= overflow;
593036f2f6bSJohn McCall 
594036f2f6bSJohn McCall     // Add in the cookie, and check whether it's overflowed.
595036f2f6bSJohn McCall     if (cookieSize != 0) {
596036f2f6bSJohn McCall       // Save the current size without a cookie.  This shouldn't be
597036f2f6bSJohn McCall       // used if there was overflow.
598036f2f6bSJohn McCall       sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
599036f2f6bSJohn McCall 
600036f2f6bSJohn McCall       allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
601036f2f6bSJohn McCall       hasAnyOverflow |= overflow;
6028ed55a54SJohn McCall     }
6038ed55a54SJohn McCall 
604036f2f6bSJohn McCall     // On overflow, produce a -1 so operator new will fail.
605455f42c9SAaron Ballman     if (hasAnyOverflow) {
606455f42c9SAaron Ballman       size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
607455f42c9SAaron Ballman     } else {
608036f2f6bSJohn McCall       size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
609455f42c9SAaron Ballman     }
61032ac583dSChris Lattner 
611036f2f6bSJohn McCall   // Otherwise, we might need to use the overflow intrinsics.
6128ed55a54SJohn McCall   } else {
613f862eb6aSSebastian Redl     // There are up to five conditions we need to test for:
614036f2f6bSJohn McCall     // 1) if isSigned, we need to check whether numElements is negative;
615036f2f6bSJohn McCall     // 2) if numElementsWidth > sizeWidth, we need to check whether
616036f2f6bSJohn McCall     //   numElements is larger than something representable in size_t;
617f862eb6aSSebastian Redl     // 3) if minElements > 0, we need to check whether numElements is smaller
618f862eb6aSSebastian Redl     //    than that.
619f862eb6aSSebastian Redl     // 4) we need to compute
620036f2f6bSJohn McCall     //      sizeWithoutCookie := numElements * typeSizeMultiplier
621036f2f6bSJohn McCall     //    and check whether it overflows; and
622f862eb6aSSebastian Redl     // 5) if we need a cookie, we need to compute
623036f2f6bSJohn McCall     //      size := sizeWithoutCookie + cookieSize
624036f2f6bSJohn McCall     //    and check whether it overflows.
6258ed55a54SJohn McCall 
6268a13c418SCraig Topper     llvm::Value *hasOverflow = nullptr;
6278ed55a54SJohn McCall 
628036f2f6bSJohn McCall     // If numElementsWidth > sizeWidth, then one way or another, we're
629036f2f6bSJohn McCall     // going to have to do a comparison for (2), and this happens to
630036f2f6bSJohn McCall     // take care of (1), too.
631036f2f6bSJohn McCall     if (numElementsWidth > sizeWidth) {
632036f2f6bSJohn McCall       llvm::APInt threshold(numElementsWidth, 1);
633036f2f6bSJohn McCall       threshold <<= sizeWidth;
6348ed55a54SJohn McCall 
635036f2f6bSJohn McCall       llvm::Value *thresholdV
636036f2f6bSJohn McCall         = llvm::ConstantInt::get(numElementsType, threshold);
637036f2f6bSJohn McCall 
638036f2f6bSJohn McCall       hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
639036f2f6bSJohn McCall       numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
640036f2f6bSJohn McCall 
641036f2f6bSJohn McCall     // Otherwise, if we're signed, we want to sext up to size_t.
642036f2f6bSJohn McCall     } else if (isSigned) {
643036f2f6bSJohn McCall       if (numElementsWidth < sizeWidth)
644036f2f6bSJohn McCall         numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
645036f2f6bSJohn McCall 
646036f2f6bSJohn McCall       // If there's a non-1 type size multiplier, then we can do the
647036f2f6bSJohn McCall       // signedness check at the same time as we do the multiply
648036f2f6bSJohn McCall       // because a negative number times anything will cause an
649f862eb6aSSebastian Redl       // unsigned overflow.  Otherwise, we have to do it here. But at least
650f862eb6aSSebastian Redl       // in this case, we can subsume the >= minElements check.
651036f2f6bSJohn McCall       if (typeSizeMultiplier == 1)
652036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
653f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
654036f2f6bSJohn McCall 
655036f2f6bSJohn McCall     // Otherwise, zext up to size_t if necessary.
656036f2f6bSJohn McCall     } else if (numElementsWidth < sizeWidth) {
657036f2f6bSJohn McCall       numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
658036f2f6bSJohn McCall     }
659036f2f6bSJohn McCall 
660036f2f6bSJohn McCall     assert(numElements->getType() == CGF.SizeTy);
661036f2f6bSJohn McCall 
662f862eb6aSSebastian Redl     if (minElements) {
663f862eb6aSSebastian Redl       // Don't allow allocation of fewer elements than we have initializers.
664f862eb6aSSebastian Redl       if (!hasOverflow) {
665f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateICmpULT(numElements,
666f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
667f862eb6aSSebastian Redl       } else if (numElementsWidth > sizeWidth) {
668f862eb6aSSebastian Redl         // The other existing overflow subsumes this check.
669f862eb6aSSebastian Redl         // We do an unsigned comparison, since any signed value < -1 is
670f862eb6aSSebastian Redl         // taken care of either above or below.
671f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateOr(hasOverflow,
672f862eb6aSSebastian Redl                           CGF.Builder.CreateICmpULT(numElements,
673f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements)));
674f862eb6aSSebastian Redl       }
675f862eb6aSSebastian Redl     }
676f862eb6aSSebastian Redl 
677036f2f6bSJohn McCall     size = numElements;
678036f2f6bSJohn McCall 
679036f2f6bSJohn McCall     // Multiply by the type size if necessary.  This multiplier
680036f2f6bSJohn McCall     // includes all the factors for nested arrays.
6818ed55a54SJohn McCall     //
682036f2f6bSJohn McCall     // This step also causes numElements to be scaled up by the
683036f2f6bSJohn McCall     // nested-array factor if necessary.  Overflow on this computation
684036f2f6bSJohn McCall     // can be ignored because the result shouldn't be used if
685036f2f6bSJohn McCall     // allocation fails.
686036f2f6bSJohn McCall     if (typeSizeMultiplier != 1) {
687036f2f6bSJohn McCall       llvm::Value *umul_with_overflow
6888d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
6898ed55a54SJohn McCall 
690036f2f6bSJohn McCall       llvm::Value *tsmV =
691036f2f6bSJohn McCall         llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
692036f2f6bSJohn McCall       llvm::Value *result =
69343f9bb73SDavid Blaikie           CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
6948ed55a54SJohn McCall 
695036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
696036f2f6bSJohn McCall       if (hasOverflow)
697036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
6988ed55a54SJohn McCall       else
699036f2f6bSJohn McCall         hasOverflow = overflowed;
70059486a2dSAnders Carlsson 
701036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
702036f2f6bSJohn McCall 
703036f2f6bSJohn McCall       // Also scale up numElements by the array size multiplier.
704036f2f6bSJohn McCall       if (arraySizeMultiplier != 1) {
705036f2f6bSJohn McCall         // If the base element type size is 1, then we can re-use the
706036f2f6bSJohn McCall         // multiply we just did.
707036f2f6bSJohn McCall         if (typeSize.isOne()) {
708036f2f6bSJohn McCall           assert(arraySizeMultiplier == typeSizeMultiplier);
709036f2f6bSJohn McCall           numElements = size;
710036f2f6bSJohn McCall 
711036f2f6bSJohn McCall         // Otherwise we need a separate multiply.
712036f2f6bSJohn McCall         } else {
713036f2f6bSJohn McCall           llvm::Value *asmV =
714036f2f6bSJohn McCall             llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
715036f2f6bSJohn McCall           numElements = CGF.Builder.CreateMul(numElements, asmV);
716036f2f6bSJohn McCall         }
717036f2f6bSJohn McCall       }
718036f2f6bSJohn McCall     } else {
719036f2f6bSJohn McCall       // numElements doesn't need to be scaled.
720036f2f6bSJohn McCall       assert(arraySizeMultiplier == 1);
721036f2f6bSJohn McCall     }
722036f2f6bSJohn McCall 
723036f2f6bSJohn McCall     // Add in the cookie size if necessary.
724036f2f6bSJohn McCall     if (cookieSize != 0) {
725036f2f6bSJohn McCall       sizeWithoutCookie = size;
726036f2f6bSJohn McCall 
727036f2f6bSJohn McCall       llvm::Value *uadd_with_overflow
7288d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
729036f2f6bSJohn McCall 
730036f2f6bSJohn McCall       llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
731036f2f6bSJohn McCall       llvm::Value *result =
73243f9bb73SDavid Blaikie           CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
733036f2f6bSJohn McCall 
734036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
735036f2f6bSJohn McCall       if (hasOverflow)
736036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
737036f2f6bSJohn McCall       else
738036f2f6bSJohn McCall         hasOverflow = overflowed;
739036f2f6bSJohn McCall 
740036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
741036f2f6bSJohn McCall     }
742036f2f6bSJohn McCall 
743036f2f6bSJohn McCall     // If we had any possibility of dynamic overflow, make a select to
744036f2f6bSJohn McCall     // overwrite 'size' with an all-ones value, which should cause
745036f2f6bSJohn McCall     // operator new to throw.
746036f2f6bSJohn McCall     if (hasOverflow)
747455f42c9SAaron Ballman       size = CGF.Builder.CreateSelect(hasOverflow,
748455f42c9SAaron Ballman                                  llvm::Constant::getAllOnesValue(CGF.SizeTy),
749036f2f6bSJohn McCall                                       size);
750036f2f6bSJohn McCall   }
751036f2f6bSJohn McCall 
752036f2f6bSJohn McCall   if (cookieSize == 0)
753036f2f6bSJohn McCall     sizeWithoutCookie = size;
754036f2f6bSJohn McCall   else
755036f2f6bSJohn McCall     assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
756036f2f6bSJohn McCall 
757036f2f6bSJohn McCall   return size;
75859486a2dSAnders Carlsson }
75959486a2dSAnders Carlsson 
760f862eb6aSSebastian Redl static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
7617f416cc4SJohn McCall                                     QualType AllocType, Address NewPtr) {
7621c96bc5dSRichard Smith   // FIXME: Refactor with EmitExprAsInit.
76347fb9508SJohn McCall   switch (CGF.getEvaluationKind(AllocType)) {
76447fb9508SJohn McCall   case TEK_Scalar:
765a2c1124fSDavid Blaikie     CGF.EmitScalarInit(Init, nullptr,
7667f416cc4SJohn McCall                        CGF.MakeAddrLValue(NewPtr, AllocType), false);
76747fb9508SJohn McCall     return;
76847fb9508SJohn McCall   case TEK_Complex:
7697f416cc4SJohn McCall     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
77047fb9508SJohn McCall                                   /*isInit*/ true);
77147fb9508SJohn McCall     return;
77247fb9508SJohn McCall   case TEK_Aggregate: {
7737a626f63SJohn McCall     AggValueSlot Slot
7747f416cc4SJohn McCall       = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
7758d6fc958SJohn McCall                               AggValueSlot::IsDestructed,
77646759f4fSJohn McCall                               AggValueSlot::DoesNotNeedGCBarriers,
777615ed1a3SChad Rosier                               AggValueSlot::IsNotAliased);
7787a626f63SJohn McCall     CGF.EmitAggExpr(Init, Slot);
77947fb9508SJohn McCall     return;
7807a626f63SJohn McCall   }
781d5202e09SFariborz Jahanian   }
78247fb9508SJohn McCall   llvm_unreachable("bad evaluation kind");
78347fb9508SJohn McCall }
784d5202e09SFariborz Jahanian 
785fb901c7aSDavid Blaikie void CodeGenFunction::EmitNewArrayInitializer(
786fb901c7aSDavid Blaikie     const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
7877f416cc4SJohn McCall     Address BeginPtr, llvm::Value *NumElements,
78806a67e2cSRichard Smith     llvm::Value *AllocSizeWithoutCookie) {
78906a67e2cSRichard Smith   // If we have a type with trivial initialization and no initializer,
79006a67e2cSRichard Smith   // there's nothing to do.
7916047f07eSSebastian Redl   if (!E->hasInitializer())
79206a67e2cSRichard Smith     return;
793b66b08efSFariborz Jahanian 
7947f416cc4SJohn McCall   Address CurPtr = BeginPtr;
795d5202e09SFariborz Jahanian 
79606a67e2cSRichard Smith   unsigned InitListElements = 0;
797f862eb6aSSebastian Redl 
798f862eb6aSSebastian Redl   const Expr *Init = E->getInitializer();
7997f416cc4SJohn McCall   Address EndOfInit = Address::invalid();
80006a67e2cSRichard Smith   QualType::DestructionKind DtorKind = ElementType.isDestructedType();
80106a67e2cSRichard Smith   EHScopeStack::stable_iterator Cleanup;
80206a67e2cSRichard Smith   llvm::Instruction *CleanupDominator = nullptr;
8031c96bc5dSRichard Smith 
8047f416cc4SJohn McCall   CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
8057f416cc4SJohn McCall   CharUnits ElementAlign =
8067f416cc4SJohn McCall     BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
8077f416cc4SJohn McCall 
808f862eb6aSSebastian Redl   // If the initializer is an initializer list, first do the explicit elements.
809f862eb6aSSebastian Redl   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
81006a67e2cSRichard Smith     InitListElements = ILE->getNumInits();
811f62290a1SChad Rosier 
8121c96bc5dSRichard Smith     // If this is a multi-dimensional array new, we will initialize multiple
8131c96bc5dSRichard Smith     // elements with each init list element.
8141c96bc5dSRichard Smith     QualType AllocType = E->getAllocatedType();
8151c96bc5dSRichard Smith     if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
8161c96bc5dSRichard Smith             AllocType->getAsArrayTypeUnsafe())) {
817fb901c7aSDavid Blaikie       ElementTy = ConvertTypeForMem(AllocType);
8187f416cc4SJohn McCall       CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
81906a67e2cSRichard Smith       InitListElements *= getContext().getConstantArrayElementCount(CAT);
8201c96bc5dSRichard Smith     }
8211c96bc5dSRichard Smith 
82206a67e2cSRichard Smith     // Enter a partial-destruction Cleanup if necessary.
82306a67e2cSRichard Smith     if (needsEHCleanup(DtorKind)) {
82406a67e2cSRichard Smith       // In principle we could tell the Cleanup where we are more
825f62290a1SChad Rosier       // directly, but the control flow can get so varied here that it
826f62290a1SChad Rosier       // would actually be quite complex.  Therefore we go through an
827f62290a1SChad Rosier       // alloca.
8287f416cc4SJohn McCall       EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
8297f416cc4SJohn McCall                                    "array.init.end");
8307f416cc4SJohn McCall       CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
8317f416cc4SJohn McCall       pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
8327f416cc4SJohn McCall                                        ElementType, ElementAlign,
83306a67e2cSRichard Smith                                        getDestroyer(DtorKind));
83406a67e2cSRichard Smith       Cleanup = EHStack.stable_begin();
835f62290a1SChad Rosier     }
836f62290a1SChad Rosier 
8377f416cc4SJohn McCall     CharUnits StartAlign = CurPtr.getAlignment();
838f862eb6aSSebastian Redl     for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
839f62290a1SChad Rosier       // Tell the cleanup that it needs to destroy up to this
840f62290a1SChad Rosier       // element.  TODO: some of these stores can be trivially
841f62290a1SChad Rosier       // observed to be unnecessary.
8427f416cc4SJohn McCall       if (EndOfInit.isValid()) {
8437f416cc4SJohn McCall         auto FinishedPtr =
8447f416cc4SJohn McCall           Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
8457f416cc4SJohn McCall         Builder.CreateStore(FinishedPtr, EndOfInit);
8467f416cc4SJohn McCall       }
84706a67e2cSRichard Smith       // FIXME: If the last initializer is an incomplete initializer list for
84806a67e2cSRichard Smith       // an array, and we have an array filler, we can fold together the two
84906a67e2cSRichard Smith       // initialization loops.
8501c96bc5dSRichard Smith       StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
85106a67e2cSRichard Smith                               ILE->getInit(i)->getType(), CurPtr);
8527f416cc4SJohn McCall       CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
8537f416cc4SJohn McCall                                                  Builder.getSize(1),
8547f416cc4SJohn McCall                                                  "array.exp.next"),
8557f416cc4SJohn McCall                        StartAlign.alignmentAtOffset((i + 1) * ElementSize));
856f862eb6aSSebastian Redl     }
857f862eb6aSSebastian Redl 
858f862eb6aSSebastian Redl     // The remaining elements are filled with the array filler expression.
859f862eb6aSSebastian Redl     Init = ILE->getArrayFiller();
8601c96bc5dSRichard Smith 
86106a67e2cSRichard Smith     // Extract the initializer for the individual array elements by pulling
86206a67e2cSRichard Smith     // out the array filler from all the nested initializer lists. This avoids
86306a67e2cSRichard Smith     // generating a nested loop for the initialization.
86406a67e2cSRichard Smith     while (Init && Init->getType()->isConstantArrayType()) {
86506a67e2cSRichard Smith       auto *SubILE = dyn_cast<InitListExpr>(Init);
86606a67e2cSRichard Smith       if (!SubILE)
86706a67e2cSRichard Smith         break;
86806a67e2cSRichard Smith       assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
86906a67e2cSRichard Smith       Init = SubILE->getArrayFiller();
870f862eb6aSSebastian Redl     }
871f862eb6aSSebastian Redl 
87206a67e2cSRichard Smith     // Switch back to initializing one base element at a time.
8737f416cc4SJohn McCall     CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
874f62290a1SChad Rosier   }
875e6c980c4SChandler Carruth 
87606a67e2cSRichard Smith   // Attempt to perform zero-initialization using memset.
87706a67e2cSRichard Smith   auto TryMemsetInitialization = [&]() -> bool {
87806a67e2cSRichard Smith     // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
87906a67e2cSRichard Smith     // we can initialize with a memset to -1.
88006a67e2cSRichard Smith     if (!CGM.getTypes().isZeroInitializable(ElementType))
88106a67e2cSRichard Smith       return false;
882e6c980c4SChandler Carruth 
88306a67e2cSRichard Smith     // Optimization: since zero initialization will just set the memory
88406a67e2cSRichard Smith     // to all zeroes, generate a single memset to do it in one shot.
88506a67e2cSRichard Smith 
88606a67e2cSRichard Smith     // Subtract out the size of any elements we've already initialized.
88706a67e2cSRichard Smith     auto *RemainingSize = AllocSizeWithoutCookie;
88806a67e2cSRichard Smith     if (InitListElements) {
88906a67e2cSRichard Smith       // We know this can't overflow; we check this when doing the allocation.
89006a67e2cSRichard Smith       auto *InitializedSize = llvm::ConstantInt::get(
89106a67e2cSRichard Smith           RemainingSize->getType(),
89206a67e2cSRichard Smith           getContext().getTypeSizeInChars(ElementType).getQuantity() *
89306a67e2cSRichard Smith               InitListElements);
89406a67e2cSRichard Smith       RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
89599210dc9SJohn McCall     }
896d5202e09SFariborz Jahanian 
89706a67e2cSRichard Smith     // Create the memset.
8987f416cc4SJohn McCall     Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
89906a67e2cSRichard Smith     return true;
90006a67e2cSRichard Smith   };
90105fc5be3SDouglas Gregor 
902454a7cdfSRichard Smith   // If all elements have already been initialized, skip any further
903454a7cdfSRichard Smith   // initialization.
904454a7cdfSRichard Smith   llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
905454a7cdfSRichard Smith   if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
906454a7cdfSRichard Smith     // If there was a Cleanup, deactivate it.
907454a7cdfSRichard Smith     if (CleanupDominator)
908454a7cdfSRichard Smith       DeactivateCleanupBlock(Cleanup, CleanupDominator);
909454a7cdfSRichard Smith     return;
910454a7cdfSRichard Smith   }
911454a7cdfSRichard Smith 
912454a7cdfSRichard Smith   assert(Init && "have trailing elements to initialize but no initializer");
913454a7cdfSRichard Smith 
91406a67e2cSRichard Smith   // If this is a constructor call, try to optimize it out, and failing that
91506a67e2cSRichard Smith   // emit a single loop to initialize all remaining elements.
916454a7cdfSRichard Smith   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9176047f07eSSebastian Redl     CXXConstructorDecl *Ctor = CCE->getConstructor();
918d153103cSDouglas Gregor     if (Ctor->isTrivial()) {
91905fc5be3SDouglas Gregor       // If new expression did not specify value-initialization, then there
92005fc5be3SDouglas Gregor       // is no initialization.
9216047f07eSSebastian Redl       if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
92205fc5be3SDouglas Gregor         return;
92305fc5be3SDouglas Gregor 
92406a67e2cSRichard Smith       if (TryMemsetInitialization())
9253a202f60SAnders Carlsson         return;
9263a202f60SAnders Carlsson     }
92705fc5be3SDouglas Gregor 
92806a67e2cSRichard Smith     // Store the new Cleanup position for irregular Cleanups.
92906a67e2cSRichard Smith     //
93006a67e2cSRichard Smith     // FIXME: Share this cleanup with the constructor call emission rather than
93106a67e2cSRichard Smith     // having it create a cleanup of its own.
9327f416cc4SJohn McCall     if (EndOfInit.isValid())
9337f416cc4SJohn McCall       Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
93406a67e2cSRichard Smith 
93506a67e2cSRichard Smith     // Emit a constructor call loop to initialize the remaining elements.
93606a67e2cSRichard Smith     if (InitListElements)
93706a67e2cSRichard Smith       NumElements = Builder.CreateSub(
93806a67e2cSRichard Smith           NumElements,
93906a67e2cSRichard Smith           llvm::ConstantInt::get(NumElements->getType(), InitListElements));
94070b9c01bSAlexey Samsonov     EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
94148ddcf2cSEli Friedman                                CCE->requiresZeroInitialization());
94205fc5be3SDouglas Gregor     return;
9436047f07eSSebastian Redl   }
94406a67e2cSRichard Smith 
94506a67e2cSRichard Smith   // If this is value-initialization, we can usually use memset.
94606a67e2cSRichard Smith   ImplicitValueInitExpr IVIE(ElementType);
947454a7cdfSRichard Smith   if (isa<ImplicitValueInitExpr>(Init)) {
94806a67e2cSRichard Smith     if (TryMemsetInitialization())
94906a67e2cSRichard Smith       return;
95006a67e2cSRichard Smith 
95106a67e2cSRichard Smith     // Switch to an ImplicitValueInitExpr for the element type. This handles
95206a67e2cSRichard Smith     // only one case: multidimensional array new of pointers to members. In
95306a67e2cSRichard Smith     // all other cases, we already have an initializer for the array element.
95406a67e2cSRichard Smith     Init = &IVIE;
95506a67e2cSRichard Smith   }
95606a67e2cSRichard Smith 
95706a67e2cSRichard Smith   // At this point we should have found an initializer for the individual
95806a67e2cSRichard Smith   // elements of the array.
95906a67e2cSRichard Smith   assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
96006a67e2cSRichard Smith          "got wrong type of element to initialize");
96106a67e2cSRichard Smith 
962454a7cdfSRichard Smith   // If we have an empty initializer list, we can usually use memset.
963454a7cdfSRichard Smith   if (auto *ILE = dyn_cast<InitListExpr>(Init))
964454a7cdfSRichard Smith     if (ILE->getNumInits() == 0 && TryMemsetInitialization())
965d5202e09SFariborz Jahanian       return;
96659486a2dSAnders Carlsson 
967cb77930dSYunzhong Gao   // If we have a struct whose every field is value-initialized, we can
968cb77930dSYunzhong Gao   // usually use memset.
969cb77930dSYunzhong Gao   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
970cb77930dSYunzhong Gao     if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
971cb77930dSYunzhong Gao       if (RType->getDecl()->isStruct()) {
972cb77930dSYunzhong Gao         unsigned NumFields = 0;
973cb77930dSYunzhong Gao         for (auto *Field : RType->getDecl()->fields())
974cb77930dSYunzhong Gao           if (!Field->isUnnamedBitfield())
975cb77930dSYunzhong Gao             ++NumFields;
976cb77930dSYunzhong Gao         if (ILE->getNumInits() == NumFields)
977cb77930dSYunzhong Gao           for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
978cb77930dSYunzhong Gao             if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
979cb77930dSYunzhong Gao               --NumFields;
980cb77930dSYunzhong Gao         if (ILE->getNumInits() == NumFields && TryMemsetInitialization())
981cb77930dSYunzhong Gao           return;
982cb77930dSYunzhong Gao       }
983cb77930dSYunzhong Gao     }
984cb77930dSYunzhong Gao   }
985cb77930dSYunzhong Gao 
98606a67e2cSRichard Smith   // Create the loop blocks.
98706a67e2cSRichard Smith   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
98806a67e2cSRichard Smith   llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
98906a67e2cSRichard Smith   llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
99059486a2dSAnders Carlsson 
99106a67e2cSRichard Smith   // Find the end of the array, hoisted out of the loop.
99206a67e2cSRichard Smith   llvm::Value *EndPtr =
9937f416cc4SJohn McCall     Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
99406a67e2cSRichard Smith 
99506a67e2cSRichard Smith   // If the number of elements isn't constant, we have to now check if there is
99606a67e2cSRichard Smith   // anything left to initialize.
99706a67e2cSRichard Smith   if (!ConstNum) {
9987f416cc4SJohn McCall     llvm::Value *IsEmpty =
9997f416cc4SJohn McCall       Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
100006a67e2cSRichard Smith     Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
100106a67e2cSRichard Smith   }
100206a67e2cSRichard Smith 
100306a67e2cSRichard Smith   // Enter the loop.
100406a67e2cSRichard Smith   EmitBlock(LoopBB);
100506a67e2cSRichard Smith 
100606a67e2cSRichard Smith   // Set up the current-element phi.
100706a67e2cSRichard Smith   llvm::PHINode *CurPtrPhi =
10087f416cc4SJohn McCall     Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
10097f416cc4SJohn McCall   CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
10107f416cc4SJohn McCall 
10117f416cc4SJohn McCall   CurPtr = Address(CurPtrPhi, ElementAlign);
101206a67e2cSRichard Smith 
101306a67e2cSRichard Smith   // Store the new Cleanup position for irregular Cleanups.
10147f416cc4SJohn McCall   if (EndOfInit.isValid())
10157f416cc4SJohn McCall     Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
101606a67e2cSRichard Smith 
101706a67e2cSRichard Smith   // Enter a partial-destruction Cleanup if necessary.
101806a67e2cSRichard Smith   if (!CleanupDominator && needsEHCleanup(DtorKind)) {
10197f416cc4SJohn McCall     pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
10207f416cc4SJohn McCall                                    ElementType, ElementAlign,
102106a67e2cSRichard Smith                                    getDestroyer(DtorKind));
102206a67e2cSRichard Smith     Cleanup = EHStack.stable_begin();
102306a67e2cSRichard Smith     CleanupDominator = Builder.CreateUnreachable();
102406a67e2cSRichard Smith   }
102506a67e2cSRichard Smith 
102606a67e2cSRichard Smith   // Emit the initializer into this element.
102706a67e2cSRichard Smith   StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
102806a67e2cSRichard Smith 
102906a67e2cSRichard Smith   // Leave the Cleanup if we entered one.
103006a67e2cSRichard Smith   if (CleanupDominator) {
103106a67e2cSRichard Smith     DeactivateCleanupBlock(Cleanup, CleanupDominator);
103206a67e2cSRichard Smith     CleanupDominator->eraseFromParent();
103306a67e2cSRichard Smith   }
103406a67e2cSRichard Smith 
103506a67e2cSRichard Smith   // Advance to the next element by adjusting the pointer type as necessary.
103606a67e2cSRichard Smith   llvm::Value *NextPtr =
10377f416cc4SJohn McCall     Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
10387f416cc4SJohn McCall                                        "array.next");
103906a67e2cSRichard Smith 
104006a67e2cSRichard Smith   // Check whether we've gotten to the end of the array and, if so,
104106a67e2cSRichard Smith   // exit the loop.
104206a67e2cSRichard Smith   llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
104306a67e2cSRichard Smith   Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
104406a67e2cSRichard Smith   CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
104506a67e2cSRichard Smith 
104606a67e2cSRichard Smith   EmitBlock(ContBB);
104706a67e2cSRichard Smith }
104806a67e2cSRichard Smith 
104906a67e2cSRichard Smith static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1050fb901c7aSDavid Blaikie                                QualType ElementType, llvm::Type *ElementTy,
10517f416cc4SJohn McCall                                Address NewPtr, llvm::Value *NumElements,
105206a67e2cSRichard Smith                                llvm::Value *AllocSizeWithoutCookie) {
10539b479666SDavid Blaikie   ApplyDebugLocation DL(CGF, E);
105406a67e2cSRichard Smith   if (E->isArray())
1055fb901c7aSDavid Blaikie     CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
105606a67e2cSRichard Smith                                 AllocSizeWithoutCookie);
105706a67e2cSRichard Smith   else if (const Expr *Init = E->getInitializer())
105866e4197fSDavid Blaikie     StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
105959486a2dSAnders Carlsson }
106059486a2dSAnders Carlsson 
10618d0dc31dSRichard Smith /// Emit a call to an operator new or operator delete function, as implicitly
10628d0dc31dSRichard Smith /// created by new-expressions and delete-expressions.
10638d0dc31dSRichard Smith static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
10648d0dc31dSRichard Smith                                 const FunctionDecl *Callee,
10658d0dc31dSRichard Smith                                 const FunctionProtoType *CalleeType,
10668d0dc31dSRichard Smith                                 const CallArgList &Args) {
10678d0dc31dSRichard Smith   llvm::Instruction *CallOrInvoke;
10681235a8daSRichard Smith   llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
10698d0dc31dSRichard Smith   RValue RV =
1070f770683fSPeter Collingbourne       CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1071f770683fSPeter Collingbourne                        Args, CalleeType, /*chainCall=*/false),
1072f770683fSPeter Collingbourne                    CalleeAddr, ReturnValueSlot(), Args, Callee, &CallOrInvoke);
10738d0dc31dSRichard Smith 
10748d0dc31dSRichard Smith   /// C++1y [expr.new]p10:
10758d0dc31dSRichard Smith   ///   [In a new-expression,] an implementation is allowed to omit a call
10768d0dc31dSRichard Smith   ///   to a replaceable global allocation function.
10778d0dc31dSRichard Smith   ///
10788d0dc31dSRichard Smith   /// We model such elidable calls with the 'builtin' attribute.
10796956d587SRafael Espindola   llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
10801235a8daSRichard Smith   if (Callee->isReplaceableGlobalAllocationFunction() &&
10816956d587SRafael Espindola       Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
10828d0dc31dSRichard Smith     // FIXME: Add addAttribute to CallSite.
10838d0dc31dSRichard Smith     if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
10848d0dc31dSRichard Smith       CI->addAttribute(llvm::AttributeSet::FunctionIndex,
10858d0dc31dSRichard Smith                        llvm::Attribute::Builtin);
10868d0dc31dSRichard Smith     else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
10878d0dc31dSRichard Smith       II->addAttribute(llvm::AttributeSet::FunctionIndex,
10888d0dc31dSRichard Smith                        llvm::Attribute::Builtin);
10898d0dc31dSRichard Smith     else
10908d0dc31dSRichard Smith       llvm_unreachable("unexpected kind of call instruction");
10918d0dc31dSRichard Smith   }
10928d0dc31dSRichard Smith 
10938d0dc31dSRichard Smith   return RV;
10948d0dc31dSRichard Smith }
10958d0dc31dSRichard Smith 
1096760520bcSRichard Smith RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1097760520bcSRichard Smith                                                  const Expr *Arg,
1098760520bcSRichard Smith                                                  bool IsDelete) {
1099760520bcSRichard Smith   CallArgList Args;
1100760520bcSRichard Smith   const Stmt *ArgS = Arg;
1101f05779e2SDavid Blaikie   EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS));
1102760520bcSRichard Smith   // Find the allocation or deallocation function that we're calling.
1103760520bcSRichard Smith   ASTContext &Ctx = getContext();
1104760520bcSRichard Smith   DeclarationName Name = Ctx.DeclarationNames
1105760520bcSRichard Smith       .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1106760520bcSRichard Smith   for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1107599bed75SRichard Smith     if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1108599bed75SRichard Smith       if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1109760520bcSRichard Smith         return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1110760520bcSRichard Smith   llvm_unreachable("predeclared global operator new/delete is missing");
1111760520bcSRichard Smith }
1112760520bcSRichard Smith 
1113824c2f53SJohn McCall namespace {
1114824c2f53SJohn McCall   /// A cleanup to call the given 'operator delete' function upon
1115824c2f53SJohn McCall   /// abnormal exit from a new expression.
11167e70d680SDavid Blaikie   class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1117824c2f53SJohn McCall     size_t NumPlacementArgs;
1118824c2f53SJohn McCall     const FunctionDecl *OperatorDelete;
1119824c2f53SJohn McCall     llvm::Value *Ptr;
1120824c2f53SJohn McCall     llvm::Value *AllocSize;
1121824c2f53SJohn McCall 
1122824c2f53SJohn McCall     RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1123824c2f53SJohn McCall 
1124824c2f53SJohn McCall   public:
1125824c2f53SJohn McCall     static size_t getExtraSize(size_t NumPlacementArgs) {
1126824c2f53SJohn McCall       return NumPlacementArgs * sizeof(RValue);
1127824c2f53SJohn McCall     }
1128824c2f53SJohn McCall 
1129824c2f53SJohn McCall     CallDeleteDuringNew(size_t NumPlacementArgs,
1130824c2f53SJohn McCall                         const FunctionDecl *OperatorDelete,
1131824c2f53SJohn McCall                         llvm::Value *Ptr,
1132824c2f53SJohn McCall                         llvm::Value *AllocSize)
1133824c2f53SJohn McCall       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1134824c2f53SJohn McCall         Ptr(Ptr), AllocSize(AllocSize) {}
1135824c2f53SJohn McCall 
1136824c2f53SJohn McCall     void setPlacementArg(unsigned I, RValue Arg) {
1137824c2f53SJohn McCall       assert(I < NumPlacementArgs && "index out of range");
1138824c2f53SJohn McCall       getPlacementArgs()[I] = Arg;
1139824c2f53SJohn McCall     }
1140824c2f53SJohn McCall 
11414f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
1142824c2f53SJohn McCall       const FunctionProtoType *FPT
1143824c2f53SJohn McCall         = OperatorDelete->getType()->getAs<FunctionProtoType>();
11449cacbabdSAlp Toker       assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
11459cacbabdSAlp Toker              (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
1146824c2f53SJohn McCall 
1147824c2f53SJohn McCall       CallArgList DeleteArgs;
1148824c2f53SJohn McCall 
1149824c2f53SJohn McCall       // The first argument is always a void*.
11509cacbabdSAlp Toker       FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
115143dca6a8SEli Friedman       DeleteArgs.add(RValue::get(Ptr), *AI++);
1152824c2f53SJohn McCall 
1153824c2f53SJohn McCall       // A member 'operator delete' can take an extra 'size_t' argument.
11549cacbabdSAlp Toker       if (FPT->getNumParams() == NumPlacementArgs + 2)
115543dca6a8SEli Friedman         DeleteArgs.add(RValue::get(AllocSize), *AI++);
1156824c2f53SJohn McCall 
1157824c2f53SJohn McCall       // Pass the rest of the arguments, which must match exactly.
1158824c2f53SJohn McCall       for (unsigned I = 0; I != NumPlacementArgs; ++I)
115943dca6a8SEli Friedman         DeleteArgs.add(getPlacementArgs()[I], *AI++);
1160824c2f53SJohn McCall 
1161824c2f53SJohn McCall       // Call 'operator delete'.
11628d0dc31dSRichard Smith       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1163824c2f53SJohn McCall     }
1164824c2f53SJohn McCall   };
11657f9c92a9SJohn McCall 
11667f9c92a9SJohn McCall   /// A cleanup to call the given 'operator delete' function upon
11677f9c92a9SJohn McCall   /// abnormal exit from a new expression when the new expression is
11687f9c92a9SJohn McCall   /// conditional.
11697e70d680SDavid Blaikie   class CallDeleteDuringConditionalNew final : public EHScopeStack::Cleanup {
11707f9c92a9SJohn McCall     size_t NumPlacementArgs;
11717f9c92a9SJohn McCall     const FunctionDecl *OperatorDelete;
1172cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type Ptr;
1173cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type AllocSize;
11747f9c92a9SJohn McCall 
1175cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type *getPlacementArgs() {
1176cb5f77f0SJohn McCall       return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
11777f9c92a9SJohn McCall     }
11787f9c92a9SJohn McCall 
11797f9c92a9SJohn McCall   public:
11807f9c92a9SJohn McCall     static size_t getExtraSize(size_t NumPlacementArgs) {
1181cb5f77f0SJohn McCall       return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
11827f9c92a9SJohn McCall     }
11837f9c92a9SJohn McCall 
11847f9c92a9SJohn McCall     CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
11857f9c92a9SJohn McCall                                    const FunctionDecl *OperatorDelete,
1186cb5f77f0SJohn McCall                                    DominatingValue<RValue>::saved_type Ptr,
1187cb5f77f0SJohn McCall                               DominatingValue<RValue>::saved_type AllocSize)
11887f9c92a9SJohn McCall       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
11897f9c92a9SJohn McCall         Ptr(Ptr), AllocSize(AllocSize) {}
11907f9c92a9SJohn McCall 
1191cb5f77f0SJohn McCall     void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
11927f9c92a9SJohn McCall       assert(I < NumPlacementArgs && "index out of range");
11937f9c92a9SJohn McCall       getPlacementArgs()[I] = Arg;
11947f9c92a9SJohn McCall     }
11957f9c92a9SJohn McCall 
11964f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
11977f9c92a9SJohn McCall       const FunctionProtoType *FPT
11987f9c92a9SJohn McCall         = OperatorDelete->getType()->getAs<FunctionProtoType>();
11999cacbabdSAlp Toker       assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
12009cacbabdSAlp Toker              (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
12017f9c92a9SJohn McCall 
12027f9c92a9SJohn McCall       CallArgList DeleteArgs;
12037f9c92a9SJohn McCall 
12047f9c92a9SJohn McCall       // The first argument is always a void*.
12059cacbabdSAlp Toker       FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
120643dca6a8SEli Friedman       DeleteArgs.add(Ptr.restore(CGF), *AI++);
12077f9c92a9SJohn McCall 
12087f9c92a9SJohn McCall       // A member 'operator delete' can take an extra 'size_t' argument.
12099cacbabdSAlp Toker       if (FPT->getNumParams() == NumPlacementArgs + 2) {
1210cb5f77f0SJohn McCall         RValue RV = AllocSize.restore(CGF);
121143dca6a8SEli Friedman         DeleteArgs.add(RV, *AI++);
12127f9c92a9SJohn McCall       }
12137f9c92a9SJohn McCall 
12147f9c92a9SJohn McCall       // Pass the rest of the arguments, which must match exactly.
12157f9c92a9SJohn McCall       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1216cb5f77f0SJohn McCall         RValue RV = getPlacementArgs()[I].restore(CGF);
121743dca6a8SEli Friedman         DeleteArgs.add(RV, *AI++);
12187f9c92a9SJohn McCall       }
12197f9c92a9SJohn McCall 
12207f9c92a9SJohn McCall       // Call 'operator delete'.
12218d0dc31dSRichard Smith       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
12227f9c92a9SJohn McCall     }
12237f9c92a9SJohn McCall   };
1224ab9db510SAlexander Kornienko }
12257f9c92a9SJohn McCall 
12267f9c92a9SJohn McCall /// Enter a cleanup to call 'operator delete' if the initializer in a
12277f9c92a9SJohn McCall /// new-expression throws.
12287f9c92a9SJohn McCall static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
12297f9c92a9SJohn McCall                                   const CXXNewExpr *E,
12307f416cc4SJohn McCall                                   Address NewPtr,
12317f9c92a9SJohn McCall                                   llvm::Value *AllocSize,
12327f9c92a9SJohn McCall                                   const CallArgList &NewArgs) {
12337f9c92a9SJohn McCall   // If we're not inside a conditional branch, then the cleanup will
12347f9c92a9SJohn McCall   // dominate and we can do the easier (and more efficient) thing.
12357f9c92a9SJohn McCall   if (!CGF.isInConditionalBranch()) {
12367f9c92a9SJohn McCall     CallDeleteDuringNew *Cleanup = CGF.EHStack
12377f9c92a9SJohn McCall       .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
12387f9c92a9SJohn McCall                                                  E->getNumPlacementArgs(),
12397f9c92a9SJohn McCall                                                  E->getOperatorDelete(),
12407f416cc4SJohn McCall                                                  NewPtr.getPointer(),
12417f416cc4SJohn McCall                                                  AllocSize);
12427f9c92a9SJohn McCall     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1243f4258eb4SEli Friedman       Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
12447f9c92a9SJohn McCall 
12457f9c92a9SJohn McCall     return;
12467f9c92a9SJohn McCall   }
12477f9c92a9SJohn McCall 
12487f9c92a9SJohn McCall   // Otherwise, we need to save all this stuff.
1249cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedNewPtr =
12507f416cc4SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
1251cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedAllocSize =
1252cb5f77f0SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
12537f9c92a9SJohn McCall 
12547f9c92a9SJohn McCall   CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
1255f4beacd0SJohn McCall     .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
12567f9c92a9SJohn McCall                                                  E->getNumPlacementArgs(),
12577f9c92a9SJohn McCall                                                  E->getOperatorDelete(),
12587f9c92a9SJohn McCall                                                  SavedNewPtr,
12597f9c92a9SJohn McCall                                                  SavedAllocSize);
12607f9c92a9SJohn McCall   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1261cb5f77f0SJohn McCall     Cleanup->setPlacementArg(I,
1262f4258eb4SEli Friedman                      DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
12637f9c92a9SJohn McCall 
1264f4beacd0SJohn McCall   CGF.initFullExprCleanup();
1265824c2f53SJohn McCall }
1266824c2f53SJohn McCall 
126759486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
126875f9498aSJohn McCall   // The element type being allocated.
126975f9498aSJohn McCall   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
12708ed55a54SJohn McCall 
127175f9498aSJohn McCall   // 1. Build a call to the allocation function.
127275f9498aSJohn McCall   FunctionDecl *allocator = E->getOperatorNew();
127359486a2dSAnders Carlsson 
1274f862eb6aSSebastian Redl   // If there is a brace-initializer, cannot allocate fewer elements than inits.
1275f862eb6aSSebastian Redl   unsigned minElements = 0;
1276f862eb6aSSebastian Redl   if (E->isArray() && E->hasInitializer()) {
1277f862eb6aSSebastian Redl     if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1278f862eb6aSSebastian Redl       minElements = ILE->getNumInits();
1279f862eb6aSSebastian Redl   }
1280f862eb6aSSebastian Redl 
12818a13c418SCraig Topper   llvm::Value *numElements = nullptr;
12828a13c418SCraig Topper   llvm::Value *allocSizeWithoutCookie = nullptr;
128375f9498aSJohn McCall   llvm::Value *allocSize =
1284f862eb6aSSebastian Redl     EmitCXXNewAllocSize(*this, E, minElements, numElements,
1285f862eb6aSSebastian Redl                         allocSizeWithoutCookie);
128659486a2dSAnders Carlsson 
12877f416cc4SJohn McCall   // Emit the allocation call.  If the allocator is a global placement
12887f416cc4SJohn McCall   // operator, just "inline" it directly.
12897f416cc4SJohn McCall   Address allocation = Address::invalid();
12907f416cc4SJohn McCall   CallArgList allocatorArgs;
12917f416cc4SJohn McCall   if (allocator->isReservedGlobalPlacementOperator()) {
1292*53dcf94dSJohn McCall     assert(E->getNumPlacementArgs() == 1);
1293*53dcf94dSJohn McCall     const Expr *arg = *E->placement_arguments().begin();
1294*53dcf94dSJohn McCall 
12957f416cc4SJohn McCall     AlignmentSource alignSource;
1296*53dcf94dSJohn McCall     allocation = EmitPointerWithAlignment(arg, &alignSource);
12977f416cc4SJohn McCall 
12987f416cc4SJohn McCall     // The pointer expression will, in many cases, be an opaque void*.
12997f416cc4SJohn McCall     // In these cases, discard the computed alignment and use the
13007f416cc4SJohn McCall     // formal alignment of the allocated type.
13017f416cc4SJohn McCall     if (alignSource != AlignmentSource::Decl) {
13027f416cc4SJohn McCall       allocation = Address(allocation.getPointer(),
13037f416cc4SJohn McCall                            getContext().getTypeAlignInChars(allocType));
13047f416cc4SJohn McCall     }
13057f416cc4SJohn McCall 
1306*53dcf94dSJohn McCall     // Set up allocatorArgs for the call to operator delete if it's not
1307*53dcf94dSJohn McCall     // the reserved global operator.
1308*53dcf94dSJohn McCall     if (E->getOperatorDelete() &&
1309*53dcf94dSJohn McCall         !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1310*53dcf94dSJohn McCall       allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1311*53dcf94dSJohn McCall       allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
1312*53dcf94dSJohn McCall     }
1313*53dcf94dSJohn McCall 
13147f416cc4SJohn McCall   } else {
13157f416cc4SJohn McCall     const FunctionProtoType *allocatorType =
13167f416cc4SJohn McCall       allocator->getType()->castAs<FunctionProtoType>();
13177f416cc4SJohn McCall 
13187f416cc4SJohn McCall     // The allocation size is the first argument.
13197f416cc4SJohn McCall     QualType sizeType = getContext().getSizeType();
132043dca6a8SEli Friedman     allocatorArgs.add(RValue::get(allocSize), sizeType);
132159486a2dSAnders Carlsson 
132259486a2dSAnders Carlsson     // We start at 1 here because the first argument (the allocation size)
132359486a2dSAnders Carlsson     // has already been emitted.
1324f05779e2SDavid Blaikie     EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1325f05779e2SDavid Blaikie                  /* CalleeDecl */ nullptr,
13268e1162c7SAlexey Samsonov                  /*ParamsToSkip*/ 1);
132759486a2dSAnders Carlsson 
13287f416cc4SJohn McCall     RValue RV =
13297f416cc4SJohn McCall       EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
13307f416cc4SJohn McCall 
13317f416cc4SJohn McCall     // For now, only assume that the allocation function returns
13327f416cc4SJohn McCall     // something satisfactorily aligned for the element type, plus
13337f416cc4SJohn McCall     // the cookie if we have one.
13347f416cc4SJohn McCall     CharUnits allocationAlign =
13357f416cc4SJohn McCall       getContext().getTypeAlignInChars(allocType);
13367f416cc4SJohn McCall     if (allocSize != allocSizeWithoutCookie) {
13377f416cc4SJohn McCall       CharUnits cookieAlign = getSizeAlign(); // FIXME?
13387f416cc4SJohn McCall       allocationAlign = std::max(allocationAlign, cookieAlign);
13397f416cc4SJohn McCall     }
13407f416cc4SJohn McCall 
13417f416cc4SJohn McCall     allocation = Address(RV.getScalarVal(), allocationAlign);
13427ec4b434SJohn McCall   }
134359486a2dSAnders Carlsson 
134475f9498aSJohn McCall   // Emit a null check on the allocation result if the allocation
134575f9498aSJohn McCall   // function is allowed to return null (because it has a non-throwing
1346902a0238SRichard Smith   // exception spec or is the reserved placement new) and we have an
134775f9498aSJohn McCall   // interesting initializer.
1348902a0238SRichard Smith   bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
13496047f07eSSebastian Redl     (!allocType.isPODType(getContext()) || E->hasInitializer());
135059486a2dSAnders Carlsson 
13518a13c418SCraig Topper   llvm::BasicBlock *nullCheckBB = nullptr;
13528a13c418SCraig Topper   llvm::BasicBlock *contBB = nullptr;
135359486a2dSAnders Carlsson 
1354f7dcf320SJohn McCall   // The null-check means that the initializer is conditionally
1355f7dcf320SJohn McCall   // evaluated.
1356f7dcf320SJohn McCall   ConditionalEvaluation conditional(*this);
1357f7dcf320SJohn McCall 
135875f9498aSJohn McCall   if (nullCheck) {
1359f7dcf320SJohn McCall     conditional.begin(*this);
136075f9498aSJohn McCall 
136175f9498aSJohn McCall     nullCheckBB = Builder.GetInsertBlock();
136275f9498aSJohn McCall     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
136375f9498aSJohn McCall     contBB = createBasicBlock("new.cont");
136475f9498aSJohn McCall 
13657f416cc4SJohn McCall     llvm::Value *isNull =
13667f416cc4SJohn McCall       Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
136775f9498aSJohn McCall     Builder.CreateCondBr(isNull, contBB, notNullBB);
136875f9498aSJohn McCall     EmitBlock(notNullBB);
136959486a2dSAnders Carlsson   }
137059486a2dSAnders Carlsson 
1371824c2f53SJohn McCall   // If there's an operator delete, enter a cleanup to call it if an
1372824c2f53SJohn McCall   // exception is thrown.
137375f9498aSJohn McCall   EHScopeStack::stable_iterator operatorDeleteCleanup;
13748a13c418SCraig Topper   llvm::Instruction *cleanupDominator = nullptr;
13757ec4b434SJohn McCall   if (E->getOperatorDelete() &&
13767ec4b434SJohn McCall       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
137775f9498aSJohn McCall     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
137875f9498aSJohn McCall     operatorDeleteCleanup = EHStack.stable_begin();
1379f4beacd0SJohn McCall     cleanupDominator = Builder.CreateUnreachable();
1380824c2f53SJohn McCall   }
1381824c2f53SJohn McCall 
1382cf9b1f65SEli Friedman   assert((allocSize == allocSizeWithoutCookie) ==
1383cf9b1f65SEli Friedman          CalculateCookiePadding(*this, E).isZero());
1384cf9b1f65SEli Friedman   if (allocSize != allocSizeWithoutCookie) {
1385cf9b1f65SEli Friedman     assert(E->isArray());
1386cf9b1f65SEli Friedman     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1387cf9b1f65SEli Friedman                                                        numElements,
1388cf9b1f65SEli Friedman                                                        E, allocType);
1389cf9b1f65SEli Friedman   }
1390cf9b1f65SEli Friedman 
1391fb901c7aSDavid Blaikie   llvm::Type *elementTy = ConvertTypeForMem(allocType);
13927f416cc4SJohn McCall   Address result = Builder.CreateElementBitCast(allocation, elementTy);
1393824c2f53SJohn McCall 
1394338c9d0aSPiotr Padlewski   // Passing pointer through invariant.group.barrier to avoid propagation of
1395338c9d0aSPiotr Padlewski   // vptrs information which may be included in previous type.
1396338c9d0aSPiotr Padlewski   if (CGM.getCodeGenOpts().StrictVTablePointers &&
1397338c9d0aSPiotr Padlewski       CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1398338c9d0aSPiotr Padlewski       allocator->isReservedGlobalPlacementOperator())
1399338c9d0aSPiotr Padlewski     result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()),
1400338c9d0aSPiotr Padlewski                      result.getAlignment());
1401338c9d0aSPiotr Padlewski 
1402fb901c7aSDavid Blaikie   EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
140399210dc9SJohn McCall                      allocSizeWithoutCookie);
14048ed55a54SJohn McCall   if (E->isArray()) {
14058ed55a54SJohn McCall     // NewPtr is a pointer to the base element type.  If we're
14068ed55a54SJohn McCall     // allocating an array of arrays, we'll need to cast back to the
14078ed55a54SJohn McCall     // array pointer type.
14082192fe50SChris Lattner     llvm::Type *resultType = ConvertTypeForMem(E->getType());
14097f416cc4SJohn McCall     if (result.getType() != resultType)
141075f9498aSJohn McCall       result = Builder.CreateBitCast(result, resultType);
141147b4629bSFariborz Jahanian   }
141259486a2dSAnders Carlsson 
1413824c2f53SJohn McCall   // Deactivate the 'operator delete' cleanup if we finished
1414824c2f53SJohn McCall   // initialization.
1415f4beacd0SJohn McCall   if (operatorDeleteCleanup.isValid()) {
1416f4beacd0SJohn McCall     DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1417f4beacd0SJohn McCall     cleanupDominator->eraseFromParent();
1418f4beacd0SJohn McCall   }
1419824c2f53SJohn McCall 
14207f416cc4SJohn McCall   llvm::Value *resultPtr = result.getPointer();
142175f9498aSJohn McCall   if (nullCheck) {
1422f7dcf320SJohn McCall     conditional.end(*this);
1423f7dcf320SJohn McCall 
142475f9498aSJohn McCall     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
142575f9498aSJohn McCall     EmitBlock(contBB);
142659486a2dSAnders Carlsson 
14277f416cc4SJohn McCall     llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
14287f416cc4SJohn McCall     PHI->addIncoming(resultPtr, notNullBB);
14297f416cc4SJohn McCall     PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
143075f9498aSJohn McCall                      nullCheckBB);
143159486a2dSAnders Carlsson 
14327f416cc4SJohn McCall     resultPtr = PHI;
143359486a2dSAnders Carlsson   }
143459486a2dSAnders Carlsson 
14357f416cc4SJohn McCall   return resultPtr;
143659486a2dSAnders Carlsson }
143759486a2dSAnders Carlsson 
143859486a2dSAnders Carlsson void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
143959486a2dSAnders Carlsson                                      llvm::Value *Ptr,
144059486a2dSAnders Carlsson                                      QualType DeleteTy) {
14418ed55a54SJohn McCall   assert(DeleteFD->getOverloadedOperator() == OO_Delete);
14428ed55a54SJohn McCall 
144359486a2dSAnders Carlsson   const FunctionProtoType *DeleteFTy =
144459486a2dSAnders Carlsson     DeleteFD->getType()->getAs<FunctionProtoType>();
144559486a2dSAnders Carlsson 
144659486a2dSAnders Carlsson   CallArgList DeleteArgs;
144759486a2dSAnders Carlsson 
144821122cf6SAnders Carlsson   // Check if we need to pass the size to the delete operator.
14498a13c418SCraig Topper   llvm::Value *Size = nullptr;
145021122cf6SAnders Carlsson   QualType SizeTy;
14519cacbabdSAlp Toker   if (DeleteFTy->getNumParams() == 2) {
14529cacbabdSAlp Toker     SizeTy = DeleteFTy->getParamType(1);
14537df3cbebSKen Dyck     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
14547df3cbebSKen Dyck     Size = llvm::ConstantInt::get(ConvertType(SizeTy),
14557df3cbebSKen Dyck                                   DeleteTypeSize.getQuantity());
145621122cf6SAnders Carlsson   }
145721122cf6SAnders Carlsson 
14589cacbabdSAlp Toker   QualType ArgTy = DeleteFTy->getParamType(0);
145959486a2dSAnders Carlsson   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
146043dca6a8SEli Friedman   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
146159486a2dSAnders Carlsson 
146221122cf6SAnders Carlsson   if (Size)
146343dca6a8SEli Friedman     DeleteArgs.add(RValue::get(Size), SizeTy);
146459486a2dSAnders Carlsson 
146559486a2dSAnders Carlsson   // Emit the call to delete.
14668d0dc31dSRichard Smith   EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
146759486a2dSAnders Carlsson }
146859486a2dSAnders Carlsson 
14698ed55a54SJohn McCall namespace {
14708ed55a54SJohn McCall   /// Calls the given 'operator delete' on a single object.
14717e70d680SDavid Blaikie   struct CallObjectDelete final : EHScopeStack::Cleanup {
14728ed55a54SJohn McCall     llvm::Value *Ptr;
14738ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
14748ed55a54SJohn McCall     QualType ElementType;
14758ed55a54SJohn McCall 
14768ed55a54SJohn McCall     CallObjectDelete(llvm::Value *Ptr,
14778ed55a54SJohn McCall                      const FunctionDecl *OperatorDelete,
14788ed55a54SJohn McCall                      QualType ElementType)
14798ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
14808ed55a54SJohn McCall 
14814f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
14828ed55a54SJohn McCall       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
14838ed55a54SJohn McCall     }
14848ed55a54SJohn McCall   };
1485ab9db510SAlexander Kornienko }
14868ed55a54SJohn McCall 
14870c0b6d9aSDavid Majnemer void
14880c0b6d9aSDavid Majnemer CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
14890c0b6d9aSDavid Majnemer                                              llvm::Value *CompletePtr,
14900c0b6d9aSDavid Majnemer                                              QualType ElementType) {
14910c0b6d9aSDavid Majnemer   EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
14920c0b6d9aSDavid Majnemer                                         OperatorDelete, ElementType);
14930c0b6d9aSDavid Majnemer }
14940c0b6d9aSDavid Majnemer 
14958ed55a54SJohn McCall /// Emit the code for deleting a single object.
14968ed55a54SJohn McCall static void EmitObjectDelete(CodeGenFunction &CGF,
14970868137aSDavid Majnemer                              const CXXDeleteExpr *DE,
14987f416cc4SJohn McCall                              Address Ptr,
14990868137aSDavid Majnemer                              QualType ElementType) {
15008ed55a54SJohn McCall   // Find the destructor for the type, if applicable.  If the
15018ed55a54SJohn McCall   // destructor is virtual, we'll just emit the vcall and return.
15028a13c418SCraig Topper   const CXXDestructorDecl *Dtor = nullptr;
15038ed55a54SJohn McCall   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
15048ed55a54SJohn McCall     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1505b23533dbSEli Friedman     if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
15068ed55a54SJohn McCall       Dtor = RD->getDestructor();
15078ed55a54SJohn McCall 
15088ed55a54SJohn McCall       if (Dtor->isVirtual()) {
15090868137aSDavid Majnemer         CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
15100868137aSDavid Majnemer                                                     Dtor);
15118ed55a54SJohn McCall         return;
15128ed55a54SJohn McCall       }
15138ed55a54SJohn McCall     }
15148ed55a54SJohn McCall   }
15158ed55a54SJohn McCall 
15168ed55a54SJohn McCall   // Make sure that we call delete even if the dtor throws.
1517e4df6c8dSJohn McCall   // This doesn't have to a conditional cleanup because we're going
1518e4df6c8dSJohn McCall   // to pop it off in a second.
15190868137aSDavid Majnemer   const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
15208ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
15217f416cc4SJohn McCall                                             Ptr.getPointer(),
15227f416cc4SJohn McCall                                             OperatorDelete, ElementType);
15238ed55a54SJohn McCall 
15248ed55a54SJohn McCall   if (Dtor)
15258ed55a54SJohn McCall     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
152661535005SDouglas Gregor                               /*ForVirtualBase=*/false,
152761535005SDouglas Gregor                               /*Delegating=*/false,
152861535005SDouglas Gregor                               Ptr);
1529bbafb8a7SDavid Blaikie   else if (CGF.getLangOpts().ObjCAutoRefCount &&
153031168b07SJohn McCall            ElementType->isObjCLifetimeType()) {
153131168b07SJohn McCall     switch (ElementType.getObjCLifetime()) {
153231168b07SJohn McCall     case Qualifiers::OCL_None:
153331168b07SJohn McCall     case Qualifiers::OCL_ExplicitNone:
153431168b07SJohn McCall     case Qualifiers::OCL_Autoreleasing:
153531168b07SJohn McCall       break;
153631168b07SJohn McCall 
15377f416cc4SJohn McCall     case Qualifiers::OCL_Strong:
15387f416cc4SJohn McCall       CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
153931168b07SJohn McCall       break;
154031168b07SJohn McCall 
154131168b07SJohn McCall     case Qualifiers::OCL_Weak:
154231168b07SJohn McCall       CGF.EmitARCDestroyWeak(Ptr);
154331168b07SJohn McCall       break;
154431168b07SJohn McCall     }
154531168b07SJohn McCall   }
15468ed55a54SJohn McCall 
15478ed55a54SJohn McCall   CGF.PopCleanupBlock();
15488ed55a54SJohn McCall }
15498ed55a54SJohn McCall 
15508ed55a54SJohn McCall namespace {
15518ed55a54SJohn McCall   /// Calls the given 'operator delete' on an array of objects.
15527e70d680SDavid Blaikie   struct CallArrayDelete final : EHScopeStack::Cleanup {
15538ed55a54SJohn McCall     llvm::Value *Ptr;
15548ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
15558ed55a54SJohn McCall     llvm::Value *NumElements;
15568ed55a54SJohn McCall     QualType ElementType;
15578ed55a54SJohn McCall     CharUnits CookieSize;
15588ed55a54SJohn McCall 
15598ed55a54SJohn McCall     CallArrayDelete(llvm::Value *Ptr,
15608ed55a54SJohn McCall                     const FunctionDecl *OperatorDelete,
15618ed55a54SJohn McCall                     llvm::Value *NumElements,
15628ed55a54SJohn McCall                     QualType ElementType,
15638ed55a54SJohn McCall                     CharUnits CookieSize)
15648ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
15658ed55a54SJohn McCall         ElementType(ElementType), CookieSize(CookieSize) {}
15668ed55a54SJohn McCall 
15674f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
15688ed55a54SJohn McCall       const FunctionProtoType *DeleteFTy =
15698ed55a54SJohn McCall         OperatorDelete->getType()->getAs<FunctionProtoType>();
15709cacbabdSAlp Toker       assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
15718ed55a54SJohn McCall 
15728ed55a54SJohn McCall       CallArgList Args;
15738ed55a54SJohn McCall 
15748ed55a54SJohn McCall       // Pass the pointer as the first argument.
15759cacbabdSAlp Toker       QualType VoidPtrTy = DeleteFTy->getParamType(0);
15768ed55a54SJohn McCall       llvm::Value *DeletePtr
15778ed55a54SJohn McCall         = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
157843dca6a8SEli Friedman       Args.add(RValue::get(DeletePtr), VoidPtrTy);
15798ed55a54SJohn McCall 
15808ed55a54SJohn McCall       // Pass the original requested size as the second argument.
15819cacbabdSAlp Toker       if (DeleteFTy->getNumParams() == 2) {
15829cacbabdSAlp Toker         QualType size_t = DeleteFTy->getParamType(1);
15832192fe50SChris Lattner         llvm::IntegerType *SizeTy
15848ed55a54SJohn McCall           = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
15858ed55a54SJohn McCall 
15868ed55a54SJohn McCall         CharUnits ElementTypeSize =
15878ed55a54SJohn McCall           CGF.CGM.getContext().getTypeSizeInChars(ElementType);
15888ed55a54SJohn McCall 
15898ed55a54SJohn McCall         // The size of an element, multiplied by the number of elements.
15908ed55a54SJohn McCall         llvm::Value *Size
15918ed55a54SJohn McCall           = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1592149e6031SDavid Majnemer         if (NumElements)
15938ed55a54SJohn McCall           Size = CGF.Builder.CreateMul(Size, NumElements);
15948ed55a54SJohn McCall 
15958ed55a54SJohn McCall         // Plus the size of the cookie if applicable.
15968ed55a54SJohn McCall         if (!CookieSize.isZero()) {
15978ed55a54SJohn McCall           llvm::Value *CookieSizeV
15988ed55a54SJohn McCall             = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
15998ed55a54SJohn McCall           Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
16008ed55a54SJohn McCall         }
16018ed55a54SJohn McCall 
160243dca6a8SEli Friedman         Args.add(RValue::get(Size), size_t);
16038ed55a54SJohn McCall       }
16048ed55a54SJohn McCall 
16058ed55a54SJohn McCall       // Emit the call to delete.
16068d0dc31dSRichard Smith       EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
16078ed55a54SJohn McCall     }
16088ed55a54SJohn McCall   };
1609ab9db510SAlexander Kornienko }
16108ed55a54SJohn McCall 
16118ed55a54SJohn McCall /// Emit the code for deleting an array of objects.
16128ed55a54SJohn McCall static void EmitArrayDelete(CodeGenFunction &CGF,
1613284c48ffSJohn McCall                             const CXXDeleteExpr *E,
16147f416cc4SJohn McCall                             Address deletedPtr,
1615ca2c56f2SJohn McCall                             QualType elementType) {
16168a13c418SCraig Topper   llvm::Value *numElements = nullptr;
16178a13c418SCraig Topper   llvm::Value *allocatedPtr = nullptr;
1618ca2c56f2SJohn McCall   CharUnits cookieSize;
1619ca2c56f2SJohn McCall   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1620ca2c56f2SJohn McCall                                       numElements, allocatedPtr, cookieSize);
16218ed55a54SJohn McCall 
1622ca2c56f2SJohn McCall   assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
16238ed55a54SJohn McCall 
16248ed55a54SJohn McCall   // Make sure that we call delete even if one of the dtors throws.
1625ca2c56f2SJohn McCall   const FunctionDecl *operatorDelete = E->getOperatorDelete();
16268ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1627ca2c56f2SJohn McCall                                            allocatedPtr, operatorDelete,
1628ca2c56f2SJohn McCall                                            numElements, elementType,
1629ca2c56f2SJohn McCall                                            cookieSize);
16308ed55a54SJohn McCall 
1631ca2c56f2SJohn McCall   // Destroy the elements.
1632ca2c56f2SJohn McCall   if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1633ca2c56f2SJohn McCall     assert(numElements && "no element count for a type with a destructor!");
163431168b07SJohn McCall 
16357f416cc4SJohn McCall     CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
16367f416cc4SJohn McCall     CharUnits elementAlign =
16377f416cc4SJohn McCall       deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
16387f416cc4SJohn McCall 
16397f416cc4SJohn McCall     llvm::Value *arrayBegin = deletedPtr.getPointer();
1640ca2c56f2SJohn McCall     llvm::Value *arrayEnd =
16417f416cc4SJohn McCall       CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
164297eab0a2SJohn McCall 
164397eab0a2SJohn McCall     // Note that it is legal to allocate a zero-length array, and we
164497eab0a2SJohn McCall     // can never fold the check away because the length should always
164597eab0a2SJohn McCall     // come from a cookie.
16467f416cc4SJohn McCall     CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
1647ca2c56f2SJohn McCall                          CGF.getDestroyer(dtorKind),
164897eab0a2SJohn McCall                          /*checkZeroLength*/ true,
1649ca2c56f2SJohn McCall                          CGF.needsEHCleanup(dtorKind));
16508ed55a54SJohn McCall   }
16518ed55a54SJohn McCall 
1652ca2c56f2SJohn McCall   // Pop the cleanup block.
16538ed55a54SJohn McCall   CGF.PopCleanupBlock();
16548ed55a54SJohn McCall }
16558ed55a54SJohn McCall 
165659486a2dSAnders Carlsson void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
165759486a2dSAnders Carlsson   const Expr *Arg = E->getArgument();
16587f416cc4SJohn McCall   Address Ptr = EmitPointerWithAlignment(Arg);
165959486a2dSAnders Carlsson 
166059486a2dSAnders Carlsson   // Null check the pointer.
166159486a2dSAnders Carlsson   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
166259486a2dSAnders Carlsson   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
166359486a2dSAnders Carlsson 
16647f416cc4SJohn McCall   llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
166559486a2dSAnders Carlsson 
166659486a2dSAnders Carlsson   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
166759486a2dSAnders Carlsson   EmitBlock(DeleteNotNull);
166859486a2dSAnders Carlsson 
16698ed55a54SJohn McCall   // We might be deleting a pointer to array.  If so, GEP down to the
16708ed55a54SJohn McCall   // first non-array element.
16718ed55a54SJohn McCall   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
16728ed55a54SJohn McCall   QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
16738ed55a54SJohn McCall   if (DeleteTy->isConstantArrayType()) {
16748ed55a54SJohn McCall     llvm::Value *Zero = Builder.getInt32(0);
16750e62c1ccSChris Lattner     SmallVector<llvm::Value*,8> GEP;
167659486a2dSAnders Carlsson 
16778ed55a54SJohn McCall     GEP.push_back(Zero); // point at the outermost array
16788ed55a54SJohn McCall 
16798ed55a54SJohn McCall     // For each layer of array type we're pointing at:
16808ed55a54SJohn McCall     while (const ConstantArrayType *Arr
16818ed55a54SJohn McCall              = getContext().getAsConstantArrayType(DeleteTy)) {
16828ed55a54SJohn McCall       // 1. Unpeel the array type.
16838ed55a54SJohn McCall       DeleteTy = Arr->getElementType();
16848ed55a54SJohn McCall 
16858ed55a54SJohn McCall       // 2. GEP to the first element of the array.
16868ed55a54SJohn McCall       GEP.push_back(Zero);
16878ed55a54SJohn McCall     }
16888ed55a54SJohn McCall 
16897f416cc4SJohn McCall     Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
16907f416cc4SJohn McCall                   Ptr.getAlignment());
16918ed55a54SJohn McCall   }
16928ed55a54SJohn McCall 
16937f416cc4SJohn McCall   assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
16948ed55a54SJohn McCall 
16957270ef57SReid Kleckner   if (E->isArrayForm()) {
16967270ef57SReid Kleckner     EmitArrayDelete(*this, E, Ptr, DeleteTy);
16977270ef57SReid Kleckner   } else {
16987270ef57SReid Kleckner     EmitObjectDelete(*this, E, Ptr, DeleteTy);
16997270ef57SReid Kleckner   }
170059486a2dSAnders Carlsson 
170159486a2dSAnders Carlsson   EmitBlock(DeleteEnd);
170259486a2dSAnders Carlsson }
170359486a2dSAnders Carlsson 
17041c3d95ebSDavid Majnemer static bool isGLValueFromPointerDeref(const Expr *E) {
17051c3d95ebSDavid Majnemer   E = E->IgnoreParens();
17061c3d95ebSDavid Majnemer 
17071c3d95ebSDavid Majnemer   if (const auto *CE = dyn_cast<CastExpr>(E)) {
17081c3d95ebSDavid Majnemer     if (!CE->getSubExpr()->isGLValue())
17091c3d95ebSDavid Majnemer       return false;
17101c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(CE->getSubExpr());
17111c3d95ebSDavid Majnemer   }
17121c3d95ebSDavid Majnemer 
17131c3d95ebSDavid Majnemer   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
17141c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(OVE->getSourceExpr());
17151c3d95ebSDavid Majnemer 
17161c3d95ebSDavid Majnemer   if (const auto *BO = dyn_cast<BinaryOperator>(E))
17171c3d95ebSDavid Majnemer     if (BO->getOpcode() == BO_Comma)
17181c3d95ebSDavid Majnemer       return isGLValueFromPointerDeref(BO->getRHS());
17191c3d95ebSDavid Majnemer 
17201c3d95ebSDavid Majnemer   if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
17211c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
17221c3d95ebSDavid Majnemer            isGLValueFromPointerDeref(ACO->getFalseExpr());
17231c3d95ebSDavid Majnemer 
17241c3d95ebSDavid Majnemer   // C++11 [expr.sub]p1:
17251c3d95ebSDavid Majnemer   //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
17261c3d95ebSDavid Majnemer   if (isa<ArraySubscriptExpr>(E))
17271c3d95ebSDavid Majnemer     return true;
17281c3d95ebSDavid Majnemer 
17291c3d95ebSDavid Majnemer   if (const auto *UO = dyn_cast<UnaryOperator>(E))
17301c3d95ebSDavid Majnemer     if (UO->getOpcode() == UO_Deref)
17311c3d95ebSDavid Majnemer       return true;
17321c3d95ebSDavid Majnemer 
17331c3d95ebSDavid Majnemer   return false;
17341c3d95ebSDavid Majnemer }
17351c3d95ebSDavid Majnemer 
1736747e301eSWarren Hunt static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
17372192fe50SChris Lattner                                          llvm::Type *StdTypeInfoPtrTy) {
1738940f02d2SAnders Carlsson   // Get the vtable pointer.
17397f416cc4SJohn McCall   Address ThisPtr = CGF.EmitLValue(E).getAddress();
1740940f02d2SAnders Carlsson 
1741940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
1742940f02d2SAnders Carlsson   //   If the glvalue expression is obtained by applying the unary * operator to
1743940f02d2SAnders Carlsson   //   a pointer and the pointer is a null pointer value, the typeid expression
1744940f02d2SAnders Carlsson   //   throws the std::bad_typeid exception.
17451c3d95ebSDavid Majnemer   //
17461c3d95ebSDavid Majnemer   // However, this paragraph's intent is not clear.  We choose a very generous
17471c3d95ebSDavid Majnemer   // interpretation which implores us to consider comma operators, conditional
17481c3d95ebSDavid Majnemer   // operators, parentheses and other such constructs.
17491162d25cSDavid Majnemer   QualType SrcRecordTy = E->getType();
17501c3d95ebSDavid Majnemer   if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
17511c3d95ebSDavid Majnemer           isGLValueFromPointerDeref(E), SrcRecordTy)) {
1752940f02d2SAnders Carlsson     llvm::BasicBlock *BadTypeidBlock =
1753940f02d2SAnders Carlsson         CGF.createBasicBlock("typeid.bad_typeid");
17541162d25cSDavid Majnemer     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
1755940f02d2SAnders Carlsson 
17567f416cc4SJohn McCall     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
1757940f02d2SAnders Carlsson     CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1758940f02d2SAnders Carlsson 
1759940f02d2SAnders Carlsson     CGF.EmitBlock(BadTypeidBlock);
17601162d25cSDavid Majnemer     CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1761940f02d2SAnders Carlsson     CGF.EmitBlock(EndBlock);
1762940f02d2SAnders Carlsson   }
1763940f02d2SAnders Carlsson 
17641162d25cSDavid Majnemer   return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
17651162d25cSDavid Majnemer                                         StdTypeInfoPtrTy);
1766940f02d2SAnders Carlsson }
1767940f02d2SAnders Carlsson 
176859486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
17692192fe50SChris Lattner   llvm::Type *StdTypeInfoPtrTy =
1770940f02d2SAnders Carlsson     ConvertType(E->getType())->getPointerTo();
1771fd7dfeb7SAnders Carlsson 
17723f4336cbSAnders Carlsson   if (E->isTypeOperand()) {
17733f4336cbSAnders Carlsson     llvm::Constant *TypeInfo =
1774143c55eaSDavid Majnemer         CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
1775940f02d2SAnders Carlsson     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
17763f4336cbSAnders Carlsson   }
1777fd7dfeb7SAnders Carlsson 
1778940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
1779940f02d2SAnders Carlsson   //   When typeid is applied to a glvalue expression whose type is a
1780940f02d2SAnders Carlsson   //   polymorphic class type, the result refers to a std::type_info object
1781940f02d2SAnders Carlsson   //   representing the type of the most derived object (that is, the dynamic
1782940f02d2SAnders Carlsson   //   type) to which the glvalue refers.
1783ef8bf436SRichard Smith   if (E->isPotentiallyEvaluated())
1784940f02d2SAnders Carlsson     return EmitTypeidFromVTable(*this, E->getExprOperand(),
1785940f02d2SAnders Carlsson                                 StdTypeInfoPtrTy);
1786940f02d2SAnders Carlsson 
1787940f02d2SAnders Carlsson   QualType OperandTy = E->getExprOperand()->getType();
1788940f02d2SAnders Carlsson   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1789940f02d2SAnders Carlsson                                StdTypeInfoPtrTy);
179059486a2dSAnders Carlsson }
179159486a2dSAnders Carlsson 
1792c1c9971cSAnders Carlsson static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1793c1c9971cSAnders Carlsson                                           QualType DestTy) {
17942192fe50SChris Lattner   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1795c1c9971cSAnders Carlsson   if (DestTy->isPointerType())
1796c1c9971cSAnders Carlsson     return llvm::Constant::getNullValue(DestLTy);
1797c1c9971cSAnders Carlsson 
1798c1c9971cSAnders Carlsson   /// C++ [expr.dynamic.cast]p9:
1799c1c9971cSAnders Carlsson   ///   A failed cast to reference type throws std::bad_cast
18001162d25cSDavid Majnemer   if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
18011162d25cSDavid Majnemer     return nullptr;
1802c1c9971cSAnders Carlsson 
1803c1c9971cSAnders Carlsson   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1804c1c9971cSAnders Carlsson   return llvm::UndefValue::get(DestLTy);
1805c1c9971cSAnders Carlsson }
1806c1c9971cSAnders Carlsson 
18077f416cc4SJohn McCall llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
180859486a2dSAnders Carlsson                                               const CXXDynamicCastExpr *DCE) {
18093f4336cbSAnders Carlsson   QualType DestTy = DCE->getTypeAsWritten();
18103f4336cbSAnders Carlsson 
1811c1c9971cSAnders Carlsson   if (DCE->isAlwaysNull())
18121162d25cSDavid Majnemer     if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
18131162d25cSDavid Majnemer       return T;
1814c1c9971cSAnders Carlsson 
1815c1c9971cSAnders Carlsson   QualType SrcTy = DCE->getSubExpr()->getType();
1816c1c9971cSAnders Carlsson 
18171162d25cSDavid Majnemer   // C++ [expr.dynamic.cast]p7:
18181162d25cSDavid Majnemer   //   If T is "pointer to cv void," then the result is a pointer to the most
18191162d25cSDavid Majnemer   //   derived object pointed to by v.
18201162d25cSDavid Majnemer   const PointerType *DestPTy = DestTy->getAs<PointerType>();
18211162d25cSDavid Majnemer 
18221162d25cSDavid Majnemer   bool isDynamicCastToVoid;
18231162d25cSDavid Majnemer   QualType SrcRecordTy;
18241162d25cSDavid Majnemer   QualType DestRecordTy;
18251162d25cSDavid Majnemer   if (DestPTy) {
18261162d25cSDavid Majnemer     isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
18271162d25cSDavid Majnemer     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
18281162d25cSDavid Majnemer     DestRecordTy = DestPTy->getPointeeType();
18291162d25cSDavid Majnemer   } else {
18301162d25cSDavid Majnemer     isDynamicCastToVoid = false;
18311162d25cSDavid Majnemer     SrcRecordTy = SrcTy;
18321162d25cSDavid Majnemer     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
18331162d25cSDavid Majnemer   }
18341162d25cSDavid Majnemer 
18351162d25cSDavid Majnemer   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
18361162d25cSDavid Majnemer 
1837882d790fSAnders Carlsson   // C++ [expr.dynamic.cast]p4:
1838882d790fSAnders Carlsson   //   If the value of v is a null pointer value in the pointer case, the result
1839882d790fSAnders Carlsson   //   is the null pointer value of type T.
18401162d25cSDavid Majnemer   bool ShouldNullCheckSrcValue =
18411162d25cSDavid Majnemer       CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
18421162d25cSDavid Majnemer                                                          SrcRecordTy);
184359486a2dSAnders Carlsson 
18448a13c418SCraig Topper   llvm::BasicBlock *CastNull = nullptr;
18458a13c418SCraig Topper   llvm::BasicBlock *CastNotNull = nullptr;
1846882d790fSAnders Carlsson   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
1847fa8b4955SDouglas Gregor 
1848882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1849882d790fSAnders Carlsson     CastNull = createBasicBlock("dynamic_cast.null");
1850882d790fSAnders Carlsson     CastNotNull = createBasicBlock("dynamic_cast.notnull");
1851882d790fSAnders Carlsson 
18527f416cc4SJohn McCall     llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
1853882d790fSAnders Carlsson     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1854882d790fSAnders Carlsson     EmitBlock(CastNotNull);
185559486a2dSAnders Carlsson   }
185659486a2dSAnders Carlsson 
18577f416cc4SJohn McCall   llvm::Value *Value;
18581162d25cSDavid Majnemer   if (isDynamicCastToVoid) {
18597f416cc4SJohn McCall     Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
18601162d25cSDavid Majnemer                                                   DestTy);
18611162d25cSDavid Majnemer   } else {
18621162d25cSDavid Majnemer     assert(DestRecordTy->isRecordType() &&
18631162d25cSDavid Majnemer            "destination type must be a record type!");
18647f416cc4SJohn McCall     Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
18651162d25cSDavid Majnemer                                                 DestTy, DestRecordTy, CastEnd);
18661162d25cSDavid Majnemer   }
18673f4336cbSAnders Carlsson 
1868882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1869882d790fSAnders Carlsson     EmitBranch(CastEnd);
187059486a2dSAnders Carlsson 
1871882d790fSAnders Carlsson     EmitBlock(CastNull);
1872882d790fSAnders Carlsson     EmitBranch(CastEnd);
187359486a2dSAnders Carlsson   }
187459486a2dSAnders Carlsson 
1875882d790fSAnders Carlsson   EmitBlock(CastEnd);
187659486a2dSAnders Carlsson 
1877882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1878882d790fSAnders Carlsson     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1879882d790fSAnders Carlsson     PHI->addIncoming(Value, CastNotNull);
1880882d790fSAnders Carlsson     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
188159486a2dSAnders Carlsson 
1882882d790fSAnders Carlsson     Value = PHI;
188359486a2dSAnders Carlsson   }
188459486a2dSAnders Carlsson 
1885882d790fSAnders Carlsson   return Value;
188659486a2dSAnders Carlsson }
1887c370a7eeSEli Friedman 
1888c370a7eeSEli Friedman void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
18898631f3e8SEli Friedman   RunCleanupsScope Scope(*this);
18907f416cc4SJohn McCall   LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType());
18918631f3e8SEli Friedman 
1892c370a7eeSEli Friedman   CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
189353c7616eSJames Y Knight   for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
1894c370a7eeSEli Friedman                                                e = E->capture_init_end();
1895c370a7eeSEli Friedman        i != e; ++i, ++CurField) {
1896c370a7eeSEli Friedman     // Emit initialization
189740ed2973SDavid Blaikie     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
189839c81e28SAlexey Bataev     if (CurField->hasCapturedVLAType()) {
189939c81e28SAlexey Bataev       auto VAT = CurField->getCapturedVLAType();
190039c81e28SAlexey Bataev       EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
190139c81e28SAlexey Bataev     } else {
19025f1a04ffSEli Friedman       ArrayRef<VarDecl *> ArrayIndexes;
19035f1a04ffSEli Friedman       if (CurField->getType()->isArrayType())
19045f1a04ffSEli Friedman         ArrayIndexes = E->getCaptureInitIndexVars(i);
190540ed2973SDavid Blaikie       EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
1906c370a7eeSEli Friedman     }
1907c370a7eeSEli Friedman   }
190839c81e28SAlexey Bataev }
1909