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;
620c0b6d9aSDavid Majnemer     CGF.EmitCallArgs(Args, FPT, CE->arg_begin() + ArgsToSkip, CE->arg_end(),
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 
16927da15baSAnders Carlsson   llvm::Value *This;
170aad4af6dSNico Weber   if (IsArrow)
1713b33c4ecSRafael Espindola     This = EmitScalarExpr(Base);
172f93ac894SFariborz Jahanian   else
1733b33c4ecSRafael Espindola     This = EmitLValue(Base).getAddress();
174ecbe2e97SRafael Espindola 
17527da15baSAnders Carlsson 
1760d635f53SJohn McCall   if (MD->isTrivial()) {
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;
188aad4af6dSNico Weber         llvm::Value *RHS =
189aad4af6dSNico Weber             EmitLValue(*(CE->arg_begin() + ArgsToSkip)).getAddress();
1901ca66919SBenjamin Kramer         EmitAggregateAssign(This, RHS, CE->getType());
19127da15baSAnders Carlsson         return RValue::get(This);
19227da15baSAnders Carlsson       }
19327da15baSAnders Carlsson 
19464225794SFrancois Pichet       if (isa<CXXConstructorDecl>(MD) &&
19522653bacSSebastian Redl           cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
19622653bacSSebastian Redl         // Trivial move and copy ctor are the same.
197525bf650SAlexey Samsonov         assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
19864225794SFrancois Pichet         llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress();
199525bf650SAlexey Samsonov         EmitAggregateCopy(This, RHS, CE->arg_begin()->getType());
20064225794SFrancois Pichet         return RValue::get(This);
20164225794SFrancois Pichet       }
20264225794SFrancois Pichet       llvm_unreachable("unknown trivial member function");
20364225794SFrancois Pichet     }
204aad4af6dSNico Weber   }
20564225794SFrancois Pichet 
2060d635f53SJohn McCall   // Compute the function type we're calling.
2073abfe958SNico Weber   const CXXMethodDecl *CalleeDecl =
2083abfe958SNico Weber       DevirtualizedMethod ? DevirtualizedMethod : MD;
2098a13c418SCraig Topper   const CGFunctionInfo *FInfo = nullptr;
2103abfe958SNico Weber   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
2118d2a19b4SRafael Espindola     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
2128d2a19b4SRafael Espindola         Dtor, StructorType::Complete);
2133abfe958SNico Weber   else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
2148d2a19b4SRafael Espindola     FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
2158d2a19b4SRafael Espindola         Ctor, StructorType::Complete);
21664225794SFrancois Pichet   else
217ade60977SEli Friedman     FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
2180d635f53SJohn McCall 
219e7de47efSReid Kleckner   llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
2200d635f53SJohn McCall 
22127da15baSAnders Carlsson   // C++ [class.virtual]p12:
22227da15baSAnders Carlsson   //   Explicit qualification with the scope operator (5.1) suppresses the
22327da15baSAnders Carlsson   //   virtual call mechanism.
22427da15baSAnders Carlsson   //
22527da15baSAnders Carlsson   // We also don't emit a virtual call if the base expression has a record type
22627da15baSAnders Carlsson   // because then we know what the type is.
2273b33c4ecSRafael Espindola   bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
22819cee187SStephen Lin   llvm::Value *Callee;
2299dc6eef7SStephen Lin 
2300d635f53SJohn McCall   if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
23119cee187SStephen Lin     assert(CE->arg_begin() == CE->arg_end() &&
2329dc6eef7SStephen Lin            "Destructor shouldn't have explicit parameters");
2339dc6eef7SStephen Lin     assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
2349dc6eef7SStephen Lin     if (UseVirtualCall) {
235aad4af6dSNico Weber       CGM.getCXXABI().EmitVirtualDestructorCall(
236aad4af6dSNico Weber           *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
23727da15baSAnders Carlsson     } else {
238aad4af6dSNico Weber       if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
239aad4af6dSNico Weber         Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
2403b33c4ecSRafael Espindola       else if (!DevirtualizedMethod)
2411ac0ec86SRafael Espindola         Callee =
2421ac0ec86SRafael Espindola             CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty);
24349e860b2SRafael Espindola       else {
2443b33c4ecSRafael Espindola         const CXXDestructorDecl *DDtor =
2453b33c4ecSRafael Espindola           cast<CXXDestructorDecl>(DevirtualizedMethod);
24649e860b2SRafael Espindola         Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
24749e860b2SRafael Espindola       }
248a5bf76bdSAlexey Samsonov       EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
249a5bf76bdSAlexey Samsonov                                   /*ImplicitParam=*/nullptr, QualType(), CE);
25027da15baSAnders Carlsson     }
2518a13c418SCraig Topper     return RValue::get(nullptr);
2529dc6eef7SStephen Lin   }
2539dc6eef7SStephen Lin 
2549dc6eef7SStephen Lin   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
25564225794SFrancois Pichet     Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
2560d635f53SJohn McCall   } else if (UseVirtualCall) {
25788fd439aSTimur Iskhodzhanov     Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty);
25827da15baSAnders Carlsson   } else {
259aad4af6dSNico Weber     if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
260aad4af6dSNico Weber       Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
2613b33c4ecSRafael Espindola     else if (!DevirtualizedMethod)
262727a771aSRafael Espindola       Callee = CGM.GetAddrOfFunction(MD, Ty);
26349e860b2SRafael Espindola     else {
2643b33c4ecSRafael Espindola       Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
26549e860b2SRafael Espindola     }
26627da15baSAnders Carlsson   }
26727da15baSAnders Carlsson 
268f1749427STimur Iskhodzhanov   if (MD->isVirtual()) {
269f1749427STimur Iskhodzhanov     This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
270f1749427STimur Iskhodzhanov         *this, MD, This, UseVirtualCall);
271f1749427STimur Iskhodzhanov   }
27288fd439aSTimur Iskhodzhanov 
273a5bf76bdSAlexey Samsonov   return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This,
274a5bf76bdSAlexey Samsonov                                      /*ImplicitParam=*/nullptr, QualType(), CE);
27527da15baSAnders Carlsson }
27627da15baSAnders Carlsson 
27727da15baSAnders Carlsson RValue
27827da15baSAnders Carlsson CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
27927da15baSAnders Carlsson                                               ReturnValueSlot ReturnValue) {
28027da15baSAnders Carlsson   const BinaryOperator *BO =
28127da15baSAnders Carlsson       cast<BinaryOperator>(E->getCallee()->IgnoreParens());
28227da15baSAnders Carlsson   const Expr *BaseExpr = BO->getLHS();
28327da15baSAnders Carlsson   const Expr *MemFnExpr = BO->getRHS();
28427da15baSAnders Carlsson 
28527da15baSAnders Carlsson   const MemberPointerType *MPT =
2860009fcc3SJohn McCall     MemFnExpr->getType()->castAs<MemberPointerType>();
287475999dcSJohn McCall 
28827da15baSAnders Carlsson   const FunctionProtoType *FPT =
2890009fcc3SJohn McCall     MPT->getPointeeType()->castAs<FunctionProtoType>();
29027da15baSAnders Carlsson   const CXXRecordDecl *RD =
29127da15baSAnders Carlsson     cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
29227da15baSAnders Carlsson 
29327da15baSAnders Carlsson   // Get the member function pointer.
294a1dee530SJohn McCall   llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
29527da15baSAnders Carlsson 
29627da15baSAnders Carlsson   // Emit the 'this' pointer.
29727da15baSAnders Carlsson   llvm::Value *This;
29827da15baSAnders Carlsson 
299e302792bSJohn McCall   if (BO->getOpcode() == BO_PtrMemI)
30027da15baSAnders Carlsson     This = EmitScalarExpr(BaseExpr);
30127da15baSAnders Carlsson   else
30227da15baSAnders Carlsson     This = EmitLValue(BaseExpr).getAddress();
30327da15baSAnders Carlsson 
304e30752c9SRichard Smith   EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This,
305e30752c9SRichard Smith                 QualType(MPT->getClass(), 0));
30669d0d262SRichard Smith 
307475999dcSJohn McCall   // Ask the ABI to load the callee.  Note that This is modified.
308475999dcSJohn McCall   llvm::Value *Callee =
3092b0d66dfSDavid Majnemer     CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, MemFnPtr, MPT);
31027da15baSAnders Carlsson 
31127da15baSAnders Carlsson   CallArgList Args;
31227da15baSAnders Carlsson 
31327da15baSAnders Carlsson   QualType ThisType =
31427da15baSAnders Carlsson     getContext().getPointerType(getContext().getTagDeclType(RD));
31527da15baSAnders Carlsson 
31627da15baSAnders Carlsson   // Push the this ptr.
31743dca6a8SEli Friedman   Args.add(RValue::get(This), ThisType);
31827da15baSAnders Carlsson 
3198dda7b27SJohn McCall   RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
3208dda7b27SJohn McCall 
32127da15baSAnders Carlsson   // And the rest of the call args
3228e1162c7SAlexey Samsonov   EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getDirectCallee());
3235fa40c3bSNick Lewycky   return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
3245fa40c3bSNick Lewycky                   Callee, ReturnValue, Args);
32527da15baSAnders Carlsson }
32627da15baSAnders Carlsson 
32727da15baSAnders Carlsson RValue
32827da15baSAnders Carlsson CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
32927da15baSAnders Carlsson                                                const CXXMethodDecl *MD,
33027da15baSAnders Carlsson                                                ReturnValueSlot ReturnValue) {
33127da15baSAnders Carlsson   assert(MD->isInstance() &&
33227da15baSAnders Carlsson          "Trying to emit a member call expr on a static method!");
333aad4af6dSNico Weber   return EmitCXXMemberOrOperatorMemberCallExpr(
334aad4af6dSNico Weber       E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
335aad4af6dSNico Weber       /*IsArrow=*/false, E->getArg(0));
33627da15baSAnders Carlsson }
33727da15baSAnders Carlsson 
338fe883422SPeter Collingbourne RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
339fe883422SPeter Collingbourne                                                ReturnValueSlot ReturnValue) {
340fe883422SPeter Collingbourne   return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
341fe883422SPeter Collingbourne }
342fe883422SPeter Collingbourne 
343fde961dbSEli Friedman static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
344fde961dbSEli Friedman                                             llvm::Value *DestPtr,
345fde961dbSEli Friedman                                             const CXXRecordDecl *Base) {
346fde961dbSEli Friedman   if (Base->isEmpty())
347fde961dbSEli Friedman     return;
348fde961dbSEli Friedman 
349fde961dbSEli Friedman   DestPtr = CGF.EmitCastToVoidPtr(DestPtr);
350fde961dbSEli Friedman 
351fde961dbSEli Friedman   const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
352fde961dbSEli Friedman   CharUnits Size = Layout.getNonVirtualSize();
353d640d7d9SWarren Hunt   CharUnits Align = Layout.getNonVirtualAlignment();
354fde961dbSEli Friedman 
355fde961dbSEli Friedman   llvm::Value *SizeVal = CGF.CGM.getSize(Size);
356fde961dbSEli Friedman 
357fde961dbSEli Friedman   // If the type contains a pointer to data member we can't memset it to zero.
358fde961dbSEli Friedman   // Instead, create a null constant and copy it to the destination.
359fde961dbSEli Friedman   // TODO: there are other patterns besides zero that we can usefully memset,
360fde961dbSEli Friedman   // like -1, which happens to be the pattern used by member-pointers.
361fde961dbSEli Friedman   // TODO: isZeroInitializable can be over-conservative in the case where a
362fde961dbSEli Friedman   // virtual base contains a member pointer.
363fde961dbSEli Friedman   if (!CGF.CGM.getTypes().isZeroInitializable(Base)) {
364fde961dbSEli Friedman     llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base);
365fde961dbSEli Friedman 
366fde961dbSEli Friedman     llvm::GlobalVariable *NullVariable =
367fde961dbSEli Friedman       new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(),
368fde961dbSEli Friedman                                /*isConstant=*/true,
369fde961dbSEli Friedman                                llvm::GlobalVariable::PrivateLinkage,
370fde961dbSEli Friedman                                NullConstant, Twine());
371fde961dbSEli Friedman     NullVariable->setAlignment(Align.getQuantity());
372fde961dbSEli Friedman     llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable);
373fde961dbSEli Friedman 
374fde961dbSEli Friedman     // Get and call the appropriate llvm.memcpy overload.
375fde961dbSEli Friedman     CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity());
376fde961dbSEli Friedman     return;
377fde961dbSEli Friedman   }
378fde961dbSEli Friedman 
379fde961dbSEli Friedman   // Otherwise, just memset the whole thing to zero.  This is legal
380fde961dbSEli Friedman   // because in LLVM, all default initializers (other than the ones we just
381fde961dbSEli Friedman   // handled above) are guaranteed to have a bit pattern of all zeros.
382fde961dbSEli Friedman   CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal,
383fde961dbSEli Friedman                            Align.getQuantity());
384fde961dbSEli Friedman }
385fde961dbSEli Friedman 
38627da15baSAnders Carlsson void
3877a626f63SJohn McCall CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
3887a626f63SJohn McCall                                       AggValueSlot Dest) {
3897a626f63SJohn McCall   assert(!Dest.isIgnored() && "Must have a destination!");
39027da15baSAnders Carlsson   const CXXConstructorDecl *CD = E->getConstructor();
391630c76efSDouglas Gregor 
392630c76efSDouglas Gregor   // If we require zero initialization before (or instead of) calling the
393630c76efSDouglas Gregor   // constructor, as can be the case with a non-user-provided default
39403535265SArgyrios Kyrtzidis   // constructor, emit the zero initialization now, unless destination is
39503535265SArgyrios Kyrtzidis   // already zeroed.
396fde961dbSEli Friedman   if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
397fde961dbSEli Friedman     switch (E->getConstructionKind()) {
398fde961dbSEli Friedman     case CXXConstructExpr::CK_Delegating:
399fde961dbSEli Friedman     case CXXConstructExpr::CK_Complete:
4007a626f63SJohn McCall       EmitNullInitialization(Dest.getAddr(), E->getType());
401fde961dbSEli Friedman       break;
402fde961dbSEli Friedman     case CXXConstructExpr::CK_VirtualBase:
403fde961dbSEli Friedman     case CXXConstructExpr::CK_NonVirtualBase:
404fde961dbSEli Friedman       EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent());
405fde961dbSEli Friedman       break;
406fde961dbSEli Friedman     }
407fde961dbSEli Friedman   }
408630c76efSDouglas Gregor 
409630c76efSDouglas Gregor   // If this is a call to a trivial default constructor, do nothing.
410630c76efSDouglas Gregor   if (CD->isTrivial() && CD->isDefaultConstructor())
41127da15baSAnders Carlsson     return;
412630c76efSDouglas Gregor 
4138ea46b66SJohn McCall   // Elide the constructor if we're constructing from a temporary.
4148ea46b66SJohn McCall   // The temporary check is required because Sema sets this on NRVO
4158ea46b66SJohn McCall   // returns.
4169c6890a7SRichard Smith   if (getLangOpts().ElideConstructors && E->isElidable()) {
4178ea46b66SJohn McCall     assert(getContext().hasSameUnqualifiedType(E->getType(),
4188ea46b66SJohn McCall                                                E->getArg(0)->getType()));
4197a626f63SJohn McCall     if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
4207a626f63SJohn McCall       EmitAggExpr(E->getArg(0), Dest);
42127da15baSAnders Carlsson       return;
42227da15baSAnders Carlsson     }
423222cf0efSDouglas Gregor   }
424630c76efSDouglas Gregor 
425f677a8e9SJohn McCall   if (const ConstantArrayType *arrayType
426f677a8e9SJohn McCall         = getContext().getAsConstantArrayType(E->getType())) {
42770b9c01bSAlexey Samsonov     EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(), E);
428f677a8e9SJohn McCall   } else {
429bceca20aSCameron Esfahani     CXXCtorType Type = Ctor_Complete;
430271c3681SAlexis Hunt     bool ForVirtualBase = false;
43161535005SDouglas Gregor     bool Delegating = false;
432271c3681SAlexis Hunt 
433271c3681SAlexis Hunt     switch (E->getConstructionKind()) {
434271c3681SAlexis Hunt      case CXXConstructExpr::CK_Delegating:
43561bc1737SAlexis Hunt       // We should be emitting a constructor; GlobalDecl will assert this
43661bc1737SAlexis Hunt       Type = CurGD.getCtorType();
43761535005SDouglas Gregor       Delegating = true;
438271c3681SAlexis Hunt       break;
43961bc1737SAlexis Hunt 
440271c3681SAlexis Hunt      case CXXConstructExpr::CK_Complete:
441271c3681SAlexis Hunt       Type = Ctor_Complete;
442271c3681SAlexis Hunt       break;
443271c3681SAlexis Hunt 
444271c3681SAlexis Hunt      case CXXConstructExpr::CK_VirtualBase:
445271c3681SAlexis Hunt       ForVirtualBase = true;
446271c3681SAlexis Hunt       // fall-through
447271c3681SAlexis Hunt 
448271c3681SAlexis Hunt      case CXXConstructExpr::CK_NonVirtualBase:
449271c3681SAlexis Hunt       Type = Ctor_Base;
450271c3681SAlexis Hunt     }
451e11f9ce9SAnders Carlsson 
45227da15baSAnders Carlsson     // Call the constructor.
45361535005SDouglas Gregor     EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, Dest.getAddr(),
45470b9c01bSAlexey Samsonov                            E);
45527da15baSAnders Carlsson   }
456e11f9ce9SAnders Carlsson }
45727da15baSAnders Carlsson 
458e988bdacSFariborz Jahanian void
459e988bdacSFariborz Jahanian CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest,
460e988bdacSFariborz Jahanian                                             llvm::Value *Src,
46150198098SFariborz Jahanian                                             const Expr *Exp) {
4625d413781SJohn McCall   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
463e988bdacSFariborz Jahanian     Exp = E->getSubExpr();
464e988bdacSFariborz Jahanian   assert(isa<CXXConstructExpr>(Exp) &&
465e988bdacSFariborz Jahanian          "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
466e988bdacSFariborz Jahanian   const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
467e988bdacSFariborz Jahanian   const CXXConstructorDecl *CD = E->getConstructor();
468e988bdacSFariborz Jahanian   RunCleanupsScope Scope(*this);
469e988bdacSFariborz Jahanian 
470e988bdacSFariborz Jahanian   // If we require zero initialization before (or instead of) calling the
471e988bdacSFariborz Jahanian   // constructor, as can be the case with a non-user-provided default
472e988bdacSFariborz Jahanian   // constructor, emit the zero initialization now.
473e988bdacSFariborz Jahanian   // FIXME. Do I still need this for a copy ctor synthesis?
474e988bdacSFariborz Jahanian   if (E->requiresZeroInitialization())
475e988bdacSFariborz Jahanian     EmitNullInitialization(Dest, E->getType());
476e988bdacSFariborz Jahanian 
47799da11cfSChandler Carruth   assert(!getContext().getAsConstantArrayType(E->getType())
47899da11cfSChandler Carruth          && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
479525bf650SAlexey Samsonov   EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
480e988bdacSFariborz Jahanian }
481e988bdacSFariborz Jahanian 
4828ed55a54SJohn McCall static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
4838ed55a54SJohn McCall                                         const CXXNewExpr *E) {
48421122cf6SAnders Carlsson   if (!E->isArray())
4853eb55cfeSKen Dyck     return CharUnits::Zero();
48621122cf6SAnders Carlsson 
4877ec4b434SJohn McCall   // No cookie is required if the operator new[] being used is the
4887ec4b434SJohn McCall   // reserved placement operator new[].
4897ec4b434SJohn McCall   if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
4903eb55cfeSKen Dyck     return CharUnits::Zero();
491399f499fSAnders Carlsson 
492284c48ffSJohn McCall   return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
49359486a2dSAnders Carlsson }
49459486a2dSAnders Carlsson 
495036f2f6bSJohn McCall static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
496036f2f6bSJohn McCall                                         const CXXNewExpr *e,
497f862eb6aSSebastian Redl                                         unsigned minElements,
498036f2f6bSJohn McCall                                         llvm::Value *&numElements,
499036f2f6bSJohn McCall                                         llvm::Value *&sizeWithoutCookie) {
500036f2f6bSJohn McCall   QualType type = e->getAllocatedType();
50159486a2dSAnders Carlsson 
502036f2f6bSJohn McCall   if (!e->isArray()) {
503036f2f6bSJohn McCall     CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
504036f2f6bSJohn McCall     sizeWithoutCookie
505036f2f6bSJohn McCall       = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
506036f2f6bSJohn McCall     return sizeWithoutCookie;
50705fc5be3SDouglas Gregor   }
50859486a2dSAnders Carlsson 
509036f2f6bSJohn McCall   // The width of size_t.
510036f2f6bSJohn McCall   unsigned sizeWidth = CGF.SizeTy->getBitWidth();
511036f2f6bSJohn McCall 
5128ed55a54SJohn McCall   // Figure out the cookie size.
513036f2f6bSJohn McCall   llvm::APInt cookieSize(sizeWidth,
514036f2f6bSJohn McCall                          CalculateCookiePadding(CGF, e).getQuantity());
5158ed55a54SJohn McCall 
51659486a2dSAnders Carlsson   // Emit the array size expression.
5177648fb46SArgyrios Kyrtzidis   // We multiply the size of all dimensions for NumElements.
5187648fb46SArgyrios Kyrtzidis   // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
519036f2f6bSJohn McCall   numElements = CGF.EmitScalarExpr(e->getArraySize());
520036f2f6bSJohn McCall   assert(isa<llvm::IntegerType>(numElements->getType()));
5218ed55a54SJohn McCall 
522036f2f6bSJohn McCall   // The number of elements can be have an arbitrary integer type;
523036f2f6bSJohn McCall   // essentially, we need to multiply it by a constant factor, add a
524036f2f6bSJohn McCall   // cookie size, and verify that the result is representable as a
525036f2f6bSJohn McCall   // size_t.  That's just a gloss, though, and it's wrong in one
526036f2f6bSJohn McCall   // important way: if the count is negative, it's an error even if
527036f2f6bSJohn McCall   // the cookie size would bring the total size >= 0.
5286ab2fa8fSDouglas Gregor   bool isSigned
5296ab2fa8fSDouglas Gregor     = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
5302192fe50SChris Lattner   llvm::IntegerType *numElementsType
531036f2f6bSJohn McCall     = cast<llvm::IntegerType>(numElements->getType());
532036f2f6bSJohn McCall   unsigned numElementsWidth = numElementsType->getBitWidth();
533036f2f6bSJohn McCall 
534036f2f6bSJohn McCall   // Compute the constant factor.
535036f2f6bSJohn McCall   llvm::APInt arraySizeMultiplier(sizeWidth, 1);
5367648fb46SArgyrios Kyrtzidis   while (const ConstantArrayType *CAT
537036f2f6bSJohn McCall              = CGF.getContext().getAsConstantArrayType(type)) {
538036f2f6bSJohn McCall     type = CAT->getElementType();
539036f2f6bSJohn McCall     arraySizeMultiplier *= CAT->getSize();
5407648fb46SArgyrios Kyrtzidis   }
54159486a2dSAnders Carlsson 
542036f2f6bSJohn McCall   CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
543036f2f6bSJohn McCall   llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
544036f2f6bSJohn McCall   typeSizeMultiplier *= arraySizeMultiplier;
545036f2f6bSJohn McCall 
546036f2f6bSJohn McCall   // This will be a size_t.
547036f2f6bSJohn McCall   llvm::Value *size;
54832ac583dSChris Lattner 
54932ac583dSChris Lattner   // If someone is doing 'new int[42]' there is no need to do a dynamic check.
55032ac583dSChris Lattner   // Don't bloat the -O0 code.
551036f2f6bSJohn McCall   if (llvm::ConstantInt *numElementsC =
552036f2f6bSJohn McCall         dyn_cast<llvm::ConstantInt>(numElements)) {
553036f2f6bSJohn McCall     const llvm::APInt &count = numElementsC->getValue();
55432ac583dSChris Lattner 
555036f2f6bSJohn McCall     bool hasAnyOverflow = false;
55632ac583dSChris Lattner 
557036f2f6bSJohn McCall     // If 'count' was a negative number, it's an overflow.
558036f2f6bSJohn McCall     if (isSigned && count.isNegative())
559036f2f6bSJohn McCall       hasAnyOverflow = true;
5608ed55a54SJohn McCall 
561036f2f6bSJohn McCall     // We want to do all this arithmetic in size_t.  If numElements is
562036f2f6bSJohn McCall     // wider than that, check whether it's already too big, and if so,
563036f2f6bSJohn McCall     // overflow.
564036f2f6bSJohn McCall     else if (numElementsWidth > sizeWidth &&
565036f2f6bSJohn McCall              numElementsWidth - sizeWidth > count.countLeadingZeros())
566036f2f6bSJohn McCall       hasAnyOverflow = true;
567036f2f6bSJohn McCall 
568036f2f6bSJohn McCall     // Okay, compute a count at the right width.
569036f2f6bSJohn McCall     llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
570036f2f6bSJohn McCall 
571f862eb6aSSebastian Redl     // If there is a brace-initializer, we cannot allocate fewer elements than
572f862eb6aSSebastian Redl     // there are initializers. If we do, that's treated like an overflow.
573f862eb6aSSebastian Redl     if (adjustedCount.ult(minElements))
574f862eb6aSSebastian Redl       hasAnyOverflow = true;
575f862eb6aSSebastian Redl 
576036f2f6bSJohn McCall     // Scale numElements by that.  This might overflow, but we don't
577036f2f6bSJohn McCall     // care because it only overflows if allocationSize does, too, and
578036f2f6bSJohn McCall     // if that overflows then we shouldn't use this.
579036f2f6bSJohn McCall     numElements = llvm::ConstantInt::get(CGF.SizeTy,
580036f2f6bSJohn McCall                                          adjustedCount * arraySizeMultiplier);
581036f2f6bSJohn McCall 
582036f2f6bSJohn McCall     // Compute the size before cookie, and track whether it overflowed.
583036f2f6bSJohn McCall     bool overflow;
584036f2f6bSJohn McCall     llvm::APInt allocationSize
585036f2f6bSJohn McCall       = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
586036f2f6bSJohn McCall     hasAnyOverflow |= overflow;
587036f2f6bSJohn McCall 
588036f2f6bSJohn McCall     // Add in the cookie, and check whether it's overflowed.
589036f2f6bSJohn McCall     if (cookieSize != 0) {
590036f2f6bSJohn McCall       // Save the current size without a cookie.  This shouldn't be
591036f2f6bSJohn McCall       // used if there was overflow.
592036f2f6bSJohn McCall       sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
593036f2f6bSJohn McCall 
594036f2f6bSJohn McCall       allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
595036f2f6bSJohn McCall       hasAnyOverflow |= overflow;
5968ed55a54SJohn McCall     }
5978ed55a54SJohn McCall 
598036f2f6bSJohn McCall     // On overflow, produce a -1 so operator new will fail.
599455f42c9SAaron Ballman     if (hasAnyOverflow) {
600455f42c9SAaron Ballman       size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
601455f42c9SAaron Ballman     } else {
602036f2f6bSJohn McCall       size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
603455f42c9SAaron Ballman     }
60432ac583dSChris Lattner 
605036f2f6bSJohn McCall   // Otherwise, we might need to use the overflow intrinsics.
6068ed55a54SJohn McCall   } else {
607f862eb6aSSebastian Redl     // There are up to five conditions we need to test for:
608036f2f6bSJohn McCall     // 1) if isSigned, we need to check whether numElements is negative;
609036f2f6bSJohn McCall     // 2) if numElementsWidth > sizeWidth, we need to check whether
610036f2f6bSJohn McCall     //   numElements is larger than something representable in size_t;
611f862eb6aSSebastian Redl     // 3) if minElements > 0, we need to check whether numElements is smaller
612f862eb6aSSebastian Redl     //    than that.
613f862eb6aSSebastian Redl     // 4) we need to compute
614036f2f6bSJohn McCall     //      sizeWithoutCookie := numElements * typeSizeMultiplier
615036f2f6bSJohn McCall     //    and check whether it overflows; and
616f862eb6aSSebastian Redl     // 5) if we need a cookie, we need to compute
617036f2f6bSJohn McCall     //      size := sizeWithoutCookie + cookieSize
618036f2f6bSJohn McCall     //    and check whether it overflows.
6198ed55a54SJohn McCall 
6208a13c418SCraig Topper     llvm::Value *hasOverflow = nullptr;
6218ed55a54SJohn McCall 
622036f2f6bSJohn McCall     // If numElementsWidth > sizeWidth, then one way or another, we're
623036f2f6bSJohn McCall     // going to have to do a comparison for (2), and this happens to
624036f2f6bSJohn McCall     // take care of (1), too.
625036f2f6bSJohn McCall     if (numElementsWidth > sizeWidth) {
626036f2f6bSJohn McCall       llvm::APInt threshold(numElementsWidth, 1);
627036f2f6bSJohn McCall       threshold <<= sizeWidth;
6288ed55a54SJohn McCall 
629036f2f6bSJohn McCall       llvm::Value *thresholdV
630036f2f6bSJohn McCall         = llvm::ConstantInt::get(numElementsType, threshold);
631036f2f6bSJohn McCall 
632036f2f6bSJohn McCall       hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
633036f2f6bSJohn McCall       numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
634036f2f6bSJohn McCall 
635036f2f6bSJohn McCall     // Otherwise, if we're signed, we want to sext up to size_t.
636036f2f6bSJohn McCall     } else if (isSigned) {
637036f2f6bSJohn McCall       if (numElementsWidth < sizeWidth)
638036f2f6bSJohn McCall         numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
639036f2f6bSJohn McCall 
640036f2f6bSJohn McCall       // If there's a non-1 type size multiplier, then we can do the
641036f2f6bSJohn McCall       // signedness check at the same time as we do the multiply
642036f2f6bSJohn McCall       // because a negative number times anything will cause an
643f862eb6aSSebastian Redl       // unsigned overflow.  Otherwise, we have to do it here. But at least
644f862eb6aSSebastian Redl       // in this case, we can subsume the >= minElements check.
645036f2f6bSJohn McCall       if (typeSizeMultiplier == 1)
646036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
647f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
648036f2f6bSJohn McCall 
649036f2f6bSJohn McCall     // Otherwise, zext up to size_t if necessary.
650036f2f6bSJohn McCall     } else if (numElementsWidth < sizeWidth) {
651036f2f6bSJohn McCall       numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
652036f2f6bSJohn McCall     }
653036f2f6bSJohn McCall 
654036f2f6bSJohn McCall     assert(numElements->getType() == CGF.SizeTy);
655036f2f6bSJohn McCall 
656f862eb6aSSebastian Redl     if (minElements) {
657f862eb6aSSebastian Redl       // Don't allow allocation of fewer elements than we have initializers.
658f862eb6aSSebastian Redl       if (!hasOverflow) {
659f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateICmpULT(numElements,
660f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements));
661f862eb6aSSebastian Redl       } else if (numElementsWidth > sizeWidth) {
662f862eb6aSSebastian Redl         // The other existing overflow subsumes this check.
663f862eb6aSSebastian Redl         // We do an unsigned comparison, since any signed value < -1 is
664f862eb6aSSebastian Redl         // taken care of either above or below.
665f862eb6aSSebastian Redl         hasOverflow = CGF.Builder.CreateOr(hasOverflow,
666f862eb6aSSebastian Redl                           CGF.Builder.CreateICmpULT(numElements,
667f862eb6aSSebastian Redl                               llvm::ConstantInt::get(CGF.SizeTy, minElements)));
668f862eb6aSSebastian Redl       }
669f862eb6aSSebastian Redl     }
670f862eb6aSSebastian Redl 
671036f2f6bSJohn McCall     size = numElements;
672036f2f6bSJohn McCall 
673036f2f6bSJohn McCall     // Multiply by the type size if necessary.  This multiplier
674036f2f6bSJohn McCall     // includes all the factors for nested arrays.
6758ed55a54SJohn McCall     //
676036f2f6bSJohn McCall     // This step also causes numElements to be scaled up by the
677036f2f6bSJohn McCall     // nested-array factor if necessary.  Overflow on this computation
678036f2f6bSJohn McCall     // can be ignored because the result shouldn't be used if
679036f2f6bSJohn McCall     // allocation fails.
680036f2f6bSJohn McCall     if (typeSizeMultiplier != 1) {
681036f2f6bSJohn McCall       llvm::Value *umul_with_overflow
6828d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
6838ed55a54SJohn McCall 
684036f2f6bSJohn McCall       llvm::Value *tsmV =
685036f2f6bSJohn McCall         llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
686036f2f6bSJohn McCall       llvm::Value *result =
687036f2f6bSJohn McCall         CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV);
6888ed55a54SJohn McCall 
689036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
690036f2f6bSJohn McCall       if (hasOverflow)
691036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
6928ed55a54SJohn McCall       else
693036f2f6bSJohn McCall         hasOverflow = overflowed;
69459486a2dSAnders Carlsson 
695036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
696036f2f6bSJohn McCall 
697036f2f6bSJohn McCall       // Also scale up numElements by the array size multiplier.
698036f2f6bSJohn McCall       if (arraySizeMultiplier != 1) {
699036f2f6bSJohn McCall         // If the base element type size is 1, then we can re-use the
700036f2f6bSJohn McCall         // multiply we just did.
701036f2f6bSJohn McCall         if (typeSize.isOne()) {
702036f2f6bSJohn McCall           assert(arraySizeMultiplier == typeSizeMultiplier);
703036f2f6bSJohn McCall           numElements = size;
704036f2f6bSJohn McCall 
705036f2f6bSJohn McCall         // Otherwise we need a separate multiply.
706036f2f6bSJohn McCall         } else {
707036f2f6bSJohn McCall           llvm::Value *asmV =
708036f2f6bSJohn McCall             llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
709036f2f6bSJohn McCall           numElements = CGF.Builder.CreateMul(numElements, asmV);
710036f2f6bSJohn McCall         }
711036f2f6bSJohn McCall       }
712036f2f6bSJohn McCall     } else {
713036f2f6bSJohn McCall       // numElements doesn't need to be scaled.
714036f2f6bSJohn McCall       assert(arraySizeMultiplier == 1);
715036f2f6bSJohn McCall     }
716036f2f6bSJohn McCall 
717036f2f6bSJohn McCall     // Add in the cookie size if necessary.
718036f2f6bSJohn McCall     if (cookieSize != 0) {
719036f2f6bSJohn McCall       sizeWithoutCookie = size;
720036f2f6bSJohn McCall 
721036f2f6bSJohn McCall       llvm::Value *uadd_with_overflow
7228d375cefSBenjamin Kramer         = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
723036f2f6bSJohn McCall 
724036f2f6bSJohn McCall       llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
725036f2f6bSJohn McCall       llvm::Value *result =
726036f2f6bSJohn McCall         CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV);
727036f2f6bSJohn McCall 
728036f2f6bSJohn McCall       llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
729036f2f6bSJohn McCall       if (hasOverflow)
730036f2f6bSJohn McCall         hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
731036f2f6bSJohn McCall       else
732036f2f6bSJohn McCall         hasOverflow = overflowed;
733036f2f6bSJohn McCall 
734036f2f6bSJohn McCall       size = CGF.Builder.CreateExtractValue(result, 0);
735036f2f6bSJohn McCall     }
736036f2f6bSJohn McCall 
737036f2f6bSJohn McCall     // If we had any possibility of dynamic overflow, make a select to
738036f2f6bSJohn McCall     // overwrite 'size' with an all-ones value, which should cause
739036f2f6bSJohn McCall     // operator new to throw.
740036f2f6bSJohn McCall     if (hasOverflow)
741455f42c9SAaron Ballman       size = CGF.Builder.CreateSelect(hasOverflow,
742455f42c9SAaron Ballman                                  llvm::Constant::getAllOnesValue(CGF.SizeTy),
743036f2f6bSJohn McCall                                       size);
744036f2f6bSJohn McCall   }
745036f2f6bSJohn McCall 
746036f2f6bSJohn McCall   if (cookieSize == 0)
747036f2f6bSJohn McCall     sizeWithoutCookie = size;
748036f2f6bSJohn McCall   else
749036f2f6bSJohn McCall     assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
750036f2f6bSJohn McCall 
751036f2f6bSJohn McCall   return size;
75259486a2dSAnders Carlsson }
75359486a2dSAnders Carlsson 
754f862eb6aSSebastian Redl static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
755*66e4197fSDavid Blaikie                                     QualType AllocType, llvm::Value *NewPtr) {
7561c96bc5dSRichard Smith   // FIXME: Refactor with EmitExprAsInit.
75738cd36dbSEli Friedman   CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType);
75847fb9508SJohn McCall   switch (CGF.getEvaluationKind(AllocType)) {
75947fb9508SJohn McCall   case TEK_Scalar:
760a2c1124fSDavid Blaikie     CGF.EmitScalarInit(Init, nullptr,
761*66e4197fSDavid Blaikie                        CGF.MakeAddrLValue(NewPtr, AllocType, Alignment), false);
76247fb9508SJohn McCall     return;
76347fb9508SJohn McCall   case TEK_Complex:
76447fb9508SJohn McCall     CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType,
76547fb9508SJohn McCall                                                            Alignment),
76647fb9508SJohn McCall                                   /*isInit*/ true);
76747fb9508SJohn McCall     return;
76847fb9508SJohn McCall   case TEK_Aggregate: {
7697a626f63SJohn McCall     AggValueSlot Slot
770c1d85b93SEli Friedman       = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(),
7718d6fc958SJohn McCall                               AggValueSlot::IsDestructed,
77246759f4fSJohn McCall                               AggValueSlot::DoesNotNeedGCBarriers,
773615ed1a3SChad Rosier                               AggValueSlot::IsNotAliased);
7747a626f63SJohn McCall     CGF.EmitAggExpr(Init, Slot);
77547fb9508SJohn McCall     return;
7767a626f63SJohn McCall   }
777d5202e09SFariborz Jahanian   }
77847fb9508SJohn McCall   llvm_unreachable("bad evaluation kind");
77947fb9508SJohn McCall }
780d5202e09SFariborz Jahanian 
781d5202e09SFariborz Jahanian void
782d5202e09SFariborz Jahanian CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E,
78306a67e2cSRichard Smith                                          QualType ElementType,
78406a67e2cSRichard Smith                                          llvm::Value *BeginPtr,
78506a67e2cSRichard Smith                                          llvm::Value *NumElements,
78606a67e2cSRichard Smith                                          llvm::Value *AllocSizeWithoutCookie) {
78706a67e2cSRichard Smith   // If we have a type with trivial initialization and no initializer,
78806a67e2cSRichard Smith   // there's nothing to do.
7896047f07eSSebastian Redl   if (!E->hasInitializer())
79006a67e2cSRichard Smith     return;
791b66b08efSFariborz Jahanian 
79206a67e2cSRichard Smith   llvm::Value *CurPtr = BeginPtr;
793d5202e09SFariborz Jahanian 
79406a67e2cSRichard Smith   unsigned InitListElements = 0;
795f862eb6aSSebastian Redl 
796f862eb6aSSebastian Redl   const Expr *Init = E->getInitializer();
79706a67e2cSRichard Smith   llvm::AllocaInst *EndOfInit = nullptr;
79806a67e2cSRichard Smith   QualType::DestructionKind DtorKind = ElementType.isDestructedType();
79906a67e2cSRichard Smith   EHScopeStack::stable_iterator Cleanup;
80006a67e2cSRichard Smith   llvm::Instruction *CleanupDominator = nullptr;
8011c96bc5dSRichard Smith 
802f862eb6aSSebastian Redl   // If the initializer is an initializer list, first do the explicit elements.
803f862eb6aSSebastian Redl   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
80406a67e2cSRichard Smith     InitListElements = ILE->getNumInits();
805f62290a1SChad Rosier 
8061c96bc5dSRichard Smith     // If this is a multi-dimensional array new, we will initialize multiple
8071c96bc5dSRichard Smith     // elements with each init list element.
8081c96bc5dSRichard Smith     QualType AllocType = E->getAllocatedType();
8091c96bc5dSRichard Smith     if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
8101c96bc5dSRichard Smith             AllocType->getAsArrayTypeUnsafe())) {
81106a67e2cSRichard Smith       unsigned AS = CurPtr->getType()->getPointerAddressSpace();
8121c96bc5dSRichard Smith       llvm::Type *AllocPtrTy = ConvertTypeForMem(AllocType)->getPointerTo(AS);
81306a67e2cSRichard Smith       CurPtr = Builder.CreateBitCast(CurPtr, AllocPtrTy);
81406a67e2cSRichard Smith       InitListElements *= getContext().getConstantArrayElementCount(CAT);
8151c96bc5dSRichard Smith     }
8161c96bc5dSRichard Smith 
81706a67e2cSRichard Smith     // Enter a partial-destruction Cleanup if necessary.
81806a67e2cSRichard Smith     if (needsEHCleanup(DtorKind)) {
81906a67e2cSRichard Smith       // In principle we could tell the Cleanup where we are more
820f62290a1SChad Rosier       // directly, but the control flow can get so varied here that it
821f62290a1SChad Rosier       // would actually be quite complex.  Therefore we go through an
822f62290a1SChad Rosier       // alloca.
82306a67e2cSRichard Smith       EndOfInit = CreateTempAlloca(BeginPtr->getType(), "array.init.end");
82406a67e2cSRichard Smith       CleanupDominator = Builder.CreateStore(BeginPtr, EndOfInit);
82506a67e2cSRichard Smith       pushIrregularPartialArrayCleanup(BeginPtr, EndOfInit, ElementType,
82606a67e2cSRichard Smith                                        getDestroyer(DtorKind));
82706a67e2cSRichard Smith       Cleanup = EHStack.stable_begin();
828f62290a1SChad Rosier     }
829f62290a1SChad Rosier 
830f862eb6aSSebastian Redl     for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
831f62290a1SChad Rosier       // Tell the cleanup that it needs to destroy up to this
832f62290a1SChad Rosier       // element.  TODO: some of these stores can be trivially
833f62290a1SChad Rosier       // observed to be unnecessary.
83406a67e2cSRichard Smith       if (EndOfInit)
83506a67e2cSRichard Smith         Builder.CreateStore(Builder.CreateBitCast(CurPtr, BeginPtr->getType()),
83606a67e2cSRichard Smith                             EndOfInit);
83706a67e2cSRichard Smith       // FIXME: If the last initializer is an incomplete initializer list for
83806a67e2cSRichard Smith       // an array, and we have an array filler, we can fold together the two
83906a67e2cSRichard Smith       // initialization loops.
8401c96bc5dSRichard Smith       StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
84106a67e2cSRichard Smith                               ILE->getInit(i)->getType(), CurPtr);
84206a67e2cSRichard Smith       CurPtr = Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.exp.next");
843f862eb6aSSebastian Redl     }
844f862eb6aSSebastian Redl 
845f862eb6aSSebastian Redl     // The remaining elements are filled with the array filler expression.
846f862eb6aSSebastian Redl     Init = ILE->getArrayFiller();
8471c96bc5dSRichard Smith 
84806a67e2cSRichard Smith     // Extract the initializer for the individual array elements by pulling
84906a67e2cSRichard Smith     // out the array filler from all the nested initializer lists. This avoids
85006a67e2cSRichard Smith     // generating a nested loop for the initialization.
85106a67e2cSRichard Smith     while (Init && Init->getType()->isConstantArrayType()) {
85206a67e2cSRichard Smith       auto *SubILE = dyn_cast<InitListExpr>(Init);
85306a67e2cSRichard Smith       if (!SubILE)
85406a67e2cSRichard Smith         break;
85506a67e2cSRichard Smith       assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
85606a67e2cSRichard Smith       Init = SubILE->getArrayFiller();
857f862eb6aSSebastian Redl     }
858f862eb6aSSebastian Redl 
85906a67e2cSRichard Smith     // Switch back to initializing one base element at a time.
86006a67e2cSRichard Smith     CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr->getType());
861f62290a1SChad Rosier   }
862e6c980c4SChandler Carruth 
86306a67e2cSRichard Smith   // Attempt to perform zero-initialization using memset.
86406a67e2cSRichard Smith   auto TryMemsetInitialization = [&]() -> bool {
86506a67e2cSRichard Smith     // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
86606a67e2cSRichard Smith     // we can initialize with a memset to -1.
86706a67e2cSRichard Smith     if (!CGM.getTypes().isZeroInitializable(ElementType))
86806a67e2cSRichard Smith       return false;
869e6c980c4SChandler Carruth 
87006a67e2cSRichard Smith     // Optimization: since zero initialization will just set the memory
87106a67e2cSRichard Smith     // to all zeroes, generate a single memset to do it in one shot.
87206a67e2cSRichard Smith 
87306a67e2cSRichard Smith     // Subtract out the size of any elements we've already initialized.
87406a67e2cSRichard Smith     auto *RemainingSize = AllocSizeWithoutCookie;
87506a67e2cSRichard Smith     if (InitListElements) {
87606a67e2cSRichard Smith       // We know this can't overflow; we check this when doing the allocation.
87706a67e2cSRichard Smith       auto *InitializedSize = llvm::ConstantInt::get(
87806a67e2cSRichard Smith           RemainingSize->getType(),
87906a67e2cSRichard Smith           getContext().getTypeSizeInChars(ElementType).getQuantity() *
88006a67e2cSRichard Smith               InitListElements);
88106a67e2cSRichard Smith       RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
88299210dc9SJohn McCall     }
883d5202e09SFariborz Jahanian 
88406a67e2cSRichard Smith     // Create the memset.
88506a67e2cSRichard Smith     CharUnits Alignment = getContext().getTypeAlignInChars(ElementType);
88606a67e2cSRichard Smith     Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize,
887705ba07eSKen Dyck                          Alignment.getQuantity(), false);
88806a67e2cSRichard Smith     return true;
88906a67e2cSRichard Smith   };
89005fc5be3SDouglas Gregor 
891454a7cdfSRichard Smith   // If all elements have already been initialized, skip any further
892454a7cdfSRichard Smith   // initialization.
893454a7cdfSRichard Smith   llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
894454a7cdfSRichard Smith   if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
895454a7cdfSRichard Smith     // If there was a Cleanup, deactivate it.
896454a7cdfSRichard Smith     if (CleanupDominator)
897454a7cdfSRichard Smith       DeactivateCleanupBlock(Cleanup, CleanupDominator);
898454a7cdfSRichard Smith     return;
899454a7cdfSRichard Smith   }
900454a7cdfSRichard Smith 
901454a7cdfSRichard Smith   assert(Init && "have trailing elements to initialize but no initializer");
902454a7cdfSRichard Smith 
90306a67e2cSRichard Smith   // If this is a constructor call, try to optimize it out, and failing that
90406a67e2cSRichard Smith   // emit a single loop to initialize all remaining elements.
905454a7cdfSRichard Smith   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9066047f07eSSebastian Redl     CXXConstructorDecl *Ctor = CCE->getConstructor();
907d153103cSDouglas Gregor     if (Ctor->isTrivial()) {
90805fc5be3SDouglas Gregor       // If new expression did not specify value-initialization, then there
90905fc5be3SDouglas Gregor       // is no initialization.
9106047f07eSSebastian Redl       if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
91105fc5be3SDouglas Gregor         return;
91205fc5be3SDouglas Gregor 
91306a67e2cSRichard Smith       if (TryMemsetInitialization())
9143a202f60SAnders Carlsson         return;
9153a202f60SAnders Carlsson     }
91605fc5be3SDouglas Gregor 
91706a67e2cSRichard Smith     // Store the new Cleanup position for irregular Cleanups.
91806a67e2cSRichard Smith     //
91906a67e2cSRichard Smith     // FIXME: Share this cleanup with the constructor call emission rather than
92006a67e2cSRichard Smith     // having it create a cleanup of its own.
92106a67e2cSRichard Smith     if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
92206a67e2cSRichard Smith 
92306a67e2cSRichard Smith     // Emit a constructor call loop to initialize the remaining elements.
92406a67e2cSRichard Smith     if (InitListElements)
92506a67e2cSRichard Smith       NumElements = Builder.CreateSub(
92606a67e2cSRichard Smith           NumElements,
92706a67e2cSRichard Smith           llvm::ConstantInt::get(NumElements->getType(), InitListElements));
92870b9c01bSAlexey Samsonov     EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
92948ddcf2cSEli Friedman                                CCE->requiresZeroInitialization());
93005fc5be3SDouglas Gregor     return;
9316047f07eSSebastian Redl   }
93206a67e2cSRichard Smith 
93306a67e2cSRichard Smith   // If this is value-initialization, we can usually use memset.
93406a67e2cSRichard Smith   ImplicitValueInitExpr IVIE(ElementType);
935454a7cdfSRichard Smith   if (isa<ImplicitValueInitExpr>(Init)) {
93606a67e2cSRichard Smith     if (TryMemsetInitialization())
93706a67e2cSRichard Smith       return;
93806a67e2cSRichard Smith 
93906a67e2cSRichard Smith     // Switch to an ImplicitValueInitExpr for the element type. This handles
94006a67e2cSRichard Smith     // only one case: multidimensional array new of pointers to members. In
94106a67e2cSRichard Smith     // all other cases, we already have an initializer for the array element.
94206a67e2cSRichard Smith     Init = &IVIE;
94306a67e2cSRichard Smith   }
94406a67e2cSRichard Smith 
94506a67e2cSRichard Smith   // At this point we should have found an initializer for the individual
94606a67e2cSRichard Smith   // elements of the array.
94706a67e2cSRichard Smith   assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
94806a67e2cSRichard Smith          "got wrong type of element to initialize");
94906a67e2cSRichard Smith 
950454a7cdfSRichard Smith   // If we have an empty initializer list, we can usually use memset.
951454a7cdfSRichard Smith   if (auto *ILE = dyn_cast<InitListExpr>(Init))
952454a7cdfSRichard Smith     if (ILE->getNumInits() == 0 && TryMemsetInitialization())
953d5202e09SFariborz Jahanian       return;
95459486a2dSAnders Carlsson 
95506a67e2cSRichard Smith   // Create the loop blocks.
95606a67e2cSRichard Smith   llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
95706a67e2cSRichard Smith   llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
95806a67e2cSRichard Smith   llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
95959486a2dSAnders Carlsson 
96006a67e2cSRichard Smith   // Find the end of the array, hoisted out of the loop.
96106a67e2cSRichard Smith   llvm::Value *EndPtr =
96206a67e2cSRichard Smith     Builder.CreateInBoundsGEP(BeginPtr, NumElements, "array.end");
96306a67e2cSRichard Smith 
96406a67e2cSRichard Smith   // If the number of elements isn't constant, we have to now check if there is
96506a67e2cSRichard Smith   // anything left to initialize.
96606a67e2cSRichard Smith   if (!ConstNum) {
96706a67e2cSRichard Smith     llvm::Value *IsEmpty = Builder.CreateICmpEQ(CurPtr, EndPtr,
96806a67e2cSRichard Smith                                                 "array.isempty");
96906a67e2cSRichard Smith     Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
97006a67e2cSRichard Smith   }
97106a67e2cSRichard Smith 
97206a67e2cSRichard Smith   // Enter the loop.
97306a67e2cSRichard Smith   EmitBlock(LoopBB);
97406a67e2cSRichard Smith 
97506a67e2cSRichard Smith   // Set up the current-element phi.
97606a67e2cSRichard Smith   llvm::PHINode *CurPtrPhi =
97706a67e2cSRichard Smith     Builder.CreatePHI(CurPtr->getType(), 2, "array.cur");
97806a67e2cSRichard Smith   CurPtrPhi->addIncoming(CurPtr, EntryBB);
97906a67e2cSRichard Smith   CurPtr = CurPtrPhi;
98006a67e2cSRichard Smith 
98106a67e2cSRichard Smith   // Store the new Cleanup position for irregular Cleanups.
98206a67e2cSRichard Smith   if (EndOfInit) Builder.CreateStore(CurPtr, EndOfInit);
98306a67e2cSRichard Smith 
98406a67e2cSRichard Smith   // Enter a partial-destruction Cleanup if necessary.
98506a67e2cSRichard Smith   if (!CleanupDominator && needsEHCleanup(DtorKind)) {
98606a67e2cSRichard Smith     pushRegularPartialArrayCleanup(BeginPtr, CurPtr, ElementType,
98706a67e2cSRichard Smith                                    getDestroyer(DtorKind));
98806a67e2cSRichard Smith     Cleanup = EHStack.stable_begin();
98906a67e2cSRichard Smith     CleanupDominator = Builder.CreateUnreachable();
99006a67e2cSRichard Smith   }
99106a67e2cSRichard Smith 
99206a67e2cSRichard Smith   // Emit the initializer into this element.
99306a67e2cSRichard Smith   StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
99406a67e2cSRichard Smith 
99506a67e2cSRichard Smith   // Leave the Cleanup if we entered one.
99606a67e2cSRichard Smith   if (CleanupDominator) {
99706a67e2cSRichard Smith     DeactivateCleanupBlock(Cleanup, CleanupDominator);
99806a67e2cSRichard Smith     CleanupDominator->eraseFromParent();
99906a67e2cSRichard Smith   }
100006a67e2cSRichard Smith 
100106a67e2cSRichard Smith   // Advance to the next element by adjusting the pointer type as necessary.
100206a67e2cSRichard Smith   llvm::Value *NextPtr =
100306a67e2cSRichard Smith       Builder.CreateConstInBoundsGEP1_32(CurPtr, 1, "array.next");
100406a67e2cSRichard Smith 
100506a67e2cSRichard Smith   // Check whether we've gotten to the end of the array and, if so,
100606a67e2cSRichard Smith   // exit the loop.
100706a67e2cSRichard Smith   llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
100806a67e2cSRichard Smith   Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
100906a67e2cSRichard Smith   CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
101006a67e2cSRichard Smith 
101106a67e2cSRichard Smith   EmitBlock(ContBB);
101206a67e2cSRichard Smith }
101306a67e2cSRichard Smith 
101406a67e2cSRichard Smith static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
101506a67e2cSRichard Smith                                QualType ElementType,
101606a67e2cSRichard Smith                                llvm::Value *NewPtr,
101706a67e2cSRichard Smith                                llvm::Value *NumElements,
101806a67e2cSRichard Smith                                llvm::Value *AllocSizeWithoutCookie) {
1019*66e4197fSDavid Blaikie   ApplyDebugLocation DL(CGF, E->getStartLoc());
102006a67e2cSRichard Smith   if (E->isArray())
102106a67e2cSRichard Smith     CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements,
102206a67e2cSRichard Smith                                 AllocSizeWithoutCookie);
102306a67e2cSRichard Smith   else if (const Expr *Init = E->getInitializer())
1024*66e4197fSDavid Blaikie     StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
102559486a2dSAnders Carlsson }
102659486a2dSAnders Carlsson 
10278d0dc31dSRichard Smith /// Emit a call to an operator new or operator delete function, as implicitly
10288d0dc31dSRichard Smith /// created by new-expressions and delete-expressions.
10298d0dc31dSRichard Smith static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
10308d0dc31dSRichard Smith                                 const FunctionDecl *Callee,
10318d0dc31dSRichard Smith                                 const FunctionProtoType *CalleeType,
10328d0dc31dSRichard Smith                                 const CallArgList &Args) {
10338d0dc31dSRichard Smith   llvm::Instruction *CallOrInvoke;
10341235a8daSRichard Smith   llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
10358d0dc31dSRichard Smith   RValue RV =
1036f770683fSPeter Collingbourne       CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1037f770683fSPeter Collingbourne                        Args, CalleeType, /*chainCall=*/false),
1038f770683fSPeter Collingbourne                    CalleeAddr, ReturnValueSlot(), Args, Callee, &CallOrInvoke);
10398d0dc31dSRichard Smith 
10408d0dc31dSRichard Smith   /// C++1y [expr.new]p10:
10418d0dc31dSRichard Smith   ///   [In a new-expression,] an implementation is allowed to omit a call
10428d0dc31dSRichard Smith   ///   to a replaceable global allocation function.
10438d0dc31dSRichard Smith   ///
10448d0dc31dSRichard Smith   /// We model such elidable calls with the 'builtin' attribute.
10456956d587SRafael Espindola   llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
10461235a8daSRichard Smith   if (Callee->isReplaceableGlobalAllocationFunction() &&
10476956d587SRafael Espindola       Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
10488d0dc31dSRichard Smith     // FIXME: Add addAttribute to CallSite.
10498d0dc31dSRichard Smith     if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
10508d0dc31dSRichard Smith       CI->addAttribute(llvm::AttributeSet::FunctionIndex,
10518d0dc31dSRichard Smith                        llvm::Attribute::Builtin);
10528d0dc31dSRichard Smith     else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
10538d0dc31dSRichard Smith       II->addAttribute(llvm::AttributeSet::FunctionIndex,
10548d0dc31dSRichard Smith                        llvm::Attribute::Builtin);
10558d0dc31dSRichard Smith     else
10568d0dc31dSRichard Smith       llvm_unreachable("unexpected kind of call instruction");
10578d0dc31dSRichard Smith   }
10588d0dc31dSRichard Smith 
10598d0dc31dSRichard Smith   return RV;
10608d0dc31dSRichard Smith }
10618d0dc31dSRichard Smith 
1062760520bcSRichard Smith RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1063760520bcSRichard Smith                                                  const Expr *Arg,
1064760520bcSRichard Smith                                                  bool IsDelete) {
1065760520bcSRichard Smith   CallArgList Args;
1066760520bcSRichard Smith   const Stmt *ArgS = Arg;
1067760520bcSRichard Smith   EmitCallArgs(Args, *Type->param_type_begin(),
1068760520bcSRichard Smith                ConstExprIterator(&ArgS), ConstExprIterator(&ArgS + 1));
1069760520bcSRichard Smith   // Find the allocation or deallocation function that we're calling.
1070760520bcSRichard Smith   ASTContext &Ctx = getContext();
1071760520bcSRichard Smith   DeclarationName Name = Ctx.DeclarationNames
1072760520bcSRichard Smith       .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1073760520bcSRichard Smith   for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1074599bed75SRichard Smith     if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1075599bed75SRichard Smith       if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1076760520bcSRichard Smith         return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1077760520bcSRichard Smith   llvm_unreachable("predeclared global operator new/delete is missing");
1078760520bcSRichard Smith }
1079760520bcSRichard Smith 
1080824c2f53SJohn McCall namespace {
1081824c2f53SJohn McCall   /// A cleanup to call the given 'operator delete' function upon
1082824c2f53SJohn McCall   /// abnormal exit from a new expression.
1083824c2f53SJohn McCall   class CallDeleteDuringNew : public EHScopeStack::Cleanup {
1084824c2f53SJohn McCall     size_t NumPlacementArgs;
1085824c2f53SJohn McCall     const FunctionDecl *OperatorDelete;
1086824c2f53SJohn McCall     llvm::Value *Ptr;
1087824c2f53SJohn McCall     llvm::Value *AllocSize;
1088824c2f53SJohn McCall 
1089824c2f53SJohn McCall     RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1090824c2f53SJohn McCall 
1091824c2f53SJohn McCall   public:
1092824c2f53SJohn McCall     static size_t getExtraSize(size_t NumPlacementArgs) {
1093824c2f53SJohn McCall       return NumPlacementArgs * sizeof(RValue);
1094824c2f53SJohn McCall     }
1095824c2f53SJohn McCall 
1096824c2f53SJohn McCall     CallDeleteDuringNew(size_t NumPlacementArgs,
1097824c2f53SJohn McCall                         const FunctionDecl *OperatorDelete,
1098824c2f53SJohn McCall                         llvm::Value *Ptr,
1099824c2f53SJohn McCall                         llvm::Value *AllocSize)
1100824c2f53SJohn McCall       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1101824c2f53SJohn McCall         Ptr(Ptr), AllocSize(AllocSize) {}
1102824c2f53SJohn McCall 
1103824c2f53SJohn McCall     void setPlacementArg(unsigned I, RValue Arg) {
1104824c2f53SJohn McCall       assert(I < NumPlacementArgs && "index out of range");
1105824c2f53SJohn McCall       getPlacementArgs()[I] = Arg;
1106824c2f53SJohn McCall     }
1107824c2f53SJohn McCall 
11084f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
1109824c2f53SJohn McCall       const FunctionProtoType *FPT
1110824c2f53SJohn McCall         = OperatorDelete->getType()->getAs<FunctionProtoType>();
11119cacbabdSAlp Toker       assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
11129cacbabdSAlp Toker              (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
1113824c2f53SJohn McCall 
1114824c2f53SJohn McCall       CallArgList DeleteArgs;
1115824c2f53SJohn McCall 
1116824c2f53SJohn McCall       // The first argument is always a void*.
11179cacbabdSAlp Toker       FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
111843dca6a8SEli Friedman       DeleteArgs.add(RValue::get(Ptr), *AI++);
1119824c2f53SJohn McCall 
1120824c2f53SJohn McCall       // A member 'operator delete' can take an extra 'size_t' argument.
11219cacbabdSAlp Toker       if (FPT->getNumParams() == NumPlacementArgs + 2)
112243dca6a8SEli Friedman         DeleteArgs.add(RValue::get(AllocSize), *AI++);
1123824c2f53SJohn McCall 
1124824c2f53SJohn McCall       // Pass the rest of the arguments, which must match exactly.
1125824c2f53SJohn McCall       for (unsigned I = 0; I != NumPlacementArgs; ++I)
112643dca6a8SEli Friedman         DeleteArgs.add(getPlacementArgs()[I], *AI++);
1127824c2f53SJohn McCall 
1128824c2f53SJohn McCall       // Call 'operator delete'.
11298d0dc31dSRichard Smith       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1130824c2f53SJohn McCall     }
1131824c2f53SJohn McCall   };
11327f9c92a9SJohn McCall 
11337f9c92a9SJohn McCall   /// A cleanup to call the given 'operator delete' function upon
11347f9c92a9SJohn McCall   /// abnormal exit from a new expression when the new expression is
11357f9c92a9SJohn McCall   /// conditional.
11367f9c92a9SJohn McCall   class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup {
11377f9c92a9SJohn McCall     size_t NumPlacementArgs;
11387f9c92a9SJohn McCall     const FunctionDecl *OperatorDelete;
1139cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type Ptr;
1140cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type AllocSize;
11417f9c92a9SJohn McCall 
1142cb5f77f0SJohn McCall     DominatingValue<RValue>::saved_type *getPlacementArgs() {
1143cb5f77f0SJohn McCall       return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
11447f9c92a9SJohn McCall     }
11457f9c92a9SJohn McCall 
11467f9c92a9SJohn McCall   public:
11477f9c92a9SJohn McCall     static size_t getExtraSize(size_t NumPlacementArgs) {
1148cb5f77f0SJohn McCall       return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
11497f9c92a9SJohn McCall     }
11507f9c92a9SJohn McCall 
11517f9c92a9SJohn McCall     CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
11527f9c92a9SJohn McCall                                    const FunctionDecl *OperatorDelete,
1153cb5f77f0SJohn McCall                                    DominatingValue<RValue>::saved_type Ptr,
1154cb5f77f0SJohn McCall                               DominatingValue<RValue>::saved_type AllocSize)
11557f9c92a9SJohn McCall       : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
11567f9c92a9SJohn McCall         Ptr(Ptr), AllocSize(AllocSize) {}
11577f9c92a9SJohn McCall 
1158cb5f77f0SJohn McCall     void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
11597f9c92a9SJohn McCall       assert(I < NumPlacementArgs && "index out of range");
11607f9c92a9SJohn McCall       getPlacementArgs()[I] = Arg;
11617f9c92a9SJohn McCall     }
11627f9c92a9SJohn McCall 
11634f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
11647f9c92a9SJohn McCall       const FunctionProtoType *FPT
11657f9c92a9SJohn McCall         = OperatorDelete->getType()->getAs<FunctionProtoType>();
11669cacbabdSAlp Toker       assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
11679cacbabdSAlp Toker              (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
11687f9c92a9SJohn McCall 
11697f9c92a9SJohn McCall       CallArgList DeleteArgs;
11707f9c92a9SJohn McCall 
11717f9c92a9SJohn McCall       // The first argument is always a void*.
11729cacbabdSAlp Toker       FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
117343dca6a8SEli Friedman       DeleteArgs.add(Ptr.restore(CGF), *AI++);
11747f9c92a9SJohn McCall 
11757f9c92a9SJohn McCall       // A member 'operator delete' can take an extra 'size_t' argument.
11769cacbabdSAlp Toker       if (FPT->getNumParams() == NumPlacementArgs + 2) {
1177cb5f77f0SJohn McCall         RValue RV = AllocSize.restore(CGF);
117843dca6a8SEli Friedman         DeleteArgs.add(RV, *AI++);
11797f9c92a9SJohn McCall       }
11807f9c92a9SJohn McCall 
11817f9c92a9SJohn McCall       // Pass the rest of the arguments, which must match exactly.
11827f9c92a9SJohn McCall       for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1183cb5f77f0SJohn McCall         RValue RV = getPlacementArgs()[I].restore(CGF);
118443dca6a8SEli Friedman         DeleteArgs.add(RV, *AI++);
11857f9c92a9SJohn McCall       }
11867f9c92a9SJohn McCall 
11877f9c92a9SJohn McCall       // Call 'operator delete'.
11888d0dc31dSRichard Smith       EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
11897f9c92a9SJohn McCall     }
11907f9c92a9SJohn McCall   };
11917f9c92a9SJohn McCall }
11927f9c92a9SJohn McCall 
11937f9c92a9SJohn McCall /// Enter a cleanup to call 'operator delete' if the initializer in a
11947f9c92a9SJohn McCall /// new-expression throws.
11957f9c92a9SJohn McCall static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
11967f9c92a9SJohn McCall                                   const CXXNewExpr *E,
11977f9c92a9SJohn McCall                                   llvm::Value *NewPtr,
11987f9c92a9SJohn McCall                                   llvm::Value *AllocSize,
11997f9c92a9SJohn McCall                                   const CallArgList &NewArgs) {
12007f9c92a9SJohn McCall   // If we're not inside a conditional branch, then the cleanup will
12017f9c92a9SJohn McCall   // dominate and we can do the easier (and more efficient) thing.
12027f9c92a9SJohn McCall   if (!CGF.isInConditionalBranch()) {
12037f9c92a9SJohn McCall     CallDeleteDuringNew *Cleanup = CGF.EHStack
12047f9c92a9SJohn McCall       .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
12057f9c92a9SJohn McCall                                                  E->getNumPlacementArgs(),
12067f9c92a9SJohn McCall                                                  E->getOperatorDelete(),
12077f9c92a9SJohn McCall                                                  NewPtr, AllocSize);
12087f9c92a9SJohn McCall     for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1209f4258eb4SEli Friedman       Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
12107f9c92a9SJohn McCall 
12117f9c92a9SJohn McCall     return;
12127f9c92a9SJohn McCall   }
12137f9c92a9SJohn McCall 
12147f9c92a9SJohn McCall   // Otherwise, we need to save all this stuff.
1215cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedNewPtr =
1216cb5f77f0SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(NewPtr));
1217cb5f77f0SJohn McCall   DominatingValue<RValue>::saved_type SavedAllocSize =
1218cb5f77f0SJohn McCall     DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
12197f9c92a9SJohn McCall 
12207f9c92a9SJohn McCall   CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
1221f4beacd0SJohn McCall     .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
12227f9c92a9SJohn McCall                                                  E->getNumPlacementArgs(),
12237f9c92a9SJohn McCall                                                  E->getOperatorDelete(),
12247f9c92a9SJohn McCall                                                  SavedNewPtr,
12257f9c92a9SJohn McCall                                                  SavedAllocSize);
12267f9c92a9SJohn McCall   for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1227cb5f77f0SJohn McCall     Cleanup->setPlacementArg(I,
1228f4258eb4SEli Friedman                      DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
12297f9c92a9SJohn McCall 
1230f4beacd0SJohn McCall   CGF.initFullExprCleanup();
1231824c2f53SJohn McCall }
1232824c2f53SJohn McCall 
123359486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
123475f9498aSJohn McCall   // The element type being allocated.
123575f9498aSJohn McCall   QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
12368ed55a54SJohn McCall 
123775f9498aSJohn McCall   // 1. Build a call to the allocation function.
123875f9498aSJohn McCall   FunctionDecl *allocator = E->getOperatorNew();
123975f9498aSJohn McCall   const FunctionProtoType *allocatorType =
124075f9498aSJohn McCall     allocator->getType()->castAs<FunctionProtoType>();
124159486a2dSAnders Carlsson 
124275f9498aSJohn McCall   CallArgList allocatorArgs;
124359486a2dSAnders Carlsson 
124459486a2dSAnders Carlsson   // The allocation size is the first argument.
124575f9498aSJohn McCall   QualType sizeType = getContext().getSizeType();
124659486a2dSAnders Carlsson 
1247f862eb6aSSebastian Redl   // If there is a brace-initializer, cannot allocate fewer elements than inits.
1248f862eb6aSSebastian Redl   unsigned minElements = 0;
1249f862eb6aSSebastian Redl   if (E->isArray() && E->hasInitializer()) {
1250f862eb6aSSebastian Redl     if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1251f862eb6aSSebastian Redl       minElements = ILE->getNumInits();
1252f862eb6aSSebastian Redl   }
1253f862eb6aSSebastian Redl 
12548a13c418SCraig Topper   llvm::Value *numElements = nullptr;
12558a13c418SCraig Topper   llvm::Value *allocSizeWithoutCookie = nullptr;
125675f9498aSJohn McCall   llvm::Value *allocSize =
1257f862eb6aSSebastian Redl     EmitCXXNewAllocSize(*this, E, minElements, numElements,
1258f862eb6aSSebastian Redl                         allocSizeWithoutCookie);
125959486a2dSAnders Carlsson 
126043dca6a8SEli Friedman   allocatorArgs.add(RValue::get(allocSize), sizeType);
126159486a2dSAnders Carlsson 
126259486a2dSAnders Carlsson   // We start at 1 here because the first argument (the allocation size)
126359486a2dSAnders Carlsson   // has already been emitted.
1264cbe875a5SAlexey Samsonov   EmitCallArgs(allocatorArgs, allocatorType, E->placement_arg_begin(),
12658e1162c7SAlexey Samsonov                E->placement_arg_end(), /* CalleeDecl */ nullptr,
12668e1162c7SAlexey Samsonov                /*ParamsToSkip*/ 1);
126759486a2dSAnders Carlsson 
12687ec4b434SJohn McCall   // Emit the allocation call.  If the allocator is a global placement
12697ec4b434SJohn McCall   // operator, just "inline" it directly.
12707ec4b434SJohn McCall   RValue RV;
12717ec4b434SJohn McCall   if (allocator->isReservedGlobalPlacementOperator()) {
12727ec4b434SJohn McCall     assert(allocatorArgs.size() == 2);
12737ec4b434SJohn McCall     RV = allocatorArgs[1].RV;
12747ec4b434SJohn McCall     // TODO: kill any unnecessary computations done for the size
12757ec4b434SJohn McCall     // argument.
12767ec4b434SJohn McCall   } else {
12778d0dc31dSRichard Smith     RV = EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
12787ec4b434SJohn McCall   }
127959486a2dSAnders Carlsson 
128075f9498aSJohn McCall   // Emit a null check on the allocation result if the allocation
128175f9498aSJohn McCall   // function is allowed to return null (because it has a non-throwing
128275f9498aSJohn McCall   // exception spec; for this part, we inline
128375f9498aSJohn McCall   // CXXNewExpr::shouldNullCheckAllocation()) and we have an
128475f9498aSJohn McCall   // interesting initializer.
128531ad754cSSebastian Redl   bool nullCheck = allocatorType->isNothrow(getContext()) &&
12866047f07eSSebastian Redl     (!allocType.isPODType(getContext()) || E->hasInitializer());
128759486a2dSAnders Carlsson 
12888a13c418SCraig Topper   llvm::BasicBlock *nullCheckBB = nullptr;
12898a13c418SCraig Topper   llvm::BasicBlock *contBB = nullptr;
129059486a2dSAnders Carlsson 
129175f9498aSJohn McCall   llvm::Value *allocation = RV.getScalarVal();
1292ea2fea2aSMicah Villmow   unsigned AS = allocation->getType()->getPointerAddressSpace();
129359486a2dSAnders Carlsson 
1294f7dcf320SJohn McCall   // The null-check means that the initializer is conditionally
1295f7dcf320SJohn McCall   // evaluated.
1296f7dcf320SJohn McCall   ConditionalEvaluation conditional(*this);
1297f7dcf320SJohn McCall 
129875f9498aSJohn McCall   if (nullCheck) {
1299f7dcf320SJohn McCall     conditional.begin(*this);
130075f9498aSJohn McCall 
130175f9498aSJohn McCall     nullCheckBB = Builder.GetInsertBlock();
130275f9498aSJohn McCall     llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
130375f9498aSJohn McCall     contBB = createBasicBlock("new.cont");
130475f9498aSJohn McCall 
130575f9498aSJohn McCall     llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull");
130675f9498aSJohn McCall     Builder.CreateCondBr(isNull, contBB, notNullBB);
130775f9498aSJohn McCall     EmitBlock(notNullBB);
130859486a2dSAnders Carlsson   }
130959486a2dSAnders Carlsson 
1310824c2f53SJohn McCall   // If there's an operator delete, enter a cleanup to call it if an
1311824c2f53SJohn McCall   // exception is thrown.
131275f9498aSJohn McCall   EHScopeStack::stable_iterator operatorDeleteCleanup;
13138a13c418SCraig Topper   llvm::Instruction *cleanupDominator = nullptr;
13147ec4b434SJohn McCall   if (E->getOperatorDelete() &&
13157ec4b434SJohn McCall       !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
131675f9498aSJohn McCall     EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
131775f9498aSJohn McCall     operatorDeleteCleanup = EHStack.stable_begin();
1318f4beacd0SJohn McCall     cleanupDominator = Builder.CreateUnreachable();
1319824c2f53SJohn McCall   }
1320824c2f53SJohn McCall 
1321cf9b1f65SEli Friedman   assert((allocSize == allocSizeWithoutCookie) ==
1322cf9b1f65SEli Friedman          CalculateCookiePadding(*this, E).isZero());
1323cf9b1f65SEli Friedman   if (allocSize != allocSizeWithoutCookie) {
1324cf9b1f65SEli Friedman     assert(E->isArray());
1325cf9b1f65SEli Friedman     allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1326cf9b1f65SEli Friedman                                                        numElements,
1327cf9b1f65SEli Friedman                                                        E, allocType);
1328cf9b1f65SEli Friedman   }
1329cf9b1f65SEli Friedman 
13302192fe50SChris Lattner   llvm::Type *elementPtrTy
133175f9498aSJohn McCall     = ConvertTypeForMem(allocType)->getPointerTo(AS);
133275f9498aSJohn McCall   llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy);
1333824c2f53SJohn McCall 
133499210dc9SJohn McCall   EmitNewInitializer(*this, E, allocType, result, numElements,
133599210dc9SJohn McCall                      allocSizeWithoutCookie);
13368ed55a54SJohn McCall   if (E->isArray()) {
13378ed55a54SJohn McCall     // NewPtr is a pointer to the base element type.  If we're
13388ed55a54SJohn McCall     // allocating an array of arrays, we'll need to cast back to the
13398ed55a54SJohn McCall     // array pointer type.
13402192fe50SChris Lattner     llvm::Type *resultType = ConvertTypeForMem(E->getType());
134175f9498aSJohn McCall     if (result->getType() != resultType)
134275f9498aSJohn McCall       result = Builder.CreateBitCast(result, resultType);
134347b4629bSFariborz Jahanian   }
134459486a2dSAnders Carlsson 
1345824c2f53SJohn McCall   // Deactivate the 'operator delete' cleanup if we finished
1346824c2f53SJohn McCall   // initialization.
1347f4beacd0SJohn McCall   if (operatorDeleteCleanup.isValid()) {
1348f4beacd0SJohn McCall     DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1349f4beacd0SJohn McCall     cleanupDominator->eraseFromParent();
1350f4beacd0SJohn McCall   }
1351824c2f53SJohn McCall 
135275f9498aSJohn McCall   if (nullCheck) {
1353f7dcf320SJohn McCall     conditional.end(*this);
1354f7dcf320SJohn McCall 
135575f9498aSJohn McCall     llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
135675f9498aSJohn McCall     EmitBlock(contBB);
135759486a2dSAnders Carlsson 
135820c0f02cSJay Foad     llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2);
135975f9498aSJohn McCall     PHI->addIncoming(result, notNullBB);
136075f9498aSJohn McCall     PHI->addIncoming(llvm::Constant::getNullValue(result->getType()),
136175f9498aSJohn McCall                      nullCheckBB);
136259486a2dSAnders Carlsson 
136375f9498aSJohn McCall     result = PHI;
136459486a2dSAnders Carlsson   }
136559486a2dSAnders Carlsson 
136675f9498aSJohn McCall   return result;
136759486a2dSAnders Carlsson }
136859486a2dSAnders Carlsson 
136959486a2dSAnders Carlsson void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
137059486a2dSAnders Carlsson                                      llvm::Value *Ptr,
137159486a2dSAnders Carlsson                                      QualType DeleteTy) {
13728ed55a54SJohn McCall   assert(DeleteFD->getOverloadedOperator() == OO_Delete);
13738ed55a54SJohn McCall 
137459486a2dSAnders Carlsson   const FunctionProtoType *DeleteFTy =
137559486a2dSAnders Carlsson     DeleteFD->getType()->getAs<FunctionProtoType>();
137659486a2dSAnders Carlsson 
137759486a2dSAnders Carlsson   CallArgList DeleteArgs;
137859486a2dSAnders Carlsson 
137921122cf6SAnders Carlsson   // Check if we need to pass the size to the delete operator.
13808a13c418SCraig Topper   llvm::Value *Size = nullptr;
138121122cf6SAnders Carlsson   QualType SizeTy;
13829cacbabdSAlp Toker   if (DeleteFTy->getNumParams() == 2) {
13839cacbabdSAlp Toker     SizeTy = DeleteFTy->getParamType(1);
13847df3cbebSKen Dyck     CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
13857df3cbebSKen Dyck     Size = llvm::ConstantInt::get(ConvertType(SizeTy),
13867df3cbebSKen Dyck                                   DeleteTypeSize.getQuantity());
138721122cf6SAnders Carlsson   }
138821122cf6SAnders Carlsson 
13899cacbabdSAlp Toker   QualType ArgTy = DeleteFTy->getParamType(0);
139059486a2dSAnders Carlsson   llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
139143dca6a8SEli Friedman   DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
139259486a2dSAnders Carlsson 
139321122cf6SAnders Carlsson   if (Size)
139443dca6a8SEli Friedman     DeleteArgs.add(RValue::get(Size), SizeTy);
139559486a2dSAnders Carlsson 
139659486a2dSAnders Carlsson   // Emit the call to delete.
13978d0dc31dSRichard Smith   EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
139859486a2dSAnders Carlsson }
139959486a2dSAnders Carlsson 
14008ed55a54SJohn McCall namespace {
14018ed55a54SJohn McCall   /// Calls the given 'operator delete' on a single object.
14028ed55a54SJohn McCall   struct CallObjectDelete : EHScopeStack::Cleanup {
14038ed55a54SJohn McCall     llvm::Value *Ptr;
14048ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
14058ed55a54SJohn McCall     QualType ElementType;
14068ed55a54SJohn McCall 
14078ed55a54SJohn McCall     CallObjectDelete(llvm::Value *Ptr,
14088ed55a54SJohn McCall                      const FunctionDecl *OperatorDelete,
14098ed55a54SJohn McCall                      QualType ElementType)
14108ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
14118ed55a54SJohn McCall 
14124f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
14138ed55a54SJohn McCall       CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
14148ed55a54SJohn McCall     }
14158ed55a54SJohn McCall   };
14168ed55a54SJohn McCall }
14178ed55a54SJohn McCall 
14180c0b6d9aSDavid Majnemer void
14190c0b6d9aSDavid Majnemer CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
14200c0b6d9aSDavid Majnemer                                              llvm::Value *CompletePtr,
14210c0b6d9aSDavid Majnemer                                              QualType ElementType) {
14220c0b6d9aSDavid Majnemer   EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
14230c0b6d9aSDavid Majnemer                                         OperatorDelete, ElementType);
14240c0b6d9aSDavid Majnemer }
14250c0b6d9aSDavid Majnemer 
14268ed55a54SJohn McCall /// Emit the code for deleting a single object.
14278ed55a54SJohn McCall static void EmitObjectDelete(CodeGenFunction &CGF,
14280868137aSDavid Majnemer                              const CXXDeleteExpr *DE,
14298ed55a54SJohn McCall                              llvm::Value *Ptr,
14300868137aSDavid Majnemer                              QualType ElementType) {
14318ed55a54SJohn McCall   // Find the destructor for the type, if applicable.  If the
14328ed55a54SJohn McCall   // destructor is virtual, we'll just emit the vcall and return.
14338a13c418SCraig Topper   const CXXDestructorDecl *Dtor = nullptr;
14348ed55a54SJohn McCall   if (const RecordType *RT = ElementType->getAs<RecordType>()) {
14358ed55a54SJohn McCall     CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1436b23533dbSEli Friedman     if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
14378ed55a54SJohn McCall       Dtor = RD->getDestructor();
14388ed55a54SJohn McCall 
14398ed55a54SJohn McCall       if (Dtor->isVirtual()) {
14400868137aSDavid Majnemer         CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
14410868137aSDavid Majnemer                                                     Dtor);
14428ed55a54SJohn McCall         return;
14438ed55a54SJohn McCall       }
14448ed55a54SJohn McCall     }
14458ed55a54SJohn McCall   }
14468ed55a54SJohn McCall 
14478ed55a54SJohn McCall   // Make sure that we call delete even if the dtor throws.
1448e4df6c8dSJohn McCall   // This doesn't have to a conditional cleanup because we're going
1449e4df6c8dSJohn McCall   // to pop it off in a second.
14500868137aSDavid Majnemer   const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
14518ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
14528ed55a54SJohn McCall                                             Ptr, OperatorDelete, ElementType);
14538ed55a54SJohn McCall 
14548ed55a54SJohn McCall   if (Dtor)
14558ed55a54SJohn McCall     CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
145661535005SDouglas Gregor                               /*ForVirtualBase=*/false,
145761535005SDouglas Gregor                               /*Delegating=*/false,
145861535005SDouglas Gregor                               Ptr);
1459bbafb8a7SDavid Blaikie   else if (CGF.getLangOpts().ObjCAutoRefCount &&
146031168b07SJohn McCall            ElementType->isObjCLifetimeType()) {
146131168b07SJohn McCall     switch (ElementType.getObjCLifetime()) {
146231168b07SJohn McCall     case Qualifiers::OCL_None:
146331168b07SJohn McCall     case Qualifiers::OCL_ExplicitNone:
146431168b07SJohn McCall     case Qualifiers::OCL_Autoreleasing:
146531168b07SJohn McCall       break;
146631168b07SJohn McCall 
146731168b07SJohn McCall     case Qualifiers::OCL_Strong: {
146831168b07SJohn McCall       // Load the pointer value.
146931168b07SJohn McCall       llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr,
147031168b07SJohn McCall                                              ElementType.isVolatileQualified());
147131168b07SJohn McCall 
1472cdda29c9SJohn McCall       CGF.EmitARCRelease(PtrValue, ARCPreciseLifetime);
147331168b07SJohn McCall       break;
147431168b07SJohn McCall     }
147531168b07SJohn McCall 
147631168b07SJohn McCall     case Qualifiers::OCL_Weak:
147731168b07SJohn McCall       CGF.EmitARCDestroyWeak(Ptr);
147831168b07SJohn McCall       break;
147931168b07SJohn McCall     }
148031168b07SJohn McCall   }
14818ed55a54SJohn McCall 
14828ed55a54SJohn McCall   CGF.PopCleanupBlock();
14838ed55a54SJohn McCall }
14848ed55a54SJohn McCall 
14858ed55a54SJohn McCall namespace {
14868ed55a54SJohn McCall   /// Calls the given 'operator delete' on an array of objects.
14878ed55a54SJohn McCall   struct CallArrayDelete : EHScopeStack::Cleanup {
14888ed55a54SJohn McCall     llvm::Value *Ptr;
14898ed55a54SJohn McCall     const FunctionDecl *OperatorDelete;
14908ed55a54SJohn McCall     llvm::Value *NumElements;
14918ed55a54SJohn McCall     QualType ElementType;
14928ed55a54SJohn McCall     CharUnits CookieSize;
14938ed55a54SJohn McCall 
14948ed55a54SJohn McCall     CallArrayDelete(llvm::Value *Ptr,
14958ed55a54SJohn McCall                     const FunctionDecl *OperatorDelete,
14968ed55a54SJohn McCall                     llvm::Value *NumElements,
14978ed55a54SJohn McCall                     QualType ElementType,
14988ed55a54SJohn McCall                     CharUnits CookieSize)
14998ed55a54SJohn McCall       : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
15008ed55a54SJohn McCall         ElementType(ElementType), CookieSize(CookieSize) {}
15018ed55a54SJohn McCall 
15024f12f10dSCraig Topper     void Emit(CodeGenFunction &CGF, Flags flags) override {
15038ed55a54SJohn McCall       const FunctionProtoType *DeleteFTy =
15048ed55a54SJohn McCall         OperatorDelete->getType()->getAs<FunctionProtoType>();
15059cacbabdSAlp Toker       assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
15068ed55a54SJohn McCall 
15078ed55a54SJohn McCall       CallArgList Args;
15088ed55a54SJohn McCall 
15098ed55a54SJohn McCall       // Pass the pointer as the first argument.
15109cacbabdSAlp Toker       QualType VoidPtrTy = DeleteFTy->getParamType(0);
15118ed55a54SJohn McCall       llvm::Value *DeletePtr
15128ed55a54SJohn McCall         = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
151343dca6a8SEli Friedman       Args.add(RValue::get(DeletePtr), VoidPtrTy);
15148ed55a54SJohn McCall 
15158ed55a54SJohn McCall       // Pass the original requested size as the second argument.
15169cacbabdSAlp Toker       if (DeleteFTy->getNumParams() == 2) {
15179cacbabdSAlp Toker         QualType size_t = DeleteFTy->getParamType(1);
15182192fe50SChris Lattner         llvm::IntegerType *SizeTy
15198ed55a54SJohn McCall           = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
15208ed55a54SJohn McCall 
15218ed55a54SJohn McCall         CharUnits ElementTypeSize =
15228ed55a54SJohn McCall           CGF.CGM.getContext().getTypeSizeInChars(ElementType);
15238ed55a54SJohn McCall 
15248ed55a54SJohn McCall         // The size of an element, multiplied by the number of elements.
15258ed55a54SJohn McCall         llvm::Value *Size
15268ed55a54SJohn McCall           = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
15278ed55a54SJohn McCall         Size = CGF.Builder.CreateMul(Size, NumElements);
15288ed55a54SJohn McCall 
15298ed55a54SJohn McCall         // Plus the size of the cookie if applicable.
15308ed55a54SJohn McCall         if (!CookieSize.isZero()) {
15318ed55a54SJohn McCall           llvm::Value *CookieSizeV
15328ed55a54SJohn McCall             = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
15338ed55a54SJohn McCall           Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
15348ed55a54SJohn McCall         }
15358ed55a54SJohn McCall 
153643dca6a8SEli Friedman         Args.add(RValue::get(Size), size_t);
15378ed55a54SJohn McCall       }
15388ed55a54SJohn McCall 
15398ed55a54SJohn McCall       // Emit the call to delete.
15408d0dc31dSRichard Smith       EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
15418ed55a54SJohn McCall     }
15428ed55a54SJohn McCall   };
15438ed55a54SJohn McCall }
15448ed55a54SJohn McCall 
15458ed55a54SJohn McCall /// Emit the code for deleting an array of objects.
15468ed55a54SJohn McCall static void EmitArrayDelete(CodeGenFunction &CGF,
1547284c48ffSJohn McCall                             const CXXDeleteExpr *E,
1548ca2c56f2SJohn McCall                             llvm::Value *deletedPtr,
1549ca2c56f2SJohn McCall                             QualType elementType) {
15508a13c418SCraig Topper   llvm::Value *numElements = nullptr;
15518a13c418SCraig Topper   llvm::Value *allocatedPtr = nullptr;
1552ca2c56f2SJohn McCall   CharUnits cookieSize;
1553ca2c56f2SJohn McCall   CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1554ca2c56f2SJohn McCall                                       numElements, allocatedPtr, cookieSize);
15558ed55a54SJohn McCall 
1556ca2c56f2SJohn McCall   assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
15578ed55a54SJohn McCall 
15588ed55a54SJohn McCall   // Make sure that we call delete even if one of the dtors throws.
1559ca2c56f2SJohn McCall   const FunctionDecl *operatorDelete = E->getOperatorDelete();
15608ed55a54SJohn McCall   CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1561ca2c56f2SJohn McCall                                            allocatedPtr, operatorDelete,
1562ca2c56f2SJohn McCall                                            numElements, elementType,
1563ca2c56f2SJohn McCall                                            cookieSize);
15648ed55a54SJohn McCall 
1565ca2c56f2SJohn McCall   // Destroy the elements.
1566ca2c56f2SJohn McCall   if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1567ca2c56f2SJohn McCall     assert(numElements && "no element count for a type with a destructor!");
156831168b07SJohn McCall 
1569ca2c56f2SJohn McCall     llvm::Value *arrayEnd =
1570ca2c56f2SJohn McCall       CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end");
157197eab0a2SJohn McCall 
157297eab0a2SJohn McCall     // Note that it is legal to allocate a zero-length array, and we
157397eab0a2SJohn McCall     // can never fold the check away because the length should always
157497eab0a2SJohn McCall     // come from a cookie.
1575ca2c56f2SJohn McCall     CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType,
1576ca2c56f2SJohn McCall                          CGF.getDestroyer(dtorKind),
157797eab0a2SJohn McCall                          /*checkZeroLength*/ true,
1578ca2c56f2SJohn McCall                          CGF.needsEHCleanup(dtorKind));
15798ed55a54SJohn McCall   }
15808ed55a54SJohn McCall 
1581ca2c56f2SJohn McCall   // Pop the cleanup block.
15828ed55a54SJohn McCall   CGF.PopCleanupBlock();
15838ed55a54SJohn McCall }
15848ed55a54SJohn McCall 
158559486a2dSAnders Carlsson void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
158659486a2dSAnders Carlsson   const Expr *Arg = E->getArgument();
158759486a2dSAnders Carlsson   llvm::Value *Ptr = EmitScalarExpr(Arg);
158859486a2dSAnders Carlsson 
158959486a2dSAnders Carlsson   // Null check the pointer.
159059486a2dSAnders Carlsson   llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
159159486a2dSAnders Carlsson   llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
159259486a2dSAnders Carlsson 
159398981b10SAnders Carlsson   llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull");
159459486a2dSAnders Carlsson 
159559486a2dSAnders Carlsson   Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
159659486a2dSAnders Carlsson   EmitBlock(DeleteNotNull);
159759486a2dSAnders Carlsson 
15988ed55a54SJohn McCall   // We might be deleting a pointer to array.  If so, GEP down to the
15998ed55a54SJohn McCall   // first non-array element.
16008ed55a54SJohn McCall   // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
16018ed55a54SJohn McCall   QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
16028ed55a54SJohn McCall   if (DeleteTy->isConstantArrayType()) {
16038ed55a54SJohn McCall     llvm::Value *Zero = Builder.getInt32(0);
16040e62c1ccSChris Lattner     SmallVector<llvm::Value*,8> GEP;
160559486a2dSAnders Carlsson 
16068ed55a54SJohn McCall     GEP.push_back(Zero); // point at the outermost array
16078ed55a54SJohn McCall 
16088ed55a54SJohn McCall     // For each layer of array type we're pointing at:
16098ed55a54SJohn McCall     while (const ConstantArrayType *Arr
16108ed55a54SJohn McCall              = getContext().getAsConstantArrayType(DeleteTy)) {
16118ed55a54SJohn McCall       // 1. Unpeel the array type.
16128ed55a54SJohn McCall       DeleteTy = Arr->getElementType();
16138ed55a54SJohn McCall 
16148ed55a54SJohn McCall       // 2. GEP to the first element of the array.
16158ed55a54SJohn McCall       GEP.push_back(Zero);
16168ed55a54SJohn McCall     }
16178ed55a54SJohn McCall 
1618040dd82fSJay Foad     Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first");
16198ed55a54SJohn McCall   }
16208ed55a54SJohn McCall 
162104f36218SDouglas Gregor   assert(ConvertTypeForMem(DeleteTy) ==
162204f36218SDouglas Gregor          cast<llvm::PointerType>(Ptr->getType())->getElementType());
16238ed55a54SJohn McCall 
162459486a2dSAnders Carlsson   if (E->isArrayForm()) {
1625284c48ffSJohn McCall     EmitArrayDelete(*this, E, Ptr, DeleteTy);
16268ed55a54SJohn McCall   } else {
16270868137aSDavid Majnemer     EmitObjectDelete(*this, E, Ptr, DeleteTy);
162859486a2dSAnders Carlsson   }
162959486a2dSAnders Carlsson 
163059486a2dSAnders Carlsson   EmitBlock(DeleteEnd);
163159486a2dSAnders Carlsson }
163259486a2dSAnders Carlsson 
16331c3d95ebSDavid Majnemer static bool isGLValueFromPointerDeref(const Expr *E) {
16341c3d95ebSDavid Majnemer   E = E->IgnoreParens();
16351c3d95ebSDavid Majnemer 
16361c3d95ebSDavid Majnemer   if (const auto *CE = dyn_cast<CastExpr>(E)) {
16371c3d95ebSDavid Majnemer     if (!CE->getSubExpr()->isGLValue())
16381c3d95ebSDavid Majnemer       return false;
16391c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(CE->getSubExpr());
16401c3d95ebSDavid Majnemer   }
16411c3d95ebSDavid Majnemer 
16421c3d95ebSDavid Majnemer   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
16431c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(OVE->getSourceExpr());
16441c3d95ebSDavid Majnemer 
16451c3d95ebSDavid Majnemer   if (const auto *BO = dyn_cast<BinaryOperator>(E))
16461c3d95ebSDavid Majnemer     if (BO->getOpcode() == BO_Comma)
16471c3d95ebSDavid Majnemer       return isGLValueFromPointerDeref(BO->getRHS());
16481c3d95ebSDavid Majnemer 
16491c3d95ebSDavid Majnemer   if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
16501c3d95ebSDavid Majnemer     return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
16511c3d95ebSDavid Majnemer            isGLValueFromPointerDeref(ACO->getFalseExpr());
16521c3d95ebSDavid Majnemer 
16531c3d95ebSDavid Majnemer   // C++11 [expr.sub]p1:
16541c3d95ebSDavid Majnemer   //   The expression E1[E2] is identical (by definition) to *((E1)+(E2))
16551c3d95ebSDavid Majnemer   if (isa<ArraySubscriptExpr>(E))
16561c3d95ebSDavid Majnemer     return true;
16571c3d95ebSDavid Majnemer 
16581c3d95ebSDavid Majnemer   if (const auto *UO = dyn_cast<UnaryOperator>(E))
16591c3d95ebSDavid Majnemer     if (UO->getOpcode() == UO_Deref)
16601c3d95ebSDavid Majnemer       return true;
16611c3d95ebSDavid Majnemer 
16621c3d95ebSDavid Majnemer   return false;
16631c3d95ebSDavid Majnemer }
16641c3d95ebSDavid Majnemer 
1665747e301eSWarren Hunt static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
16662192fe50SChris Lattner                                          llvm::Type *StdTypeInfoPtrTy) {
1667940f02d2SAnders Carlsson   // Get the vtable pointer.
1668940f02d2SAnders Carlsson   llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress();
1669940f02d2SAnders Carlsson 
1670940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
1671940f02d2SAnders Carlsson   //   If the glvalue expression is obtained by applying the unary * operator to
1672940f02d2SAnders Carlsson   //   a pointer and the pointer is a null pointer value, the typeid expression
1673940f02d2SAnders Carlsson   //   throws the std::bad_typeid exception.
16741c3d95ebSDavid Majnemer   //
16751c3d95ebSDavid Majnemer   // However, this paragraph's intent is not clear.  We choose a very generous
16761c3d95ebSDavid Majnemer   // interpretation which implores us to consider comma operators, conditional
16771c3d95ebSDavid Majnemer   // operators, parentheses and other such constructs.
16781162d25cSDavid Majnemer   QualType SrcRecordTy = E->getType();
16791c3d95ebSDavid Majnemer   if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
16801c3d95ebSDavid Majnemer           isGLValueFromPointerDeref(E), SrcRecordTy)) {
1681940f02d2SAnders Carlsson     llvm::BasicBlock *BadTypeidBlock =
1682940f02d2SAnders Carlsson         CGF.createBasicBlock("typeid.bad_typeid");
16831162d25cSDavid Majnemer     llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
1684940f02d2SAnders Carlsson 
1685940f02d2SAnders Carlsson     llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr);
1686940f02d2SAnders Carlsson     CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1687940f02d2SAnders Carlsson 
1688940f02d2SAnders Carlsson     CGF.EmitBlock(BadTypeidBlock);
16891162d25cSDavid Majnemer     CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1690940f02d2SAnders Carlsson     CGF.EmitBlock(EndBlock);
1691940f02d2SAnders Carlsson   }
1692940f02d2SAnders Carlsson 
16931162d25cSDavid Majnemer   return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
16941162d25cSDavid Majnemer                                         StdTypeInfoPtrTy);
1695940f02d2SAnders Carlsson }
1696940f02d2SAnders Carlsson 
169759486a2dSAnders Carlsson llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
16982192fe50SChris Lattner   llvm::Type *StdTypeInfoPtrTy =
1699940f02d2SAnders Carlsson     ConvertType(E->getType())->getPointerTo();
1700fd7dfeb7SAnders Carlsson 
17013f4336cbSAnders Carlsson   if (E->isTypeOperand()) {
17023f4336cbSAnders Carlsson     llvm::Constant *TypeInfo =
1703143c55eaSDavid Majnemer         CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
1704940f02d2SAnders Carlsson     return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
17053f4336cbSAnders Carlsson   }
1706fd7dfeb7SAnders Carlsson 
1707940f02d2SAnders Carlsson   // C++ [expr.typeid]p2:
1708940f02d2SAnders Carlsson   //   When typeid is applied to a glvalue expression whose type is a
1709940f02d2SAnders Carlsson   //   polymorphic class type, the result refers to a std::type_info object
1710940f02d2SAnders Carlsson   //   representing the type of the most derived object (that is, the dynamic
1711940f02d2SAnders Carlsson   //   type) to which the glvalue refers.
1712ef8bf436SRichard Smith   if (E->isPotentiallyEvaluated())
1713940f02d2SAnders Carlsson     return EmitTypeidFromVTable(*this, E->getExprOperand(),
1714940f02d2SAnders Carlsson                                 StdTypeInfoPtrTy);
1715940f02d2SAnders Carlsson 
1716940f02d2SAnders Carlsson   QualType OperandTy = E->getExprOperand()->getType();
1717940f02d2SAnders Carlsson   return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1718940f02d2SAnders Carlsson                                StdTypeInfoPtrTy);
171959486a2dSAnders Carlsson }
172059486a2dSAnders Carlsson 
1721c1c9971cSAnders Carlsson static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1722c1c9971cSAnders Carlsson                                           QualType DestTy) {
17232192fe50SChris Lattner   llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1724c1c9971cSAnders Carlsson   if (DestTy->isPointerType())
1725c1c9971cSAnders Carlsson     return llvm::Constant::getNullValue(DestLTy);
1726c1c9971cSAnders Carlsson 
1727c1c9971cSAnders Carlsson   /// C++ [expr.dynamic.cast]p9:
1728c1c9971cSAnders Carlsson   ///   A failed cast to reference type throws std::bad_cast
17291162d25cSDavid Majnemer   if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
17301162d25cSDavid Majnemer     return nullptr;
1731c1c9971cSAnders Carlsson 
1732c1c9971cSAnders Carlsson   CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1733c1c9971cSAnders Carlsson   return llvm::UndefValue::get(DestLTy);
1734c1c9971cSAnders Carlsson }
1735c1c9971cSAnders Carlsson 
1736882d790fSAnders Carlsson llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value,
173759486a2dSAnders Carlsson                                               const CXXDynamicCastExpr *DCE) {
17383f4336cbSAnders Carlsson   QualType DestTy = DCE->getTypeAsWritten();
17393f4336cbSAnders Carlsson 
1740c1c9971cSAnders Carlsson   if (DCE->isAlwaysNull())
17411162d25cSDavid Majnemer     if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
17421162d25cSDavid Majnemer       return T;
1743c1c9971cSAnders Carlsson 
1744c1c9971cSAnders Carlsson   QualType SrcTy = DCE->getSubExpr()->getType();
1745c1c9971cSAnders Carlsson 
17461162d25cSDavid Majnemer   // C++ [expr.dynamic.cast]p7:
17471162d25cSDavid Majnemer   //   If T is "pointer to cv void," then the result is a pointer to the most
17481162d25cSDavid Majnemer   //   derived object pointed to by v.
17491162d25cSDavid Majnemer   const PointerType *DestPTy = DestTy->getAs<PointerType>();
17501162d25cSDavid Majnemer 
17511162d25cSDavid Majnemer   bool isDynamicCastToVoid;
17521162d25cSDavid Majnemer   QualType SrcRecordTy;
17531162d25cSDavid Majnemer   QualType DestRecordTy;
17541162d25cSDavid Majnemer   if (DestPTy) {
17551162d25cSDavid Majnemer     isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
17561162d25cSDavid Majnemer     SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
17571162d25cSDavid Majnemer     DestRecordTy = DestPTy->getPointeeType();
17581162d25cSDavid Majnemer   } else {
17591162d25cSDavid Majnemer     isDynamicCastToVoid = false;
17601162d25cSDavid Majnemer     SrcRecordTy = SrcTy;
17611162d25cSDavid Majnemer     DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
17621162d25cSDavid Majnemer   }
17631162d25cSDavid Majnemer 
17641162d25cSDavid Majnemer   assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
17651162d25cSDavid Majnemer 
1766882d790fSAnders Carlsson   // C++ [expr.dynamic.cast]p4:
1767882d790fSAnders Carlsson   //   If the value of v is a null pointer value in the pointer case, the result
1768882d790fSAnders Carlsson   //   is the null pointer value of type T.
17691162d25cSDavid Majnemer   bool ShouldNullCheckSrcValue =
17701162d25cSDavid Majnemer       CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
17711162d25cSDavid Majnemer                                                          SrcRecordTy);
177259486a2dSAnders Carlsson 
17738a13c418SCraig Topper   llvm::BasicBlock *CastNull = nullptr;
17748a13c418SCraig Topper   llvm::BasicBlock *CastNotNull = nullptr;
1775882d790fSAnders Carlsson   llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
1776fa8b4955SDouglas Gregor 
1777882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1778882d790fSAnders Carlsson     CastNull = createBasicBlock("dynamic_cast.null");
1779882d790fSAnders Carlsson     CastNotNull = createBasicBlock("dynamic_cast.notnull");
1780882d790fSAnders Carlsson 
1781882d790fSAnders Carlsson     llvm::Value *IsNull = Builder.CreateIsNull(Value);
1782882d790fSAnders Carlsson     Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1783882d790fSAnders Carlsson     EmitBlock(CastNotNull);
178459486a2dSAnders Carlsson   }
178559486a2dSAnders Carlsson 
17861162d25cSDavid Majnemer   if (isDynamicCastToVoid) {
17871162d25cSDavid Majnemer     Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, Value, SrcRecordTy,
17881162d25cSDavid Majnemer                                                   DestTy);
17891162d25cSDavid Majnemer   } else {
17901162d25cSDavid Majnemer     assert(DestRecordTy->isRecordType() &&
17911162d25cSDavid Majnemer            "destination type must be a record type!");
17921162d25cSDavid Majnemer     Value = CGM.getCXXABI().EmitDynamicCastCall(*this, Value, SrcRecordTy,
17931162d25cSDavid Majnemer                                                 DestTy, DestRecordTy, CastEnd);
17941162d25cSDavid Majnemer   }
17953f4336cbSAnders Carlsson 
1796882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1797882d790fSAnders Carlsson     EmitBranch(CastEnd);
179859486a2dSAnders Carlsson 
1799882d790fSAnders Carlsson     EmitBlock(CastNull);
1800882d790fSAnders Carlsson     EmitBranch(CastEnd);
180159486a2dSAnders Carlsson   }
180259486a2dSAnders Carlsson 
1803882d790fSAnders Carlsson   EmitBlock(CastEnd);
180459486a2dSAnders Carlsson 
1805882d790fSAnders Carlsson   if (ShouldNullCheckSrcValue) {
1806882d790fSAnders Carlsson     llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1807882d790fSAnders Carlsson     PHI->addIncoming(Value, CastNotNull);
1808882d790fSAnders Carlsson     PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
180959486a2dSAnders Carlsson 
1810882d790fSAnders Carlsson     Value = PHI;
181159486a2dSAnders Carlsson   }
181259486a2dSAnders Carlsson 
1813882d790fSAnders Carlsson   return Value;
181459486a2dSAnders Carlsson }
1815c370a7eeSEli Friedman 
1816c370a7eeSEli Friedman void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
18178631f3e8SEli Friedman   RunCleanupsScope Scope(*this);
181839c81e28SAlexey Bataev   LValue SlotLV =
181939c81e28SAlexey Bataev       MakeAddrLValue(Slot.getAddr(), E->getType(), Slot.getAlignment());
18208631f3e8SEli Friedman 
1821c370a7eeSEli Friedman   CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1822c370a7eeSEli Friedman   for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(),
1823c370a7eeSEli Friedman                                          e = E->capture_init_end();
1824c370a7eeSEli Friedman        i != e; ++i, ++CurField) {
1825c370a7eeSEli Friedman     // Emit initialization
182640ed2973SDavid Blaikie     LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
182739c81e28SAlexey Bataev     if (CurField->hasCapturedVLAType()) {
182839c81e28SAlexey Bataev       auto VAT = CurField->getCapturedVLAType();
182939c81e28SAlexey Bataev       EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
183039c81e28SAlexey Bataev     } else {
18315f1a04ffSEli Friedman       ArrayRef<VarDecl *> ArrayIndexes;
18325f1a04ffSEli Friedman       if (CurField->getType()->isArrayType())
18335f1a04ffSEli Friedman         ArrayIndexes = E->getCaptureInitIndexVars(i);
183440ed2973SDavid Blaikie       EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);
1835c370a7eeSEli Friedman     }
1836c370a7eeSEli Friedman   }
183739c81e28SAlexey Bataev }
1838